h1zdZdZgdZddlZddlZddlZddlZddlZ 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 "/usr/lib/python3.11/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.9c8d|_|jx|_}d|_t |jd}|d}||_|}t|dkrdSt|dkr |d} | d st|d d d }|d }t|d krtt|dt|d f}n;#ttf$r'|tjd|zYdSwxYw|dkr|jdkrd|_|dkr%|tjd|zdS||_d t|cxkrdks'n|tjd|zdS|dd \}}t|d kr2d|_|dkr%|tjd|zdS||c|_|_|j dr"d |jd z|_ t*j|j|j|_n#t*jj$r9}|tjdt |Yd}~dSd}~wt*jj$r9}|tjdt |Yd}~dSd}~wwxYw|jdd} | dkrd|_n*| dkr|jdkrd|_|jdd} | dkr,|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 zBad 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 requestlinesplitlen startswith ValueErrorint IndexError send_errorr BAD_REQUESTprotocol_versionHTTP_VERSION_NOT_SUPPORTEDpathlstriphttpclient parse_headersrfile MessageClassheaders LineTooLongREQUEST_HEADER_FIELDS_TOO_LARGE HTTPExceptiongetlowerhandle_expect_100) rversionr7wordsbase_version_numberversion_numberr0rBerrconntypeexpects r parse_requestz$BaseHTTPRequestHandler.parse_request si )-)EEw $$. == !((00 &!!## u::??5 u::??BiG ))'22%$$&-mmC&;&;A&>#!4!:!:3!?!?~&&!++$$!$^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))++ uts7BD&&4EE 0J;;M.LM.MMcl|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 rrOz(BaseHTTPRequestHandler.handle_expect_100us2  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. iir,NTdo_zUnsupported method (%r)zRequest timed out: %r)rGreadliner5r9r7r2r0r>rREQUEST_URI_TOO_LONGr3rWhasattrNOT_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)r3rkr\s 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. )???roNzcode %d, message %sr+r-Fquote)codemessageexplainzUTF-8replacez Content-TypeContent-LengthHEAD) responsesKeyErrorrg send_response send_headerr NO_CONTENT RESET_CONTENT NOT_MODIFIEDerror_message_formathtmlescapeencodeerror_content_typer4r9r[r0rdwrite)rrsrtrushortmsglongmsgbodycontents rr>z!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_requestrYr|version_stringdate_time_stringrrsrts rr{z$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"Nrr,_headers_bufferz %s %d %s latin-1strict)r2ryrarappendr@rrs rrYz)BaseHTTPRequestHandler.send_response_onlys  : - -4>))"nT215GG G4!233 *')$  ' '*D':*;z!BaseHTTPRequestHandler.8s" 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)rrrrts 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_versionr\s rrz%BaseHTTPRequestHandler.version_stringUs"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_stringYs.   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_string_sWikk04s0C0C-eS"b"aA *T^E*D"b".> >r)MonTueWedThuFriSatSun) NJanFebMarAprMayJunJulAugSepOctNovDecc|jdS)zReturn the client address.r)client_addressr\s rrz%BaseHTTPRequestHandler.address_stringms"1%%rHTTP/1.0c,i|]}||j|jfSr)phrase description)rvs rrz!BaseHTTPRequestHandler.|s3  AHam $r)NNN)rr)2rrr__doc__rrPr8r __version__rDEFAULT_ERROR_MESSAGErDEFAULT_ERROR_CONTENT_TYPErr1rWrOrkrmr>r{rYr|r[rrrgr4 maketrans itertoolschainrangerordrrrr weekdaynamerrr@rDrE HTTPMessagerHr __members__valuesryrrrrrs=ddNck//11!44K !;.N03 )hhhT$###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 rrz!SimpleHTTPRequestHandler.__init__sG   I9--$)&)))))rc|}|rK |||j|dS#|wxYwdS)zServe a GET request.N) send_headcopyfilerdr-rfs rdo_GETzSimpleHTTPRequestHandler.do_GETsa NN      a,,,    s A Ac^|}|r|dSdS)zServe a HEAD request.N)rr-rs 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%Locationrw0)z index.htmlz index.htmzFile not foundrbzIf-Modified-Sincez If-None-Match)tzinfo) microsecond Content-typez Last-Modified),translate_pathrBrisdirurllibparseurlsplitendswithr{rMOVED_PERMANENTLY urlunsplitr|r[risfilelist_directory guess_typer> NOT_FOUNDopenOSErrorfstatfilenorIrrparsedate_to_datetimerrvdatetimetimezoneutc fromtimestampst_mtimerr- TypeErrorr= OverflowErrorr;OKr4r) rrBrparts new_partsnew_urlindexctypefsims last_modifs rrz"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}n/#t$r"tj |}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)rN)as rz9SimpleHTTPRequestHandler.list_directory..s r)key surrogatepasserrorsFrqzDirectory listing for zzzzzz z

z

z