o w[eO@sdZdZgdZddlZddlZddlZddlZddlZ ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddl mZdZdZGdd d ejZGd d d ejeZGd d d ejZGdddeZ ddZ!da"ddZ#ddZ$Gddde Z%ddZ&eedddfddZ'e(dkrddl)Z)ddl*Z*e)+Z,e,j-dd d!d"e,j-d#d$d%d&d'e,j-d(d)e .d*d+e,j-d,d-de/d.d/d0e,0Z1e1j2re%Z3ne Z3Gd1d2d2eZ4e'e3e4e1j5e1j6d3dSdS)4a@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) HTTPStatusa Error response

Error response

Error code: %(code)d

Message: %(message)s.

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

ztext/html;charset=utf-8c@seZdZdZddZdS)rcCs4tj||jdd\}}t||_||_dS)z.Override server_bind to store the server name.N) socketserver TCPServer server_bindserver_addresssocketgetfqdn server_name server_port)selfhostportr"/usr/lib/python3.10/http/server.pyr s   zHTTPServer.server_bindN)__name__ __module__ __qualname__allow_reuse_addressr rrrrrs rc@seZdZdZdS)rTN)rrrdaemon_threadsrrrrrsrc @s*eZdZdZdejdZdeZ e Z e Z dZddZdd Zd d Zd d Zd5ddZd6ddZd6ddZddZddZddZd7ddZddZed d!eed"ed#d$DZ d%e e!d&<d'd(Z"d)d*Z#d6d+d,Z$d-d.Z%gd/Z&gd0Z'd1d2Z(d3Z)e*j+j,Z-d4d!e.j/0DZ1dS)8raHTTP 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.9c Csd|_|j|_}d|_t|jd}|d}||_|}t |dkr&dSt |dkr|d}z*| d s8t |d d d }|d }t |d krMt t |dt |d f}Wnt t fyo|tjd|YdSw|dkr||jdkr|d|_|dkr|tjd|dS||_d t |krdksn|tjd|dS|dd \}}t |d krd|_|dkr|tjd|dS|||_|_|j drd |jd |_z tjj|j|jd|_Wn?tjjy }z|tjdt|WYd}~dSd}~wtjjy(}z|tjdt|WYd}~dSd}~ww|jdd} | dkr;d|_n| dkrK|jdkrKd|_|jdd} | dkrl|jdkrl|jdkrl| sldSdS) 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-1z rFzHTTP//r.r zBad request version (%r))rrzHTTP/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) rversionr/wordsbase_version_numberversion_numberr(r:errconntypeexpectrrr parse_request s                z$BaseHTTPRequestHandler.parse_requestcCs|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_headersrrrrrGvs z(BaseHTTPRequestHandler.handle_expect_100c CszW|jd|_t|jdkr!d|_d|_d|_|tj WdS|js*d|_ WdS| s1WdSd|j}t ||sH|tj d|jWdSt||}||jWdStys}z|d|d|_ WYd}~dSd}~ww) 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)r?readliner-r1r/r*r(r6rREQUEST_URI_TOO_LONGr+rOhasattrNOT_IMPLEMENTEDgetattrwfileflush TimeoutError log_error)rmnamemethoderrrhandle_one_requests:     z)BaseHTTPRequestHandler.handle_one_requestcCs*d|_||js||jr dSdS)z&Handle multiple requests if necessary.TN)r+rarSrrrhandles zBaseHTTPRequestHandler.handleNcCsz |j|\}}Wn tyd\}}Ynw|dur|}|dur#|}|d||||||ddd}|dkrp|tjtjtjfvrp|j |t j |ddt j |ddd }| 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. )???rcNzcode %d, message %sr#r%Fquote)codemessageexplainzUTF-8replacez Content-TypeContent-LengthHEAD) responsesKeyErrorr] send_response send_headerr NO_CONTENT RESET_CONTENT NOT_MODIFIEDerror_message_formathtmlescapeencodeerror_content_typer,r1rRr(rZwrite)rrgrhrishortmsglongmsgbodycontentrrrr6s<       z!BaseHTTPRequestHandler.send_errorcCs:||||||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_requestrPrpversion_stringdate_time_stringrrgrhrrrros  z$BaseHTTPRequestHandler.send_responsecCsh|jdkr2|dur||jvr|j|d}nd}t|ds g|_|jd|j||fdddSdS) zSend the response header only.rNrr$_headers_bufferz %s %d %s latin-1strict)r*rmrWrappendr8rwrrrrrPs    z)BaseHTTPRequestHandler.send_response_onlycCsv|jdkrt|ds g|_|jd||fdd|dkr7|dkr,d|_d S|d kr9d |_d Sd Sd S) z)Send a MIME header to the headers buffer.rrz%s: %s rr connectionr%Tr&FN)r*rWrrrwrFr+)rkeywordvaluerrrrps       z"BaseHTTPRequestHandler.send_headercCs&|jdkr|jd|dSdS)z,Send the blank line ending the MIME headers.rs N)r*rr flush_headersrSrrrrRs   z"BaseHTTPRequestHandler.end_headerscCs,t|dr|jd|jg|_dSdS)Nr)rWrZryjoinrrSrrrrs  z$BaseHTTPRequestHandler.flush_headers-cCs.t|tr|j}|d|jt|t|dS)zNLog an accepted request. This is called by send_response(). z "%s" %s %sN) isinstancerr log_messager/r,)rrgsizerrrrs z"BaseHTTPRequestHandler.log_requestcGs|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)rformatargsrrrr])s z BaseHTTPRequestHandler.log_errorcCsi|] }|d|dqS)z\x02xr).0crrr 9sz!BaseHTTPRequestHandler. z\\\cGs2||}tjd||||jfdS)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%s - - [%s] %s N)sysstderrryaddress_stringlog_date_time_string translate_control_char_table)rrrrhrrrr<s  z"BaseHTTPRequestHandler.log_messagecCs|jd|jS)z*Return the server software version string. )server_version sys_versionrSrrrrVsz%BaseHTTPRequestHandler.version_stringcCs |durt}tjj|ddS)z@Return the current date and time formatted for a message header.NT)usegmt)timeemailutils formatdate)r timestamprrrrZsz'BaseHTTPRequestHandler.date_time_stringc CsBt}t|\ }}}}}}}} } d||j|||||f} | S)z.Return the current time formatted for logging.z%02d/%3s/%04d %02d:%02d:%02d)r localtime monthname) rnowyearmonthdayhhmmssxyzsrrrr`s z+BaseHTTPRequestHandler.log_date_time_string)MonTueWedThuFriSatSun) NJanFebMarAprMayJunJulAugSepOctNovDeccCs |jdS)zReturn the client address.r)client_addressrSrrrrns z%BaseHTTPRequestHandler.address_stringHTTP/1.0cCsi|] }||j|jfqSr)phrase description)rvrrrr}s )NNN)rr)2rrr__doc__rrHr0r __version__rDEFAULT_ERROR_MESSAGErtDEFAULT_ERROR_CONTENT_TYPErxr)rOrGrarbr6rorPrprRrrr]r, maketrans itertoolschainrangerordrrrr weekdaynamerrr8r<r= HTTPMessager@r __members__valuesrmrrrrrsFgj%  5       rcsxeZdZdZdeZdddddZZdd fd d Zd d Z ddZ ddZ ddZ ddZ ddZddZZS)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 directorycs2|durt}t||_tj|i|dSr)osgetcwdfspathrsuper__init__)rrrkwargs __class__rrrs z!SimpleHTTPRequestHandler.__init__cCs8|}|rz|||jW|dS|wdS)zServe a GET request.N) send_headcopyfilerZr%rfrrrdo_GETs zSimpleHTTPRequestHandler.do_GETcCs|}|r |dSdS)zServe a HEAD request.N)rr%rrrrdo_HEADs z SimpleHTTPRequestHandler.do_HEADc CsL||j}d}tj|rgtj|j}|jdsL|t j |d|d|dd|d|df}tj |}| d|| d d | dSd D]}tj||}tj|ra|}nqN||S||}|drz|t jd dSzt|d }Wnty|t jd YdSwzt|}d|jvrd|jvrz tj|jd} Wn ttttfyYn:w| j dur| j!t"j#j$d} | j t"j#j$urt"j"%|j&t"j#j$} | j!dd} | | kr|t j'| |(WdS|t j)| d|| d t*|d| d|+|j&| |WS|()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. Nrrrr rLocationrk0)z index.htmlz index.htmzFile not foundrbzIf-Modified-Sincez If-None-Match)tzinfo) microsecond Content-typez Last-Modified),translate_pathr:risdirurllibparseurlsplitendswithrorMOVED_PERMANENTLY urlunsplitrprRrisfilelist_directory guess_typer6 NOT_FOUNDopenOSErrorfstatfilenorArrparsedate_to_datetime TypeErrorr5 OverflowErrorr3rrjdatetimetimezoneutc fromtimestampst_mtimersr%OKr,r) rr:rparts new_partsnew_urlindexctypefsims last_modifrrrrs                      z"SimpleHTTPRequestHandler.send_headc Cszt|}Wnty|tjdYdSw|jdddg}z tjj |j dd}Wnt y>tj |j }Ynwt j |dd }t}d |}|d |d |d ||d||d||d|D]9}tj ||}|} } tj |r|d} |d} tj |r|d} |dtjj| ddt j | dd fqt|dd||d} t} | | | d|tj|dd||dtt| || 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 directoryNcSs|Sr)rF)arrrsz9SimpleHTTPRequestHandler.list_directory..)key surrogatepasserrorsFrezDirectory listing for %szZz z@z%s z

