o
    `gc                     @   s$  d dl Z d dlZ d dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z d dlmZ d dlmZ d dlmZmZmZmZmZmZmZmZmZmZmZ d dlZd dlZdd	lmZm Z  dd
l!m"Z" ddl#m$Z$ ddlm%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z<m=Z= dZ>erddl?m@Z@ ee(e1de dge:f ZAee:gee= f ZBe(dde'i i ddddeCd
ZDG dd deEZFG dd  d eEZGeG ZHejIdddd!G d"d# d#ZJeee(eJf e1f ZKG d$d de"ZLdS )%    N)deque)suppress)escape)
HTTPStatus)Logger)TYPE_CHECKINGAny	AwaitableCallableDequeOptionalSequenceTupleTypeUnioncast   )AbstractAccessLoggerAbstractStreamWriter)BaseProtocol)ceil_timeout)HttpProcessingErrorHttpRequestParserHttpVersion10RawRequestMessageStreamWriter)BadHttpMethod)access_loggerserver_logger)EMPTY_PAYLOADStreamReader)tcp_keepalive)HTTPExceptionHTTPInternalServerError)AccessLogger)BaseRequest)ResponseStreamResponse)RequestHandlerRequestPayloadErrorPayloadAccessError)Serverr(   zasyncio.Task[None]UNKNOWN/TFc                   @      e Zd ZdZdS )r)   zPayload parsing error.N__name__
__module____qualname____doc__ r4   r4   O/var/www/html/propose/venv/lib/python3.10/site-packages/aiohttp/web_protocol.pyr)   P       r)   c                   @   r.   )r*   z-Payload was accessed after response was sent.Nr/   r4   r4   r4   r5   r*   T   r6   r*   )auto_attribsfrozenslotsc                   @   s&   e Zd ZU eed< eed< eed< dS )_ErrInfostatusexcmessageN)r0   r1   r2   int__annotations__BaseExceptionstrr4   r4   r4   r5   r:   [   s   
 r:   c                !       sF  e Zd ZdZdZddeeeejdddddd	dd
dddde	j
dedededee dedededededededededef  fddZdefd d!Zedefd"d#Zd\d%ee dd&fd'd(Zd)e	jdd&f fd*d+Zd,ee dd&f fd-d.Zd/edd&fd0d1Zd]d2d3Zd4edd&fd5d6Z d7edd&fd8d9Z!d]d:d;Z"d]d<d=Z#d>e$d?e%d@edd&fdAdBZ&dCedDedd&fdEdFZ'dCedDedd&fdGdHZ(d]dIdJZ)d>e$dKedLe*e$ge+e% f de,e%ef fdMdNZ-d]dOdPZ.d>e$dQe%dKede,e%ef fdRdSZ/	T	&	&d^d>e$dUed,ee dVee de%f
dWdXZ0dYe1de*e$ge+e% f fdZd[Z2  Z3S )_r(   aj  HTTP protocol implementation.

    RequestHandler handles incoming HTTP request. It reads request line,
    request headers and request payload and calls handle_request() method.
    By default it always returns with 404 response.

    RequestHandler handles errors in incoming request, like bad
    status line, bad headers or incomplete payload. If any error occurs,
    connection gets closed.

    keepalive_timeout -- number of seconds before closing
                         keep-alive connection

    tcp_keepalive -- TCP keep-alive is on, default is on

    debug -- enable debug mode

    logger -- custom logger object

    access_log_class -- custom class for access_logger

    access_log -- custom logging object

    access_log_format -- access log format string

    loop -- Optional event loop

    max_line_size -- Optional maximum header line size

    max_field_size -- Optional maximum header field size

    max_headers -- Optional maximum header size

    timeout_ceil_threshold -- Optional value to specify
                              threshold to ceil() timeout
                              values

    )_request_count
_keepalive_manager_request_handler_request_factory_tcp_keepalive_next_keepalive_close_time_keepalive_handle_keepalive_timeout_lingering_time	_messages_message_tail_handler_waiter_waiter_task_handler_upgrade_payload_parser_request_parser_reading_pausedloggerdebug
access_logr   _close_force_close_current_request_timeout_ceil_threshold_request_in_progressi.  TFi  i   g      $@i      )keepalive_timeoutr!   rU   access_log_classrW   access_log_formatrV   max_line_sizemax_headersmax_field_sizelingering_timeread_bufsizeauto_decompresstimeout_ceil_thresholdmanagerr+   loopr^   r!   rU   r_   rW   r`   rV   ra   rb   rc   rd   re   rf   rg   c             
      s  t  | d| _d| _d | _|| _|j| _|j| _	|| _
