a
    nJhZ                     @   s  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#m$Z$ ddlm%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: dZ;er^ddl<m=Z= ee(e/dedge7f Z>ee7gee: f Z?e(dde'i i dddde@d
ZAG dd deBZCG dd deBZDejEdddd G d!d" d"ZFeee(eFf e/f ZGG d#d de!ZHdS )$    N)deque)suppress)escape)
HTTPStatus)Logger)TYPE_CHECKINGAny	AwaitableCallableDequeOptionalSequenceTupleTypeUnioncast   )AbstractAccessLoggerAbstractStreamWriter)BaseProtocol)ceil_timeoutset_exception)HttpProcessingErrorHttpRequestParserHttpVersion10RawRequestMessageStreamWriter)access_loggerserver_logger)EMPTY_PAYLOADStreamReader)tcp_keepalive)HTTPException)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__ r2   r2   F/var/www/shaz/venv/lib/python3.9/site-packages/aiohttp/web_protocol.pyr(   N   s   r(   c                   @   s   e Zd ZdZdS )r)   z-Payload was accessed after response was sent.Nr-   r2   r2   r2   r3   r)   R   s   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)r.   r/   r0   int__annotations__BaseExceptionstrr2   r2   r2   r3   r7   V   s   
r7   c                       s  e Zd 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dIe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d0d1d2Z'eedd3d4d5Z(eedd3d6d7Z)ddd8d9Z*e%ee+e%ge,e& f e-e&ef d:d;d<Z.ddd=d>Z/e%e&eed?d@dAZ0dJe%eee ee e&dCdDdEZ1e2e+e%ge,e& f dFdGdHZ3  Z4S )Kr'   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

    r   )_request_count
