
    F\hT                         S r SSKJrJrJr  SSKJr  SSKrSSKrSSK	r	/ SQr
/ SQr/ SQrS	 r1 S
kR                  rS rS r " S S5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      rg)z/Base classes for server/gateway implementations   )FileWrapperguess_schemeis_hop_by_hop)Headers    N)BaseHandlerSimpleHandlerBaseCGIHandler
CGIHandlerIISCGIHandlerread_environ)MonTueWedThuFriSatSun)NJanFebMarAprMayJunJulAugSepOctNovDecc           	      j    [         R                  " U 5      u	  pp4pVpxn	S[        U   U[        U   XXV4-  $ )Nz#%s, %02d %3s %4d %02d:%02d:%02d GMT)timegmtime_weekdayname
_monthname)
	timestampyearmonthdayhhmmsswdyzs
             '/usr/lib/python3.13/wsgiref/handlers.pyformat_date_timer1      sB    -1[[-C*D""0R#z%0$B4      >
   HTTPS	AUTH_TYPE	PATH_INFOREMOTE_USERSCRIPT_NAMECONTENT_TYPEQUERY_STRINGREMOTE_IDENTCONTENT_LENGTHREQUEST_METHODc                     [        U 5      =(       dV    U R                  S5      =(       d>    U R                  S5      =(       d&    U R                  S5      =(       a    [        U SS  5      $ )NHTTP_SSL_	REDIRECT_	   )_is_request
startswith_needs_transcode)ks    r0   rD   rD      sT    q> CQ\\'2 Call66J CLL%A*:1QR5*ACr2   c                     [         R                  " 5       n Sn SR                  SU5        0 n[        R
                  R                  5        GH*  u  p4[        U5      (       Ga  [         R                  S:X  a  [        R
                  R                  SS5      R                  5       nUR                  S5      (       a!  UR                  S5      R                  S5      nOUR                  S	5      (       a  OUR                  S
5      (       a'  SU;   a!  UR                  S5      R                  S5      nOBUR                  U S5      R                  S5      nO UR                  X5      R                  S5      nXBU'   GM-     U$ ! [         a    Sn GN`f = f)z'Read environment, fixing HTTP variablessurrogateescape zutf-8replacewin32SERVER_SOFTWAREzmicrosoft-iis/
iso-8859-1zapache/zsimplehttp/zpython/3)sysgetfilesystemencodingencodeLookupErrorosenvironitemsrD   platformgetlowerrC   decode)encescrR   rE   vsoftwares         r0   r   r   "   sW   

#
#
%C
C
		'3 G
 

  "A ||w&::>>*;R@FFH &&'788)00>A ((33 ''66"h.)00>A i077EA
 HHS&--l;
W #X Ng  s   E< <FFc                   
   \ rS rSrSrSrSrSrSrSr	Sr
Sr\" 5       r\r\rSrSrS	/rS
rS=rrSrSrSrS rS rS rS rS rS r S&S jr!S r"S r#S r$S r%S r&S r'S r(S r)S r*S r+S r,S r-S r.S  r/S! r0S" r1S# r2S$ r3S%r4g)'r   ^   z+Manage the invocation of a WSGI application)r   r   TFz1.0Nz500 Internal Server Error)zContent-Typez
text/plains;   A server error occurred.  Please contact the administrator.r   c                     U R                  5         U" U R                  U R                  5      U l        U R	                  5         g! [
        [        [        4 a     g   U R                  5          g!   U R                  5         e = f= f)zInvoke the applicationN)
setup_environrR   start_responseresultfinish_responseConnectionAbortedErrorBrokenPipeErrorConnectionResetErrorhandle_errorclose)selfapplications     r0   runBaseHandler.run   sv    	 %dllD4G4GHDK  "&9MN 	 	!!#

s$   AA BBA00BBc                    U R                   R                  5       =ol        U R                  5         U R	                  5       US'   U R                  5       US'   U R                  US'   U R                  US'   U R                  5       US'   U R                  US'   U R                  US'   U R                  b  U R                  US	'   U R                  (       a/  U R                  (       a  UR                  S
U R                  5        ggg)z&Set up the environment for one requestz
wsgi.inputzwsgi.errorszwsgi.versionzwsgi.run_oncezwsgi.url_schemezwsgi.multithreadzwsgi.multiprocessNzwsgi.file_wrapperrK   )
os_environcopyrR   add_cgi_vars	get_stdin
get_stderrwsgi_versionwsgi_run_once
get_schemewsgi_multithreadwsgi_multiprocesswsgi_file_wrapperorigin_serverserver_software
setdefault)rh   envs     r0   r_   BaseHandler.setup_environ   s     "__1133l#'>>#3L#'??#4M#'#4#4N#'#5#5O#'??#4#'#8#8#'#9#9 !!-'+'='=C#$$"6"6NN,T-A-AB #7r2   c                 X    U R                  5       (       a  U R                  5       (       d4  U R                   H  nU R                  U5        M     U R	                  5         U R                  5         g!   [        U R                  S5      (       a  U R                  R                  5         e = f)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.
rg   N)result_is_filesendfilera   writefinish_contentrg   hasattrrh   datas     r0   rb   BaseHandler.finish_response   s~    	&&(( KKDJJt$ (##% JJL	 t{{G,,!!#s   AA1 18B)c                 ,    [        U R                  5      $ )z Return the URL scheme being used)r   rR   rh   s    r0   rt   BaseHandler.get_scheme   s    DLL))r2   c                      [        U R                  5      nUS:X  a#  [        U R                  5      U R                  S'   gg! [
        [        [        4 a     gf = f)z@Compute Content-Length or switch to chunked encoding if possibler   Content-LengthN)lenra   str
bytes_sentheaders	TypeErrorAttributeErrorNotImplementedError)rh   blockss     r0   set_content_lengthBaseHandler.set_content_length   sZ    	%F qy14T__1E-.  .)<= 		s   A AAc                 F    SU R                   ;  a  U R                  5         gg)zaMake any necessary header changes or defaults

Subclasses can extend this to add other defaults.
r   N)r   r   r   s    r0   cleanup_headersBaseHandler.cleanup_headers   s!    
 4<</##% 0r2   c                    U(       a   U R                   (       a  e  SnOU R                  b  [        S5      eXl        U R	                  U5      U l        U R                  US5      nU R                  U5         U HG  u  pEU R                  US5      nU R                  US5      n[        U5      (       d  M;   SU SU S35       e   U R                  $ ! Snf = f)	z4'start_response()' callable as specified by PEP 3333NzHeaders already set!StatuszHeader namezHeader valuezHop-by-hop header, 'z: z', not allowed)	headers_sentr   AssertionErrorstatusheaders_class_convert_string_type_validate_statusr   r   )rh   r   r   exc_infonamevals         r0   r`   BaseHandler.start_response   s      $$ %  \\% !788))'2**68<f%$	00}E//^D(.. J-dV2cU.IJ. % zz!  s   C Cc                     [        U5      S:  a  [        S5      eUS S R                  5       (       d  [        S5      eUS   S:w  a  [        S5      eg )N   z$Status must be at least 4 characters   z(Status message must begin w/3-digit code z+Status message must have a space after code)r   r   isdigit)rh   r   s     r0   r   BaseHandler._validate_status   sW    v;? !GHHbqz!!## !KLL!9 !NOO r2   c                 r    [        U5      [        L a  U$ [        SR                  U[	        U5      5      5      e)zConvert/check value type.z!{0} must be of type str (got {1}))typer   r   formatrepr)rh   valuetitles      r0   r    BaseHandler._convert_string_type  s4    ;#L/66ud5kJ
 	
r2   c                 f   U R                   (       a  U R                  5       (       a  U R                  SU R                  < SU R                  < S3R                  S5      5        SU R                  ;  a?  U R                  S[        [        R                  " 5       5      -  R                  S5      5        U R                  (       a?  SU R                  ;  a.  U R                  SU R                  -  R                  S5      5        g
g
g
g
U R                  S	U R                  -  R                  S5      5        g
)z6Transmit version/status/date/server, via self._write()zHTTP/r   z
rL   Datez
Date: %s
ServerzServer: %s
zStatus: %s
N)
rx   client_is_modern_writehttp_versionr   rO   r   r1   r"   ry   r   s    r0   send_preambleBaseHandler.send_preamble  s    $$&&1B1B4;;OWWXdef-KK'*:499;*GGOOP\] ''HDLL,HKK!1D4H4H!H P PQ] ^_ -I' ' KK)DKK7??MNr2   c                 P   [        U5      [        L d   S5       eU R                  (       d  [        S5      eU R                  (       d!  [        U5      U l        U R                  5         OU =R                  [        U5      -  sl        U R                  U5        U R                  5         g)z+'write()' callable as specified by PEP 3333z)write() argument must be a bytes instancezwrite() before start_response()N)
r   bytesr   r   r   r   r   send_headersr   _flushr   s     r0   r   BaseHandler.write  s~     DzU" 	87	8" {{ !BCC""!$iDOOOs4y(O 	Dr2   c                     g)a  Platform-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.
F r   s    r0   r   BaseHandler.sendfile.  s    $ r2   c                     U R                   (       d-  U R                  R                  SS5        U R                  5         gg)z.Ensure headers and content have both been sentr   0N)r   r   rz   r   r   s    r0   r   BaseHandler.finish_contentC  s1       LL##$4c:r2   c                 "    [        U R                  S5      (       a  U R                  R                  5         S=U l        =U l        =U l        U l        SU l        SU l        g! S=U l        =U l        =U l        U l        SU l        SU l        f = f)ztClose the iterable (if needed) and reset all instance vars

Subclasses may want to also drop the client connection.
rg   Nr   F)r   ra   rg   r   r   rR   r   r   r   s    r0   rg   BaseHandler.closeM  s    
	;t{{7++!!#FJJDKJ$,Jt|DOU!2 GKJDKJ$,Jt|DOU!2s   5A" ",Bc                     U R                  5         SU l        U R                  (       a  U R                  5       (       a5  U R	                  5         U R                  [        U R                  5      5        gg)z1Transmit headers to the client, via self._write()TN)r   r   rx   r   r   r   r   r   r   s    r0   r   BaseHandler.send_headersZ  sS     !!T%:%:%<%< KKdll+, &=r2   c                 \    U R                   nUSL=(       a    [        U R                  U5      $ )z@True if 'self.result' is an instance of 'self.wsgi_file_wrapper'N)rw   
isinstancera   )rh   wrappers     r0   r~   BaseHandler.result_is_filec  s(    ((d"Fz$++g'FFr2   c                 B    U R                   S   R                  5       S:g  $ )z,True if client can accept status and headersSERVER_PROTOCOLzHTTP/0.9)rR   upperr   s    r0   r   BaseHandler.client_is_moderni  s     ||-.446*DDr2   c                      SSK Jn  U R                  5       nU" US   US   US   U R                  U5        UR	                  5         Sng! Snf = f)zqLog the 'exc_info' tuple in the server log

Subclasses may override to retarget the output or change its format.
r   )print_exceptionr      N)	tracebackr   rq   traceback_limitflush)rh   r   r   stderrs       r0   log_exceptionBaseHandler.log_exceptionn  sR    
		1__&FXa[(1+$$f LLNHtHs   AA
 
Ac                     U R                  [        R                  " 5       5        U R                  (       d<  U R	                  U R
                  U R                  5      U l        U R                  5         gg)z>Log current error, and send error output to client if possibleN)	r   rM   r   r   error_outputrR   r`   ra   rb   r   s    r0   rf   BaseHandler.handle_error~  sN    3<<>*  ++DLL$:M:MNDK  " !r2   c                     U" U R                   U R                  SS [        R                  " 5       5        U R                  /$ )a  WSGI 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_headersrM   r   
error_body)rh   rR   r`   s      r0   r   BaseHandler.error_output  s4     	t((););A)>s||~N  r2   c                     [         e)zOverride 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.
r   r   s     r0   r   BaseHandler._write  s
     "!r2   c                     [         e)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.
r   r   s    r0   r   BaseHandler._flush  s
     "!r2   c                     [         e)z4Override in subclass to return suitable 'wsgi.input'r   r   s    r0   rp   BaseHandler.get_stdin      !!r2   c                     [         e)z5Override in subclass to return suitable 'wsgi.errors'r   r   s    r0   rq   BaseHandler.get_stderr  r   r2   c                     [         e)z>Override in subclass to insert CGI variables in 'self.environ'r   r   s    r0   ro   BaseHandler.add_cgi_vars  r   r2   )r   rR   r   r   ra   r   N)5__name__
__module____qualname____firstlineno____doc__rr   ru   rv   rs   rx   r   ry   r   rm   r   rw   r   r   r   r   r   r   r   ra   r   r   r   rj   r_   rb   rt   r   r   r`   r   r   r   r   r   r   rg   r   r~   r   r   rf   r   r   r   rp   rq   ro   __static_attributes__r   r2   r0   r   r   ^   s    5 LMMLO
 J $M O.L23MOJ FVLGJ0C*4*
	&4P
O**
;-GE
 #!&"""""r2   r   c                   B    \ rS rSrSr SS jrS rS rS rS r	S r
S	rg
)r	   i  aU  Handler 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)c                 L    Xl         X l        X0l        X@l        XPl        X`l        g r   )stdinstdoutr   base_envru   rv   )rh   r   r   r   rR   multithreadmultiprocesss          r0   __init__SimpleHandler.__init__  s$     
 +!-r2   c                     U R                   $ r   )r   r   s    r0   rp   SimpleHandler.get_stdin  s    zzr2   c                     U R                   $ r   )r   r   s    r0   rq   SimpleHandler.get_stderr  s    {{r2   c                 N    U R                   R                  U R                  5        g r   )rR   updater   r   s    r0   ro   SimpleHandler.add_cgi_vars  s    DMM*r2   c                     U R                   R                  U5      nUb  U[        U5      :X  a  g SSKJn  U" S[
        5        XS  =n(       a)  U R                   R                  U5      nXS  =n(       a  M(  g g )Nr   )warnz9SimpleHandler.stdout.write() should not do partial writes)r   r   r   warningsr  DeprecationWarning)rh   r   ra   r  s       r0   r   SimpleHandler._write  sq    ""4(>Vs4y0!H	 7m#d#[[&&t,F 7m#d##r2   c                 n    U R                   R                  5         U R                   R                  U l        g r   )r   r   r   r   s    r0   r   SimpleHandler._flush  s#    kk''r2   )r   r   r   r   r   rv   ru   N)TF)r   r   r   r   r   r   rp   rq   ro   r   r   r   r   r2   r0   r	   r	     s*    
 (-.+-(r2   r	   c                       \ rS rSrSrSrSrg)r
   i  a  CGI-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.
Fr   N)r   r   r   r   r   rx   r   r   r2   r0   r
   r
     s    & Mr2   r
   c                   &    \ rS rSrSrSr0 rS rSrg)r   i  a  CGI-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           
          [         R                  U [        R                  R                  [        R
                  R                  [        R                  [        5       SSS9  g )NFTr   r   )r
   r   rM   r   bufferr   r   r   r   s    r0   r   CGIHandler.__init__  s?    #))""CJJ$5$5szzND 	  	
r2   r   N	r   r   r   r   r   rs   rm   r   r   r   r2   r0   r   r     s     M J
r2   r   c                   &    \ rS rSrSrSr0 rS rSrg)r   i  zCGI-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           
      h   [        5       nUR                  SS5      nUR                  SS5      nUS-   R                  US-   5      (       a  U[        U5      S  US'   [        R                  U [        R                  R                  [        R                  R                  [        R                  USSS9  g )Nr5   rH   r7   /FTr  )r   rU   rC   r   r
   r   rM   r   r  r   r   )rh   rR   pathscripts       r0   r   IISCGIHandler.__init__4  s    {{;+]B/H  ,,#'F#5GK #))""CJJ$5$5szzT 	  	
r2   r   Nr  r   r2   r0   r   r     s     MJ 	
r2   r   )r   utilr   r   r   r   r   rM   rQ   r"   __all__r$   r%   r1   __contains__rB   rD   r   r   r	   r
   r   r   r   r2   r0   <module>r     s    5 : :    A8
 , 
C9xV" V"r
,(K ,(^] 0
 
<!
N !
r2   