o
    f:                     @   s   d Z dgZddlZddlZddlZedZedZG dd deZ	dd	 Z
d
d Zdd ZG dd dZG dd dZG dd dZG dd dZG dd dZdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& ZdS )'a&  
Middleware to check for obedience to the WSGI specification.

Some of the things this checks:

* Signature of the application and start_response (including that
  keyword arguments are not used).

* Environment checks:

  - Environment is a dictionary (and not a subclass).

  - That all the required keys are in the environment: REQUEST_METHOD,
    SERVER_NAME, SERVER_PORT, wsgi.version, wsgi.input, wsgi.errors,
    wsgi.multithread, wsgi.multiprocess, wsgi.run_once

  - That HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH are not in the
    environment (these headers should appear as CONTENT_LENGTH and
    CONTENT_TYPE).

  - Warns if QUERY_STRING is missing, as the cgi module acts
    unpredictably in that case.

  - That CGI-style variables (that don't contain a .) have
    (non-unicode) string values

  - That wsgi.version is a tuple

  - That wsgi.url_scheme is 'http' or 'https' (@@: is this too
    restrictive?)

  - Warns if the REQUEST_METHOD is not known (@@: probably too
    restrictive).

  - That SCRIPT_NAME and PATH_INFO are empty or start with /

  - That at least one of SCRIPT_NAME or PATH_INFO are set.

  - That CONTENT_LENGTH is a positive integer.

  - That SCRIPT_NAME is not '/' (it should be '', and PATH_INFO should
    be '/').

  - That wsgi.input has the methods read, readline, readlines, and
    __iter__

  - That wsgi.errors has the methods flush, write, writelines

* The status is a string, contains a space, starts with an integer,
  and that integer is in range (> 100).

* That the headers is a list (not a subclass, not another kind of
  sequence).

* That the items of the headers are tuples of strings.

* That there is no 'status' header (that is used in CGI, but not in
  WSGI).

* That the headers don't contain newlines or colons, end in _ or -, or
  contain characters codes below 037.

* That Content-Type is given if there is content (CGI often has a
  default content type, but WSGI does not).

* That no Content-Type is given when there is no content (@@: is this
  too restrictive?)

* That the exc_info argument to start_response is a tuple or None.

* That all calls to the writer are with strings, and no other methods
  on the writer are accessed.

* That wsgi.input is used properly:

  - .read() is called with exactly one argument

  - That it returns a string

  - That readline, readlines, and __iter__ return strings

  - That .close() is not called

  - No other methods are provided

* That wsgi.errors is used properly:

  - .write() and .writelines() is called with a string

  - That .close() is not called, and no other methods are provided.

* The response iterator:

  - That it is not a string (it should be a list of a single string; a
    string will work, but perform horribly).

  - That .__next__() returns a string

  - That the iterator is not iterated over until start_response has
    been called (that can signal either a server or application
    error).

  - That .close() is called (doesn't raise exception, only prints to
    sys.stderr, because we only know it isn't called when the object
    is garbage collected).
	validator    Nz^[a-zA-Z][a-zA-Z0-9\-_]*$z[\000-\037]c                   @   s   e Zd ZdZdS )WSGIWarningz:
    Raised in response to WSGI-spec-related warnings
    N)__name__
__module____qualname____doc__ r   r   '/usr/lib/python3.10/wsgiref/validate.pyr   y   s    r   c                 G   s   | st | d S N)AssertionError)condargsr   r   r	   assert_~   s   r   c                 C   s$   t | tu r| S td|t| )Nz!{0} must be of type str (got {1}))typestrr   formatrepr)valuetitler   r   r	   check_string_type   s
   r   c                    s    fdd}|S )a  
    When applied between a WSGI server and a WSGI application, this
    middleware will check for WSGI compliance on a number of levels.
    This middleware does not modify the request or response in any
    way, but will raise an AssertionError if anything seems off
    (except for a failure to close the application iterator, which
    will be printed to stderr -- there's no way to raise an exception
    at that point).
    c                     s   t t| dkd t | d | \} t| g  fdd}t|d |d< t|d |d< ||}t |d uo=|dkd	 t| t|S )
N   zTwo arguments requiredNo keyword arguments allowedc                     s   t t| dkpt| dkd| f  t | d | d }| d }t| dkr+| d }nd }t| t| t|| t| d  t |  S )Nr      zInvalid number of arguments: %sr   r      )r   lencheck_statuscheck_headerscheck_content_typecheck_exc_infoappendWriteWrapper)r   kwstatusheadersexc_infostart_responsestart_response_startedr   r	   start_response_wrapper   s   