_keepalive_manager_request_handler_request_factory_tcp_keepalive_keepalive_time_keepalive_handle_keepalive_timeout_lingering_time	_messages_message_tail_waiter_task_handler_upgrade_payload_parser_request_parserZ_reading_pausedloggerdebug
access_logr   _close_force_close_current_request_timeout_ceil_thresholdg     R@TFi  i   g      $@i      )keepalive_timeoutr!   rP   access_log_classrR   access_log_formatrQ   max_line_sizemax_headersmax_field_sizelingering_timeread_bufsizeauto_decompresstimeout_ceil_thresholdr*   )managerlooprX   r!   rP   rY   rR   rZ   rQ   r[   r\   r]   r^   r_   r`   ra   c             
      s   t  | d| _d| _d | _|| _|j| _|j| _	|| _
d| _d | _|| _t|| _t | _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 S )Nr   Fg            )r[   r]   r\   Zpayload_exceptionr`   rW   )#super__init__r?   r@   rU   rA   request_handlerrB   Zrequest_factoryrC   rD   rE   rF   rG   floatrH   r   rI   rJ   rK   rL   rM   rN   r   r(   rO   rV   	TypeError
ValueErrorrP   rQ   rR   r   rS   rT   )selfrb   rc   rX   r!   rP   rY   rR   rZ   rQ   r[   r\   r]   r^   r_   r`   ra   	__class__r2   r3   rf      sV    
zRequestHandler.__init__)returnc                 C   s   d | jj| jd urdndS )Nz<{} {}>	connectedZdisconnected)formatrm   r.   	transportrk   r2   r2   r3   __repr__   s    zRequestHandler.__repr__c                 C   s   | j S N)rG   rr   r2   r2   r3   rX      s    z RequestHandler.keepalive_timeout      .@N)timeoutrn   c              
      s   d| _ | jdur| j  | jr*| j  ttjtj t|4 I dH P | j	durf| j	
t  | jdur| j s| jI dH  W d  I dH  q1 I dH s0    Y  W d   n1 s0    Y  | jdur| j  | jdur| j  d| _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)rT   rF   cancelrK   r   asyncioCancelledErrorTimeoutErrorr   rU   _cancelrL   donerq   close)rk   rv   r2   r2   r3   shutdown   s     



T



zRequestHandler.shutdown)rq   rn   c                    sX   t  | ttj|}| jr&t| | j| 	 | _
| jd usFJ | j| | d S rt   )re   connection_mader   rx   	TransportrD   r!   _loopcreate_taskstartrL   rA   )rk   rq   Zreal_transportrl   r2   r3   r     s    zRequestHandler.connection_made)r9   rn   c                    s   | j d u rd S | j | | t | | j j}d | _ d| _d | _d | _d | _| jd urb| j	  | j
d ur|d u r|td}| j
| | jd ur| j	  |r| jd ur| j	  d | _| jd ur| j  d | _d S )NTzConnection lost)rA   connection_lostre   handler_cancellationrT   rC   rB   rO   rF   rw   rU   ConnectionResetErrorr{   rK   rL   rN   Zfeed_eof)rk   r9   r   rl   r2   r3   r   %  s0    








zRequestHandler.connection_lost)parserrn   c                 C   s2   | j d u sJ || _ | jr.| j | j d| _d S )Nrd   )rN   rJ   	feed_data)rk   r   r2   r2   r3   
set_parserI  s
    zRequestHandler.set_parserc                 C   s   d S rt   r2   rr   r2   r2   r3   eof_receivedS  s    zRequestHandler.eof_received)datarn   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:   Frd   r2   r   )rT   rS   rN   rM   rO   r   r   r7   r:   r   r?   rI   appendrK   r|   Z
set_resultrJ   r}   )
rk   r   messagesZupgradedtailr9   msgpayloadwaitereofr2   r2   r3   data_receivedV  s4    
zRequestHandler.data_received)valrn   c                 C   s    || _ | jr| j  d| _dS )zMSet keep-alive connection mode.

        :param bool val: new state.
        N)r@   rF   rw   )rk   r   r2   r2   r3   
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)rS   rK   rw   rr   r2   r2   r3   r}     s    zRequestHandler.closec                 C   s4   d| _ | jr| j  | jdur0| j  d| _dS )zForcefully close connection.TN)rT   rK   rw   rq   r}   rr   r2   r2   r3   force_close  s    


zRequestHandler.force_close)requestresponsetimern   c                 C   s(   | j d ur$| j ||| j |  d S rt   )r   logr   r   )rk   r   r   r   r2   r2   r3   
log_access  s    
zRequestHandler.log_access)argskwrn   c                 O   s   | j r| jj |i | d S rt   )rQ   rP   rk   r   r   r2   r2   r3   	log_debug  s    zRequestHandler.log_debugc                 O   s   | j j|i | d S rt   )rP   	exceptionr   r2   r2   r3   log_exception  s    zRequestHandler.log_exceptionc                 C   sT   | j s| jsd S | j| j }| jr<| j |kr<|   d S | j| j	| j
| _d S rt   )rT   r@   rE   rG   rK   r   r   r   Z
call_laterKEEPALIVE_RESCHEDULE_DELAY_process_keepaliverF   )rk   nextr2   r2   r3   r     s    z!RequestHandler._process_keepalive)r   
start_timerg   rn   c              
      sZ  | j d usJ z,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 }~n~d }~0  t	y" } z.| |d|}| |||I d H }W Y d }~n8d }~0 0 t
|ddr>tdt | |||I d H }||fS )NzRequest handler timed out.exc_infoi    Z__http_exception__Fzlreturning HTTPException object is deprecated (#2415) and will be removed, please raise the exception instead)rB   rU   r"   finish_responserx   ry   rz   r   handle_error	ExceptiongetattrwarningswarnDeprecationWarning)rk   r   r   rg   respr9   resetr2   r2   r3   _handle_request  s2    ((*zRequestHandler._handle_requestc              
      s  | j }| j}|dusJ | j}|dus*J | j}d}| jdusBJ | jdusPJ | js| jszHz| | _	| j	I dH  W n" t
jy   Y W d| _	qY n0 W d| _	nd| _	0 | j \}}| }| jd7  _t| |}	t|tr| |}
t}n| j}
| ||| |	|}z$z| j | |||
}z|I dH \}}W n t
jtfy   | d Y W W | jdu r|dur| d nX| js| jr| js|dur| j  }|| _| jdu r||| | j| _nqqY n0 ~|r~| d W W | jdu r"|dur"| d nX| js| jr| js|durz| j  }|| _| jdu rz||| | j| _nqqt|j | _|! s| j"}| jsf|rf| d| | }|| }t#t
j$t
j |! sF||k rFt%|| 4 I dH & |& I dH  W d  I dH  q:1 I dH s00    Y  | }qW d   n1 s\0    Y  |! s| js| d | '  t(|t)  W n t
jy<   | d Y W | jdu r|dur| d nX| js| jr| js|dur4| j  }|| _| jdu r4||| | j| _nqqY n~ t*y~ } z*| j+rb| j,d	|d
 | -  W Y d}~nDd}~0  t.y } z"| j,d|d
 | -  W Y d}~n
d}~0 0 W | jdu r|dur| d nX| js| jr| js|dur6| j  }|| _| jdu r6||| | j| _nqqP| jdu rZ|durZ| d n`| js| jr| js|dur| j  }|| _| jdu r||| | j| _n   Y q0 qP| jsd| _| jdur| 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   z&Ignored premature client disconnectionz'Ignored premature client disconnection.z(Ignored premature client disconnection 2z'Start lingering close timer for %s sec.zUncompleted request.z'Ignored premature client disconnection zUnhandled runtime exceptionr   zUnhandled exception)/r   rL   rA   rG   rC   rB   rT   rI   Zcreate_futurerK   rx   ry   popleftr   Zrequests_countr   
isinstancer7   _make_error_handlerERRORr   r   ConnectionErrorr   rq   r@   rS   rE   rF   Zcall_atr   boolr   Zis_eofrH   r   rz   r   Zreadanyr}   r   r)   RuntimeErrorrQ   r   r   r   )rk   rc   handlerrb   rX   r   r:   r   r   writerrg   r   taskr   nowr^   Zend_tr9   r2   r2   r3   r     s   	




