a °:j!ºã@südZdZgd¢ZddlZddlZddlZddlZddlZ ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddlmZddl mZdZdZGd d „d ejƒZGd d „d ejeƒZGd d„dej ƒZ!Gdd„de!ƒZ"dd„Z#da$dd„Z%dd„Z&Gdd„de"ƒZ'dd„Z(e!edddfdd„Z)e*dkrøddl+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- 1¡Z2e2j3rÆe'Z4nee"e2j5d2Z4Gd3d4„d4eƒZ6e)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)Ú HTTPServerÚThreadingHTTPServerÚBaseHTTPRequestHandlerÚSimpleHTTPRequestHandlerÚCGIHTTPRequestHandleréN)Ú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@seZdZdZdd„ZdS)récCs4tj |¡|jdd…\}}t |¡|_||_dS)z.Override server_bind to store the server name.Né)Ú socketserverÚ TCPServerÚ server_bindZserver_addressÚsocketZgetfqdnÚ server_nameÚ server_port)ÚselfÚhostÚport©rú!/usr/lib/python3.9/http/server.pyr ˆs  zHTTPServer.server_bindN)Ú__name__Ú __module__Ú __qualname__Zallow_reuse_addressr rrrrr„src@seZdZdZdS)rTN)rrrZdaemon_threadsrrrrrsrc@søeZdZdZdej ¡dZdeZ e Z e Z dZdd„Zdd „Zd d „Zd d „Zd/dd„Zd0dd„Zd1dd„Zdd„Zdd„Zdd„Zd2dd„Zdd„Zd d!„Zd"d#„Zd3d$d%„Zd&d'„Zgd(¢Zgd)¢Z d*d+„Z!d,Z"e#j$j%Z&d-d.„e'j( )¡DƒZ*dS)4ra¿HTTP 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 Csêd|_|j|_}d|_t|jdƒ}| d¡}||_| ¡}t |ƒdkrLdSt |ƒdkr |d}zT|  d ¡srt ‚| d d ¡d }| d ¡}t |ƒd krœt ‚t |dƒt |d ƒf}Wn*t t fyà| tjd|¡YdS0|dkrú|jdkrúd|_|dkr| tjd|¡dS||_d t |ƒkrusÿz!BaseHTTPRequestHandler.)NN)N)N)rprp)N)+rrrÚ__doc__rwr<r*r}Ú __version__r|ÚDEFAULT_ERROR_MESSAGEr\ÚDEFAULT_ERROR_CONTENT_TYPEr`r#r?r;rLrMr0rYr@rZrArmrcrIrrrdrerzZ weekdaynamer‚ryr1r4r5Z HTTPMessager7rÚ __members__ÚvaluesrWrrrrr”s<gj% 5    þrcsxeZdZdZdeZdddddœZZdd œ‡fd d „ Zd d „Z dd„Z dd„Z dd„Z dd„Z dd„Zdd„Z‡ZS)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/gzipúapplication/octet-streamzapplication/x-bzip2zapplication/x-xz)z.gzz.Zz.bz2z.xzN©Ú directorycs2|durt ¡}t |¡|_tƒj|i|¤ŽdS©N)ÚosÚgetcwdÚfspathr•ÚsuperÚ__init__)rr•rvÚkwargs©Ú __class__rrr›s z!SimpleHTTPRequestHandler.__init__cCs6| ¡}|r2z| ||j¡W| ¡n | ¡0dS)zServe a GET request.N)Ú send_headÚcopyfilerGr ©rÚfrrrÚdo_GET–s zSimpleHTTPRequestHandler.do_GETcCs| ¡}|r| ¡dS)zServe a HEAD request.N)rŸr r¡rrrÚdo_HEADŸsz SimpleHTTPRequestHandler.do_HEADc CsZ| |j¡}d}tj |¡rÂtj |j¡}|j d¡sŒ| t j ¡|d|d|dd|d|df}tj  |¡}|  d|¡|  ¡dSd D]&}tj ||¡}tj |¡r|}qÂq| |¡S| |¡}| d¡rè| t jd ¡dSzt|d ƒ}Wn$ty| t jd ¡YdS0z t | ¡¡}d |jvròd |jvròztj |jd ¡} WnttttfyxYnz0| j dur–| j!t"j#j$d} | j t"j#j$uròt"j" %|j&t"j#j$¡} | j!dd} | | krò| t j'¡|  ¡| (¡WdS| t j)¡|  d|¡|  dt*|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 réZLocation)z index.htmlz index.htmzFile not foundÚrbzIf-Modified-Sincez If-None-Match)Útzinfo)Z microsecondú Content-typerVéz Last-Modified),Útranslate_pathr2r—ÚisdirÚurllibÚparseZurlsplitÚendswithrYrZMOVED_PERMANENTLYZ urlunsplitrZrAroÚexistsÚlist_directoryÚ guess_typer0Ú NOT_FOUNDÚopenÚOSErrorÚfstatÚfilenor8rr€Zparsedate_to_datetimeÚ TypeErrorr/Ú OverflowErrorr-r§rUÚdatetimeÚtimezoneZutcZ fromtimestampÚst_mtimer[r ÚOKr&re) rr2r¢ÚpartsZ new_partsZnew_urlÚindexZctypeZfsZimsZ last_modifrrrrŸ¥s|     ÿ       ÿÿ  ÿ      ÿz"SimpleHTTPRequestHandler.send_headc CsÒzt |¡}Wn"ty0| tjd¡YdS0|jdd„dg}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 f¡qæ| d¡d |¡ |d¡} t ¡} |  | ¡|  d¡| tj¡| dd|¡| dtt| ƒƒ¡| ¡| S)zûHelper 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:)ÚarrrÚ rnz9SimpleHTTPRequestHandler.list_directory..)ÚkeyÚ surrogatepass©ÚerrorsFrPzDirectory listing for %szZz z@z%s z

