lJc @sdZdZddgZddkZddkZddkZddkZddkZdZdZ dei fdYZ dei fd YZ e e d d Zed jo endS( s HTTP server base class. Note: the class in this module doesn't implement any HTTP request; see SimpleHTTPServer for simple implementations of GET, HEAD and POST (including CGI scripts). It does, however, optionally implement HTTP/1.1 persistent connections, as of version 0.3. Contents: - BaseHTTPRequestHandler: HTTP request handler base class - test: test function XXX To do: - log requests even later (to capture byte count) - log user-agent header and other interesting goodies - send error log to separate file s0.3t HTTPServertBaseHTTPRequestHandleriNs Error response

Error response

Error code %(code)d.

Message: %(message)s.

Error code explanation: %(code)s = %(explain)s. cCs(|iddiddiddS(Nt&s&ts>(treplace(thtml((s!/sys/lib/python/BaseHTTPServer.pyt _quote_html\scBseZdZdZRS(icCsHtii||iid \}}ti||_||_dS(s.Override server_bind to store the server name.iN(t SocketServert TCPServert server_bindtsockett getsocknametgetfqdnt server_namet server_port(tselfthosttport((s!/sys/lib/python/BaseHTTPServer.pyR cs(t__name__t __module__tallow_reuse_addressR (((s!/sys/lib/python/BaseHTTPServer.pyR_sc BseZdZdeiidZdeZdZ dZ dZ ddZ eZddZd Zd Zd d d Zd ZdZdZddZdZdddddddgZddddddddd d!d"d#d$g Zd%Zd&ZeiZhdd)<dd,<dd/<dd2<dd5<dd8<dd;<dd><ddA<ddD<ddG<ddJ<ddM<ddP<ddS<ddU<ddX<dd[<dd^<dda<ddd<ddg<ddj<ddm<ddp<dds<ddv<ddy<dd|<dd<dd<dd<dd<dd<dd<dd<dd<dd<dd<dd where is a (case-sensitive) keyword such as GET or POST, is a string containing path information for the request, and should be the string "HTTP/1.0" or "HTTP/1.1". is encoded using the URL encoding scheme (using %xx to signify the ASCII character with hex code xx). The specification specifies that lines are separated by CRLF but for compatibility with the widest range of clients recommends servers also handle LF. Similarly, whitespace in the request line is treated sensibly (allowing multiple spaces between components and allowing trailing whitespace). Similarly, for output, lines ought to be separated by CRLF pairs but most clients grok LF characters just fine. If the first line of the request has the form (i.e. is left out) then this is assumed to be an HTTP 0.9 request; this form has no optional headers and data part and the reply consists of just the data. The reply form of the HTTP 1.x protocol again has three parts: 1. One line giving the response code 2. An optional set of RFC-822-style headers 3. The data Again, the headers and data are separated by a blank line. The response code line has the form where is the protocol version ("HTTP/1.0" or "HTTP/1.1"), is a 3-digit response code indicating success or failure of the request, and is an optional human-readable string explaining what the response code means. This server parses the request and the headers, and then calls a function specific to the request type (). Specifically, a request SPAM will be handled by a method do_SPAM(). If no such method exists the server sends an error response to the client. If it exists, it is called with no arguments: do_SPAM() Note that the request name is case sensitive (i.e. SPAM and spam are different requests). The various request details are stored in instance variables: - client_address is the client IP address in the form (host, port); - command, path and version are the broken-down request line; - headers is an instance of mimetools.Message (or a derived class) containing the header information; - rfile is a file object open for reading positioned at the start of the optional input data part; - wfile is a file object open for writing. IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING! The first thing to be written must be the response line. Then follow 0 or more header lines, then a blank line, and then the actual data (if any). The meaning of the header lines depends on the command executed by the server; in most cases, when data is returned, there should be at least one header line of the form Content-type: / where and should be registered MIME types, e.g. "text/html" or "text/plain". sPython/is BaseHTTP/c Csd|_d|_}d|_|i}|ddjo|d }n |ddjo|d }n||_|i}t|djo-|\}}}|d d jo|id d |t Snyf|id dd}|id }t|djo t nt |dt |df}Wn1t t fj o|id d |t SnX|djo|i djo d|_n|djo|idd|t Sq7n}t|djoB|\}}d|_|djo|id d|t Sq7n(|pt Sn|id d|t S||||_|_|_|i|id|_|iidd}|idjo d|_n1|idjo|i djo d|_ntS(s'Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back. sHTTP/0.9iis is iisHTTP/isBad request version (%r)t/t.iisHTTP/1.1isInvalid HTTP Version (%s)tGETsBad HTTP/0.9 request type (%r)sBad request syntax (%r)t Connectionttcloses keep-aliveN(ii(ii(tNonetcommandtrequest_versiontclose_connectiontraw_requestlinet requestlinetsplittlent send_errortFalset ValueErrortintt IndexErrortprotocol_versiontpatht MessageClasstrfiletheaderstgettlowertTrue( RtversionR!twordsRR*tbase_version_numbertversion_numbertconntype((s!/sys/lib/python/BaseHTTPServer.pyt parse_requestsd       $              cCs|ii|_|ipd|_dSn|ipdSnd|i}t||p|idd|idSnt||}|dS(sHandle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. iNtdo_isUnsupported method (%r)( R,treadlineR RR6RthasattrR$tgetattr(Rtmnametmethod((s!/sys/lib/python/BaseHTTPServer.pythandle_one_request#s    cCs3d|_|ix|ip|iqWdS(s&Handle multiple requests if necessary.iN(RR=(R((s!/sys/lib/python/BaseHTTPServer.pythandle8s   cCsy|i|\}}Wntj od\}}nX|djo |}n|}|id|||ih|d<t|d<|d<}|i|||idd|idd |i|i d jo.|d jo!|djo|i i |ndS(sSend and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user. s???scode %d, message %stcodetmessagetexplains Content-Types text/htmlRRtHEADiii0N(s???s???(ii0( t responsestKeyErrorRt log_errorterror_message_formatRt send_responset send_headert end_headersRtwfiletwrite(RR?R@tshorttlongRAtcontent((s!/sys/lib/python/BaseHTTPServer.pyR$@s   ( *cCs|i||djo/||ijo|i|d}qId}n|idjo$|iid|i||fn|id|i|id|i dS(sSend the response header and log the response code. Also send two standard headers with the server software version and the current date. iRsHTTP/0.9s %s %d %s tServertDateN( t log_requestRRCRRJRKR)RHtversion_stringtdate_time_string(RR?R@((s!/sys/lib/python/BaseHTTPServer.pyRGas    cCs|idjo|iid||fn|idjoD|idjo d|_q|idjo d|_qndS( sSend a MIME header.sHTTP/0.9s%s: %s t connectionRis keep-aliveiN(RRJRKR/R(Rtkeywordtvalue((s!/sys/lib/python/BaseHTTPServer.pyRHus cCs(|idjo|iidndS(s,Send the blank line ending the MIME headers.sHTTP/0.9s N(RRJRK(R((s!/sys/lib/python/BaseHTTPServer.pyRIst-cCs)|id|it|t|dS(sNLog an accepted request. This is called by send_response(). s "%s" %s %sN(t log_messageR!tstr(RR?tsize((s!/sys/lib/python/BaseHTTPServer.pyRQs cGs|i|dS(sLog an error. This is called when a request cannot be fulfilled. By default it passes the message on to log_message(). Arguments are the same as for log_message(). XXX This should go to the separate error log. N(RX(Rtargs((s!/sys/lib/python/BaseHTTPServer.pyREs cGs1tiid|i|i||fdS(sLog an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it's just like printf!). The client host and current date/time are prefixed to every message. s%s - - [%s] %s N(tsyststderrRKtaddress_stringtlog_date_time_string(RtformatR[((s!/sys/lib/python/BaseHTTPServer.pyRXs   cCs|id|iS(s*Return the server software version string.t (tserver_versiont sys_version(R((s!/sys/lib/python/BaseHTTPServer.pyRRsc Csx|djoti}nti|\ }}}}}}}} } d|i|||i|||||f} | S(s@Return the current date and time formatted for a message header.s#%s, %02d %3s %4d %02d:%02d:%02d GMTN(Rttimetgmtimet weekdaynamet monthname( Rt timestamptyeartmonthtdaythhtmmtsstwdtytzts((s!/sys/lib/python/BaseHTTPServer.pyRSs * c Cs]ti}ti|\ }}}}}}}} } d||i|||||f} | S(s.Return the current time formatted for logging.s%02d/%3s/%04d %02d:%02d:%02d(Rdt localtimeRg( RtnowRiRjRkRlRmRntxRpRqRr((s!/sys/lib/python/BaseHTTPServer.pyR_s  * tMontTuetWedtThutFritSattSuntJantFebtMartAprtMaytJuntJultAugtSeptOcttNovtDeccCs |id \}}ti|S(sReturn the client address formatted for logging. This version looks up the full hostname using gethostbyaddr(), and tries to find a name that contains at least one dot. i(tclient_addressR R (RRR((s!/sys/lib/python/BaseHTTPServer.pyR^ssHTTP/1.0tContinues!Request received, please continueidsSwitching Protocolss.Switching to new protocol; obey Upgrade headerietOKs#Request fulfilled, document followsitCreatedsDocument created, URL followsitAccepteds/Request accepted, processing continues off-lineisNon-Authoritative InformationsRequest fulfilled from cacheis No Contents"Request fulfilled, nothing followsis Reset Contents#Clear input form for further input.isPartial ContentsPartial content follows.isMultiple Choicess,Object has several resources -- see URI listi,sMoved Permanentlys(Object moved permanently -- see URI listi-tFounds(Object moved temporarily -- see URI listi.s See Others'Object moved -- see Method and URL listi/s Not Modifieds)Document has not changed since given timei0s Use ProxysAYou must use proxy specified in Location to access this resource.i1sTemporary Redirecti3s Bad Requests(Bad request syntax or unsupported methodit Unauthorizeds*No permission -- see authorization schemesisPayment Requireds"No payment -- see charging schemesit Forbiddens0Request forbidden -- authorization will not helpis Not FoundsNothing matches the given URIisMethod Not Alloweds,Specified method is invalid for this server.isNot Acceptables&URI not available in preferred format.isProxy Authentication Requireds8You must authenticate with this proxy before proceeding.isRequest Timeouts#Request timed out; try again later.itConflictsRequest conflict.itGones6URI no longer exists and has been permanently removed.isLength Requireds#Client must specify Content-Length.isPrecondition Faileds!Precondition in headers is false.isRequest Entity Too LargesEntity is too large.isRequest-URI Too LongsURI is too long.isUnsupported Media Types"Entity body in unsupported format.isRequested Range Not SatisfiablesCannot satisfy request range.isExpectation Faileds(Expect condition could not be satisfied.isInternal Server ErrorsServer got itself in troubleisNot Implementeds&Server does not support this operationis Bad Gateways,Invalid responses from another server/proxy.isService Unavailables8The server cannot process the request due to a high loadisGateway Timeouts4The gateway server did not receive a timely responseisHTTP Version Not SupportedsCannot fulfill request.iN(sContinues!Request received, please continue(sSwitching Protocolss.Switching to new protocol; obey Upgrade header(sOKs#Request fulfilled, document follows(sCreatedsDocument created, URL follows(sAccepteds/Request accepted, processing continues off-line(sNon-Authoritative InformationsRequest fulfilled from cache(s No Contents"Request fulfilled, nothing follows(s Reset Contents#Clear input form for further input.(sPartial ContentsPartial content follows.(sMultiple Choicess,Object has several resources -- see URI list(sMoved Permanentlys(Object moved permanently -- see URI list(sFounds(Object moved temporarily -- see URI list(s See Others'Object moved -- see Method and URL list(s Not Modifieds)Document has not changed since given time(s Use ProxysAYou must use proxy specified in Location to access this resource.(sTemporary Redirects(Object moved temporarily -- see URI list(s Bad Requests(Bad request syntax or unsupported method(s Unauthorizeds*No permission -- see authorization schemes(sPayment Requireds"No payment -- see charging schemes(s Forbiddens0Request forbidden -- authorization will not help(s Not FoundsNothing matches the given URI(sMethod Not Alloweds,Specified method is invalid for this server.(sNot Acceptables&URI not available in preferred format.(sProxy Authentication Requireds8You must authenticate with this proxy before proceeding.(sRequest Timeouts#Request timed out; try again later.(sConflictsRequest conflict.(sGones6URI no longer exists and has been permanently removed.(sLength Requireds#Client must specify Content-Length.(sPrecondition Faileds!Precondition in headers is false.(sRequest Entity Too LargesEntity is too large.(sRequest-URI Too LongsURI is too long.(sUnsupported Media Types"Entity body in unsupported format.(sRequested Range Not SatisfiablesCannot satisfy request range.(sExpectation Faileds(Expect condition could not be satisfied.(sInternal Server ErrorsServer got itself in trouble(sNot Implementeds&Server does not support this operation(s Bad Gateways,Invalid responses from another server/proxy.(sService Unavailables8The server cannot process the request due to a high load(sGateway Timeouts4The gateway server did not receive a timely response(sHTTP Version Not SupportedsCannot fulfill request.(!RRt__doc__R\R1R"Rct __version__RbR6R=R>RR$tDEFAULT_ERROR_MESSAGERFRGRHRIRQRERXRRRSR_RfRgR^R)t mimetoolstMessageR+RC(((s!/sys/lib/python/BaseHTTPServer.pyRksf  H                                                  sHTTP/1.0cCstidottid}nd}d|f}||_|||}|ii}dG|dGdG|dGdGH|idS( sTest the HTTP request handler class. This runs an HTTP server on port 8000 (or the first command line argument). ii@RsServing HTTP oniRs...N(R\targvR'R)R R t serve_forever(t HandlerClasst ServerClasstprotocolRtserver_addressthttpdtsa((s!/sys/lib/python/BaseHTTPServer.pyttest*s   t__main__(RRt__all__R\RdR RRRRR RtStreamRequestHandlerRRR(((s!/sys/lib/python/BaseHTTPServer.pyss 3