/




)



<,

	


 





zRequestHandler.start)r   r   r   rn   c                    s   | j dur6| j d d| _| jr6| j | j d| _z
|j}W n2 tyr   |du r`tdntd|Y n0 z ||I dH  |	 I dH  W n" t
y   | ||| Y dS 0 | ||| dS d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.
        NFrd   z+Missing return statement on request handlerz7Web-handler should return a response instance, got {!r}T)rO   Zset_upgradedrM   rJ   r   prepareAttributeErrorr   rp   	write_eofr   r   )rk   r   r   r   Zprepare_methr2   r2   r3   r   Z  s0    




zRequestHandler.finish_responser   )r   r8   r9   r:   rn   c           
      C   s   | j d|d |jjdkr"tdd}|tjkrdtj}tjj}d}| jr~t	t
 t }W d   n1 st0    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.
        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

)r8   textcontent_type)r   r   Zoutput_sizer   r   INTERNAL_SERVER_ERRORrp   descriptionrQ   r   r   	traceback
format_excheadersgethtml_escaper%   r   )
rk   r   r8   r9   r:   ctr   r   tbr   r2   r2   r3   r     s8    

&zRequestHandler.handle_error)err_inforn   c                    s   t td fdd}|S )N)r   rn   c                    s    |  j j jS rt   )r   r8   r9   r:   )r   r   rk   r2   r3   r     s    z3RequestHandler._make_error_handler.<locals>.handler)r$   r&   )rk   r   r   r2   r   r3   r     s    z"RequestHandler._make_error_handler)ru   )r   NN)5r.   r/   r0   r1   r   	__slots__r   r#   r   Z
LOG_FORMATrx   ZAbstractEventLooprh   r   r   r   r   r>   r;   rf   rs   propertyrX   r   r~   Z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__r2   r2   rl   r3   r'   `   s   '"J$
'



'z(   4)Irx   Zasyncio.streamsr   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   Zhelpersr   r   r   r   r   r   r   r   r   r   streamsr   r    Ztcp_helpersr!   Zweb_exceptionsr"   Zweb_logr#   Zweb_requestr$   Zweb_responser%   r&   __all__Z
web_serverr*   Z_RequestFactoryZ_RequestHandlerURLr   r   r(   r)   sr7   Z_MsgTyper'   r2   r2   r2   r3   <module>   sl   4