zfc@s dZdZddgZddlZddlZddlZddlmZmZe-ej rxedde nddl Z WdQXddl Z d Z d Zd Zde jfd YZde jfd YZeeddZedkrendS(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 HTTPServertBaseHTTPRequestHandleriN(tfilterwarningstcatch_warningstignores.*mimetools has been removeds Error response

Error response

Error code %(code)d.

Message: %(message)s.

Error code explanation: %(code)s = %(explain)s. s text/htmlcCs(|jddjddjddS(Nt&s&ts>(treplace(thtml((s&/usr/lib64/python2.7/BaseHTTPServer.pyt _quote_htmlcscBseZdZdZRS(icCsHtjj||jjd \}}tj||_||_dS(s.Override server_bind to store the server name.iN(t SocketServert TCPServert server_bindtsockett getsocknametgetfqdnt server_namet server_port(tselfthosttport((s&/usr/lib64/python2.7/BaseHTTPServer.pyR js(t__name__t __module__tallow_reuse_addressR (((s&/usr/lib64/python2.7/BaseHTTPServer.pyRfsc BsCeZdZdejjdZdeZdZ dZ dZ dZ ddZeZeZdd Zd Zd Zd d d ZdZdZdZddZdZdddddddgZdddddddd d!d"d#d$d%g Zd&Zd'Ze j!Z"i(dd*6dd-6dd06dd36dd66dd96dd<6dd?6ddB6ddE6ddH6ddK6ddN6ddQ6ddT6ddV6ddY6dd\6dd_6ddb6dde6ddh6ddk6ddn6ddq6ddt6ddw6ddz6dd}6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6Z#RS(sHTTP request handler base class. The following explanation of HTTP serves to guide you through the code as well as to expose any misunderstandings I may have about HTTP (so you don't need to read the code to figure out I'm wrong :-). HTTP (HyperText Transfer Protocol) is an extensible protocol on top of a reliable stream transport (e.g. TCP/IP). The protocol recognizes three parts to a request: 1. One line identifying the request type and path 2. An optional set of RFC-822-style headers 3. An optional data part The headers and data are separated by a blank line. The first line of the request has the form 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/sHTTP/0.9c Csd|_|j|_}d|_|j}|jd}||_|j}t |dkry|\}}}|d dkr|j dd|t Syd|jddd}|jd }t |d krt nt |d t |df}Wn,t tfk r*|j dd|t SX|dkrR|jd krRd |_n|dkr|j d d|t Snpt |d kr|\}}d|_|dkr|j dd|t Sn"|st S|j dd|t S||||_|_|_|j|jd |_|jjdd}|jdkrQd|_n-|jdkr~|jd kr~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. 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(tNonetcommandtdefault_request_versiontrequest_versiontclose_connectiontraw_requestlinetrstript requestlinetsplittlent send_errortFalset ValueErrortintt IndexErrortprotocol_versiontpatht MessageClasstrfiletheaderstgettlowertTrue( RtversionR&twordsR R/tbase_version_numbertversion_numbertconntype((s&/usr/lib64/python2.7/BaseHTTPServer.pyt parse_requests^      $           cCsy|jjd|_t|jdkrYd|_d|_d|_|jddS|jsod|_dS|j sdSd|j}t ||s|jdd |jdSt ||}||j j Wn0tjk r }|jd |d|_dSXdS( 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. iiRiNitdo_isUnsupported method (%r)sRequest timed out: %r(R1treadlineR$R(R&R"R R)R#R;thasattrtgetattrtwfiletflushRttimeoutt log_error(Rtmnametmethodte((s&/usr/lib64/python2.7/BaseHTTPServer.pythandle_one_request-s0         cCs1d|_|jx|js,|jqWdS(s&Handle multiple requests if necessary.iN(R#RG(R((s&/usr/lib64/python2.7/BaseHTTPServer.pythandlePs   cCsy|j|\}}Wntk r6d\}}nX|dkrL|}n|}|jd|||j|||jddd}|dkr|dkr|ji|d 6t|d 6|d 6}|jd |jn|j |j d kr|r|j j |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 %sRRiiii0tcodetmessagetexplains Content-TypetHEADN(s???s???(iii0( t responsestKeyErrorRRCt send_responset send_headerterror_message_formatR terror_content_typet end_headersR R@twrite(RRIRJtshorttlongRKtcontent((s&/usr/lib64/python2.7/BaseHTTPServer.pyR)Xs(        cCs|j||dkrE||jkr<|j|d}qEd}n|jdkrw|jjd|j||fn|jd|j|jd|j 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_requestRRMR"R@RTR.RPtversion_stringtdate_time_string(RRIRJ((s&/usr/lib64/python2.7/BaseHTTPServer.pyROs    cCs|jdkr,|jjd||fn|jdkr}|jdkr\d|_q}|jdkr}d|_q}ndS( sSend a MIME header.sHTTP/0.9s%s: %s t connectionRis keep-aliveiN(R"R@RTR4R#(Rtkeywordtvalue((s&/usr/lib64/python2.7/BaseHTTPServer.pyRPs cCs&|jdkr"|jjdndS(s,Send the blank line ending the MIME headers.sHTTP/0.9s N(R"R@RT(R((s&/usr/lib64/python2.7/BaseHTTPServer.pyRSst-cCs)|jd|jt|t|dS(sNLog an accepted request. This is called by send_response(). s "%s" %s %sN(t log_messageR&tstr(RRItsize((s&/usr/lib64/python2.7/BaseHTTPServer.pyRZs cGs|j||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(Ra(Rtformattargs((s&/usr/lib64/python2.7/BaseHTTPServer.pyRCs cGs2tjjd|jd|j||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 ip address and current date/time are prefixed to every message. s%s - - [%s] %s iN(tsyststderrRTtclient_addresstlog_date_time_string(RRdRe((s&/usr/lib64/python2.7/BaseHTTPServer.pyRas   cCs|jd|jS(s*Return the server software version string.t (tserver_versiont sys_version(R((s&/usr/lib64/python2.7/BaseHTTPServer.pyR[sc Csv|dkrtj}ntj|\ }}}}}}}} } d|j|||j|||||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&/usr/lib64/python2.7/BaseHTTPServer.pyR\s * c Cs]tj}tj|\ }}}}}}}} } d||j|||||f} | S(s.Return the current time formatted for logging.s%02d/%3s/%04d %02d:%02d:%02d(Rmt localtimeRp( RtnowRrRsRtRuRvRwtxRyRzR{((s&/usr/lib64/python2.7/BaseHTTPServer.pyRis  * tMontTuetWedtThutFritSattSuntJantFebtMartAprtMaytJuntJultAugtSeptOcttNovtDeccCs |jd \}}tj|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(RhRR(RRR((s&/usr/lib64/python2.7/BaseHTTPServer.pytaddress_stringssHTTP/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 resource.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(Rs!Request received, please continue(sSwitching Protocolss.Switching to new protocol; obey Upgrade header(Rs#Request fulfilled, document follows(RsDocument created, URL follows(Rs/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(Rs(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(Rs*No permission -- see authorization schemes(sPayment Requireds"No payment -- see charging schemes(Rs0Request forbidden -- authorization will not help(s Not FoundsNothing matches the given URI(sMethod Not Alloweds.Specified method is invalid for this resource.(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.(RsRequest conflict.(Rs6URI 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__RfR6R'Rlt __version__RkR!R;RGRHRR)tDEFAULT_ERROR_MESSAGERQtDEFAULT_ERROR_CONTENT_TYPERRRORPRSRZRCRaR[R\RiRoRpRR.t mimetoolstMessageR0RM(((s&/usr/lib64/python2.7/BaseHTTPServer.pyRrsf  E #  *        sHTTP/1.0cCstjdr#ttjd}nd}d|f}||_|||}|jj}dG|dGdG|dGdGH|jdS( 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(RftargvR,R.RRt serve_forever(t HandlerClasst ServerClasstprotocolRtserver_addressthttpdtsa((s&/usr/lib64/python2.7/BaseHTTPServer.pyttestNs   t__main__(RRt__all__RfRmRtwarningsRRt py3kwarningtDeprecationWarningRR RRR R RtStreamRequestHandlerRRR(((s&/usr/lib64/python2.7/BaseHTTPServer.pyts,3