a
    h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# 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l/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9 dZ:erZddl;m<Z< ee'e.dedge6f Z=ee6gee9 f Z>e'dde&i i dddde?d
Z@G dd deAZBG dd deAZCejDdddd G d!d" d"ZEeee'eEf e.f ZFG d#d de!ZGd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)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__ r1   r1   Y/var/www/html/swiplay.fr/scambot/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,   r1   r1   r1   r2   r(   R   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-   r.   r/   int__annotations__BaseExceptionstrr1   r1   r1   r2   r5   V   s   
r5   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    rN   access_log_classrP   access_log_formatrO   max_line_sizemax_headersmax_field_sizelingering_timeread_bufsizeauto_decompresstimeout_ceil_thresholdr)   )managerlooprV   r    rN   rW   rP   rX   rO   rY   rZ   r[   r\   r]   r^   r_   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            )rY   r[   rZ   Zpayload_exceptionr^   rU   )#super__init__r=   r>   rS   r?   request_handlerr@   Zrequest_factoryrA   rB   rC   rD   rE   floatrF   r   rG   rH   rI   rJ   rK   rL   r   r'   rM   rT   	TypeError
ValueErrorrN   rO   rP   r   rQ   rR   )selfr`   ra   rV   r    rN   rW   rP   rX   rO   rY   rZ   r[   r\   r]   r^   r_   	__class__r1   r2   rd      sV    
zRequestHandler.__init__)returnc                 C   s   d | jj| jd urdndS )Nz<{} {}>	connectedZdisconnected)formatrk   r-   	transportri   r1   r1   r2   __repr__   s    zRequestHandler.__repr__c                 C   s   | j S N)rE   rp   r1   r1   r2   rV      s    z RequestHandler.keepalive_timeout      .@N)timeoutrl   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)rR   rD   cancelrI   r   asyncioCancelledErrorTimeoutErrorr   rS   _cancelrJ   donero   close)ri   rt   r1   r1   r2   shutdown   s     



T



zRequestHandler.shutdown)ro   rl   c                    sX   t  | ttj|}| jr&t| | j| 	 | _
| jd usFJ | j| | d S rr   )rc   connection_mader   rv   	TransportrB   r    _loopcreate_taskstartrJ   r?   )ri   ro   Zreal_transportrj   r1   r2   r}     s    zRequestHandler.connection_made)r7   rl   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)r?   connection_lostrc   handler_cancellationrR   rA   r@   rM   rD   ru   rS   ConnectionResetErrorry   rI   rJ   rL   Zfeed_eof)ri   r7   r   rj   r1   r2   r   %  s0    








zRequestHandler.connection_lost)parserrl   c                 C   s2   | j d u sJ || _ | jr.| j | j d| _d S )Nrb   )rL   rH   	feed_data)ri   r   r1   r1   r2   
set_parserI  s
    zRequestHandler.set_parserc                 C   s   d S rr   r1   rp   r1   r1   r2   eof_receivedS  s    zRequestHandler.eof_received)datarl   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  )r6   r7   r8   Frb   r1   r   )rR   rQ   rL   rK   rM   r   r   r5   r8   r   r=   rG   appendrI   rz   Z
set_resultrH   r{   )
ri   r   messagesZupgradedtailr7   msgpayloadwaitereofr1   r1   r2   data_receivedV  s4    
zRequestHandler.data_received)valrl   c                 C   s    || _ | jr| j  d| _dS )zMSet keep-alive connection mode.

        :param bool val: new state.
        N)r>   rD   ru   )ri   r   r1   r1   r2   
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)rQ   rI   ru   rp   r1   r1   r2   r{     s    zRequestHandler.closec                 C   s4   d| _ | jr| j  | jdur0| j  d| _dS )zForcefully close connection.TN)rR   rI   ru   ro   r{   rp   r1   r1   r2   force_close  s    


zRequestHandler.force_close)requestresponsetimerl   c                 C   s(   | j d ur$| j ||| j |  d S rr   )r   logr   r   )ri   r   r   r   r1   r1   r2   
log_access  s    
zRequestHandler.log_access)argskwrl   c                 O   s   | j r| jj |i | d S rr   )rO   rN   ri   r   r   r1   r1   r2   	log_debug  s    zRequestHandler.log_debugc                 O   s   | j j|i | d S rr   )rN   	exceptionr   r1   r1   r2   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 rr   )rR   r>   rC   rE   rI   r   r   r   Z
call_laterKEEPALIVE_RESCHEDULE_DELAY_process_keepaliverD   )ri   nextr1   r1   r2   r     s    z!RequestHandler._process_keepalive)r   
start_timere   rl   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)r@   rS   r!   finish_responserv   rw   rx   r   handle_error	ExceptiongetattrwarningswarnDeprecationWarning)ri   r   r   re   respr7   resetr1   r1   r2   _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)  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   rJ   r?   rE   rA   r@   rR   rG   Zcreate_futurerI   rv   rw   popleftr   Zrequests_countr   
isinstancer5   _make_error_handlerERRORr   r   ConnectionErrorr   ro   r>   rQ   rC   rD   Zcall_atr   boolr   Zis_eofrF   r   rx   r   Zreadanyr{   Zset_exceptionr(   RuntimeErrorrO   r   r   r   )ri   ra   handlerr`   rV   r   r8   r   r   writerre   r   Ztaskr   nowr\   Zend_tr7   r1   r1   r2   r     s   	




/




)



<,

	


 





zRequestHandler.start)r   r   r   rl   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.
        NFrb   z+Missing return statement on request handlerz7Web-handler should return a response instance, got {!r}T)rM   Zset_upgradedrK   rH   r   prepareAttributeErrorr   rn   	write_eofr   r   )ri   r   r   r   Zprepare_methr1   r1   r2   r   Z  s0    




zRequestHandler.finish_responser   )r   r6   r7   r8   rl   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

)r6   textcontent_type)r   r   Zoutput_sizer   r   INTERNAL_SERVER_ERRORrn   descriptionrO   r   r   	traceback
format_excheadersgethtml_escaper$   r   )
ri   r   r6   r7   r8   ctr   r   tbr   r1   r1   r2   r     s8    

&zRequestHandler.handle_error)err_inforl   c                    s   t td fdd}|S )N)r   rl   c                    s    |  j j jS rr   )r   r6   r7   r8   )r   r   ri   r1   r2   r     s    z3RequestHandler._make_error_handler.<locals>.handler)r#   r%   )ri   r   r   r1   r   r2   r     s    z"RequestHandler._make_error_handler)rs   )r   NN)5r-   r.   r/   r0   r   	__slots__r   r"   r   Z
LOG_FORMATrv   ZAbstractEventLooprf   r   r   r   r   r<   r9   rd   rq   propertyrV   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   r5   r   __classcell__r1   r1   rj   r2   r&   `   s   '"J$
'



'z(   4)Hrv   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   Z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(   sr5   Z_MsgTyper&   r1   r1   r1   r2   <module>   sl   4