fTdZddlmZmZmZddlmZddlZddlZddl Z gdZ gdZ gdZ d Z hd jZd Zd ZGd dZGddeZGddeZGddeZGddeZy)z/Base classes for server/gateway implementations) FileWrapper guess_scheme is_hop_by_hop)HeadersN) BaseHandler SimpleHandlerBaseCGIHandler CGIHandler IISCGIHandler read_environ)MonTueWedThuFriSatSun) NJanFebMarAprMayJunJulAugSepOctNovDecc ttj|\ }}}}}}}}} dt||t|||||fzS)Nz#%s, %02d %3s %4d %02d:%02d:%02d GMT)timegmtime _weekdayname _monthname) timestampyearmonthdayhhmmsswdyzs '/usr/lib/python3.12/wsgiref/handlers.pyformat_date_timer1sN-1[[-C*D%b"b"a 0R#z%0$B4 > HTTPS AUTH_TYPE PATH_INFO REMOTE_USER SCRIPT_NAME CONTENT_TYPE QUERY_STRING REMOTE_IDENTCONTENT_LENGTHREQUEST_METHODct|xsG|jdxs4|jdxs!|jdxrt|ddS)NHTTP_SSL_ REDIRECT_ ) _is_request startswith_needs_transcode)ks r0rDrDsT q> CQ\\'2 Call66J C LL % A*:1QR5*ACr2ctj}d} djd|i}tj j D]\}}t|rtjdk(rtj jddj}|jdr!|jdjd}n|jd rny|jd r%d |vr!|jdjd}nC|j|djd}n!|j||jd}|||<|S#t$rd}YHwxYw) z'Read environment, fixing HTTP variablessurrogateescapezutf-8replacewin32SERVER_SOFTWAREzmicrosoft-iis/ iso-8859-1zapache/z simplehttp/zpython/3) sysgetfilesystemencodingencode LookupErrorosenvironitemsrDplatformgetlowerrCdecode)encescrRrEvsoftwares r0r r "sV # # %C C '3G    "+1 A ||w&::>>*;R@FFH&&'78)00>A((3 '' 6"h.)00>A i077 EA HHS#&--l; W+X Ng sE$$ E32E3ceZdZdZdZdZdZdZdZdZ dZ e Z e ZeZdZdZdgZd ZdxZZdZdZd Zd Zd Zd ZdZdZdZd$dZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+dZ,dZ-dZ.d Z/d!Z0d"Z1d#Z2y)%rz+Manage the invocation of a WSGI application)rrTFz1.0Nz500 Internal Server Error)z Content-Typez text/plains;A server error occurred. Please contact the administrator.rc |j||j|j|_|j y#t t tf$rYy |jYy#|jxYwxYw)zInvoke the applicationN) setup_environrRstart_responseresultfinish_responseConnectionAbortedErrorBrokenPipeErrorConnectionResetError handle_errorclose)self applications r0runzBaseHandler.runsv     %dllD4G4GHDK  "&9MN    !!#  s$AABBA//BBc|jjx}|_|j|j |d<|j |d<|j |d<|j|d<|j|d<|j|d<|j|d<|j|j|d <|jr*|jr|jd |jyyy) z&Set up the environment for one requestz wsgi.inputz wsgi.errorsz wsgi.versionz wsgi.run_oncezwsgi.url_schemezwsgi.multithreadzwsgi.multiprocessNzwsgi.file_wrapperrK) os_environcopyrR add_cgi_vars get_stdin get_stderr wsgi_version wsgi_run_once get_schemewsgi_multithreadwsgi_multiprocesswsgi_file_wrapper origin_serverserver_software setdefault)rgenvs r0r^zBaseHandler.setup_environs"__1133dl #'>>#3L#'??#4M#'#4#4N#'#5#5O#'??#4 #'#8#8 #'#9#9   ! ! -'+'='=C# $   $"6"6 NN,T-A-A B#7 r2c6 |jr|js2|jD]}|j||j |j y#t |jdr|jj xYw)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. rfN)result_is_filesendfiler`writefinish_contentrfhasattrrgdatas r0razBaseHandler.finish_responses{ &&(  KK%DJJt$%##% JJL t{{G, !!# s AA%%3Bc,t|jS)z Return the URL scheme being used)rrRrgs r0rrzBaseHandler.get_schemesDLL))r2c t|j}|dk(r#t|j|jd<yy#t t tf$rYywxYw)z@Compute Content-Length or switch to chunked encoding if possiblerContent-LengthN)lenr`str bytes_sentheaders TypeErrorAttributeErrorNotImplementedError)rgblockss r0set_content_lengthzBaseHandler.set_content_lengthsZ %Fqy14T__1E -..)<=   sAAAcBd|jvr|jyy)zqMake any necessary header changes or defaults Subclasses can extend this to add other defaults. rN)rrrs r0cleanup_headerszBaseHandler.cleanup_headerss! 4<< /  # # % 0r2c|r |jr d}n|j td||_|j ||_|j |d}|j | |D]B\}}|j |d}|j |d}t|s6Jd|d|d|jS#d}wxYw) z4'start_response()' callable as specified by PEP 3333NzHeaders already set!Statusz Header namez Header valuezHop-by-hop header, 'z: z', not allowed) headers_sentrAssertionErrorstatus headers_class_convert_string_type_validate_statusrr})rgrrexc_infonamevals r0r_zBaseHandler.start_responses  $$%  \\ % !78 8 ))'2 **68< f% $ J c00}E//^D(.J-dV2cU.IJ. J zz! s CCct|dkr td|ddjs td|ddk7r tdy)Nz$Status must be at least 4 charactersz(Status message must begin w/3-digit code z+Status message must have a space after code)rrisdigit)rgrs r0rzBaseHandler._validate_statussT v;? !GH Hbqz!!# !KL L !9  !NO O r2cpt|tur|Stdj|t |)zConvert/check value type.z!{0} must be of type str (got {1}))typerrformatrepr)rgvaluetitles r0rz BaseHandler._convert_string_types4 ;# L / 6 6ud5k J  r2c:|jr|jr|jd|jd|jdj dd|j vr>|jdttjzj d|jr=d|j vr.|jd|jzj dy y y y |jd |jzj dy ) z6Transmit version/status/date/server, via self._write()zHTTP/rz rLDatez Date: %s Serverz Server: %s z Status: %s N) rvclient_is_modern_write http_versionrrOrr1r"rwrs r0 send_preamblezBaseHandler.send_preamble s   $$& 1B1B4;;OWWXdef-KK'*:499;*GGOOP\]''HDLL,HKK!1D4H4H!H P PQ] ^_-I' ' KK)DKK7?? M Nr2c:t|tusJd|js td|js!t ||_|jn|xj t |z c_|j||jy)z+'write()' callable as specified by PEP 3333z)write() argument must be a bytes instancezwrite() before start_response()N) rbytesrrrrr send_headersr_flushrs r0r}zBaseHandler.writes~DzU" 8 7 8"{{ !BC C""!$iDO     OOs4y (O D r2cy)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. Frs r0r|zBaseHandler.sendfile.s$r2cv|js-|jjdd|jyy)z.Ensure headers and content have both been sentr0N)rrrxrrs r0r~zBaseHandler.finish_contentCs1   LL # #$4c :     r2c t|jdr|jjdx|_x|_x|_|_d|_d|_y#dx|_x|_x|_|_d|_d|_wxYw)zClose the iterable (if needed) and reset all instance vars Subclasses may want to also drop the client connection. rfNrF)rr`rfrrrRrrrs r0rfzBaseHandler.closeMs  ;t{{7+ !!#FJ JDK J$, Jt|DOU!2GK JDK J$, Jt|DOU!2s 0A,B c|jd|_|jr|jr5|j |j t |jyy)z1Transmit headers to the client, via self._write()TN)rrrvrrrrrrs r0rzBaseHandler.send_headersZsP  !!T%:%:%<    KKdll+ ,&=r2cR|j}|duxrt|j|S)z@True if 'self.result' is an instance of 'self.wsgi_file_wrapper'N)ru isinstancer`)rgwrappers r0r{zBaseHandler.result_is_filecs(((d"Fz$++g'FFr2cB|jdjdk7S)z,True if client can accept status and headersSERVER_PROTOCOLzHTTP/0.9)rRupperrs r0rzBaseHandler.client_is_modernis ||-.446*DDr2c ddlm}|j}||d|d|d|j||j d}y#d}wxYw)zLog the 'exc_info' tuple in the server log Subclasses may override to retarget the output or change its format. r)print_exceptionrN) tracebackrrotraceback_limitflush)rgrrstderrs r0 log_exceptionzBaseHandler.log_exceptionnsR  1__&F  Xa[(1+$$f  LLNHtHs AA Ac|jtj|js<|j |j |j |_|jyy)z>Log current error, and send error output to client if possibleN) rrMrr error_outputrRr_r`rars r0rezBaseHandler.handle_error~sN 3<<>*  ++DLL$:M:MNDK  "!r2c||j|jddtj|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_headersrMr error_body)rgrRr_s r0rzBaseHandler.error_outputs4 t((););A)>s||~N  r2ct)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. rrs r0rzBaseHandler._writes "!r2ct)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. rrs r0rzBaseHandler._flushs "!r2ct)z4Override in subclass to return suitable 'wsgi.input'rrs r0rnzBaseHandler.get_stdin!!r2ct)z5Override in subclass to return suitable 'wsgi.errors'rrs r0rozBaseHandler.get_stderrrr2ct)z>Override in subclass to insert CGI variables in 'self.environ'rrs r0rmzBaseHandler.add_cgi_varsrr2N)3__name__ __module__ __qualname____doc__rprsrtrqrvrrwr rkrrurrrrrrrr`rrrrir^rarrrrr_rrrr}r|r~rfrr{rrrerrrrnrormrr2r0rr^s5LMMLO J$MO.L23MOJFVLGJ0C*4* &4P  O** ;-G E  #!&"""""r2rc8eZdZdZ d dZdZdZdZdZdZ y) r aqHandler 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)cX||_||_||_||_||_||_yr)stdinstdoutrbase_envrsrt)rgrrrrR multithread multiprocesss r0__init__zSimpleHandler.__init__s0    +!-r2c|jSr)rrs r0rnzSimpleHandler.get_stdins zzr2c|jSr)rrs r0rozSimpleHandler.get_stderrs {{r2cN|jj|jyr)rRupdaterrs r0rmzSimpleHandler.add_cgi_varss DMM*r2c|jj|}||t|k(ryddlm}|dt ||dx}r$|jj|}||dx}r#yy)Nr)warnz9SimpleHandler.stdout.write() should not do partial writes)rr}rwarningsrDeprecationWarning)rgrr`rs r0rzSimpleHandler._writesr""4( >Vs4y0 ! H  67m#d#[[&&t,F67m#d#r2cn|jj|jj|_yr)rrrrs r0rzSimpleHandler._flushs# kk'' r2N)TF) rrrrrrnrormrrrr2r0r r s* (-.+-(r2r ceZdZdZdZy)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)rrrrrvrr2r0r r s&Mr2r ceZdZdZdZiZdZy)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 tj|tjjtj jtj tddy)NFTrr)r rrMrbufferrrr rs r0rzCGIHandler.__init__s? #))""CJJ$5$5szz ND  r2Nrrrrrqrkrrr2r0r r s MJ r2r ceZdZdZdZiZdZy)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 dt}|jdd}|jdd}|dzj|dzr|t|d|d<tj |t jjt jjt j|ddy)Nr5rHr7/FTr) r rUrCrr rrMrrrr)rgrRpathscripts r0rzIISCGIHandler.__init__4s{{;+]B/ H  ,#'F #5GK  #))""CJJ$5$5szz T  r2Nrrr2r0r r s MJ  r2r )rutilrrrrrrMrQr"__all__r$r%r1 __contains__rBrDr rr r r r rr2r0rs5::  A 8  , C9xV"V"r ,(K,(^]0