%s

z
    rú@z
  • %s
  • z

Ú Úsurrogateescaperr¨ztext/html; charset=%srV) r—Úlistdirr´r0rr²Úsortr¬r­Úunquoter2ÚUnicodeDecodeErrorr]r^rwÚgetfilesystemencodingrjror«ÚislinkrQr_ÚioÚBytesIOraÚseekrYr¼rZr&r+rA) rr2ÚlistÚrZ displaypathÚencÚtitleÚnameÚfullnameZ displaynameZlinknameZencodedr¢rrrr°üsh þ ÿ    ÿ ÿ þÿ    z'SimpleHTTPRequestHandler.list_directorycCsÌ| dd¡d}| dd¡d}| ¡ d¡}ztjj|dd}Wnty`tj |¡}Yn0t |¡}| d¡}t d|ƒ}|j }|D]0}t j   |¡sŠ|t jt jfvr¬qŠt j  ||¡}qŠ|rÈ|d7}|S) zñTranslate 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ú#rrÂrÃN)r*r(r®r¬r­rÊrËÚ posixpathÚnormpathÚfilterr•r—r2ÚdirnameÚcurdirÚpardirro)rr2Ztrailing_slashr=Zwordrrrrª6s$     z'SimpleHTTPRequestHandler.translate_pathcCst ||¡dS)añCopy 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)ÚshutilZ copyfileobj)rÚsourceZ outputfilerrrr Tsz!SimpleHTTPRequestHandler.copyfilecCsXt |¡\}}||jvr"|j|S| ¡}||jvr>|j|St |¡\}}|rT|SdS)a»Guess 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“)rÙÚsplitextÚextensions_mapr:Ú mimetypesr±)rr2ÚbaseZextZguessÚ_rrrr±ds    z#SimpleHTTPRequestHandler.guess_type)rrrrrŽr|râZ_encodings_map_defaultr›r£r¤rŸr°rªr r±Ú __classcell__rrrrr{s ü  W:rc CsÎ| d¡\}}}tj |¡}| d¡}g}|dd…D],}|dkrL| ¡q6|r6|dkr6| |¡q6|r˜| ¡}|rœ|dkrŠ| ¡d}qœ|dkrœd}nd}|r®d ||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. r×rNrz..rr)Ú partitionr¬r­rÊr*Úpoprjro) r2råÚqueryÚ path_partsZ head_partsÚpartZ tail_partZ splitpathÚcollapsed_pathrrrÚ_url_collapse_path€s.      rícCsntrtSz ddl}Wnty(YdS0z| d¡daWn,tyhdtdd„| ¡DƒƒaYn0tS) z$Internal routine to get nobody's uidrNrÚnobodyr r css|]}|dVqdS)r Nr)rŠrƒrrrÚ ¾rnznobody_uid..)rîÚpwdÚ ImportErrorÚgetpwnamrXÚmaxZgetpwall)rðrrrÚ nobody_uid²s    rôcCst |tj¡S)zTest for executable file.)r—ÚaccessÚX_OK)r2rrrÚ executableÂsr÷c@sVeZdZdZeedƒZdZdd„Zdd„Z dd „Z d d gZ d d „Z dd„Z dd„ZdS)rz­Complete 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| tjd¡dS)zRServe a POST request. This is only implemented for CGI scripts. zCan only POST to CGI scriptsN)Úis_cgiÚrun_cgir0rrErBrrrÚdo_POSTØs  þzCGIHTTPRequestHandler.do_POSTcCs| ¡r| ¡St |¡SdS)z-Version of send_head that support CGI scriptsN)rùrúrrŸrBrrrrŸæszCGIHTTPRequestHandler.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)rír2ÚfindÚcgi_directoriesÚcgi_info)rrìZdir_sepÚheadÚtailrrrrùís   zCGIHTTPRequestHandler.is_cgiz/cgi-binz/htbincCst|ƒS)z1Test whether argument path is an executable file.)r÷)rr2rrrÚ is_executable sz#CGIHTTPRequestHandler.is_executablecCstj |¡\}}| ¡dvS)z.Test whether argument path is a Python script.)z.pyz.pyw)r—r2rár:)rr2rÿrrrrÚ is_python szCGIHTTPRequestHandler.is_pythonc) Csl|j\}}|d|}| dt|ƒd¡}|dkrˆ|d|…}||dd…}| |¡}tj |¡rˆ||}}| dt|ƒd¡}q*qˆq*| 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 | ¡dSt tj¡}| ¡|d <|jj|d <d |d <|j|d<t|jjƒ|d<|j|d<tj |¡}||d<| |¡|d<| |d<| rð| |d<|jd|d<|j  d¡}|r¶| !¡}t|ƒdkr¶ddl"}ddl#}|d|d<|d $¡dkr¶z"|d %d¡}| &|¡ 'd¡}Wn|j(t)fyYn&0| !d¡}t|ƒdkr¶|d|d<|j  d¡durØ|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]}| .|d¡q€| /t j0d-¡| 1¡|  2d.d/¡}|jræ| g}d0|vrØ| 3|¡t4ƒ}|j5 6¡t 7¡}|dkr^t 8|d¡\}}t9 9|j:gggd¡dr:|j: ;d¡s q:q t <|¡}|rZ| =d1|›¡dSzZzt >|¡Wnt?y‚Yn0t @|j: A¡d¡t @|j5 A¡d¡t B| ||¡Wn(|j C|jD|j¡t Ed2¡Yn0n‚ddlF} | g}!| | ¡r:tGjH}"|" $¡ Id3¡r.|"dd4…|"d5d…}"|"d6g|!}!d0| vrN|! 3| ¡| Jd7|  K|!¡¡z tL|ƒ}#WntMtNfyˆd}#Yn0| jO|!| jP| jP| jP|d8}$|j $¡d9krÌ|#dkrÌ|j: ;|#¡}%nd}%t9 9|j:jQgggd¡dr|j:jQ Rd¡sÐqqÐ|$ S|%¡\}&}'|j5 T|&¡|'r0| =d:|'¡|$jU V¡|$jW V¡|$jX}(|(r^| =d;|(¡n | Jd<¡dS)=zExecute a CGI script.rr rNr×rzNo 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_TYPEZbasicÚasciiú:Z REMOTE_USERz content-typeZ CONTENT_TYPEzcontent-lengthÚCONTENT_LENGTHÚrefererÚ HTTP_REFERERÚacceptrú,Z HTTP_ACCEPTz user-agentÚHTTP_USER_AGENTZcookiez, Ú HTTP_COOKIE)rZ REMOTE_HOSTrr r r zScript output followsú+r{ú=zCGI script exit code ézw.exeéûÿÿÿéüÿÿÿz-uz command: %s)ÚstdinÚstdoutrxÚenvZpostz%szCGI script exit status %#xzCGI script exited OK)Yrþrür+rªr—r2r«rçr¯r0rr²ÚisfileZ FORBIDDENrÚ have_forkrÚcopyZdeepcopyÚenvironrdZserverrr1r&rr"r¬r­rÊr‡r8r9r*Úbase64Úbinasciir:r_Z decodebytesÚdecodeÚErrorÚ UnicodeErrorZget_content_typeZget_allrorÛÚ setdefaultrYr¼rmrUrjrôrGrHrøÚwaitpidÚselectr6ÚreadÚwaitstatus_to_exitcoderIÚsetuidr´Údup2r¶ÚexecveZ handle_errorZrequestÚ_exitÚ subprocessrwr÷r®rrZ list2cmdliner.r·r-ÚPopenÚPIPEZ_sockZrecvZ communicaterarxr rÚ returncode))rÚdirÚrestr2ÚiZnextdirZnextrestZ scriptdirråréZscriptZ scriptnameZ scriptfileZispyrZuqrestrrrZlengthrr ZuaÚcoZ cookie_strÚkZ decoded_queryrvrîÚpidÚstsZexitcoder(ZcmdlineZinterpÚnbytesÚpÚdatarrxZstatusrrrrús6          þþ  þ         ÿ                  ü    zCGIHTTPRequestHandler.run_cgiN)rrrrrDr—rZrbufsizerûrŸrùrýrrrúrrrrrÇs rcGs4tj|tjtjdœŽ}tt|ƒƒ\}}}}}||fS)N)ÚtypeÚflags)rZ getaddrinfoZ SOCK_STREAMZ AI_PASSIVEÚnextÚiter)ZaddressZinfosZfamilyr6ÚprotoZ canonnameZsockaddrrrrÚ_get_best_familyÎsýr;rˆi@c CsÆt||ƒ\|_}||_|||ƒ’}|j ¡dd…\}}d|vrLd|›dn|}td|›d|›d|›d|›d ƒz | ¡Wn$ty¢td ƒt  d ¡Yn0Wdƒn1s¸0YdS) 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) r;Zaddress_familyr1rZ getsocknameÚprintZ serve_foreverÚKeyboardInterruptrwÚexit) Ú HandlerClassÚ ServerClassZprotocolrÚbindZaddrZhttpdrZurl_hostrrrÚtestØs" ÿÿÿ  rDÚ__main__z--cgiÚ store_truezRun as CGI Server)ÚactionÚhelpz--bindz-bZADDRESSz8Specify alternate bind address [default: all interfaces])ÚmetavarrHz --directoryz-dz9Specify alternative directory [default:current directory])ÚdefaultrHrZstorer×z&Specify alternate port [default: 8000])rGrJr6ÚnargsrHr”cseZdZ‡fdd„Z‡ZS)ÚDualStackServercsHt t¡$|j tjtjd¡Wdƒn1s40Ytƒ ¡S)Nr) Ú contextlibÚsuppressÚ ExceptionrZ setsockoptZ IPPROTO_IPV6Z IPV6_V6ONLYršr rBrrrr s   ÿ"zDualStackServer.server_bind)rrrr rærrrrrLsrL)rArBrrC)9rrŽÚ__all__rr¹Z email.utilsrr]Z http.clientr4rÎrãr—rÙr!rßrr rwr~Z urllib.parser¬rMÚ functoolsrrrrr rZThreadingMixInrZStreamRequestHandlerrrrírîrôr÷rr;rDrÚargparseÚArgumentParserÚparserÚ add_argumentr˜r.Ú parse_argsrvZcgiZ handler_classr•rLrrCrrrrÚs”R   j0  þ  ÿ ÿÿýÿü