\d_zdZdZgdZddlZddlZddlZddlZddlZ ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddl mZdZdZGdd ejZGd d ejeZGd d ejZGddeZ dZ!da"dZ#dZ$Gdde Z%dZ&eedddfdZ'e(dkrddl)Z)ddl*Z*e)j+Z,e,-ddde,-ddd d!"e,-d#d$e j.d%&e,-d'd(d)dd*+e,-d,de/d-d./e,0Z1e1j2re%Z3ne Z3Gd0d1eZ4e'e3e4e1j5e1j6e1j72dSdS)3a@HTTP server classes. Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST, and CGIHTTPRequestHandler for CGI scripts. It does, however, optionally implement HTTP/1.1 persistent connections, as of version 0.3. Notes on CGIHTTPRequestHandler ------------------------------ This class implements GET and POST requests to cgi-bin scripts. If the os.fork() function is not present (e.g. on Windows), subprocess.Popen() is used as a fallback, with slightly altered semantics. In all cases, the implementation is intentionally naive -- all requests are executed synchronously. SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL -- it may execute arbitrary Python code or external programs. Note that status code 200 is sent prior to execution of a CGI script, so scripts cannot send other status codes such as 302 (redirect). 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 z0.6) HTTPServerThreadingHTTPServerBaseHTTPRequestHandlerSimpleHTTPRequestHandlerCGIHTTPRequestHandlerN) HTTPStatusaD Error response

Error response

Error code: %(code)d

Message: %(message)s.

Error code explanation: %(code)s - %(explain)s.

