a
    `gd                     @   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rrd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                   @   s   e Zd ZdZdS )r)   zPayload parsing error.N__name__
__module____qualname____doc__ r3   r3   b/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/aiohttp/web_protocol.pyr)   P   s   r)   c                   @   s   e Zd ZdZdS )r*   z-Payload was accessed after response was sent.Nr.   r3   r3   r3   r4   r*   T   s   r*   )Z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)r/   r0   r1   int__annotations__BaseExceptionstrr3   r3   r3   r4   r7   [   s   
r7   c                       s  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e	j
eeeee eeeeeeeeeed fddZedddZeedddZdHee ddddZe	jdd fddZee dd fddZedd d!d"Zddd#d$Zedd%d&d'Z edd(d)d*Z!ddd+d,Z"ddd-d.Z#e$e%edd/d0d1Z&eedd2d3d4Z'eedd2d5d6Z(ddd7d8Z)e$ee*e$ge+e% f e,e%ef d9d:d;Z-ddd<d=Z.e$e%ee,e%ef d>d?d@Z/dIe$eee ee e%dBdCdDZ0e1e*e$ge+e% f dEdFdGZ2  Z3S )Jr(   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_parserZ_reading_pausedloggerdebug
access_logr   _close_force_close_current_request_timeout_ceil_threshold_request_in_progressi.  TFi  i   g      $@i      )keepalive_timeoutr!   rQ   access_log_classrS   access_log_formatrR   max_line_sizemax_headersmax_field_sizelingering_timeread_bufsizeauto_decompresstimeout_ceil_thresholdr+   )managerlooprZ   r!   rQ   r[   rS   r\   rR   r]   r^   r_   r`   ra   rb   rc   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y   Y n0 || _|	| _|| _ |r|||| _!nd | _!d| _"d| _#d| _$d S )Nr   Fg            )r]   r_   r^   Zpayload_exceptionrb   rY   )%super__init__r?   r@   rV   rA   request_handlerrB   Zrequest_factoryrC   rD   rE   rF   rG   floatrH   r   rI   rJ   rL   rK   rM   rN   rO   r   r)   rP   rW   	TypeError
ValueErrorrQ   rR   rS   r   rT   rU   rX   )selfrd   re   rZ   r!   rQ   r[   rS   r\   rR   r]   r^   r_   r`   ra   rb   rc   	__class__r3   r4   rh      sZ    
zRequestHandler.__init__)returnc                 C   s   d | jj| jd urdndS )Nz<{} {}>	connecteddisconnected)formatro   r/   	transportrm   r3   r3   r4   __repr__   s    zRequestHandler.__repr__c                 C   s   | j S N)rG   ru   r3   r3   r4   rZ      s    z RequestHandler.keepalive_timeout      .@N)timeoutrp   c              	      s  d| _ | jdur| j  | jr| j | _zLt|4 I dH " | jI dH  W d  I dH  qv1 I dH sl0    Y  W n@ tj	tj
fy   d| _tjdkrt  }r| r Y n0 zt|4 I dH \ | jdur| jt	  | jdur| j st| jI dH  W d  I dH  q@1 I dH s60    Y  W nB tj	tj
fy   tjdkrt  }r| r Y n0 | 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      )rU   rF   cancelrX   _loopcreate_futurerK   r   asyncioCancelledErrorTimeoutErrorsysversion_infocurrent_task
cancellingrV   _cancelrM   doneshieldforce_close)rm   ry   taskr3   r3   r4   shutdown  sD    

:

D

zRequestHandler.shutdown)rt   rp   c                    s   t  | ttj|}| jr&t| | jd us4J | j| | | j}t	j
dkrhtj|  |dd}n||  }|| _d S )Nr{      Tre   Zeager_start)rg   connection_mader   r   	TransportrD   r!   rA   r~   r   r   Taskstartcreate_taskrM   )rm   rt   Zreal_transportre   r   rn   r3   r4   r   6  s    
zRequestHandler.connection_made)r9   rp   c                    s   | j d u rd S | j | | | j j}|   t | d | _ d | _d | _d | _| jd urd| j	  | j
d ur|d u r~td}| j
| |r| jd ur| j	  d | _| jd ur| j  d | _d S )NzConnection lost)rA   connection_losthandler_cancellationr   rg   rC   rB   rP   rF   r}   rV   ConnectionResetErrorr   rM   rO   feed_eof)rm   r9   r   rn   r3   r4   r   G  s,    






zRequestHandler.connection_lost)parserrp   c                 C   s2   | j d u sJ || _ | jr.| j | j d| _d S )Nrf   )rO   rJ   	feed_data)rm   r   r3   r3   r4   
set_parserg  s
    zRequestHandler.set_parserc                 C   s   d S rw   r3   ru   r3   r3   r4   eof_receivedq  s    zRequestHandler.eof_received)datarp   c           
   
   C   sD  | j s| jrd S | jd u r| js| jd us.J z| j|\}}}W nB ty } z*td||jdt	fg}d}d}W Y d }~n
d }~0 0 |pdD ]&\}}|  j
d7  _
| j||f q| j}|r|d ur| s|d  || _|r|r|| _nN| jd u r| jr|r|  j|7  _n$|r@| j|\}	}|	r@|   d S )Ni  )r8   r9   r:   Frf   r3   r   )rU   rT   rO   rN   rP   r   r   r7   r:   r   r?   rI   appendrL   r   
set_resultrJ   close)
rm   r   messagesZupgradedtailr9   msgpayloadwaitereofr3   r3   r4   data_receivedt  s4    
zRequestHandler.data_received)valrp   c                 C   s    || _ | jr| j  d| _dS )zMSet keep-alive connection mode.

        :param bool val: new state.
        N)r@   rF   r}   )rm   r   r3   r3   r4   
keep_alive  s    
zRequestHandler.keep_alivec                 C   s   d| _ | jr| j  dS )zClose connection.

        Stop accepting new pipelining messages and close
        connection when handlers done processing messages.
        TN)rT   rL   r}   ru   r3   r3   r4   r     s    zRequestHandler.closec                 C   s4   d| _ | jr| j  | jdur0| j  d| _dS )zForcefully close connection.TN)rU   rL   r}   rt   r   ru   r3   r3   r4   r     s    


zRequestHandler.force_close)requestresponsetimerp   c                 C   s0   | j d ur,| j jr,| j ||| j |  d S rw   )r   enabledlogr~   r   )rm   r   r   r   r3   r3   r4   
log_access  s    zRequestHandler.log_access)argskwrp   c                 O   s   | j r| jj |i | d S rw   )rR   rQ   rm   r   r   r3   r3   r4   	log_debug  s    zRequestHandler.log_debugc                 O   s   | j j|i | d S rw   )rQ   	exceptionr   r3   r3   r4   log_exception  s    zRequestHandler.log_exceptionc                 C   sb   d | _ | js| jsd S | j}| }| j}||k rF||| j| _ d S | jr^| j	 s^| 
  d S rw   )rF   rU   r@   r~   r   rE   call_at_process_keepaliverL   r   r   )rm   re   now
close_timer3   r3   r4   r     s    z!RequestHandler._process_keepalive)r   
start_timeri   rp   c              
      s  d| _ zvz,z|| _||I d H }W d | _nd | _0 W n tyv } z(|}| |||I d H \}}W Y d }~nd }~0  tjy    Y n tjy } z>| jd|d | |d}| |||I d H \}}W Y d }~nd }~0  t	y* } z2| |d|}| |||I d H \}}W Y d }~n<d }~0 0 t
|ddrFtdt | |||I d H \}}W d| _ | jd ur| jd  n d| _ | jd ur| jd  0 ||fS )	NTzRequest handler timed out.exc_infoi    Z__http_exception__Fzlreturning HTTPException object is deprecated (#2415) and will be removed, please raise the exception instead)rX   rV   r"   finish_responser   r   r   r   handle_error	ExceptiongetattrwarningswarnDeprecationWarningrK   r   )rm   r   r   ri   respr9   resetr3   r3   r4   _handle_request  s>    ,,.zRequestHandler._handle_requestc              
      s6  | j }t|}|dusJ | j}|dus.J | j}d}| jdusFJ | jdusTJ | js| jsz |	 | _
| j
I dH  W d| _
nd| _
0 | j \}}| }| jd7  _t| |}	t|tr| |}
t}n| j}
| ||| |	|}zz| |||
}tjdkr tj||dd}n
||}z|I dH \}}W n ty   | d Y W W | jdu r~|dur~| d nZ| js| jr| js|dur| }|| }|| _| jdu r||| j | _nqqY n0 ~|rx| d W W | jdu r|dur| d nZ| js| jr| js|durt| }|| }|| _| jdu rt||| j | _nqqt!|j"| _|# s| j$}| jsx|rx| d	| | }|| }zv|# s2||k r2t%|| 4 I dH & |& I dH  W d  I dH  q&1 I dH s0    Y  | }qW nB tj'tj(fyv   tjd
krrt  }rr|) rr Y n0 |# s| js| d | *  |+t, W n\ tj'y   | d  Y n< t-y } z"| j.d|d | /  W Y d}~n
d}~0 0 W | jdu r*|dur*| d nZ| js| jr| js|dur| }|| }|| _| jdu r||| j | _nqqT| jdu r|dur| d nb| js
| jr| js|dur
| }|| }|| _| jdu r
||| j | _n   Y q0 qT| js2d| _0| jdur2| j*  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.rz   zUncompleted request.zUnhandled exceptionr   )1r~   r   r   rA   rG   rC   rB   rU   rI   r   rL   popleftr   Zrequests_countr   
isinstancer7   _make_error_handlerERRORr   r   r   r   r   ConnectionErrorr   rt   r@   rT   rE   rF   r   r   boolr   Zis_eofrH   r   Zreadanyr   r   r   r   set_exception_PAYLOAD_ACCESS_ERRORr   r   r   rM   )rm   re   handlerrd   rZ   r   r:   r   r   writerri   r   coror   r   r   r   r`   Zend_ttr9   r3   r3   r4   r     s    	






