a ch@sdZdZgdZddlZddlZddlZddlZddlZ ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddlmZddl mZdZdZGd d d ejZGd d d ejeZGd ddej Z!Gddde!Z"ddZ#da$ddZ%ddZ&Gddde"Z'ddZ(e!edddfddZ)e*dkrddl+Z+e+,Z-e-j.d d!d"d#e-j.d$d%d&d'd(e-j.d)d*e /d+d,e-j.d-d.de0d/d0d1e-1Z2e2j3re'Z4nee"e2j5d2Z4Gd3d4d4eZ6e)e4e6e2j7e2j8d5dS)6a@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)partial) 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_bindZserver_addresssocketgetfqdn server_name server_port)selfhostportr,/opt/imh-python/lib/python3.9/http/server.pyr s  zHTTPServer.server_bindN)__name__ __module__ __qualname__Zallow_reuse_addressr rrrrrsrc@seZdZdZdS)rTN)rrrZdaemon_threadsrrrrrsrc@seZdZdZdejdZdeZ e Z e Z dZddZdd Zd d Zd d Zd/ddZd0ddZd1ddZddZddZddZd2ddZddZd d!Zd"d#Zd3d$d%Zd&d'Zgd(Zgd)Z d*d+Z!d,Z"e#j$j%Z&d-d.e'j()DZ*dS)4raHTTP 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 |dkrLdSt |dkr |d}zT| d srt |d d d }|d }t |d krt t |dt |d f}Wn*t t fy|tjd|YdS0|dkr|jdkrd|_|dkr|tjd|dS||_d t |kr}z"|tjdt|WYd}~dSd}~00|jdd} | dkrdd|_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-1z 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-aliveZExpectz 100-continue) commanddefault_request_versionrequest_versionclose_connectionstrraw_requestlinerstrip requestlinesplitlen startswith ValueErrorint IndexError send_errorrZ BAD_REQUESTprotocol_versionZHTTP_VERSION_NOT_SUPPORTEDpathhttpclientZ parse_headersrfile MessageClassheadersZ LineTooLongZREQUEST_HEADER_FIELDS_TOO_LARGEZ HTTPExceptiongetlowerhandle_expect_100) rversionr+wordsZbase_version_numberZversion_numberr$r4errZconntypeexpectrrr 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_onlyrZCONTINUE end_headersrrrrr<ps z(BaseHTTPRequestHandler.handle_expect_100c Csz|jd|_t|jdkrBd|_d|_d|_|tj WdS|jsTd|_ WdS| sbWdSd|j}t ||s|tj d|jWdSt||}||jWn:tjy}z |d|d|_ WYd}~dSd}~00dS) 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!NTZdo_zUnsupported method (%r)zRequest timed out: %r)r7readliner)r-r+r&r$r2rZREQUEST_URI_TOO_LONGr'rAhasattrNOT_IMPLEMENTEDgetattrwfileflushrtimeout log_error)rZmnamemethoderrrhandle_one_requests6     z)BaseHTTPRequestHandler.handle_one_requestcCs"d|_||js|qdS)z&Handle multiple requests if necessary.TN)r'rOrDrrrhandleszBaseHTTPRequestHandler.handleNcCs z|j|\}}Wnty,d\}}Yn0|dur:|}|durF|}|d||||||ddd}|dkr|tjtjtjfvr|j |t j |ddt j |ddd }| d d }|d |j |d tt|||jdkr|r|j|dS)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. )???rQNzcode %d, message %sr r"Fquote)codemessageexplainzUTF-8replacez Content-TypeContent-LengthZHEAD) responsesKeyErrorrL send_response send_headerrZ NO_CONTENTZ RESET_CONTENT NOT_MODIFIEDerror_message_formathtmlescapeencodeerror_content_typer(r-rCr$rIwrite)rrUrVrWZshortmsgZlongmsgbodyZcontentrrrr2s:      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. ZServerZDateN) log_requestrBr]version_stringdate_time_stringrrUrVrrrr\s  z$BaseHTTPRequestHandler.send_responsecCsd|jdkr`|dur0||jvr,|j|d}nd}t|ds@g|_|jd|j||fdddS) zSend the response header only.rNrr!_headers_bufferz %s %d %s latin-1strict)r&rZrFrjappendr3rbrirrrrBs    z)BaseHTTPRequestHandler.send_response_onlycCsl|jdkr6t|dsg|_|jd||fdd|dkrh|dkrVd|_n|d krhd |_d S) z)Send a MIME header to the headers buffer.rrjz%s: %s rkrl connectionr"Tr#FN)r&rFrjrmrbr;r')rkeywordvaluerrrr]s     z"BaseHTTPRequestHandler.send_headercCs"|jdkr|jd|dS)z,Send the blank line ending the MIME headers.rs N)r&rjrm flush_headersrDrrrrC s  z"BaseHTTPRequestHandler.end_headerscCs(t|dr$|jd|jg|_dS)Nrj)rFrIrdjoinrjrDrrrrqs 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) isinstancerrp log_messager+r()rrUsizerrrrfs  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)rvrformatargsrrrrL#s z BaseHTTPRequestHandler.log_errorcGs&tjd||||fdS)aLog 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. z%s - - [%s] %s N)sysstderrrdaddress_stringlog_date_time_stringrxrrrrv1s z"BaseHTTPRequestHandler.log_messagecCs|jd|jS)z*Return the server software version string. )server_version sys_versionrDrrrrgGsz%BaseHTTPRequestHandler.version_stringcCs |durt}tjj|ddS)z@Return the current date and time formatted for a message header.NT)Zusegmt)timeemailutilsZ formatdate)rZ timestamprrrrhKsz'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) rZnowZyearZmonthZdayZhhZmmssxyzsrrrr~Qs z+BaseHTTPRequestHandler.log_date_time_string)ZMonZTueZWedZThuZFriZSatZSun) NZJanZFebZMarZAprZMayZJunZJulZAugZSepZOctZNovZDeccCs |jdS)zReturn the client address.r)client_addressrDrrrr}_sz%BaseHTTPRequestHandler.address_stringHTTP/1.0cCsi|]}||j|jfqSr)phrase description).0vrrr nsz!BaseHTTPRequestHandler.)NN)N)N)rtrt)N)+rrr__doc__r{r=r,r __version__rDEFAULT_ERROR_MESSAGEr_DEFAULT_ERROR_CONTENT_TYPErcr%rAr<rOrPr2r\rBr]rCrqrfrLrvrgrhr~Z weekdaynamerr}r3r5r6Z HTTPMessager8r __members__valuesrZrrrrrs<gc% 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|dSN)osgetcwdfspathrsuper__init__)rrrzkwargs __class__rrrs z!SimpleHTTPRequestHandler.__init__cCs6|}|r2z|||jW|n |0dS)zServe a GET request.N) send_headcopyfilerIr"rfrrrdo_GETs zSimpleHTTPRequestHandler.do_GETcCs|}|r|dS)zServe a HEAD request.N)rr"rrrrdo_HEADsz SimpleHTTPRequestHandler.do_HEADc Csf||j}d}tj|rtj|j}|jds|t j |d|d|dd|d|df}tj |}| d|| d d | dSd D]&}tj||}tj|r|}qq||S||}|dr|t jd dSzt|d }Wn$ty&|t jd YdS0z t|}d|jvrd|jvrztj|jd} WnttttfyYnz0| 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|(Yn0dS)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. Nrrr r rZLocationrY0)z index.htmlz index.htmzFile not foundrbzIf-Modified-Sincez If-None-Match)tzinfo)Z microsecond Content-typez Last-Modified),translate_pathr4risdirurllibparseurlsplitendswithr\rZMOVED_PERMANENTLY urlunsplitr]rCrsexistslist_directory guess_typer2 NOT_FOUNDopenOSErrorfstatfilenor9rrZparsedate_to_datetime TypeErrorr1 OverflowErrorr/rrXdatetimetimezoneZutcZ fromtimestampst_mtimer^r"OKr(rh) rr4rpartsZ new_partsZnew_urlindexZctypefsZimsZ last_modifrrrrs~                     z"SimpleHTTPRequestHandler.send_headc Cszt|}Wn"ty0|tjdYdS0|jdddg}ztjj |j dd}Wnt yztj |}Yn0t j |dd }t}d |}|d |d |d ||d||d||d|D]v}tj ||}|} } tj |r|d} |d} tj |r4|d} |dtjj| ddt j | dd fq|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)r;)arrrrrz9SimpleHTTPRequestHandler.list_directory..)key surrogatepasserrorsFrSzDirectory listing for %szZz z@z%s z