ztext/html;charset=utf-8ceZdZdZdZdS)rctj||jdd\}}t j||_||_dS)z.Override server_bind to store the server name.N) socketserver TCPServer server_bindserver_addresssocketgetfqdn server_name server_port)selfhostports ..\python\lib\http\server.pyrzHTTPServer.server_bindsN**4000(!, d!>$//N)__name__ __module__ __qualname__allow_reuse_addressrrrrrs)     rrceZdZdZdS)rTN)rrrdaemon_threadsrrrrrsNNNrrc eZdZdZdejdzZdezZ e Z e Z dZdZdZdZd Zd#d Zd$d Zd$d ZdZdZdZd%dZdZedejededdDZ de e!d<dZ"dZ#d$dZ$dZ%gdZ&gdZ'd Z(d!Z)e*j+j,Z-d"e.j/0DZ1d S)&raHTTP 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 email.message.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". zPython/rz BaseHTTP/HTTP/0.9cd|_|jx|_}d|_t |jd}|d}||_|}t|dkrdSt|dkrp|d} | d st|d d d }|d }t|d krttd|Drtdtd|Drtdt|dt|d f}n;#ttf$r'|t jd|zYdSwxYw|dkr|jdkrd|_|dkr%|t jd|zdS||_d t|cxkrdks'n|t jd|zdS|dd \}}t|d kr2d|_|dkr%|t jd|zdS||c|_|_|j dr"d |jd z|_ t,j|j|j|_n#t,jj$r9}|t jdt |Yd}~dSd}~wt,jj$r9}|t jdt |Yd}~dSd}~wwxYw|jdd} | d krd|_n*| d!kr|jdkrd|_|jd"d} | d#kr,|jdkr!|jdkr|!sdSdS)$aHParse 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, any relevant error response has already been sent back. NTz iso-8859-1 rFzHTTP//r .r c3@K|]}| VdSN)isdigit.0 components r z7BaseHTTPRequestHandler.parse_request../s1OO99,,...OOOOOOrznon digit in http versionc3<K|]}t|dkVdS) N)lenr,s rr/z7BaseHTTPRequestHandler.parse_request..1s-KKys9~~*KKKKKKrz unreasonable length http versionzBad request version (%r))r r zHTTP/1.1)r rzInvalid HTTP version (%s)zBad request syntax (%r)GETzBad HTTP/0.9 request type (%r)z//)_classz Line too longzToo many headers Connectionclose keep-aliveExpectz 100-continue)"commanddefault_request_versionrequest_versionclose_connectionstrraw_requestlinerstrip requestlinesplitr2 startswith ValueErroranyint IndexError send_errorr BAD_REQUESTprotocol_versionHTTP_VERSION_NOT_SUPPORTEDpathlstriphttpclient parse_headersrfile MessageClassheaders LineTooLongREQUEST_HEADER_FIELDS_TOO_LARGE HTTPExceptiongetlowerhandle_expect_100) rversionrAwordsbase_version_numberversion_numberr:rLerrconntypeexpects r parse_requestz$BaseHTTPRequestHandler.parse_request s )-)EEw $$. == !((00 &!!## u::??5 u::??BiG ))'22%$$&-mmC&;&;A&>#!4!:!:3!?!?~&&!++$$OOOOOOOB$%@AAAKKNKKKKKI$%GHHH!$^A%6!7!7^A=N9O9O!O +   *.8:::uu   ''D,AZ,O,O(-%''9/2EEGGGu#*D CJJ####!#### OO&)K7 9 9 95bqb  u::??$(D !%*4w>@@@u")4 di 9   % % 4di..s333DI ;44TZ<@>  w & &$(D ! !nn,..#z11$)D !!!(B// LLNNn , ,%33$ 22))++ uts7C!E664F.-F.0L N#.MN#*.NN#cl|tj|dS)a7Decide what to do with an "Expect: 100-continue" header. If the client is expecting a 100 Continue response, we must respond with either a 100 Continue or a final response before waiting for the request body. The default is to always respond with a 100 Continue. You can behave differently (for example, reject unauthorized requests) by overriding this method. This method should either return True (possibly after sending a 100 Continue response) or send an error response and return False. T)send_response_onlyrCONTINUE end_headersrs rrYz(BaseHTTPRequestHandler.handle_expect_100ys2  3444 trc |jd|_t|jdkr6d|_d|_d|_|tj dS|js d|_ dS| sdSd|jz}t||s*|tj d|jzdSt||}||jdS#t"$r(}|d|d|_ Yd}~dSd}~wwxYw) zHandle 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. iir6NTdo_zUnsupported method (%r)zRequest timed out: %r)rQreadliner?r2rAr<r:rHrREQUEST_URI_TOO_LONGr=rahasattrNOT_IMPLEMENTEDgetattrwfileflush TimeoutError log_error)rmnamemethodes rhandle_one_requestz)BaseHTTPRequestHandler.handle_one_requests_ #':#6#6u#=#=D 4'((500#% ')$!  ?@@@' (,%%%'' DL(E4'' .- <>>>T5))F FHHH J           NN2A 6 6 6$(D ! FFFFF  s1A+D/D?DAD3D ED;;Ecd|_||js||jdSdS)z&Handle multiple requests if necessary.TN)r=rurfs rhandlezBaseHTTPRequestHandler.handlesZ $ !!!' &  # # % % %' & & & & &rNc |j|\}}n#t$rd\}}YnwxYw||}||}|d||||||ddd}|dkr|t jt jt jfvr|j |tj |dtj |dd z}| d d }|d |j |d tt|||jdkr|r|j|dSdSdS)akSend and log an error reply. Arguments are * code: an HTTP error code 3 digits * message: a simple optional 1 line reason phrase. *( HTAB / SP / VCHAR / %x80-FF ) defaults to short entry matching the response code * explain: a detailed message defaults to the long 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. )???ryNzcode %d, message %sr5r7Fquote)codemessageexplainzUTF-8replacez Content-TypeContent-LengthHEAD) responsesKeyErrorrq send_response send_headerr NO_CONTENT RESET_CONTENT NOT_MODIFIEDerror_message_formathtmlescapeencodeerror_content_typer>r2rer:rnwrite)rr}r~rshortmsglongmsgbodycontents rrHz!BaseHTTPRequestHandler.send_errors$ - $t 4 Hgg - - - , Hggg - ?G ?G ,dG<<< 4))) w///  CKK .#1#02 2 2 0;we<<<;we<<<44G >>'955D   ^T-D E E E   -s3t99~~ > > >  <6 ! !d ! J  T " " " " " " ! ! !s %%c||||||d||d|dS)zAdd the response header to the headers buffer and log the response code. Also send two standard headers with the server software version and the current date. ServerDateN) log_requestrcrversion_stringdate_time_stringrr}r~s rrz$BaseHTTPRequestHandler.send_responsesx  g... 4#6#6#8#8999 !6!6!8!899999rc|jdkrs|||jvr|j|d}nd}t|dsg|_|jd|j||fzdddSdS) zSend the response header only.r"Nrr6_headers_bufferz %s %d %s latin-1strict)r<rrkrappendrJrrs rrcz)BaseHTTPRequestHandler.send_response_onlys  : - -4>))"nT215GG G4!233 *')$  ' '*D':*;)rr}sizes rrz"BaseHTTPRequestHandler.log_request!s\ dJ ' ' :D )3t99c$ii A A A A Arc"|j|g|RdS)zLog 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)r)rformatargss rrqz BaseHTTPRequestHandler.log_error,s% '$''''''rci|] }|d|d S)z\x02xr)r-cs r z!BaseHTTPRequestHandler.<s" V V V!Q a V V Vr z\\\c ||z}tj|d|d||jddS)aZLog 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 and current date/time are prefixed to every message. Unicode control characters are replaced with escaped hex before writing the output to stderr. z - - [z]  N)sysstderrraddress_stringlog_date_time_string translate_control_char_table)rrrr~s rrz"BaseHTTPRequestHandler.log_message?s(4- --////335555!++D,DEEEEG H H H H Hrc&|jdz|jzS)z*Return the server software version string. )server_version sys_versionrfs rrz%BaseHTTPRequestHandler.version_stringYs"S(4+;;;rcn|tj}tj|dS)z@Return the current date and time formatted for a message header.NT)usegmt)timeemailutils formatdate)r timestamps rrz'BaseHTTPRequestHandler.date_time_string]s.   I{%%i%===rc tj}tj|\ }}}}}}}} } d||j|||||fz} | S)z.Return the current time formatted for logging.z%02d/%3s/%04d %02d:%02d:%02d)r localtime monthname) rnowyearmonthdayhhmmssxyzss rrz+BaseHTTPRequestHandler.log_date_time_stringcsWikk04s0C0C-eS"b"aA *T^E*D"b".> >r)MonTueWedThuFriSatSun) NJanFebMarAprMayJunJulAugSepOctNovDecc|jdS)zReturn the client address.r)client_addressrfs rrz%BaseHTTPRequestHandler.address_stringqs"1%%rHTTP/1.0c,i|]}||j|jfSr)phrase description)r-vs rrz!BaseHTTPRequestHandler.s3  AHam $r)NNr*)rr)2rrr__doc__rrZrBr __version__rDEFAULT_ERROR_MESSAGErDEFAULT_ERROR_CONTENT_TYPErr;rarYrurwrHrrcrrerrrqr> maketrans itertoolschainrangerordrrrr weekdaynamerrrJrNrO HTTPMessagerRr __members__valuesrrrrrrs=ddNck//11!44K !;.N03 )lll\$###J&&&3#3#3#3#j : : : : . . . . . . .!!! &&& A A A A ( ( (-- V VyuuT{{EE$tDTDT'U'U V V VXX%*D "HHH4<<<>>>> DCCK;;;I&&&";*L'..00IIIrrcneZdZdZdezZdddddxZZdd fd Zd Z d Z d Z dZ dZ dZdZxZS)raWSimple HTTP request handler with GET and HEAD commands. This serves files from the current directory and any of its subdirectories. The MIME type for files is determined by calling the .guess_type() method. The GET and HEAD requests are identical except that the HEAD request omits the actual contents of the file. z SimpleHTTP/zapplication/gzipapplication/octet-streamzapplication/x-bzip2zapplication/x-xz)z.gzz.Zz.bz2z.xzN directoryc|tj}tj||_t j|i|dSr*)osgetcwdfspathrsuper__init__)rrrkwargs __class__s rr z!SimpleHTTPRequestHandler.__init__sG   I9--$)&)))))rc|}|rK |||j|dS#|wxYwdS)zServe a GET request.N) send_headcopyfilernr7rfs rdo_GETzSimpleHTTPRequestHandler.do_GETsa NN      a,,,    s A Ac^|}|r|dSdS)zServe a HEAD request.N)r r7rs rdo_HEADz SimpleHTTPRequestHandler.do_HEADs4 NN     GGIIIII  rcd||j}d}tj|rCtj|j}|jds|tj |d|d|ddz|d|df}tj |}| d|| d d | dSd D]E}tj||}tj|r|}nF||S||}|dr"|tjd dS t)|d }n1#t*$r$|tjd YdSwxYw tj|}d|jvr6d|jvr, t2j|jd} | j%| t<jj } | jt<jj urt<j!|j"t<jj } | d} | | krI|tj#| |$dSn##tJtLtNtPf$rYnwxYw|tj)| d|| d tU|d| d|+|j"| |S#|$xYw)a{Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do. Nr'rr r r%Locationr0)z index.htmlz index.htmzFile not foundrbzIf-Modified-Sincez If-None-Match)tzinfo) microsecond Content-typez Last-Modified),translate_pathrLrisdirurllibparseurlsplitendswithrrMOVED_PERMANENTLY urlunsplitrrerisfilelist_directory guess_typerH NOT_FOUNDopenOSErrorfstatfilenorSrrparsedate_to_datetimerrdatetimetimezoneutc fromtimestampst_mtimerr7 TypeErrorrG OverflowErrorrDOKr>r) rrLrparts new_partsnew_urlindexctypefsims last_modifs rr z"SimpleHTTPRequestHandler.send_heads""49--  7==   1L))$)44E:&&s++ "":#?@@@"1XuQxqC"1XuQx1  ,11)<<  W555  !13777  """t2 1 1 T5117>>%(( DE**4000%% ==    OOJ02B C C C4 T4  AA    OOJ02B C C C44 ' !((**%%B#t|33't|;;(+;; %89;;C z)"kk1B1FkGGzX%6%:::%-%6%D%DK):)>&@&@ &0%7%7A%7%F%F %,, ..z/FGGG ,,...GGIII#'4'":}jID*   z} - - -   ^U 3 3 3   -s2a5zz : : :   _%%bk22 4 4 4      H  GGIII sJ G*H  H :P *M5CPPM30P2M33B$PP/c  tj|}n1#t$r$|tjdYdSwxYw|dg} tj |j d}n4#t$r'tj |j }YnwxYwtj |d}tj}d |}|d |d |d |d |d|d|d|d|d|d|D]}tj ||}|x} } tj |r |dz} |dz} tj |r|dz} |dtj| ddtj | dd|dd||d} t-j} | | | d|tj|dd|z|dt;t=| || S)zHelper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). zNo permission to list directoryNc*|Sr*)rX)as rz9SimpleHTTPRequestHandler.list_directory..s r)key surrogatepasserrorsFr{zDirectory listing for zzzzzz z

z

z