d| _d | _|| _t|| _t | _d| _d | _d | _d | _d| _d | _t| |||
||t|d| _d| _zt|| _W n ttfyc   Y nw || _|	| _|| _ |rv|||| _!nd | _!d| _"d| _#d| _$d S )Nr   Fg            )ra   rc   rb   payload_exceptionrf   r]   )%super__init__rB   rC   rZ   rD   request_handlerrE   request_factoryrF   rG   rH   rI   rJ   floatrK   r   rL   rM   rO   rN   rP   rQ   rR   r   r)   rS   r[   	TypeError
ValueErrorrU   rV   rW   r   rX   rY   r\   )selfrh   ri   r^   r!   rU   r_   rW   r`   rV   ra   rb   rc   rd   re   rf   rg   	__class__r4   r5   rm      s\   

zRequestHandler.__init__returnc                 C   s    d | jj| jd urdS dS )Nz<{} {}>	connecteddisconnected)formatru   r0   	transportrs   r4   r4   r5   __repr__   s   zRequestHandler.__repr__c                 C   s   | j S N)rJ   r{   r4   r4   r5   r^      s   z RequestHandler.keepalive_timeout      .@timeoutNc              	      s  d| _ | jdur| j  | jr^| j | _z&t|4 I dH  | jI dH  W d  I dH  n1 I dH s7w   Y  W n  tj	tj
fy]   d| _tjdkr[t  }r[| r[ Y nw z@t|4 I dH + | jduru| jt	  | jdur| j st| jI dH  W d  I dH  n1 I dH sw   Y  W n tj	tj
fy   tjdkrt  }r| r Y nw | jdur| j  |   dS )zDo worker process exit preparations.

        We need to clean up everything and stop accepting requests.
        It is especially important for keep-alive connections.
        TN      )rY   rI   cancelr\   _loopcreate_futurerN   r   asyncioCancelledErrorTimeoutErrorsysversion_infocurrent_task
cancellingrZ   _cancelrP   doneshieldforce_close)rs   r   taskr4   r4   r5   shutdown  sT   

(

	
(


	
zRequestHandler.shutdownrz   c                    s   t  | ttj|}| jrt| | jd usJ | j| | | j}t	j
dkr4tj|  |dd}n||  }|| _d S )Nr      Tri   eager_start)rl   connection_mader   r   	TransportrG   r!   rD   r   r   r   Taskstartcreate_taskrP   )rs   rz   real_transportri   r   rt   r4   r5   r   6  s   

zRequestHandler.connection_mader<   c                    s   | j d u rd S | j | | | j j}|   t | d | _ d | _d | _d | _| jd ur2| j	  | j
d urE|d u r?td}| j
| |rQ| jd urQ| j	  d | _| jd urc| j  d | _d S d S )NzConnection lost)rD   connection_losthandler_cancellationr   rl   rF   rE   rS   rI   r   rZ   ConnectionResetErrorr   rP   rR   feed_eof)rs   r<   r   rt   r4   r5   r   G  s.   







zRequestHandler.connection_lostparserc                 C   s6   | j d u sJ || _ | jr| j | j d| _d S d S )Nrj   )rR   rM   	feed_data)rs   r   r4   r4   r5   
set_parserg  s   
zRequestHandler.set_parserc                 C   s   d S r}   r4   r{   r4   r4   r5   eof_receivedq  s   zRequestHandler.eof_receiveddatac           
   
   C   sN  | j s| jrd S | jd u r~| js~| jd usJ z| j|\}}}W n! tyC } ztd||jdt	fg}d}d}W Y d }~nd }~ww |pGdD ]\}}|  j
d7  _
| j||f qH| j}|rn|d urn| sn|d  || _|rz|r||| _d S d S d S | jd u r| jr|r|  j|7  _d S |r| j|\}	}|	r|   d S d S d S )Ni  )r;   r<   r=   Frj   r4   r   )rY   rX   rR   rQ   rS   r   r   r:   r=   r   rB   rL   appendrO   r   
set_resultrM   close)
rs   r   messagesupgradedtailr<   msgpayloadwaitereofr4   r4   r5   data_receivedt  s>   

zRequestHandler.data_receivedvalc                 C   s$   || _ | jr| j  d| _dS dS )zMSet keep-alive connection mode.

        :param bool val: new state.
        N)rC   rI   r   )rs   r   r4   r4   r5   
keep_alive  s
   

zRequestHandler.keep_alivec                 C   s   d| _ | jr| j  dS dS )zClose connection.

        Stop accepting new pipelining messages and close
        connection when handlers done processing messages.
        TN)rX   rO   r   r{   r4   r4   r5   r     s   zRequestHandler.closec                 C   s8   d| _ | jr| j  | jdur| j  d| _dS dS )zForcefully close connection.TN)rY   rO   r   rz   r   r{   r4   r4   r5   r     s   



zRequestHandler.force_closerequestresponsetimec                 C   s8   | j d ur| j jr| j ||| j |  d S d S d S r}   )r   enabledlogr   r   )rs   r   r   r   r4   r4   r5   
log_access  s   zRequestHandler.log_accessargskwc                 O   s    | j r| jj |i | d S d S r}   )rV   rU   rs   r   r   r4   r4   r5   	log_debug  s   zRequestHandler.log_debugc                 O   s   | j j|i | d S r}   )rU   	exceptionr   r4   r4   r5   log_exception  s   zRequestHandler.log_exceptionc                 C   sj   d | _ | js	| jsd S | j}| }| j}||kr#||| j| _ d S | jr1| j	 s3| 
  d S d S d S r}   )rI   rY   rC   r   r   rH   call_at_process_keepaliverO   r   r   )rs   ri   now
close_timer4   r4   r5   r     s   z!RequestHandler._process_keepalive
start_timern   c              
      s  d| _ zzz|| _||I d H }W d | _nd | _w W nw ty; } z|}| |||I d H \}}W Y d }~ntd }~w tjyC     tjyn } z| jd|d | |d}| |||I d H \}}W Y d }~nAd }~w t	y } z| |d|}| |||I d H \}}W Y d }~nd }~ww t
|ddrtdt | |||I d H \}}W d| _ | jd ur| jd  ||fS d| _ | jd ur| jd  w w )	NTzRequest handler timed out.exc_infoi    __http_exception__Fzlreturning HTTPException object is deprecated (#2415) and will be removed, please raise the exception instead)r\   rZ   r"   finish_responser   r   r   r   handle_error	ExceptiongetattrwarningswarnDeprecationWarningrN   r   )rs   r   r   rn   respr<   resetr4   r4   r5   _handle_request  sL   $$$

zRequestHandler._handle_requestc              
      s<  | j }t|}|dusJ | j}|dusJ | j}d}| jdus$J | jdus+J | js| jsGz|	 | _
| j
I dH  W d| _
nd| _
w | j \}}| }| jd7  _t| |}	t|trk| |}
t}n| j}
| ||| |	|}zȐz[| |||
}tjdkrtj||dd}n||}z	|I dH \}}W nJ ty   | d Y W W | jdu r|dur| d n| js| jr| js|dur| }|| }|| _| jdu r||| j | _nnnw ~|r6| d W W | jdu r|dur| d n| js4| jr2| js2|dur0| }|| }|| _| jdu r0||| j | _nTnRnPt!|j"| _|# s| j$}| js|r| d	| | }|| }zB|# s||k rt%|| 4 I dH  |& I dH  W d  I dH  n1 I dH sw   Y  | }|# s||k sdW n! tj'tj(fy   tjd
krt  }r|) r Y nw |# s| js| d | *  |+t, W n, tj'y   | d   t-y } z| j.d|d | /  W Y d}~nd}~ww W | jdu r|dur| d no| js@| jr?| js?|dur>| }|| }|| _| jdu r>||| j | _nDnFnB| jdu rR|durR| d w | js| jr}| js}|dur|| }|| }|| _| jdu r|||| j | _w    Y nw | jr/| jsd| _0| jdur| j*  dS dS dS )a_  Process incoming request.

        It reads request line, request headers and request payload, then
        calls handle_request() method. Subclass has to override
        handle_request(). start() handles various exceptions in request
        or response handling. Connection is being closed always unless
        keep_alive(True) specified.
        Nr   r   Tr   z&Ignored premature client disconnectionz'Ignored premature client disconnection.z(Ignored premature client disconnection 2z'Start lingering close timer for %s sec.r   zUncompleted request.zUnhandled exceptionr   )1r   r   r   rD   rJ   rF   rE   rY   rL   r   rO   popleftr   requests_countr   
isinstancer:   _make_error_handlerERRORr   r   r   r   r   ConnectionErrorr   rz   rC   rX   rH   rI   r   r   boolr   is_eofrK   r   readanyr   r   r   r   set_exception_PAYLOAD_ACCESS_ERRORr   r   r   rP   )rs   ri   handlerrh   r^   r   r=   r   r   writerrn   r   coror   r   r   r   rd   end_ttr<   r4   r4   r5   r     s"  	







2

,

*
	




ezRequestHandler.startr   c              	      s  |   | jdur | jd d| _| jr | j| j d| _z|j}W n- tyR   |du r6| d n| d	| t
 }t|j|j|j|jd}|j}Y nw z||I dH  | I dH  W n tyw   | ||| |df Y S w | ||| |dfS )a   Prepare the response and write_eof, then log access.

        This has to
        be called within the context of any exception so the access logger
        can get exception information. Returns True if the client disconnects
        prematurely.
        NFrj   z+Missing return statement on request handlerz7Web-handler should return a response instance, got {!r})r;   reasontextheadersT)_finishrS   set_upgradedrQ   rM   r   prepareAttributeErrorr   ry   r#   r&   r;   r   r   r   	write_eofr   r   )rs   r   r   r   prepare_methr<   r4   r4   r5   r   ~  s@   



zRequestHandler.finish_responser   r;   r=   c           
      C   s  | j dkrt|tr| jjd|d n| jd|d |jjdkr$tdd}|t	j
kr{dt	j
}t	j
j}d}| jrRtt t }W d   n1 sMw   Y  d	|jd
dv rq|rgt|}d| d}dj||d}d	}n
|ru|}|d | }t|||d}	|	  |	S )zHandle errors.

        Returns HTTP response with specific status code. Logs additional
        information. It always closes current connection.
        r   zError handling requestr   r   zMResponse is sent already, cannot send another response with the error messagez
text/plainz{0.value} {0.phrase}Nz	text/htmlAccept z<h2>Traceback:</h2>
<pre>z</pre>zV<html><head><title>{title}</title></head><body>
<h1>{title}</h1>
{msg}
</body></html>
)titler   z

)r;   r   content_type)rB   r   r   rU   rV   r   r   output_sizer   r   INTERNAL_SERVER_ERRORry   descriptionr   r   	traceback
format_excr   gethtml_escaper&   r   )
rs   r   r;   r<   r=   ctr   r   tbr   r4   r4   r5   r     s<   


zRequestHandler.handle_errorerr_infoc                    s   dt dtf fdd}|S )Nr   rv   c                    s    |  j j jS r}   )r   r;   r<   r=   )r   r   rs   r4   r5   r     s   z3RequestHandler._make_error_handler.<locals>.handler)r%   r'   )rs   r   r   r4   r   r5   r     s   z"RequestHandler._make_error_handler)r~   )rv   N)r   NN)4r0   r1   r2   r3   	__slots__r   r$   r   
LOG_FORMATr   AbstractEventLooprp   r   r   r   r   rA   r>   rm   r|   propertyr^   r   r   BaseTransportr   r@   r   r   r   r   bytesr   r   r   r   r%   r'   r   r   r   r   r
   r	   r   r   r   r   r   r:   r   __classcell__r4   r4   rt   r5   r(   e   s    '%	
N2 

'



	




+}

-
:)Mr   asyncio.streamsr   r   r   collectionsr   
contextlibr   htmlr   r   httpr   loggingr   typingr   r   r	   r
   r   r   r   r   r   r   r   attryarlabcr   r   base_protocolr   helpersr   r   r   r   r   r   http_exceptionsr   r   r   r   streamsr   r    tcp_helpersr!   web_exceptionsr"   r#   web_logr$   web_requestr%   web_responser&   r'   __all__
web_serverr+   _RequestFactory_RequestHandlerURLr   r   r)   r*   r   sr:   _MsgTyper(   r4   r4   r4   r5   <module>   st    4