2


,

<


 

zRequestHandler.start)r   r   r   rp   c              	      s  |   | jdur>| jd d| _| jr>| j| j d| _z
|j}W nZ ty   |du rj| d n| d	| t
 }t|j|j|j|jd}|j}Y n0 z ||I dH  | I dH  W n( ty   | ||| |df Y S 0 | ||| |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.
        NFrf   z+Missing return statement on request handlerz7Web-handler should return a response instance, got {!r})r8   reasontextheadersT)Z_finishrP   Zset_upgradedrN   rJ   r   prepareAttributeErrorr   rs   r#   r&   r8   r   r   r   	write_eofr   r   )rm   r   r   r   Zprepare_methr9   r3   r3   r4   r   ~  s<    


zRequestHandler.finish_responser   )r   r8   r9   r:   rp   c           
      C   s  | j dkr*t|tr*| jjd|j|d n| jd|j|d |jjdkrPt	dd}|t
jkrdt
j}t
jj}d}| jrtt t }W d   n1 s0    Y  d	|jd
dv r|rt|}d| d}dj||d}d	}n|r|}|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 request from %sr   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

)r8   r   content_type)r?   r   r   rQ   rR   remoter   r   Zoutput_sizer   r   INTERNAL_SERVER_ERRORrs   descriptionr   r   	traceback
format_excr   gethtml_escaper&   r   )
rm   r   r8   r9   r:   ctr   r   tbr   r3   r3   r4   r     sD    