%s

z
    r@z
  • %s
  • z

 surrogateescaperrztext/html; charset=%srY) rlistdirrr2rrsortrrunquoter4UnicodeDecodeErrorr`rar{getfilesystemencodingrmrsrislinkrTrbioBytesIOrdseekr\rr]r(r-rC) rr4listrZ displaypathenctitlenamefullnameZ displaynameZlinknameencodedrrrrrsh            z'SimpleHTTPRequestHandler.list_directorycCs|ddd}|ddd}|d}ztjj|dd}Wnty`tj|}Yn0t|}|d}t d|}|j }|D]0}t j |s|t jt jfvrqt j ||}q|r|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.) ?r r#rrrN)r,r*rrrrr posixpathnormpathfilterrrr4dirnamecurdirpardirrs)rr4Ztrailing_slashr>Zwordrrrr0s$     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)rsourceZ outputfilerrrrNsz!SimpleHTTPRequestHandler.copyfilecCsXt|\}}||jvr"|j|S|}||jvr>|j|St|\}}|rT|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)rsplitextextensions_mapr; mimetypesr)rr4baseextZguess_rrrr^s    z#SimpleHTTPRequestHandler.guess_type)rrrrrrrZ_encodings_map_defaultrrrrrrrr __classcell__rrrrrts   X:rc Cs|d\}}}tj|}|d}g}|ddD],}|dkrL|q6|r6|dkr6||q6|r|}|r|dkr|d}q|dkrd}nd}|rd||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. rrNrz..rr!) partitionrrrr,poprmrs) r4rquery path_partsZ head_partspartZ tail_partZ splitpathcollapsed_pathrrr_url_collapse_pathzs.      rcCsntrtSz ddl}Wnty(YdS0z|ddaWn,tyhdtdd|DaYn0tS) z$Internal routine to get nobody's uidrNrnobodyr r css|]}|dVqdS)r Nr)rrrrr rrznobody_uid..)rpwd ImportErrorgetpwnamr[maxgetpwall)rrrr nobody_uids    rcCst|tjS)zTest for executable file.)raccessX_OK)r4rrr executablesrc@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|n|tjddS)zRServe a POST request. This is only implemented for CGI scripts. zCan only POST to CGI scriptsN)is_cgirun_cgir2rrGrDrrrdo_POSTs  zCGIHTTPRequestHandler.do_POSTcCs|r|St|SdS)z-Version of send_head that support CGI scriptsN)rrrrrDrrrrszCGIHTTPRequestHandler.send_headcCszt|j}|dd}|dkrB|d||jvrB|d|d}q|dkrv|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). rr rNTF)rr4findcgi_directoriescgi_info)rrZdir_sepheadtailrrrrs   zCGIHTTPRequestHandler.is_cgiz/cgi-binz/htbincCst|S)z1Test whether argument path is an executable file.)r)rr4rrr is_executablesz#CGIHTTPRequestHandler.is_executablecCstj|\}}|dvS)z.Test whether argument path is a Python script.)z.pyz.pyw)rr4rr;)rr4r rrrr is_pythonszCGIHTTPRequestHandler.is_pythonc) Csl|j\}}|d|}|dt|d}|dkr|d|}||dd}||}tj|r||}}|dt|d}q*qq*|d\}}} |d}|dkr|d|||d} }n |d} }|d| } || } tj| s | t j d| dStj | s.| t j d| dS|| } |jsF| sh|| sh| t j d | dSttj}||d <|jj|d <d |d <|j|d<t|jj|d<|j|d<tj|}||d<|||d<| |d<| r| |d<|jd|d<|j d}|r|!}t|dkrddl"}ddl#}|d|d<|d$dkrz"|d%d}|&|'d}Wn|j(t)fyYn&0|!d}t|dkr|d|d<|j ddur|j*|d<n|jd|d<|j d}|r||d <|j d!}|r||d"<|j+d#d$}d%,||d&<|j d'}|rP||d(<t-d|j+d)g}d*,|}|r|||d+<d,D]}|.|dq|/t j0d-|1| 2d.d/}|jr| g}d0|vr|3|t4}|j56t7}|dkr^t8|d\}}t99|j:gggddr:|j:;ds q:q t<|}|rZ|=d1|dSzZzt>|Wnt?yYn0t@|j:Adt@|j5AdtB| ||Wn(|jC|jD|jtEd2Yn0nddlF} | g}!|| r:tGjH}"|"$Id3r.|"dd4|"d5d}"|"d6g|!}!d0| vrN|!3| |Jd7| K|!z tL|}#WntMtNfyd}#Yn0| jO|!| jP| jP| jP|d8}$|j$d9kr|#dkr|j:;|#}%nd}%t99|j:jQgggddr|j:jQRdsАqq|$S|%\}&}'|j5T|&|'r0|=d:|'|$jUV|$jWV|$jX}(|(r^|=d;|(n |Jd<dS)=zExecute a CGI script.rr rNrr!zNo such CGI script (%r)z#CGI script is not a plain file (%r)z!CGI script is not executable (%r)ZSERVER_SOFTWAREZ SERVER_NAMEzCGI/1.1ZGATEWAY_INTERFACEZSERVER_PROTOCOLZ SERVER_PORTZREQUEST_METHODZ PATH_INFOZPATH_TRANSLATEDZ SCRIPT_NAME QUERY_STRINGZ REMOTE_ADDR authorizationr Z AUTH_TYPEZbasicascii:Z REMOTE_USERz content-typeZ CONTENT_TYPEzcontent-lengthCONTENT_LENGTHreferer HTTP_REFERERacceptr,Z HTTP_ACCEPTz user-agentHTTP_USER_AGENTZcookiez, HTTP_COOKIE)rZ REMOTE_HOSTrrrrzScript output follows+r=zCGI script exit code zw.exez-uz command: %s)stdinstdoutr|envZpostz%szCGI script exit status %#xzCGI script exited OK)Yr r r-rrr4rrrr2rrisfileZ FORBIDDENr have_forkrcopydeepcopyenvironrgZserverrr3r(rr$rrrrr9r:r,base64binasciir;rbZ decodebytesdecodeError UnicodeErrorZget_content_typeZget_allrsr setdefaultr\rrqrXrmrrIrJrwaitpidselectr7readwaitstatus_to_exitcoderLsetuidrdup2rexecveZ handle_errorZrequest_exit subprocessr{rrrv list2cmdliner0rr/PopenPIPE_sockrecv communicaterdr|r"r" returncode))rdirrestr4iZnextdirZnextrestZ scriptdirrrZscriptZ scriptnameZ scriptfileZispyr#Zuqrestrr)r*lengthrrZuacoZ cookie_strkZ decoded_queryrzrpidstsexitcoder7ZcmdlineZinterpnbytespdatar"r|statusrrrr s6                                           zCGIHTTPRequestHandler.run_cgiN)rrrrrFrr%Zrbufsizer rrr rrrrrrrrs rcGs4tj|tjtjd}tt|\}}}}}||fS)N)typeflags)r getaddrinfo SOCK_STREAM AI_PASSIVEnextiter)addressZinfosfamilyrLproto canonnameZsockaddrrrr_get_best_familysrWri@c Cst||\|_}||_|||}|jdd\}}d|vrLd|dn|}td|d|d|d|d z |Wn$tytd t d Yn0Wdn1s0YdS) 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) rWZaddress_familyr3r getsocknameprintZ serve_foreverKeyboardInterruptr{exit) HandlerClass ServerClassprotocolrbindaddrZhttpdrZurl_hostrrrtests"   rc__main__z--cgi store_truezRun as CGI Server)actionhelpz--bindz-bZADDRESSz8Specify alternate bind address [default: all interfaces])metavarrgz --directoryz-dz9Specify alternative directory [default:current directory])defaultrgrstorerz&Specify alternate port [default: 8000])rfrirLnargsrgrcseZdZfddZZS)DualStackServercsHtt$|jtjtjdWdn1s40YtS)Nr) contextlibsuppress Exceptionr setsockopt IPPROTO_IPV6 IPV6_V6ONLYrr rDrrrr s   "zDualStackServer.server_bind)rrrr rrrrrrlsrl)r^r_rra)9rr__all__r&rZ email.utilsrr`Z http.clientr5rrrrr0rrr r{r urllib.parserrm functoolsrrrrr rZThreadingMixInrZStreamRequestHandlerrrrrrrrrWrcrargparseArgumentParserparser add_argumentrr0 parse_argsrzZcgiZ handler_classrrlrrarrrrsR   c0