z;validator.<locals>.lint_app.<locals>.start_response_wrapper
wsgi.inputwsgi.errorsFz>The application must return an iterator, if only an empty list)r   r   check_environInputWrapperErrorWrappercheck_iteratorIteratorWrapper)r   r!   environr(   iteratorapplicationr%   r	   lint_app   s   

zvalidator.<locals>.lint_appr   )r3   r4   r   r2   r	   r      s   )c                   @   s<   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZdS )r,   c                 C   
   || _ d S r
   )input)self
wsgi_inputr   r   r	   __init__      
zInputWrapper.__init__c                 G   s0   t t|dk | jj| }t t|tu  |S Nr   )r   r   r6   readr   bytesr7   r   vr   r   r	   r<         zInputWrapper.readc                 G   s0   t t|dk | jj| }t t|tu  |S r;   )r   r   r6   readliner   r=   r>   r   r   r	   rA      r@   zInputWrapper.readlinec                 G   sJ   t t|dk | jj| }t t|tu  |D ]
}t t|tu  q|S r;   )r   r   r6   	readlinesr   listr=   )r7   r   linesliner   r   r	   rB      s   zInputWrapper.readlinesc                 c   s    	 |   }|s
d S |V  qr
   )rA   )r7   rE   r   r   r	   __iter__   s   zInputWrapper.__iter__c                 C      t dd d S )Nr   z input.close() must not be calledr   r7   r   r   r	   close      zInputWrapper.closeN)	r   r   r   r9   r<   rA   rB   rF   rJ   r   r   r   r	   r,      s    r,   c                   @   4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )r-   c                 C   r5   r
   )errors)r7   wsgi_errorsr   r   r	   r9      r:   zErrorWrapper.__init__c                 C   s    t t|tu  | j| d S r
   )r   r   r   rM   writer7   sr   r   r	   rO      s   zErrorWrapper.writec                 C   s   | j   d S r
   )rM   flushrI   r   r   r	   rR      rK   zErrorWrapper.flushc                 C   s   |D ]}|  | qd S r
   )rO   )r7   seqrE   r   r   r	   
writelines   s   zErrorWrapper.writelinesc                 C   rG   )Nr   z!errors.close() must not be calledrH   rI   r   r   r	   rJ      rK   zErrorWrapper.closeN)r   r   r   r9   rO   rR   rT   rJ   r   r   r   r	   r-      s    r-   c                   @      e Zd Zdd Zdd ZdS )r    c                 C   r5   r
   )writer)r7   wsgi_writerr   r   r	   r9      r:   zWriteWrapper.__init__c                 C   s   t t|tu  | | d S r
   )r   r   r=   rV   rP   r   r   r	   __call__   s   zWriteWrapper.__call__N)r   r   r   r9   rX   r   r   r   r	   r           r    c                   @   rU   )PartialIteratorWrapperc                 C   r5   r
   r1   )r7   wsgi_iteratorr   r   r	   r9      r:   zPartialIteratorWrapper.__init__c                 C   s   t | jd S r
   )r/   r1   rI   r   r   r	   rF     s   zPartialIteratorWrapper.__iter__N)r   r   r   r9   rF   r   r   r   r	   rZ      rY   rZ   c                   @   rL   )r/   c                 C   s    || _ t|| _d| _|| _d S )NF)original_iteratoriterr1   closedcheck_start_response)r7   r\   r`   r   r   r	   r9   	  s   

zIteratorWrapper.__init__c                 C   s   | S r
   r   rI   r   r   r	   rF     s   zIteratorWrapper.__iter__c                 C   sT   t | j d t| j}t|turt dd|f  | jd ur(t | jd d | _|S )NzIterator read after closedFz$Iterator yielded non-bytestring (%r)zjThe application returns and we started iterating over its body, but start_response has not yet been called)r   r_   nextr1   r   r=   r`   )r7   r?   r   r   r	   __next__  s   

