fdc @sCdZdZddgZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZdZdZdd ZGd ddejZGd ddejZGd d d eZddZe a!ddZ"ddZ#GdddeZ$eeddddZ%e&dkr?ej'Z(e(j)ddddde(j)d dd!d"dd#e*d$d%dd&e(j+Z,e,j-r&e%d'e$d e,j.ne%d'ed e,j.ndS((u@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 u0.6u HTTPServeruBaseHTTPRequestHandleriNu Error response

Error response

Error code: %(code)d

Message: %(message)s.

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

utext/html;charset=utf-8cCs(|jddjddjddS(Nu&u&uu>(ureplace(uhtml((u0/opt/alt/python33/lib64/python3.3/http/server.pyu _quote_html~su _quote_htmlcBs&|EeZdZdZddZdS(u HTTPServericCsNtjj||jjdd\}}tj||_||_dS(u.Override server_bind to store the server name.Ni(u socketserveru TCPServeru server_bindusocketu getsocknameugetfqdnu server_nameu server_port(uselfuhostuport((u0/opt/alt/python33/lib64/python3.3/http/server.pyu server_bindsuHTTPServer.server_bindN(u__name__u __module__u __qualname__uallow_reuse_addressu server_bind(u __locals__((u0/opt/alt/python33/lib64/python3.3/http/server.pyu HTTPServersc Bs|EeZdZdZdejjdZdeZ e Z e Z dZddZdd Zd d Zd d ZdddZdddZdddZddZddZddZddddZddZdd Zd!d"Zdd#d$Zd%d&Zd'd(d)d*d+d,d-gZ dd.d/d0d1d2d3d4d5d6d7d8d9g Z!d:d;Z"d<Z#e$j%j&Z'i,dd?6ddB6ddE6ddH6ddK6ddN6ddQ6ddT6ddW6ddZ6dd]6dd`6ddc6ddf6ddi6ddk6ddn6ddq6ddt6ddw6ddz6dd}6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6Z(dS(uBaseHTTPRequestHandleruHTTP 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". uPython/iu BaseHTTP/uHTTP/0.9c Cs)d|_|j|_}d|_t|jd}|jd}||_|j }t |dkr|\}}}|dddkr|j dd |dSyd|j d dd}|j d }t |d krt nt|d t|df}Wn0t tfk r=|j dd |dSYnX|dkre|jdkred |_n|dkr|j dd|dSnpt |d kr|\}}d|_|dkr|j dd|dSn"|sdS|j dd|dS||||_|_|_y%tjj|jd|j|_Wn,tjjk rl|j dddSYnX|jjdd}|jdkrd|_n-|jdkr|jdkrd |_n|jjdd} | jdkr%|jdkr%|jdkr%|js%dSndS( u'Parse 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, an error is sent back. iu iso-8859-1u iNiuHTTP/iuBad request version (%r)u/u.iiuHTTP/1.1iuInvalid HTTP Version (%s)uGETuBad HTTP/0.9 request type (%r)uBad request syntax (%r)u_classu Line too longu Connectionuucloseu keep-aliveuExpectu 100-continueF(ii(iiT(uNoneucommandudefault_request_versionurequest_versionuclose_connectionustruraw_requestlineurstripu requestlineusplitulenu send_erroruFalseu ValueErroruintu IndexErroruprotocol_versionupathuhttpuclientu parse_headersurfileu MessageClassuheadersu LineTooLongugetuloweruhandle_expect_100uTrue( uselfuversionu requestlineuwordsucommandupathubase_version_numberuversion_numberuconntypeuexpect((u0/opt/alt/python33/lib64/python3.3/http/server.pyu parse_requestst     $              u$BaseHTTPRequestHandler.parse_requestcCs|jd|jdS(u7Decide 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. idT(usend_response_onlyu end_headersuTrue(uself((u0/opt/alt/python33/lib64/python3.3/http/server.pyuhandle_expect_100Ws  u(BaseHTTPRequestHandler.handle_expect_100cCs&y|jjd|_t|jdkrYd|_d|_d|_|jddS|jsod|_dS|j sdSd|j}t ||s|jdd |jdSt ||}||j j WnEtjk r!}z"|jd |d|_dSWYdd}~XnXdS( uHandle 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. iiuiNiudo_iuUnsupported method (%r)uRequest timed out: %r(urfileureadlineuraw_requestlineulenu requestlineurequest_versionucommandu send_erroruclose_connectionu parse_requestuhasattrugetattruwfileuflushusocketutimeoutu log_error(uselfumnameumethodue((u0/opt/alt/python33/lib64/python3.3/http/server.pyuhandle_one_requestis0         u)BaseHTTPRequestHandler.handle_one_requestcCs1d|_|jx|js,|jqWdS(u&Handle multiple requests if necessary.iN(uclose_connectionuhandle_one_request(uself((u0/opt/alt/python33/lib64/python3.3/http/server.pyuhandles   uBaseHTTPRequestHandler.handlecCsy|j|\}}Wntk r7d\}}YnX|dkrM|}n|}|jd|||ji|d6t|d6|d6}|j|||jd|j|jdd|j |j d kr|d kr|dkr|j j |j d dndS(uSend and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short 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. u???ucode %d, message %sucodeumessageuexplainu Content-Typeu ConnectionucloseuHEADiii0uUTF-8ureplaceN(u???u???(ii0(u responsesuKeyErroruNoneu log_erroruerror_message_formatu _quote_htmlu send_responseu send_headeruerror_content_typeu end_headersucommanduwfileuwriteuencode(uselfucodeumessageushortmsgulongmsguexplainucontent((u0/opt/alt/python33/lib64/python3.3/http/server.pyu send_errors    " 'u!BaseHTTPRequestHandler.send_errorcCsM|j||j|||jd|j|jd|jdS(uAdd 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. uServeruDateN(u log_requestusend_response_onlyu send_headeruversion_stringudate_time_string(uselfucodeumessage((u0/opt/alt/python33/lib64/python3.3/http/server.pyu send_responses u$BaseHTTPRequestHandler.send_responsecCs|dkr8||jkr/|j|d}q8d}n|jdkrt|dsbg|_n|jjd|j||fjddndS( uSend the response header only.iuuHTTP/0.9u_headers_bufferu %s %d %s ulatin-1ustrictN(uNoneu responsesurequest_versionuhasattru_headers_bufferuappenduprotocol_versionuencode(uselfucodeumessage((u0/opt/alt/python33/lib64/python3.3/http/server.pyusend_response_onlys    u)BaseHTTPRequestHandler.send_response_onlycCs|jdkrSt|ds*g|_n|jjd||fjddn|jdkr|jdkrd|_q|jd krd |_qnd S( u)Send a MIME header to the headers buffer.uHTTP/0.9u_headers_bufferu%s: %s ulatin-1ustrictu connectionucloseiu keep-aliveiN(urequest_versionuhasattru_headers_bufferuappenduencodeuloweruclose_connection(uselfukeyworduvalue((u0/opt/alt/python33/lib64/python3.3/http/server.pyu send_headers    u"BaseHTTPRequestHandler.send_headercCs0|jdkr,|jjd|jndS(u,Send the blank line ending the MIME headers.uHTTP/0.9s N(urequest_versionu_headers_bufferuappendu flush_headers(uself((u0/opt/alt/python33/lib64/python3.3/http/server.pyu end_headerssu"BaseHTTPRequestHandler.end_headerscCs;t|dr7|jjdj|jg|_ndS(Nu_headers_buffers(uhasattruwfileuwriteujoinu_headers_buffer(uself((u0/opt/alt/python33/lib64/python3.3/http/server.pyu flush_headerssu$BaseHTTPRequestHandler.flush_headersu-cCs)|jd|jt|t|dS(uNLog an accepted request. This is called by send_response(). u "%s" %s %sN(u log_messageu requestlineustr(uselfucodeusize((u0/opt/alt/python33/lib64/python3.3/http/server.pyu log_requests u"BaseHTTPRequestHandler.log_requestcGs|j||dS(uLog 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(u log_message(uselfuformatuargs((u0/opt/alt/python33/lib64/python3.3/http/server.pyu log_errors u BaseHTTPRequestHandler.log_errorcGs1tjjd|j|j||fdS(uLog 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. u%s - - [%s] %s N(usysustderruwriteuaddress_stringulog_date_time_string(uselfuformatuargs((u0/opt/alt/python33/lib64/python3.3/http/server.pyu log_messages   u"BaseHTTPRequestHandler.log_messagecCs|jd|jS(u*Return the server software version string.u (userver_versionu sys_version(uself((u0/opt/alt/python33/lib64/python3.3/http/server.pyuversion_stringsu%BaseHTTPRequestHandler.version_stringc Csv|dkrtj}ntj|\ }}}}}}}} } d|j|||j|||||f} | S(u@Return the current date and time formatted for a message header.u#%s, %02d %3s %4d %02d:%02d:%02d GMTN(uNoneutimeugmtimeu weekdaynameu monthname( uselfu timestampuyearumonthudayuhhummussuwduyuzus((u0/opt/alt/python33/lib64/python3.3/http/server.pyudate_time_strings * u'BaseHTTPRequestHandler.date_time_stringc Cs]tj}tj|\ }}}}}}}} } d||j|||||f} | S(u.Return the current time formatted for logging.u%02d/%3s/%04d %02d:%02d:%02d(utimeu localtimeu monthname( uselfunowuyearumonthudayuhhummussuxuyuzus((u0/opt/alt/python33/lib64/python3.3/http/server.pyulog_date_time_string$s  * u+BaseHTTPRequestHandler.log_date_time_stringuMonuTueuWeduThuuFriuSatuSunuJanuFebuMaruApruMayuJunuJuluAuguSepuOctuNovuDeccCs |jdS(uReturn the client address.i(uclient_address(uself((u0/opt/alt/python33/lib64/python3.3/http/server.pyuaddress_string2su%BaseHTTPRequestHandler.address_stringuHTTP/1.0uContinueu!Request received, please continueiduSwitching Protocolsu.Switching to new protocol; obey Upgrade headerieuOKu#Request fulfilled, document followsiuCreateduDocument created, URL followsiuAcceptedu/Request accepted, processing continues off-lineiuNon-Authoritative InformationuRequest fulfilled from cacheiu No Contentu"Request fulfilled, nothing followsiu Reset Contentu#Clear input form for further input.iuPartial ContentuPartial content follows.iuMultiple Choicesu,Object has several resources -- see URI listi,uMoved Permanentlyu(Object moved permanently -- see URI listi-uFoundu(Object moved temporarily -- see URI listi.u See Otheru'Object moved -- see Method and URL listi/u Not Modifiedu)Document has not changed since given timei0u Use ProxyuAYou must use proxy specified in Location to access this resource.i1uTemporary Redirecti3u Bad Requestu(Bad request syntax or unsupported methodiu Unauthorizedu*No permission -- see authorization schemesiuPayment Requiredu"No payment -- see charging schemesiu Forbiddenu0Request forbidden -- authorization will not helpiu Not FounduNothing matches the given URIiuMethod Not Allowedu.Specified method is invalid for this resource.iuNot Acceptableu&URI not available in preferred format.iuProxy Authentication Requiredu8You must authenticate with this proxy before proceeding.iuRequest Timeoutu#Request timed out; try again later.iuConflictuRequest conflict.iuGoneu6URI no longer exists and has been permanently removed.iuLength Requiredu#Client must specify Content-Length.iuPrecondition Failedu!Precondition in headers is false.iuRequest Entity Too LargeuEntity is too large.iuRequest-URI Too LonguURI is too long.iuUnsupported Media Typeu"Entity body in unsupported format.iuRequested Range Not SatisfiableuCannot satisfy request range.iuExpectation Failedu(Expect condition could not be satisfied.iuPrecondition Requiredu9The origin server requires the request to be conditional.iuToo Many RequestsuPThe user has sent too many requests in a given amount of time ("rate limiting").iuRequest Header Fields Too LargeuWThe server is unwilling to process the request because its header fields are too large.iuInternal Server ErroruServer got itself in troubleiuNot Implementedu&Server does not support this operationiu Bad Gatewayu,Invalid responses from another server/proxy.iuService Unavailableu8The server cannot process the request due to a high loadiuGateway Timeoutu4The gateway server did not receive a timely responseiuHTTP Version Not SupporteduCannot fulfill request.iuNetwork Authentication Requiredu8The client needs to authenticate to gain network access.iN(uContinueu!Request received, please continue(uSwitching Protocolsu.Switching to new protocol; obey Upgrade header(uOKu#Request fulfilled, document follows(uCreateduDocument created, URL follows(uAcceptedu/Request accepted, processing continues off-line(uNon-Authoritative InformationuRequest fulfilled from cache(u No Contentu"Request fulfilled, nothing follows(u Reset Contentu#Clear input form for further input.(uPartial ContentuPartial content follows.(uMultiple Choicesu,Object has several resources -- see URI list(uMoved Permanentlyu(Object moved permanently -- see URI list(uFoundu(Object moved temporarily -- see URI list(u See Otheru'Object moved -- see Method and URL list(u Not Modifiedu)Document has not changed since given time(u Use ProxyuAYou must use proxy specified in Location to access this resource.(uTemporary Redirectu(Object moved temporarily -- see URI list(u Bad Requestu(Bad request syntax or unsupported method(u Unauthorizedu*No permission -- see authorization schemes(uPayment Requiredu"No payment -- see charging schemes(u Forbiddenu0Request forbidden -- authorization will not help(u Not FounduNothing matches the given URI(uMethod Not Allowedu.Specified method is invalid for this resource.(uNot Acceptableu&URI not available in preferred format.(uProxy Authentication Requiredu8You must authenticate with this proxy before proceeding.(uRequest Timeoutu#Request timed out; try again later.(uConflictuRequest conflict.(uGoneu6URI no longer exists and has been permanently removed.(uLength Requiredu#Client must specify Content-Length.(uPrecondition Failedu!Precondition in headers is false.(uRequest Entity Too LargeuEntity is too large.(uRequest-URI Too LonguURI is too long.(uUnsupported Media Typeu"Entity body in unsupported format.(uRequested Range Not SatisfiableuCannot satisfy request range.(uExpectation Failedu(Expect condition could not be satisfied.(uPrecondition Requiredu9The origin server requires the request to be conditional.(uToo Many RequestsuPThe user has sent too many requests in a given amount of time ("rate limiting").(uRequest Header Fields Too LargeuWThe server is unwilling to process the request because its header fields are too large.(uInternal Server ErroruServer got itself in trouble(uNot Implementedu&Server does not support this operation(u Bad Gatewayu,Invalid responses from another server/proxy.(uService Unavailableu8The server cannot process the request due to a high load(uGateway Timeoutu4The gateway server did not receive a timely response(uHTTP Version Not SupporteduCannot fulfill request.(uNetwork Authentication Requiredu8The client needs to authenticate to gain network access.()u__name__u __module__u __qualname__u__doc__usysuversionusplitu sys_versionu __version__userver_versionuDEFAULT_ERROR_MESSAGEuerror_message_formatuDEFAULT_ERROR_CONTENT_TYPEuerror_content_typeudefault_request_versionu parse_requestuhandle_expect_100uhandle_one_requestuhandleuNoneu send_erroru send_responseusend_response_onlyu send_headeru end_headersu flush_headersu log_requestu log_erroru log_messageuversion_stringudate_time_stringulog_date_time_stringu weekdaynameu monthnameuaddress_stringuprotocol_versionuhttpuclientu HTTPMessageu MessageClassu responses(u __locals__((u0/opt/alt/python33/lib64/python3.3/http/server.pyuBaseHTTPRequestHandlersf  Q  #           cBs|EeZdZdZdeZddZddZddZd d Z d d Z d dZ ddZ e jse jne jjZejidd6dd6dd6dd6dS(uSimpleHTTPRequestHandleruWSimple 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. u SimpleHTTP/c Cs>|j}|r:z|j||jWd|jXndS(uServe a GET request.N(u send_headucopyfileuwfileuclose(uselfuf((u0/opt/alt/python33/lib64/python3.3/http/server.pyudo_GETs  uSimpleHTTPRequestHandler.do_GETcCs#|j}|r|jndS(uServe a HEAD request.N(u send_headuclose(uselfuf((u0/opt/alt/python33/lib64/python3.3/http/server.pyudo_HEADs u SimpleHTTPRequestHandler.do_HEADcCs|j|j}d}tjj|r|jjdsn|jd|jd|jd|jdSxOdD]7}tjj ||}tjj |ru|}PququW|j |Sn|j |}yt |d}Wn&tk r |jdddSYnXyz|jd |jd |tj|j}|jd t|d |jd |j|j|j|SWn|jYnXdS(u{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. u/i-uLocationu index.htmlu index.htmurbiuFile not foundiu Content-typeuContent-Lengthiu Last-ModifiedN(u index.htmlu index.htm(utranslate_pathupathuNoneuosuisdiruendswithu send_responseu send_headeru end_headersujoinuexistsulist_directoryu guess_typeuopenuIOErroru send_errorufstatufilenoustrudate_time_stringust_mtimeuclose(uselfupathufuindexuctypeufs((u0/opt/alt/python33/lib64/python3.3/http/server.pyu send_heads>         u"SimpleHTTPRequestHandler.send_headc Cs#ytj|}Wn)tjk r>|jdddSYnX|jdddg}tjtj j |j }t j }d|}|jd|jd|jd ||jd ||jd ||jd x|D]}tj j||}|} } tj j|r>|d } |d } ntj j|r]|d} n|jdtj j| tj| fqW|jddj|j|} tj} | j| | jd|jd|jdd||jdtt| |j| S(uHelper 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(). iuNo permission to list directoryukeycSs |jS(N(ulower(ua((u0/opt/alt/python33/lib64/python3.3/http/server.pyusu9SimpleHTTPRequestHandler.list_directory..uDirectory listing for %suZu u@u%s u

%s

u
    u/u@u
  • %s
  • u

u iiu Content-typeutext/html; charset=%suContent-LengthN(uosulistdiruerroru send_erroruNoneusortuhtmluescapeuurllibuparseuunquoteupathusysugetfilesystemencodinguappendujoinuisdiruislinkuquoteuencodeuiouBytesIOuwriteuseeku send_responseu send_headerustrulenu end_headers( uselfupathulisturu displaypathuencutitleunameufullnameu displaynameulinknameuencodeduf((u0/opt/alt/python33/lib64/python3.3/http/server.pyulist_directorysJ             '      u'SimpleHTTPRequestHandler.list_directorycCs|jddd}|jddd}|jjd}tjtjj|}|jd}td|}t j }xS|D]K}t j j |s|t jt jfkrqnt j j||}qW|r|d7}n|S(uTranslate 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.) u?iiu#u/N(uspliturstripuendswithu posixpathunormpathuurllibuparseuunquoteufilteruNoneuosugetcwdupathudirnameucurdirupardirujoin(uselfupathutrailing_slashuwordsuword((u0/opt/alt/python33/lib64/python3.3/http/server.pyutranslate_path s   * u'SimpleHTTPRequestHandler.translate_pathcCstj||dS(uCopy 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(ushutilu copyfileobj(uselfusourceu outputfile((u0/opt/alt/python33/lib64/python3.3/http/server.pyucopyfile$su!SimpleHTTPRequestHandler.copyfilecCsdtj|\}}||jkr/|j|S|j}||jkrU|j|S|jdSdS(uGuess 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. uN(u posixpathusplitextuextensions_mapulower(uselfupathubaseuext((u0/opt/alt/python33/lib64/python3.3/http/server.pyu guess_type4s   u#SimpleHTTPRequestHandler.guess_typeuapplication/octet-streamuu text/plainu.pyu.cu.hN(u__name__u __module__u __qualname__u__doc__u __version__userver_versionudo_GETudo_HEADu send_headulist_directoryutranslate_pathucopyfileu guess_typeu mimetypesuiniteduinitu types_mapucopyuextensions_mapuupdate(u __locals__((u0/opt/alt/python33/lib64/python3.3/http/server.pyuSimpleHTTPRequestHandlers"    - 1      uSimpleHTTPRequestHandlercCs|jd}g}xS|ddD]A}|dkrE|jq&|r&|dkr&|j|q&q&W|r|j}|r|dkr|jd}q|dkrd}qqnd}ddj||f}dj|}|S(u` Given a URL path, remove extra '/'s and '.' path elements and collapse any '..' references and returns a colllapsed 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: A tuple of (head, tail) where tail is everything after the final / and head is everything before it. Head will always start with a '/' and, if it contains anything else, never have a trailing '/'. Raises: IndexError if too many '..' occur within the path. u/Niu..u.ui(usplitupopuappendujoin(upathu path_partsu head_partsupartu tail_partu splitpathucollapsed_path((u0/opt/alt/python33/lib64/python3.3/http/server.pyu_url_collapse_pathYs&       u_url_collapse_pathcCstr tSyddl}Wntk r2dSYnXy|jddaWn5tk rdtdd|jDaYnXtS( u$Internal routine to get nobody's uidiNiunobodyicss|]}|dVqdS(iN((u.0ux((u0/opt/alt/python33/lib64/python3.3/http/server.pyu sunobody_uid..i(unobodyupwdu ImportErrorugetpwnamuKeyErrorumaxugetpwall(upwd((u0/opt/alt/python33/lib64/python3.3/http/server.pyu nobody_uids   (u nobody_uidcCstj|tjS(uTest for executable file.(uosuaccessuX_OK(upath((u0/opt/alt/python33/lib64/python3.3/http/server.pyu executablesu executablecBs|EeZdZdZeedZdZddZddZ dd Z d d gZ d d Z ddZ ddZdS(uCGIHTTPRequestHandleruComplete 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. uforkicCs-|jr|jn|jdddS(uRServe a POST request. This is only implemented for CGI scripts. iuCan only POST to CGI scriptsN(uis_cgiurun_cgiu send_error(uself((u0/opt/alt/python33/lib64/python3.3/http/server.pyudo_POSTs  uCGIHTTPRequestHandler.do_POSTcCs'|jr|jStj|SdS(u-Version of send_head that support CGI scriptsN(uis_cgiurun_cgiuSimpleHTTPRequestHandleru send_head(uself((u0/opt/alt/python33/lib64/python3.3/http/server.pyu send_heads  uCGIHTTPRequestHandler.send_headcCsxttjj|j}|jdd}|d|||dd}}||jkrt||f|_dSdS(u3Test 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). u/iNTF( u_url_collapse_pathuurllibuparseuunquoteupathufinducgi_directoriesucgi_infouTrueuFalse(uselfucollapsed_pathudir_sepuheadutail((u0/opt/alt/python33/lib64/python3.3/http/server.pyuis_cgis%uCGIHTTPRequestHandler.is_cgiu/cgi-binu/htbincCs t|S(u1Test whether argument path is an executable file.(u executable(uselfupath((u0/opt/alt/python33/lib64/python3.3/http/server.pyu is_executablesu#CGIHTTPRequestHandler.is_executablecCs(tjj|\}}|jdkS(u.Test whether argument path is a Python script.u.pyu.pyw(u.pyu.pyw(uosupathusplitextulower(uselfupathuheadutail((u0/opt/alt/python33/lib64/python3.3/http/server.pyu is_pythonsuCGIHTTPRequestHandler.is_pythonc(Cs |j\}}|d|}|jdt|d}x|dkr|d|}||dd}|j|}tjj|r||}}|jdt|d}q<Pq<W|jd}|dkr|d|||dd}}nd}|jd}|dkrF|d|||d} }n |d} }|d| } |j| } tjj| s|j dd| dStjj | s|j d d | dS|j | } |j s| r |j | s |j d d | dSntjtj} |j| d <|jj| d |j9j?dtj>|j4j?dtj@| || Wq |jjA|jB|jtjCd6Yq XnddlD}| g} |j | rvtEjF}!|!j!jGd7rc|!ddD|!dEd}!n|!d:g| } nd4|kr| j*|n|jHd;|jI| ytJ|}"WntKtLfk rd}"YnX|jM| d<|jNd=|jNd>|jNd?| }#|jj!d@krB|"dkrB|j9j:|"}$nd}$xBt8j8|j9jOgggddr|j9jOjPdsKPqKqKW|#jQ|$\}%}&|j4jR|%|&r|j;dA|&n|#jSjT|#jUjT|#jV}'|'r |j;d5|'n |jHdBdS(FuExecute a CGI script.u/iiNu?uiuNo such CGI script (%r)iu#CGI script is not a plain file (%r)u!CGI script is not executable (%r)uSERVER_SOFTWAREu SERVER_NAMEuCGI/1.1uGATEWAY_INTERFACEuSERVER_PROTOCOLu SERVER_PORTuREQUEST_METHODu PATH_INFOuPATH_TRANSLATEDu SCRIPT_NAMEu QUERY_STRINGu REMOTE_ADDRu authorizationiu AUTH_TYPEubasicuasciiu:u REMOTE_USERu content-typeu CONTENT_TYPEucontent-lengthuCONTENT_LENGTHurefereru HTTP_REFERERuacceptu iu,u HTTP_ACCEPTu user-agentuHTTP_USER_AGENTucookieu, u HTTP_COOKIEu REMOTE_HOSTiuScript output followsu+u u=uCGI script exit status %#xiuw.exeiiu-uu command: %sustdinustdoutustderruenvupostu%suCGI script exited OK(u QUERY_STRINGu REMOTE_HOSTuCONTENT_LENGTHuHTTP_USER_AGENTu HTTP_COOKIEu HTTP_REFERERii(Wucgi_infoufindulenutranslate_pathuosupathuisdirurfinduexistsu send_erroruisfileu is_pythonu have_forku is_executableucopyudeepcopyuenvironuversion_stringuserveru server_nameuprotocol_versionustru server_portucommanduurllibuparseuunquoteuclient_addressuheadersugetusplitubase64ubinasciiuloweruencodeu decodebytesudecodeuErroru UnicodeErroruNoneuget_content_typeugetallmatchingheadersuappendustripujoinufilteruget_allu setdefaultu send_responseu flush_headersureplaceu nobody_uiduwfileuflushuforkuwaitpiduselecturfileureadu log_errorusetuiduerrorudup2ufilenouexecveu handle_errorurequestu_exitu subprocessusysu executableuendswithu log_messageu list2cmdlineuintu TypeErroru ValueErroruPopenuPIPEu_sockurecvu communicateuwriteustderrucloseustdoutu returncode((uselfudirurestupathuiunextdirunextrestu scriptdiruqueryuscriptu scriptnameu scriptfileuispyuenvuuqrestu authorizationubase64ubinasciiulengthurefereruacceptulineuuaucou cookie_struku decoded_queryuargsunobodyupidustsu subprocessucmdlineuinterpunbytesupudataustdoutustderrustatus((u0/opt/alt/python33/lib64/python3.3/http/server.pyurun_cgis2  ( $             !           %   !       !(   uCGIHTTPRequestHandler.run_cgiN(u__name__u __module__u __qualname__u__doc__uhasattruosu have_forkurbufsizeudo_POSTu send_headuis_cgiucgi_directoriesu is_executableu is_pythonurun_cgi(u __locals__((u0/opt/alt/python33/lib64/python3.3/http/server.pyuCGIHTTPRequestHandlers     uCGIHTTPRequestHandleruHTTP/1.0i@c Csd|f}||_|||}|jj}td|dd|ddy|jWn3tk rtd|jtjdYnXdS( uTest the HTTP request handler class. This runs an HTTP server on port 8000 (or the first command line argument). uuServing HTTP oniuportiu...u& Keyboard interrupt received, exiting.N( uprotocol_versionusocketu getsocknameuprintu serve_foreveruKeyboardInterruptu server_closeusysuexit(u HandlerClassu ServerClassuprotocoluportuserver_addressuhttpdusa((u0/opt/alt/python33/lib64/python3.3/http/server.pyutests     utestu__main__u--cgiuactionu store_trueuhelpuRun as CGI Serveruportustoreudefaultutypeunargsu?u&Specify alternate port [default: 8000]u HandlerClass(/u__doc__u __version__u__all__uhtmlu email.messageuemailu email.parseru http.clientuhttpuiou mimetypesuosu posixpathuselectushutilusocketu socketserverusysutimeu urllib.parseuurllibucopyuargparseuDEFAULT_ERROR_MESSAGEuDEFAULT_ERROR_CONTENT_TYPEu _quote_htmlu TCPServeru HTTPServeruStreamRequestHandleruBaseHTTPRequestHandleruSimpleHTTPRequestHandleru_url_collapse_pathuNoneunobodyu nobody_uidu executableuCGIHTTPRequestHandlerutestu__name__uArgumentParseruparseru add_argumentuintu parse_argsuargsucgiuport(((u0/opt/alt/python33/lib64/python3.3/http/server.pyu s^3                     +