o
    Fhi                     @   s8  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 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/m0Z0 d	dl1m2Z2m3Z3 d	dl4m5Z5 d	dl6m7Z7m8Z8 d	dl9m:Z: d	dl;m<Z< d	dl=m>Z>m?Z? dZ@erd dlAZAd	dlBmCZC ee*e3de"dge<f ZDee<gee? f ZEe*dde)i i ddddeFd
ZGG dd deHZIG d d! d!eHZJeJ ZKejLdddd"G d#d$ d$ZMeee*eMf e3f ZNG d%d de$ZOdS )&    N)deque)suppress)escape)
HTTPStatus)Logger)TYPE_CHECKINGAny	AwaitableCallableDequeOptionalSequenceTupleTypeUnioncast)under_cached_property   )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__ r5   r5   G/var/www/html/venv/lib/python3.10/site-packages/aiohttp/web_protocol.pyr*   S       r*   c                   @   r/   )r+   z-Payload was accessed after response was sent.Nr0   r5   r5   r5   r6   r+   W   r7   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)r1   r2   r3   int__annotations__BaseExceptionstrr5   r5   r5   r6   r;   ^   s   
 r;   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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d" fd#d$Zedeeeeeeeef eeef f  fd%d&Zedefd'd(Zdad*ee dd+fd,d-Zd.e	jdd+f fd/d0Zd1ee dd+f fd2d3Z d4e!dd+fd5d6Z"dbd7d8Z#d9e$dd+fd:d;Z%d<edd+fd=d>Z&dbd?d@Z'dbdAdBZ(dCe)dDe*dEee dd+fdFdGZ+dHe!dIe!dd+fdJdKZ,dHe!dIe!dd+fdLdMZ-dbdNdOZ.dCe)dPee dQe/e)ge0e* f dee*ef fdRdSZ1dbdTdUZ2dCe)dVe*dPee dee*ef fdWdXZ3	Y	+	+dcdCe)dZed1ee d[ee de*f
d\d]Z4d^e5de/e)ge0e* f fd_d`Z6  Z7S )dr)   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_progress_logging_enabled_cachei.  TFi  i   g      $@i      )keepalive_timeoutr"   rV   access_log_classrX   access_log_formatrW   max_line_sizemax_headersmax_field_sizelingering_timeread_bufsizeauto_decompresstimeout_ceil_thresholdmanagerr,   loopra   r"   rV   rb   rX   rc   rW   rd   re   rf   rg   rh   ri   rj   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 || _|	| _|| _ |r{|||| _!| j!j"| _#nd | _!d| _#d| _$d| _%d| _&i | _'d S )Nr   Fg            )rd   rf   re   payload_exceptionri   r`   )(super__init__rC   rD   r[   rE   request_handlerrF   request_factoryrG   rH   rI   rJ   rK   floatrL   r   rM   rN   rP   rO   rQ   rR   rS   r   r*   rT   r\   	TypeError
ValueErrorrV   rW   rX   r   enabledr^   rY   rZ   r]   r_   )selfrk   rl   ra   r"   rV   rb   rX   rc   rW   rd   re   rf   rg   rh   ri   rj   	__class__r5   r6   rp      sb   

zRequestHandler.__init__returnc                 C   s    d | jj| jd urdS dS )Nz<{} {}>	connecteddisconnected)formatry   r1   	transportrw   r5   r5   r6   __repr__  s   zRequestHandler.__repr__zssl.SSLContextc                 C      | j du rdS | j dS )zReturn SSLContext if available.N
sslcontextr~   get_extra_infor   r5   r5   r6   ssl_context  s
   

zRequestHandler.ssl_contextc                 C   r   )zReturn peername if available.Npeernamer   r   r5   r5   r6   r     s
   

zRequestHandler.peernamec                 C   s   | j S N)rK   r   r5   r5   r6   ra     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      )rZ   rJ   cancelr]   _loopcreate_futurerO   r   asyncioCancelledErrorTimeoutErrorsysversion_infocurrent_task
cancellingr[   _cancelrQ   doneshieldforce_close)rw   r   taskr5   r5   r6   shutdown   sT   

(

	
(


	
zRequestHandler.shutdownr~   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rl   eager_start)ro   connection_mader   r   	TransportrH   r"   rE   r   r   r   Taskstartcreate_taskrQ   )rw   r~   real_transportrl   r   rx   r5   r6   r   R  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)rE   connection_losthandler_cancellationr   ro   rG   rF   rT   rJ   r   r[   ConnectionResetErrorr   rQ   rS   feed_eof)rw   r=   r   rx   r5   r6   r   c  s.   







zRequestHandler.connection_lostparserc                 C   s6   | j d u sJ || _ | jr| j | j d| _d S d S )Nrm   )rS   rN   	feed_data)rw   r   r5   r5   r6   
set_parser  s   
zRequestHandler.set_parserc                 C   s   d S r   r5   r   r5   r5   r6   eof_received  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>   Frm   r5   r   )rZ   rY   rS   rR   rT   r   r   r;   r>   r    rC   rM   appendrP   r   
set_resultrN   close)
rw   r   messagesupgradedtailr=   msgpayloadwaitereofr5   r5   r6   data_received  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)rD   rJ   r   )rw   r   r5   r5   r6   
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)rY   rP   r   r   r5   r5   r6   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)rZ   rP   r   r~   r   r   r5   r5   r6   r     s   



