Advertisement
Guest User

HTTPRequestHandler.py

a guest
Oct 22nd, 2017
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.02 KB | None | 0 0
  1. #!/usr/bin/env python2.7
  2. # -*- coding: utf-8 -*-
  3.  
  4. import cgi
  5. import logging
  6. import os
  7.  
  8.  
  9. '''
  10. Factory to make the request handler and add arguments to it.
  11.  
  12. It exists to allow the handler to access the opts.path variable
  13. locally.
  14. '''    
  15. class HTTPRequestHandler:
  16.        
  17.     def do_GET(BaseHTTPRequestHandler):
  18.         m_BaseHTTPRequest = BaseHTTPRequestHandler
  19.            
  20.         # Parse out the arguments.
  21.         # The arguments follow a '?' in the URL. Here is an example:
  22.         #   http://example.com?arg1=val1
  23.         args = {}
  24.         idx = m_BaseHTTPRequest.path.find('?')
  25.         if idx >= 0:
  26.             rpath = m_BaseHTTPRequest.path[:idx]
  27.             args = cgi.parse_qs(m_BaseHTTPRequest.path[idx+1:])
  28.         else:
  29.             rpath = m_BaseHTTPRequest.path
  30.                
  31.         # Print out logging information about the path and args.
  32.         if 'content-type' in m_BaseHTTPRequest.headers:
  33.             ctype, _ = cgi.parse_header(m_BaseHTTPRequest.headers['content-type'])
  34.             logging.debug('TYPE %s' % (ctype))
  35.    
  36.         logging.debug('PATH %s' % (rpath))
  37.         logging.debug('ARGS %d' % (len(args)))
  38.         if len(args):
  39.             i = 0
  40.             for key in sorted(args):
  41.                 logging.debug('ARG[%d] %s=%s' % (i, key, args[key]))
  42.                 i += 1
  43.            
  44.         # Check to see whether the file is stored locally,
  45.         # if it is, display it.
  46.            
  47.         # Get the file path.
  48.         path = HTTPRequestHandler.m_opts.rootdir + rpath
  49.         dirpath = None
  50.         logging.debug('FILE %s' % (path))
  51.    
  52.         # If it is a directory look for index.html
  53.         # or process it directly if there are 3
  54.         # trailing slashed.
  55.         if rpath[-3:] == '///':
  56.             dirpath = path
  57.         elif os.path.exists(path) and os.path.isdir(path):
  58.             dirpath = path  # the directory portion
  59.             index_files = ['/index.html', '/index.htm', ]
  60.             for index_file in index_files:
  61.                 tmppath = path + index_file
  62.                 if os.path.exists(tmppath):
  63.                     path = tmppath
  64.                     break
  65.    
  66.         # Allow the user to type "///" at the end to see the
  67.         # directory listing.
  68.         if os.path.exists(path) and os.path.isfile(path):
  69.             # This is valid file, send it as the response
  70.             # after determining whether it is a type that
  71.             # the server recognizes.
  72.             _, ext = os.path.splitext(path)
  73.             ext = ext.lower()
  74.             content_type = {
  75.                 '.css': 'text/css',
  76.                 '.gif': 'image/gif',
  77.                 '.htm': 'text/html',
  78.                 '.html': 'text/html',
  79.                 '.jpeg': 'image/jpeg',
  80.                 '.jpg': 'image/jpg',
  81.                 '.js': 'text/javascript',
  82.                 '.png': 'image/png',
  83.                 '.text': 'text/plain',
  84.                 '.txt': 'text/plain',
  85.             }
  86.    
  87.             # If it is a known extension, set the correct
  88.             # content type in the response.
  89.             if ext in content_type:
  90.                 m_BaseHTTPRequest.send_response(200)  # OK
  91.                 m_BaseHTTPRequest.send_header('Content-type', content_type[ext])
  92.                 m_BaseHTTPRequest.end_headers()
  93.    
  94.                 with open(path) as ifp:
  95.                     m_BaseHTTPRequest.wfile.write(ifp.read())
  96.             else:
  97.                 # Unknown file type or a directory.
  98.                 # Treat it as plain text.
  99.                 m_BaseHTTPRequest.send_response(200)  # OK
  100.                 m_BaseHTTPRequest.send_header('Content-type', 'text/plain')
  101.                 m_BaseHTTPRequest.end_headers()
  102.    
  103.                 with open(path) as ifp:
  104.                     m_BaseHTTPRequest.wfile.write(ifp.read())
  105.         elif 1 == 2:
  106.             # There is special handling for http://127.0.0.1/info. That URL
  107.             # displays some internal information.
  108.             if m_BaseHTTPRequest.path == '/info' or m_BaseHTTPRequest.path == '/info/':
  109.                 m_BaseHTTPRequest.send_response(200)  # OK
  110.                 m_BaseHTTPRequest.send_header('Content-type', 'text/html')
  111.                 m_BaseHTTPRequest.end_headers()
  112.                 m_BaseHTTPRequest.info()
  113.         else:
  114.             if dirpath is None or m_BaseHTTPRequest.m_opts.no_dirlist == True:
  115.                 # Invalid file path, respond with a server access error
  116.                 m_BaseHTTPRequest.send_response(500)  # generic server error for now
  117.                 m_BaseHTTPRequest.send_header('Content-type', 'text/html')
  118.                 m_BaseHTTPRequest.end_headers()
  119.    
  120.                 m_BaseHTTPRequest.wfile.write('<html>')
  121.                 m_BaseHTTPRequest.wfile.write('  <head>')
  122.                 m_BaseHTTPRequest.wfile.write('    <title>Server Access Error</title>')
  123.                 m_BaseHTTPRequest.wfile.write('  </head>')
  124.                 m_BaseHTTPRequest.wfile.write('  <body>')
  125.                 m_BaseHTTPRequest.wfile.write('    <p>Server access error.</p>')
  126.                 m_BaseHTTPRequest.wfile.write('    <p>%r</p>' % (repr(m_BaseHTTPRequest.path)))
  127.                 m_BaseHTTPRequest.wfile.write('    <p><a href="%s">Back</a></p>' % (rpath))
  128.                 m_BaseHTTPRequest.wfile.write('  </body>')
  129.                 m_BaseHTTPRequest.wfile.write('</html>')
  130.             else:
  131.                 # List the directory contents. Allow simple navigation.
  132.                 logging.debug('DIR %s' % (dirpath))
  133.    
  134.                 m_BaseHTTPRequest.send_response(200)  # OK
  135.                 m_BaseHTTPRequest.send_header('Content-type', 'text/html')
  136.                 m_BaseHTTPRequest.end_headers()
  137.                            
  138.                 m_BaseHTTPRequest.wfile.write('<html>')
  139.                 m_BaseHTTPRequest.wfile.write('  <head>')
  140.                 m_BaseHTTPRequest.wfile.write('    <title>%s</title>' % (dirpath))
  141.                 m_BaseHTTPRequest.wfile.write('  </head>')
  142.                 m_BaseHTTPRequest.wfile.write('  <body>')
  143.                 m_BaseHTTPRequest.wfile.write('    <a href="%s">Home</a><br>' % ('/'));
  144.    
  145.                 # Make the directory path navigable.
  146.                 dirstr = ''
  147.                 href = None
  148.                 for seg in rpath.split('/'):
  149.                     if href is None:
  150.                         href = seg
  151.                     else:
  152.                         href = href + '/' + seg
  153.                         dirstr += '/'
  154.                     dirstr += '<a href="%s">%s</a>' % (href, seg)
  155.                 m_BaseHTTPRequest.wfile.write('    <p>Directory: %s</p>' % (dirstr))
  156.    
  157.                 # Write out the simple directory list (name and size).
  158.                 m_BaseHTTPRequest.wfile.write('    <table border="0">')
  159.                 m_BaseHTTPRequest.wfile.write('      <tbody>')
  160.                 fnames = ['..']
  161.                 fnames.extend(sorted(os.listdir(dirpath), key=str.lower))
  162.                 for fname in fnames:
  163.                     m_BaseHTTPRequest.wfile.write('        <tr>')
  164.                     m_BaseHTTPRequest.wfile.write('          <td align="left">')
  165.                     path = rpath + '/' + fname
  166.                     fpath = os.path.join(dirpath, fname)
  167.                     if os.path.isdir(path):
  168.                         m_BaseHTTPRequest.wfile.write('            <a href="%s">%s/</a>' % (path, fname))
  169.                     else:
  170.                         m_BaseHTTPRequest.wfile.write('            <a href="%s">%s</a>' % (path, fname))
  171.                     m_BaseHTTPRequest.wfile.write('          <td>&nbsp;&nbsp;</td>')
  172.                     m_BaseHTTPRequest.wfile.write('          </td>')
  173.                     m_BaseHTTPRequest.wfile.write('          <td align="right">%d</td>' % (os.path.getsize(fpath)))
  174.                     m_BaseHTTPRequest.wfile.write('        </tr>')
  175.                 m_BaseHTTPRequest.wfile.write('      </tbody>')
  176.                 m_BaseHTTPRequest.wfile.write('    </table>')
  177.                 m_BaseHTTPRequest.wfile.write('  </body>')
  178.                 m_BaseHTTPRequest.wfile.write('</html>')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement