home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / !Python / Lib / NetLib / py / BaseHTTPSe next >
Text File  |  1996-02-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 != self.protocol_version:
  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