zRequestHandler.force_closerequestresponsetimec                 C   sH   | j d ur | j jr"tr|d usJ | j ||| j |  d S d S d S r   )r   rv   r   logr   r   )rw   r   r   r   r5   r5   r6   
log_access  s
   zRequestHandler.log_accessargskwc                 O   s    | j r| jj |i | d S d S r   )rW   rV   rw   r   r   r5   r5   r6   	log_debug  s   zRequestHandler.log_debugc                 O   s   | j j|i | d S r   )rV   	exceptionr   r5   r5   r6   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   )rJ   rZ   rD   r   r   rI   call_at_process_keepaliverP   r   r   )rw   rl   now
close_timer5   r5   r6   r     s   z!RequestHandler._process_keepalive
start_timerq   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]   r[   r#   finish_responser   r   r   r   handle_error	ExceptiongetattrwarningswarnDeprecationWarningrO   r   )rw   r   r   rq   respr=   resetr5   r5   r6   _handle_request  sL   $$$

zRequestHandler._handle_requestc              
      sJ  | j }| j}|dusJ | j}d}| jdusJ | jdus J | js| js<z| | _| jI dH  W d| _nd| _w | j	 \}}| j
rJ| nd}| jd7  _t| |}t|tre| |}	t}n| j}	| ||| || jput|}
zVz| |
||	}tjdkrtj||dd}n||}z	|I dH \}}W n" ty   | d Y W W d|
_| jdu r|dur| d nMw ~|r| d W W d|
_| jdu r|dur| d n/t|j| _ |! sw| j"}| jse|re| d	| | }|| }zB|! sB||k rBt#|| 4 I dH  |$ I dH  W d  I dH  n1 I dH s/w   Y  | }|! sB||k sW n! tj%tj&fyd   tjd
krbt  }rb|' rb Y nw |! sw| jsw| d | (  |)t* W n< tj%y   | d | +    t,y } z| j-d|d | +  W Y d}~nd}~w t.y   | +   w W d|
_| jdu r|dur| d nd|
_| jdu r|dur| d w w w | j r	| j/s	| js	| | }|| _0| j1du r|2|| j3| _1nn| jr$| js!d| _| 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   )4r   rE   rK   rG   rF   rZ   rM   r   rP   popleftr^   r   requests_countr   
isinstancer;   _make_error_handlerERRORrQ   r   r   r   r   r   r   r   ConnectionErrorr   _taskr~   boolr   rD   is_eofrL   r   readanyr   r   r   r   set_exception_PAYLOAD_ACCESS_ERRORr   r   r   rA   rY   rI   rJ   r   r   )rw   rl   rk   ra   r   r>   r   r   writerrq   r   coror   r   rg   r   end_ttr=   r   r5   r5   r6   r     s   	






6

0

*
	


s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.
        NFrm   z+Missing return statement on request handlerz7Web-handler should return a response instance, got {!r})r<   reasontextheadersT)_finishrT   set_upgradedrR   rN   r   prepareAttributeErrorr   r}   r$   r'   r<   r   r   r   	write_eofr   r   )rw   r   r   r   prepare_methr=   r5   r5   r6   r     s@   



zRequestHandler.finish_responser   r<   r>   c           
      C   s  | j dkrt|tr| jjd|j|d n	| jd|j|d |jjdkr(t	dd}|t
jkrdt
j}t
jj}d}| jrVtt t }W d   n1 sQw   Y  d	|jd
dv ru|rkt|}d| d}dj||d}d	}n
|ry|}|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

)r<   r   content_type)rC   r   r   rV   rW   remoter   r   output_sizer   r   INTERNAL_SERVER_ERRORr}   descriptionr   r   	traceback
format_excr   gethtml_escaper'   r   )
rw   r   r<   r=   r>   ctr   r   tbr   r5   r5   r6   r     sD   


zRequestHandler.handle_errorerr_infoc                    s   dt dtf fdd}|S )Nr   rz   c                    s    |  j j jS r   )r   r<   r=   r>   )r   r  rw   r5   r6   handler  s   z3RequestHandler._make_error_handler.<locals>.handler)r&   r(   )rw   r  r  r5   r  r6   r     s   z"RequestHandler._make_error_handler)r   )rz   N)r   NN)8r1   r2   r3   r4   	__slots__r   r%   r   
LOG_FORMATr   AbstractEventLooprs   r   r   r   r   rB   r?   rp   r   r   r   r   r   r   r   propertyra   r   BaseTransportr   rA   r   r   r   r   bytesr   r   r   r   r&   r(   r   r   r   r   r
   r	   r   r   r   r   r;   r   __classcell__r5   r5   rx   r6   r)   h   s    ''	
Q$
2 

'



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

+ 


-
>)Pr   asyncio.streamsr   r   r   collectionsr   
contextlibr   htmlr   r   httpr   loggingr   typingr   r   r	   r
   r   r   r   r   r   r   r   attryarl	propcacher   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__ssl
web_serverr,   _RequestFactory_RequestHandlerURLr   r   r*   r+   r   sr;   _MsgTyper)   r5   r5   r5   r6   <module>   sx    4