zIteratorWrapper.__next__c                 C   s$   d| _ t| jdr| j  d S d S )NTrJ   )r_   hasattrr]   rJ   rI   r   r   r	   rJ     s   zIteratorWrapper.closec                 C   s"   | j s	tjd t| j d d S )Nz/Iterator garbage collected without being closed)r_   sysstderrrO   r   rI   r   r   r	   __del__#  s   zIteratorWrapper.__del__N)r   r   r   r9   rF   rb   rJ   rf   r   r   r   r	   r/     s    r/   c                 C   s  t t| tu dt| | f  dD ]}t || v d|f  qdD ]}t || vd||dd  f  q d| vr<tdt |  D ]}d	|v rGq@t t| | tu d
|t| | | | f  q@t t| d tu d| d f  t | d dv d| d   t	| d  t
| d  | d dvrtd| d  t t | d p| d dd| d   t | d p| d dd| d   | drt t| d dkd| d   | dst d| v d t | ddkd d S )Nz:Environment is not of the right type: %r (environment: %r))	REQUEST_METHODSERVER_NAMESERVER_PORTwsgi.versionr)   r*   zwsgi.multithreadzwsgi.multiprocesszwsgi.run_oncez$Environment missing required key: %r)HTTP_CONTENT_TYPEHTTP_CONTENT_LENGTHz8Environment should not have the key: %s (use %s instead)   QUERY_STRINGzQUERY_STRING is not in the WSGI environment; the cgi module will use sys.argv when this variable is missing, so application errors are more likely.z9Environmental variable %s is not a string: %r (value: %r)rj   z#wsgi.version should be a tuple (%r)zwsgi.url_scheme)httphttpszwsgi.url_scheme unknown: %rr)   r*   rg   )GETHEADPOSTOPTIONSPATCHPUTDELETETRACEzUnknown REQUEST_METHOD: %rSCRIPT_NAME/z$SCRIPT_NAME doesn't start with /: %r	PATH_INFOz"PATH_INFO doesn't start with /: %rCONTENT_LENGTHr   zInvalid CONTENT_LENGTH: %rzgOne of SCRIPT_NAME or PATH_INFO are required (PATH_INFO should at least be '/' if SCRIPT_NAME is empty)zOSCRIPT_NAME cannot be '/'; it should instead be '', and PATH_INFO should be '/')r   r   dictwarningswarnr   keysr   tuplecheck_inputcheck_errorsget
startswithint)r0   keyr   r   r	   r+   *  sx   







r+   c                 C   &   dD ]}t t| |d| |f  qd S )N)r<   rA   rB   rF   z-wsgi.input (%r) doesn't have the attribute %sr   rc   )r8   attrr   r   r	   r   k     
r   c                 C   r   )N)rR   rO   rT   z.wsgi.errors (%r) doesn't have the attribute %sr   )rN   r   r   r   r	   r   q  r   r   c                 C   sz   t | d} | d dd }tt|dkd|  t|}t|dkd|  t| dk s1| d d	kr;td
|  t d S d S )NStatusr   r   r   z)Status codes must be three characters: %rd   zStatus code is invalid: %r    zjThe status string (%r) should be a three-digit integer followed by a single space and a status explanation)r   splitr   r   r   r   r   r   )r"   status_code
status_intr   r   r	   r   w  s   
r   c                 C   s  t t| tu d| t| f  | D ]n}t t|tu d|t|f  t t|dk |\}}t|d}t|d}t | dkd|  t d|voKd	|vd
|  t t|d|  t |	d of|	d d|  t
|rt dd|t
|df  qd S )Nz%Headers (%r) must be of type list: %rz1Individual headers (%r) must be of type tuple: %rr   Header namezHeader valuer"   zyThe Status header cannot be used; it conflicts with CGI script, and HTTP status is not given through headers (value: %r).
:z,Header names may not contain ':' or '\n': %rzBad header name: %r-_z#Names may not end in '-' or '_': %rr   z#Bad header value: %r (bad char: %r))r   r   rC   r   r   r   lower	header_researchendswithbad_header_value_regroup)r#   itemnamer   r   r   r	   r     sB   




r   c                 C   s   t | d} t| d dd }d}|D ]\}}t |d}| dkr0||vr) d S tdd|  q||vr>tdd|  d S d S )	Nr   r   r   )   i0  r   zcontent-typezJContent-Type header found in a %s response, which must not return content.z,No Content-Type header found in headers (%s))r   r   r   r   r   )r"   r#   codeNO_MESSAGE_BODYr   r   r   r   r	   r     s   

r   c                 C   s*   t | d u p
t| tu d| t| f  d S )Nz exc_info (%r) is not a tuple: %r)r   r   r   )r$   r   r   r	   r     s   r   c                 C   s   t t| ttf d d S )NzwYou should not return a string as your application iterator, instead return a single-item list containing a bytestring.)r   
isinstancer   r=   r[   r   r   r	   r.     s   r.   )r   __all__rerd   r   compiler   r   Warningr   r   r   r   r,   r-   r    rZ   r/   r+   r   r   r   r   r   r   r.   r   r   r   r	   <module>   s0   j

7#		#A