%s

z
    r@z
  • %s
  • z

 surrogateescaperrztext/html; charset=%srk) rlistdirrr6rrsortrrunquoter:UnicodeDecodeErrorrurvrgetfilesystemencodingrrrislinkrfrwioBytesIOryseekrorrpr,r1rR) rr:listr displaypathenctitlenamefullname displaynamelinknameencodedrrrrrsl             z'SimpleHTTPRequestHandler.list_directorycCs|ddd}|ddd}|d}z tjj|dd}Wnty0tj|}Ynwt|}|d}t d|}|j }|D]}t j |sU|t jt jfvrVqEt j ||}qE|rd|d7}|S) zTranslate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) ?rr#rrrN)r0r.rrrr#r$ posixpathnormpathfilterrrr:dirnamecurdirpardirr)rr:trailing_slashrIwordrrrr?s&     z'SimpleHTTPRequestHandler.translate_pathcCst||dS)aCopy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well. N)shutil copyfileobj)rsource outputfilerrrr]sz!SimpleHTTPRequestHandler.copyfilecCsXt|\}}||jvr|j|S|}||jvr|j|St|\}}|r*|SdS)aGuess the type of a file. Argument is a PATH (a filename). Return value is a string of the form type/subtype, usable for a MIME Content-type header. The default implementation looks the file's extension up in the table self.extensions_map, using application/octet-stream as a default; however it would be permissible (if slow) to look inside the data to make a better guess. r)r6splitextextensions_maprF mimetypesr)rr:baseextguess_rrrrms    z#SimpleHTTPRequestHandler.guess_type)rrrrrrrC_encodings_map_defaultrrrrrrrr __classcell__rrrrrs    X:rc Cs|d\}}}tj|}|d}g}|ddD]}|dkr&|q|r1|dkr1||q|rL|}|rK|dkrE|d}n |dkrKd}nd}|rWd||f}dd||f}d|}|S)a Given a URL path, remove extra '/'s and '.' path elements and collapse any '..' references and returns a collapsed path. Implements something akin to RFC-2396 5.2 step 6 to parse relative paths. The utility of this function is limited to is_cgi method and helps preventing some security attacks. Returns: The reconstituted URL, which will always start with a '/'. Raises: IndexError if too many '..' occur within the path. r4rNrz..r r$) partitionrrr#r0poprr) r:rHquery path_parts head_partspart tail_part splitpathcollapsed_pathrrr_url_collapse_paths2      rTcCsntrtSzddl}Wn tyYdSwz |ddaWtSty6dtdd|DaYtSw) z$Internal routine to get nobody's uidrNrnobodyr rcss|]}|dVqdS)r Nr)rrrrr sznobody_uid..)rUpwd ImportErrorgetpwnamrnmaxgetpwall)rWrrr nobody_uids   r\cCst|tjS)zTest for executable file.)raccessX_OK)r:rrr executablesr_c@sVeZdZdZeedZdZddZddZ dd Z d d gZ d d Z ddZ ddZdS)rzComplete HTTP server with GET, HEAD and POST commands. GET and HEAD also support running CGI scripts. The POST command is *only* implemented for CGI scripts. forkrcCs&|r |dS|tjddS)zRServe a POST request. This is only implemented for CGI scripts. zCan only POST to CGI scriptsN)is_cgirun_cgir6rrXrSrrrdo_POSTs  zCGIHTTPRequestHandler.do_POSTcCs|r|St|S)z-Version of send_head that support CGI scripts)rarbrrrSrrrrs zCGIHTTPRequestHandler.send_headcCst|j}|dd}|dkr-|d||jvr-|d|d}|dkr-|d||jvs|dkrG|d|||dd}}||f|_dSdS)a3Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. If any exception is raised, the caller should assume that self.path was rejected as invalid and act accordingly. The default implementation tests whether the normalized url path begins with one of the strings in self.cgi_directories (and the next character is a '/' or the end of the string). rrrNTF)rTr:findcgi_directoriescgi_info)rrSdir_sepheadtailrrrras   zCGIHTTPRequestHandler.is_cgiz/cgi-binz/htbincCst|S)z1Test whether argument path is an executable file.)r_)rr:rrr is_executablesz#CGIHTTPRequestHandler.is_executablecCstj|\}}|dvS)z.Test whether argument path is a Python script.)z.pyz.pyw)rr:rBrF)rr:rhrirrr is_pythons zCGIHTTPRequestHandler.is_pythonc) Cs|j\}}|d|}|dt|d}|dkrG|d|}||dd}||}tj|rB||}}|dt|d}nn|dks|d\}}} |d}|dkrf|d|||d} }n|d} }|d| } || } tj| s| t j d| dStj | s| t j d| dS|| } |js| s|| s| t j d | dSttj}||d <|jj|d <d |d <|j|d<t|jj|d<|j|d<tj|}||d<|||d<| |d<| |d<|jd|d<|j d}|rV|!}t|dkrVddl"}ddl#}|d|d<|d$dkrVz|d%d}|&|'d}Wn |j(t)fyCYnw|!d}t|dkrV|d|d<|j ddurg|j*|d<n|jd|d<|j d}|r{||d <|j d!}|r||d"<|j+d#d$}d%,||d&<|j d'}|r||d(<t-d|j+d)g}d*,|}|r||d+<d,D] }|.|dq|/t j0d-|1| 2d.d/}|jrw| g}d0|vr|3|t4}|j56t7}|dkr4t8|d\}}t99|j:gggddr"|j:;dsn t99|j:gggdds t<|}|r2|=d1|dSz.zt>|Wn t?yFYnwt@|j:Adt@|j5AdtB| ||WdS|jC|jD|jtEd2YdSddlF} | g}!|| rtGjH}"|"$Id3r|"dd4|"d5d}"|"d6g|!}!d0| vr|!3| |Jd7| K|!ztL|}#WntMtNfyd}#Ynw| jO|!| jP| jP| jP|d8}$|j$d9kr|#dkr|j:;|#}%nd}%t99|j:jQgggddr|j:jQRdsnt99|j:jQgggdds|$S|%\}&}'|j5T|&|'r'|=d:|'|$jUV|$jWV|$jX}(|(r?|=d;|(dS|Jd<dS)=zExecute a CGI script.rrrNr4r$zNo such CGI script (%r)z#CGI script is not a plain file (%r)z!CGI script is not executable (%r)SERVER_SOFTWARE SERVER_NAMEzCGI/1.1GATEWAY_INTERFACESERVER_PROTOCOL SERVER_PORTREQUEST_METHOD PATH_INFOPATH_TRANSLATED SCRIPT_NAME QUERY_STRING REMOTE_ADDR authorizationr AUTH_TYPEbasicascii: REMOTE_USERz content-type CONTENT_TYPEzcontent-lengthCONTENT_LENGTHreferer HTTP_REFERERacceptr, HTTP_ACCEPTz user-agentHTTP_USER_AGENTcookiez, HTTP_COOKIE)ru REMOTE_HOSTr~rrrzScript output follows+r=zCGI script exit code rzw.exez-uz command: %s)stdinstdoutrenvpostz%szCGI script exit status %#xzCGI script exited OK)Yrfrdr1rrr:rrKexistsr6rrr FORBIDDENrk have_forkrjcopydeepcopyenvironrserverrr8r,rr(rrr#rrArEr0base64binasciirFrw decodebytesdecodeError UnicodeErrorget_content_typeget_allrr8 setdefaultrorrrjrr\rZr[r`waitpidselectr?readwaitstatus_to_exitcoder]setuidrdup2rexecve handle_errorrequest_exit subprocessrr_rr list2cmdliner4rr3PopenPIPE_sockrecv communicateryrr%r returncode))rdirrestr:inextdirnextrest scriptdirrHrMscript scriptname scriptfileispyruqrestrwrrlengthrruaco cookie_strk decoded_queryrrUpidstsexitcodercmdlineinterpnbytespdatarrstatusrrrrbs@                                            zCGIHTTPRequestHandler.run_cgiN)rrrrrWrrrbufsizercrrarerjrkrbrrrrrs  rcGs4tj|tjtjd}tt|\}}}}}||fS)N)typeflags)r getaddrinfo SOCK_STREAM AI_PASSIVEnextiter)addressinfosfamilyrproto canonnamesockaddrrrr_get_best_familysrri@c Cst||\|_}||_|||R}|jdd\}}d|vr&d|dn|}td|d|d|d|d z|WntyQtd t d Yn wWddSWddS1sewYdS) zmTest the HTTP request handler class. This runs an HTTP server on port 8000 (or the port argument). Nr r{[]zServing HTTP on z port z (http://z/) ...z& Keyboard interrupt received, exiting.r) raddress_familyr8r getsocknameprint serve_foreverKeyboardInterruptrexit) HandlerClass ServerClassprotocolrbindaddrhttpdrurl_hostrrrtests,    "r__main__z--cgi store_truezrun as CGI server)actionhelpz--bindz-bADDRESSz8specify alternate bind address (default: all interfaces))metavarrz --directoryz-dz8specify alternate directory (default: current directory))defaultrrstorer4z&specify alternate port (default: 8000))rrrnargsrcs$eZdZfddZddZZS)DualStackServercsHtt|jtjtjdWdn1swYtS)Nr) contextlibsuppress Exceptionr setsockopt IPPROTO_IPV6 IPV6_V6ONLYrr rSrrrr s   zDualStackServer.server_bindcCs|j|||tjddS)Nr)RequestHandlerClassrr)rrrrrrfinish_requests  zDualStackServer.finish_request)rrrr rrJrrrrrs r)rrrr)7rr__all__rr  email.utilsrru http.clientr<r'rrDrr6rr>rr rr urllib.parserrrrr rThreadingMixInrStreamRequestHandlerrrrTrUr\r_rrrrargparserArgumentParserparser add_argumentrr4 parse_argsrcgi handler_classrrrrrrrsR  s0