&zRequestHandler.handle_error)err_inforp   c                    s   t td fdd}|S )N)r   rp   c                    s    |  j j jS rw   )r   r8   r9   r:   )r   r   rm   r3   r4   r     s    z3RequestHandler._make_error_handler.<locals>.handler)r%   r'   )rm   r   r   r3   r   r4   r     s    z"RequestHandler._make_error_handler)rx   )r   NN)4r/   r0   r1   r2   	__slots__r   r$   r   Z
LOG_FORMATr   AbstractEventLooprj   r   r   r   r   r>   r;   rh   rv   propertyrZ   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   r7   r   __classcell__r3   r3   rn   r4   r(   e   s   '%N2 
'



+~
-   ?)Mr   Zasyncio.streamsr   r   r   collectionsr   
contextlibr   htmlr   r   httpr   loggingr   typingr   r   r	   r
   r   r   r   r   r   r   r   attrZyarlabcr   r   Zbase_protocolr   helpersr   r   r   r   r   r   Zhttp_exceptionsr   r   r   r   streamsr   r    Ztcp_helpersr!   Zweb_exceptionsr"   r#   Zweb_logr$   Zweb_requestr%   Zweb_responser&   r'   __all__Z
web_serverr+   Z_RequestFactoryZ_RequestHandlerURLr   r   r)   r*   r   sr7   Z_MsgTyper(   r3   r3   r3   r4   <module>   sr   4