a  zeT@sdZddlmZmZmZddlmZddlZddlZddl Z gdZ gdZ gdZ d d Z hd jZd d ZddZGdddZGdddeZGdddeZGdddeZGdddeZdS)z/Base classes for server/gateway implementations) FileWrapper guess_scheme is_hop_by_hop)HeadersN) BaseHandler SimpleHandlerBaseCGIHandler CGIHandler IISCGIHandler read_environ)ZMonZTueZWedZThuZFriZSatZSun) NZJanZFebZMarZAprZMayZJunZJulZAugZSepZOctZNovZDecc Cs:t|\ }}}}}}}}} dt||t|||||fS)Nz#%s, %02d %3s %4d %02d:%02d:%02d GMT)timegmtime _weekdayname _monthname) Z timestampZyearZmonthZdayZhhZmmssZwdyzrD/opt/bitninja-python-dojo/embedded/lib/python3.9/wsgiref/handlers.pyformat_date_timesr> Z QUERY_STRINGZHTTPSZ CONTENT_TYPE PATH_INFOZ AUTH_TYPEZREQUEST_METHODZ REMOTE_USER SCRIPT_NAMEZ REMOTE_IDENTZCONTENT_LENGTHcCs6t|p4|dp4|dp4|do4t|ddS)NZHTTP_ZSSL_Z REDIRECT_ ) _is_request startswith_needs_transcode)krrrrsrcCst}d}zdd|Wnty2d}Yn0i}tjD]\}}t|rtjdkrtj dd }| dr|d d}q| d rq| d rd |vr|d d}q||d d}n||| d}|||<qB|S) z'Read environment, fixing HTTP variablessurrogateescapezutf-8replacewin32SERVER_SOFTWAREzmicrosoft-iis/ iso-8859-1zapache/z simplehttp/zpython/3) sysgetfilesystemencodingencode LookupErrorosenvironitemsrplatformgetlowerrdecode)encZescr)rvZsoftwarerrrr "s0      r c@s"eZdZdZdZdZdZdZdZdZ dZ e Z e ZeZdZdZdgZd ZdZZdZdZd Zd d Zd dZddZddZddZddZd;ddZ ddZ!ddZ"ddZ#dd Z$d!d"Z%d#d$Z&d%d&Z'd'd(Z(d)d*Z)d+d,Z*d-d.Z+d/d0Z,d1d2Z-d3d4Z.d5d6Z/d7d8Z0d9d:Z1dS)YdSz |Wn| Yn0Yn0dS)zInvoke the applicationN) setup_environr)start_responseresultfinish_responseConnectionAbortedErrorBrokenPipeErrorConnectionResetError handle_errorclose)selfZ applicationrrrruns  zBaseHandler.runcCs|j}|_|||d<||d<|j|d<|j|d<||d<|j |d<|j |d<|j durx|j |d <|j r|j r|d |j dS) z&Set up the environment for one requestz wsgi.inputz wsgi.errorsz wsgi.versionz wsgi.run_oncezwsgi.url_schemezwsgi.multithreadzwsgi.multiprocessNzwsgi.file_wrapperr") os_environcopyr) add_cgi_vars get_stdin get_stderr wsgi_version wsgi_run_once get_schemewsgi_multithreadwsgi_multiprocesswsgi_file_wrapper origin_serverserver_software setdefault)r:envrrrr1s          zBaseHandler.setup_environcCsdz2|r|s0|jD]}||q|Wn$t|jdrP|jYn 0|dS)a>Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks in the event loop to iterate over the data, and to call 'self.close()' once the response is finished. r9N)result_is_filesendfiler3writefinish_contenthasattrr9r:datarrrr4s     zBaseHandler.finish_responsecCs t|jS)z Return the URL scheme being used)rr)r:rrrrCszBaseHandler.get_schemec CsHzt|j}Wntttfy&Yn0|dkrDt|j|jd<dSdS)z@Compute Content-Length or switch to chunked encoding if possiblerContent-LengthN)lenr3 TypeErrorAttributeErrorNotImplementedErrorstr bytes_sentheaders)r:Zblocksrrrset_content_lengthszBaseHandler.set_content_lengthcCsd|jvr|dS)zqMake any necessary header changes or defaults Subclasses can extend this to add other defaults. rSN)rZr[rRrrrcleanup_headerss zBaseHandler.cleanup_headerscCs|r6z(|jr&|d|d|dWd}qHd}0n|jdurHtd||_|||_||d}t|dkszJd|dd sJd |d d ksJd |D]>\}}||d }||d}t |rJd|d|dq|j S)z4'start_response()' callable as specified by PEP 3333rrNzHeaders already set!ZStatusz$Status must be at least 4 charactersz(Status message must begin w/3-digit code z+Status message must have a space after codez Header namez Header valuezHop-by-hop header, 'z: z', not allowed) headers_sentwith_tracebackrZAssertionErrorstatus headers_class_convert_string_typerTisdigitrrM)r:rdrZexc_infonamevalrrrr2s(       zBaseHandler.start_responsecCs(t|tur|Std|t|dS)zConvert/check value type.z!{0} must be of type str (got {1})N)typerXrcformatrepr)r:valuetitlerrrrfs  z BaseHandler._convert_string_typecCs|jrx|r|d|j|jfdd|jvrP|dttd|j rd|jvr|d|j dn|d|jddS) z6Transmit version/status/date/server, via self._write()z HTTP/%s %s r#ZDatez Date: %s ZServerz Server: %s z Status: %s N) rGclient_is_modern_write http_versionrdr&rZrr rHrRrrr send_preambles zBaseHandler.send_preamblecCsft|tusJd|js$tdn,|js>t||_|n|jt|7_||| dS)z+'write()' callable as specified by PEP 3333z)write() argument must be a bytes instancezwrite() before start_response()N) rkbytesrdrcrarTrY send_headersrq_flushrPrrrrMs    zBaseHandler.writecCsdS)aPlatform-specific file transmission Override this method in subclasses to support platform-specific file transmission. It is only called if the application's return iterable ('self.result') is an instance of 'self.wsgi_file_wrapper'. This method should return a true value if it was able to actually transmit the wrapped file-like object using a platform-specific approach. It should return a false value if normal iteration should be used instead. An exception can be raised to indicate that transmission was attempted, but failed. NOTE: this method should call 'self.send_headers()' if 'self.headers_sent' is false and it is going to attempt direct transmission of the file. FrrRrrrrL)szBaseHandler.sendfilecCs"|js|jdd|ndS)z.Ensure headers and content have both been sentrS0N)rarZrIrurRrrrrN>s zBaseHandler.finish_contentc Csjz>t|jdr|jWd|_|_|_|_d|_d|_n&d|_|_|_|_d|_d|_0dS)zClose the iterable (if needed) and reset all instance vars Subclasses may want to also drop the client connection. r9NrF)rOr3r9rZrdr)rYrarRrrrr9Hs  zBaseHandler.closecCs8|d|_|jr|r4||t|jdS)z1Transmit headers to the client, via self._write()TN)r\rarGrprsrqrtrZrRrrrruUs zBaseHandler.send_headerscCs|j}|duot|j|S)z@True if 'self.result' is an instance of 'self.wsgi_file_wrapper'N)rF isinstancer3)r:wrapperrrrrK^szBaseHandler.result_is_filecCs|jddkS)z,True if client can accept status and headersZSERVER_PROTOCOLzHTTP/0.9)r)upperrRrrrrpdszBaseHandler.client_is_moderncCsNzBddlm}|}||d|d|d|j||Wd}nd}0dS)zLog the 'exc_info' tuple in the server log Subclasses may override to retarget the output or change its format. r)print_exceptionrr]N) tracebackr{r@traceback_limitflush)r:rhr{stderrrrr log_exceptionis  zBaseHandler.log_exceptioncCs2|t|js.||j|j|_|dS)z>Log current error, and send error output to client if possibleN) rr$rhra error_outputr)r2r3r4rRrrrr8yszBaseHandler.handle_errorcCs$||j|jddt|jgS)aZWSGI mini-app to create error output By default, this just uses the 'error_status', 'error_headers', and 'error_body' attributes to generate an output page. It can be overridden in a subclass to dynamically generate diagnostics, choose an appropriate message for the user's preferred language, etc. Note, however, that it's not recommended from a security perspective to spit out diagnostics to any old user; ideally, you should have to do something special to enable diagnostic output, which is why we don't include any here! N) error_status error_headersr$rh error_body)r:r)r2rrrrs zBaseHandler.error_outputcCstdS)aOverride in subclass to buffer data for send to client It's okay if this method actually transmits the data; BaseHandler just separates write and flush operations for greater efficiency when the underlying system actually has such a distinction. NrWrPrrrrqszBaseHandler._writecCstdS)zOverride in subclass to force sending of recent '_write()' calls It's okay if this method is a no-op (i.e., if '_write()' actually sends the data. NrrRrrrrvszBaseHandler._flushcCstdS)z4Override in subclass to return suitable 'wsgi.input'NrrRrrrr?szBaseHandler.get_stdincCstdS)z5Override in subclass to return suitable 'wsgi.errors'NrrRrrrr@szBaseHandler.get_stderrcCstdS)z>Override in subclass to insert CGI variables in 'self.environ'NrrRrrrr>szBaseHandler.add_cgi_vars)N)2__name__ __module__ __qualname____doc__rArDrErBrGrrrHr r<rrFrrer}rrrrdr3rarZrYr;r1r4rCr[r\r2rfrsrMrLrNr9rurKrprr8rrqrvr?r@r>rrrrr^sV      rc@sBeZdZdZdddZddZdd Zd d Zd d ZddZ dS)raqHandler that's just initialized with streams, environment, etc. This handler subclass is intended for synchronous HTTP/1.0 origin servers, and handles sending the entire response output, given the correct inputs. Usage:: handler = SimpleHandler( inp,out,err,env, multithread=False, multiprocess=True ) handler.run(app)TFcCs(||_||_||_||_||_||_dSN)stdinstdoutrbase_envrDrE)r:rrrr) multithread multiprocessrrr__init__s zSimpleHandler.__init__cCs|jSr)rrRrrrr?szSimpleHandler.get_stdincCs|jSr)rrRrrrr@szSimpleHandler.get_stderrcCs|j|jdSr)r)updaterrRrrrr>szSimpleHandler.add_cgi_varscCs^|j|}|dus |t|kr$dSddlm}|dt||d}|sLqZ|j|}q:dS)Nr)warnz9SimpleHandler.stdout.write() should not do partial writes)rrMrTwarningsrDeprecationWarning)r:rQr3rrrrrqs   zSimpleHandler._writecCs|j|jj|_dSr)rr~rvrRrrrrvs zSimpleHandler._flushN)TF) rrrrrr?r@r>rqrvrrrrrs  rc@seZdZdZdZdS)r aCGI-like systems using input/output/error streams and environ mapping Usage:: handler = BaseCGIHandler(inp,out,err,env) handler.run(app) This handler class is useful for gateway protocols like ReadyExec and FastCGI, that have usable input/output/error streams and an environment mapping. It's also the base class for CGIHandler, which just uses sys.stdin, os.environ, and so on. The constructor also takes keyword arguments 'multithread' and 'multiprocess' (defaulting to 'True' and 'False' respectively) to control the configuration sent to the application. It sets 'origin_server' to False (to enable CGI-like output), and assumes that 'wsgi.run_once' is False. FN)rrrrrGrrrrr sr c@s eZdZdZdZiZddZdS)r aCGI-based invocation via sys.stdin/stdout/stderr and os.environ Usage:: CGIHandler().run(app) The difference between this class and BaseCGIHandler is that it always uses 'wsgi.run_once' of 'True', 'wsgi.multithread' of 'False', and 'wsgi.multiprocess' of 'True'. It does not take any initialization parameters, but always uses 'sys.stdin', 'os.environ', and friends. If you need to override any of these parameters, use BaseCGIHandler instead. Tc Cs(tj|tjjtjjtjtddddS)NFTrr)r rr$rbufferrrr rRrrrrszCGIHandler.__init__NrrrrrBr<rrrrrr sr c@s eZdZdZdZiZddZdS)r aCGI-based invocation with workaround for IIS path bug This handler should be used in preference to CGIHandler when deploying on Microsoft IIS without having set the config allowPathInfo option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7). Tc Csjt}|dd}|dd}|d|drD|t|d|d<tj|tjjtj jtj |ddddS)Nrrr/FTr) r r,rrTr rr$rrrr)r:r)pathZscriptrrrr2s  zIISCGIHandler.__init__Nrrrrrr sr )rutilrrrrZrr$r(r __all__rrr __contains__rrr rrr r r rrrrs"  <V2