home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / BaseHTTPServer.py < prev    next >
Text File  |  1997-08-12  |  15KB  |  483 lines

  1. """HTTP server base class.
  2.  
  3. Note: the class in this module doesn't implement any HTTP request; see
  4. SimpleHTTPServer for simple implementations of GET, HEAD and POST
  5. (including CGI scripts).
  6.  
  7. Contents:
  8.  
  9. - BaseHTTPRequestHandler: HTTP request handler base class
  10. - test: test function
  11.  
  12. XXX To do:
  13.  
  14. - send server version
  15. - log requests even later (to capture byte count)
  16. - log user-agent header and other interesting goodies
  17. - send error log to separate file
  18. - are request names really case sensitive?
  19.  
  20. """
  21.  
  22.  
  23. # See also:
  24. #
  25. # HTTP Working Group                                        T. Berners-Lee
  26. # INTERNET-DRAFT                                            R. T. Fielding
  27. # <draft-ietf-http-v10-spec-00.txt>                     H. Frystyk Nielsen
  28. # Expires September 8, 1995                                  March 8, 1995
  29. #
  30. # URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
  31.  
  32.  
  33. # Log files
  34. # ---------
  35. # Here's a quote from the NCSA httpd docs about log file format.
  36. # | The logfile format is as follows. Each line consists of: 
  37. # | 
  38. # | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb 
  39. # | 
  40. # |        host: Either the DNS name or the IP number of the remote client 
  41. # |        rfc931: Any information returned by identd for this person,
  42. # |                - otherwise. 
  43. # |        authuser: If user sent a userid for authentication, the user name,
  44. # |                  - otherwise. 
  45. # |        DD: Day 
  46. # |        Mon: Month (calendar name) 
  47. # |        YYYY: Year 
  48. # |        hh: hour (24-hour format, the machine's timezone) 
  49. # |        mm: minutes 
  50. # |        ss: seconds 
  51. # |        request: The first line of the HTTP request as sent by the client. 
  52. # |        ddd: the status code returned by the server, - if not available. 
  53. # |        bbbb: the total number of bytes sent,
  54. # |              *not including the HTTP/1.0 header*, - if not available 
  55. # | 
  56. # | You can determine the name of the file accessed through request.
  57. # (Actually, the latter is only true if you know the server configuration
  58. # at the time the request was made!)
  59.  
  60.  
  61. __version__ = "0.2"
  62.  
  63.  
  64. import sys
  65. import time
  66. import socket # For gethostbyaddr()
  67. import string
  68. import rfc822
  69. import mimetools
  70. import SocketServer
  71.  
  72. # Default error message
  73. DEFAULT_ERROR_MESSAGE = """\
  74. <head>
  75. <title>Error response</title>
  76. </head>
  77. <body>
  78. <h1>Error response</h1>
  79. <p>Error code %(code)d.
  80. <p>Message: %(message)s.
  81. <p>Error code explanation: %(code)s = %(explain)s.
  82. </body>
  83. """
  84.  
  85.  
  86. class HTTPServer(SocketServer.TCPServer):
  87.  
  88.     def server_bind(self):
  89.     """Override server_bind to store the server name."""
  90.     SocketServer.TCPServer.server_bind(self)
  91.     host, port = self.socket.getsockname()
  92.     if not host or host == '0.0.0.0':
  93.         host = socket.gethostname()
  94.     hostname, hostnames, hostaddrs = socket.gethostbyaddr(host)
  95.     if '.' not in hostname:
  96.         for host in hostnames:
  97.         if '.' in host:
  98.             hostname = host
  99.             break
  100.     self.server_name = hostname
  101.     self.server_port = port
  102.  
  103.  
  104. class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
  105.  
  106.     """HTTP request handler base class.
  107.  
  108.     The following explanation of HTTP serves to guide you through the
  109.     code as well as to expose any misunderstandings I may have about
  110.     HTTP (so you don't need to read the code to figure out I'm wrong
  111.     :-).
  112.  
  113.     HTTP (HyperText Transfer Protocol) is an extensible protocol on
  114.     top of a reliable stream transport (e.g. TCP/IP).  The protocol
  115.     recognizes three parts to a request:
  116.  
  117.     1. One line identifying the request type and path
  118.     2. An optional set of RFC-822-style headers
  119.     3. An optional data part
  120.  
  121.     The headers and data are separated by a blank line.
  122.  
  123.     The first line of the request has the form
  124.  
  125.     <command> <path> <version>
  126.  
  127.     where <command> is a (case-sensitive) keyword such as GET or POST,
  128.     <path> is a string containing path information for the request,
  129.     and <version> should be the string "HTTP/1.0".  <path> is encoded
  130.     using the URL encoding scheme (using %xx to signify the ASCII
  131.     character with hex code xx).
  132.  
  133.     The protocol is vague about whether lines are separated by LF
  134.     characters or by CRLF pairs -- for compatibility with the widest
  135.     range of clients, both should be accepted.  Similarly, whitespace
  136.     in the request line should be treated sensibly (allowing multiple
  137.     spaces between components and allowing trailing whitespace).
  138.  
  139.     Similarly, for output, lines ought to be separated by CRLF pairs
  140.     but most clients grok LF characters just fine.
  141.  
  142.     If the first line of the request has the form
  143.  
  144.     <command> <path>
  145.  
  146.     (i.e. <version> is left out) then this is assumed to be an HTTP
  147.     0.9 request; this form has no optional headers and data part and
  148.     the reply consists of just the data.
  149.  
  150.     The reply form of the HTTP 1.0 protocol again has three parts:
  151.  
  152.     1. One line giving the response code
  153.     2. An optional set of RFC-822-style headers
  154.     3. The data
  155.  
  156.     Again, the headers and data are separated by a blank line.
  157.  
  158.     The response code line has the form
  159.  
  160.     <version> <responsecode> <responsestring>
  161.  
  162.     where <version> is the protocol version (always "HTTP/1.0"),
  163.     <responsecode> is a 3-digit response code indicating success or
  164.     failure of the request, and <responsestring> is an optional
  165.     human-readable string explaining what the response code means.
  166.  
  167.     This server parses the request and the headers, and then calls a
  168.     function specific to the request type (<command>).  Specifically,
  169.     a request SPAM will be handled by a method handle_SPAM().  If no
  170.     such method exists the server sends an error response to the
  171.     client.  If it exists, it is called with no arguments:
  172.  
  173.     do_SPAM()
  174.  
  175.     Note that the request name is case sensitive (i.e. SPAM and spam
  176.     are different requests).
  177.  
  178.     The various request details are stored in instance variables:
  179.  
  180.     - client_address is the client IP address in the form (host,
  181.     port);
  182.  
  183.     - command, path and version are the broken-down request line;
  184.  
  185.     - headers is an instance of mimetools.Message (or a derived
  186.     class) containing the header information;
  187.  
  188.     - rfile is a file object open for reading positioned at the
  189.     start of the optional input data part;
  190.  
  191.     - wfile is a file object open for writing.
  192.  
  193.     IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
  194.  
  195.     The first thing to be written must be the response line.  Then
  196.     follow 0 or more header lines, then a blank line, and then the
  197.     actual data (if any).  The meaning of the header lines depends on
  198.     the command executed by the server; in most cases, when data is
  199.     returned, there should be at least one header line of the form
  200.  
  201.     Content-type: <type>/<subtype>
  202.  
  203.     where <type> and <subtype> should be registered MIME types,
  204.     e.g. "text/html" or "text/plain".
  205.  
  206.     """
  207.  
  208.     # The Python system version, truncated to its first component.
  209.     sys_version = "Python/" + string.split(sys.version)[0]
  210.  
  211.     # The server software version.  You may want to override this.
  212.     # The format is multiple whitespace-separated strings,
  213.     # where each string is of the form name[/version].
  214.     server_version = "BaseHTTP/" + __version__
  215.  
  216.     def handle(self):
  217.     """Handle a single HTTP request.
  218.  
  219.     You normally don't need to override this method; see the class
  220.     __doc__ string for information on how to handle specific HTTP
  221.     commands such as GET and POST.
  222.  
  223.     """
  224.  
  225.     self.raw_requestline = self.rfile.readline()
  226.     self.request_version = version = "HTTP/0.9" # Default
  227.     requestline = self.raw_requestline
  228.     if requestline[-2:] == '\r\n':
  229.         requestline = requestline[:-2]
  230.     elif requestline[-1:] == '\n':
  231.         requestline = requestline[:-1]
  232.     self.requestline = requestline
  233.     words = string.split(requestline)
  234.     if len(words) == 3:
  235.         [command, path, version] = words
  236.         if version[:5] != 'HTTP/':
  237.         self.send_error(400, "Bad request version (%s)" % `version`)
  238.         return
  239.     elif len(words) == 2:
  240.         [command, path] = words
  241.         if command != 'GET':
  242.         self.send_error(400,
  243.                 "Bad HTTP/0.9 request type (%s)" % `command`)
  244.         return
  245.     else:
  246.         self.send_error(400, "Bad request syntax (%s)" % `requestline`)
  247.         return
  248.     self.command, self.path, self.request_version = command, path, version
  249.     self.headers = self.MessageClass(self.rfile, 0)
  250.     mname = 'do_' + command
  251.     if not hasattr(self, mname):
  252.         self.send_error(501, "Unsupported method (%s)" % `mname`)
  253.         return
  254.     method = getattr(self, mname)
  255.     method()
  256.  
  257.     def send_error(self, code, message=None):
  258.     """Send and log an error reply.
  259.  
  260.     Arguments are the error code, and a detailed message.
  261.     The detailed message defaults to the short entry matching the
  262.     response code.
  263.  
  264.     This sends an error response (so it must be called before any
  265.     output has been generated), logs the error, and finally sends
  266.     a piece of HTML explaining the error to the user.
  267.  
  268.     """
  269.  
  270.     try:
  271.         short, long = self.responses[code]
  272.     except KeyError:
  273.         short, long = '???', '???'
  274.     if not message:
  275.         message = short
  276.     explain = long
  277.     self.log_error("code %d, message %s", code, message)
  278.     self.send_response(code, message)
  279.     self.end_headers()
  280.     self.wfile.write(self.error_message_format %
  281.              {'code': code,
  282.               'message': message,
  283.               'explain': explain})
  284.  
  285.     error_message_format = DEFAULT_ERROR_MESSAGE
  286.  
  287.     def send_response(self, code, message=None):
  288.     """Send the response header and log the response code.
  289.  
  290.     Also send two standard headers with the server software
  291.     version and the current date.
  292.  
  293.     """
  294.     self.log_request(code)
  295.     if message is None:
  296.         if self.responses.has_key(code):
  297.         message = self.responses[code][0]
  298.         else:
  299.         message = ''
  300.     if self.request_version != 'HTTP/0.9':
  301.         self.wfile.write("%s %s %s\r\n" %
  302.                  (self.protocol_version, str(code), message))
  303.     self.send_header('Server', self.version_string())
  304.     self.send_header('Date', self.date_time_string())
  305.  
  306.     def send_header(self, keyword, value):
  307.     """Send a MIME header."""
  308.     if self.request_version != 'HTTP/0.9':
  309.         self.wfile.write("%s: %s\r\n" % (keyword, value))
  310.  
  311.     def end_headers(self):
  312.     """Send the blank line ending the MIME headers."""
  313.     if self.request_version != 'HTTP/0.9':
  314.         self.wfile.write("\r\n")
  315.  
  316.     def log_request(self, code='-', size='-'):
  317.     """Log an accepted request.
  318.  
  319.     This is called by send_reponse().
  320.  
  321.     """
  322.  
  323.     self.log_message('"%s" %s %s',
  324.              self.requestline, str(code), str(size))
  325.  
  326.     def log_error(self, *args):
  327.     """Log an error.
  328.  
  329.     This is called when a request cannot be fulfilled.  By
  330.     default it passes the message on to log_message().
  331.  
  332.     Arguments are the same as for log_message().
  333.  
  334.     XXX This should go to the separate error log.
  335.  
  336.     """
  337.  
  338.     apply(self.log_message, args)
  339.  
  340.     def log_message(self, format, *args):
  341.     """Log an arbitrary message.
  342.  
  343.     This is used by all other logging functions.  Override
  344.     it if you have specific logging wishes.
  345.  
  346.     The first argument, FORMAT, is a format string for the
  347.     message to be logged.  If the format string contains
  348.     any % escapes requiring parameters, they should be
  349.     specified as subsequent arguments (it's just like
  350.     printf!).
  351.  
  352.     The client host and current date/time are prefixed to
  353.     every message.
  354.  
  355.     """
  356.  
  357.     sys.stderr.write("%s - - [%s] %s\n" %
  358.              (self.address_string(),
  359.               self.log_date_time_string(),
  360.               format%args))
  361.  
  362.     def version_string(self):
  363.     """Return the server software version string."""
  364.     return self.server_version + ' ' + self.sys_version
  365.  
  366.     def date_time_string(self):
  367.     """Return the current date and time formatted for a message header."""
  368.     now = time.time()
  369.     year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
  370.     s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
  371.         self.weekdayname[wd],
  372.         day, self.monthname[month], year,
  373.         hh, mm, ss)
  374.     return s
  375.  
  376.     def log_date_time_string(self):
  377.     """Return the current time formatted for logging."""
  378.     now = time.time()
  379.     year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
  380.     s = "%02d/%3s/%04d %02d:%02d:%02d" % (
  381.         day, self.monthname[month], year, hh, mm, ss)
  382.     return s
  383.  
  384.     weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  385.  
  386.     monthname = [None,
  387.          'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  388.          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  389.  
  390.     def address_string(self):
  391.     """Return the client address formatted for logging.
  392.  
  393.     This version looks up the full hostname using gethostbyaddr(),
  394.     and tries to find a name that contains at least one dot.
  395.  
  396.     """
  397.  
  398.     (host, port) = self.client_address
  399.     try:
  400.         name, names, addresses = socket.gethostbyaddr(host)
  401.     except socket.error, msg:
  402.         return host
  403.     names.insert(0, name)
  404.     for name in names:
  405.         if '.' in name: return name
  406.     return names[0]
  407.  
  408.  
  409.     # Essentially static class variables
  410.  
  411.     # The version of the HTTP protocol we support.
  412.     # Don't override unless you know what you're doing (hint: incoming
  413.     # requests are required to have exactly this version string).
  414.     protocol_version = "HTTP/1.0"
  415.  
  416.     # The Message-like class used to parse headers
  417.     MessageClass = mimetools.Message
  418.  
  419.     # Table mapping response codes to messages; entries have the
  420.     # form {code: (shortmessage, longmessage)}.
  421.     # See http://www.w3.org/hypertext/WWW/Protocols/HTTP/HTRESP.html
  422.     responses = {
  423.     200: ('OK', 'Request fulfilled, document follows'),
  424.     201: ('Created', 'Document created, URL follows'),
  425.     202: ('Accepted',
  426.           'Request accepted, processing continues off-line'),
  427.     203: ('Partial information', 'Request fulfilled from cache'),
  428.     204: ('No response', 'Request fulfilled, nothing follows'),
  429.     
  430.     301: ('Moved', 'Object moved permanently -- see URI list'),
  431.     302: ('Found', 'Object moved temporarily -- see URI list'),
  432.     303: ('Method', 'Object moved -- see Method and URL list'),
  433.     304: ('Not modified',
  434.           'Document has not changed singe given time'),
  435.     
  436.     400: ('Bad request',
  437.           'Bad request syntax or unsupported method'),
  438.     401: ('Unauthorized',
  439.           'No permission -- see authorization schemes'),
  440.     402: ('Payment required',
  441.           'No payment -- see charging schemes'),
  442.     403: ('Forbidden',
  443.           'Request forbidden -- authorization will not help'),
  444.     404: ('Not found', 'Nothing matches the given URI'),
  445.     
  446.     500: ('Internal error', 'Server got itself in trouble'),
  447.     501: ('Not implemented',
  448.           'Server does not support this operation'),
  449.     502: ('Service temporarily overloaded',
  450.           'The server cannot process the request due to a high load'),
  451.     503: ('Gateway timeout',
  452.           'The gateway server did not receive a timely response'),
  453.     
  454.     }
  455.  
  456.  
  457. def test(HandlerClass = BaseHTTPRequestHandler,
  458.      ServerClass = HTTPServer):
  459.     """Test the HTTP request handler class.
  460.  
  461.     This runs an HTTP server on port 8000 (or the first command line
  462.     argument).
  463.  
  464.     """
  465.  
  466.     if sys.argv[1:]:
  467.     port = string.atoi(sys.argv[1])
  468.     else:
  469.     port = 8000
  470.     server_address = ('', port)
  471.  
  472.     httpd = ServerClass(server_address, HandlerClass)
  473.  
  474.     print "Serving HTTP on port", port, "..."
  475.     httpd.serve_forever()
  476.  
  477.  
  478. if __name__ == '__main__':
  479.     test()
  480.