o
    hg                     @   sj  d dl mZmZmZmZmZmZmZmZm	Z	 ddl
mZmZmZmZmZmZmZ ddlmZmZmZ ddlmZ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% ddl&m'Z'm(Z(m)Z) dd	l*m+Z+m,Z, g d
Z-G dd de)e)dZ.G dd de)e)dZ/dZ0de	eef de1fddZ2de3de	eef dee4e	ed ee5 f f fddZ6G dd dZ7dS )    )	AnyCallablecastDictListOptionalTupleTypeUnion   )ConnectionClosedDataEndOfMessageEventInformationalResponseRequestResponse)get_comma_headerhas_expect_100_continueset_comma_header)READERSReadersType)ReceiveBuffer)
_SWITCH_CONNECT_SWITCH_UPGRADECLIENTConnectionStateDONEERRORMIGHT_SWITCH_PROTOCOL	SEND_BODYSERVERSWITCHED_PROTOCOL)LocalProtocolErrorRemoteProtocolErrorSentinel)WRITERSWritersType)
Connection	NEED_DATAPAUSEDc                   @      e Zd ZdS )r)   N__name__
__module____qualname__ r0   r0   c/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/h11/_connection.pyr)   (       r)   )	metaclassc                   @   r+   )r*   Nr,   r0   r0   r0   r1   r*   ,   r2   r*   i @  eventreturnc                 C   s0   t | jd}d|v rdS t| dddk rdS dS )N
   connection   closeFhttp_version   1.1T)r   headersgetattr)r4   
connectionr0   r0   r1   _keep_aliveH   s   r=   request_methodr0   c                 C   s   t |ttfv s
J t |tu r4|jdv s+| dks+| dkr-d|j  kr)dk r-dS  ndS |jdks4J t|jd}|rE|dgksCJ d	S t|jd
}|rVdt|d ffS t |tu r^dS dS )N)   i0     HEAD   CONNECT   ,  )content-length)r      transfer-encoding   chunked)chunkedr0      content-lengthrD   r   )http/1.0r0   )typer   r   status_coder   r:   int)r>   r4   transfer_encodingscontent_lengthsr0   r0   r1   _body_framingQ   s&   
rO   c                   @   s  e Zd ZdZefdee deddfddZe	de
ee ee f fdd	Ze	dee fd
dZe	dee fddZe	defddZd3ddZdee ddfddZdedeee  fddZdee deddfddZdee dee deeef deedef  fddZ	d4de
ee ee f dee ddfdd Ze	deeef fd!d"Zd#eddfd$d%Z deeee! ee" f fd&d'Z#deeee! ee" f fd(d)Z$dedee fd*d+Z%dedee&e  fd,d-Z'd3d.d/Z(d0e)de)fd1d2Z*dS )5r(   aB  An object encapsulating the state of an HTTP connection.

    Args:
        our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If
            you're implementing a server, pass :data:`h11.SERVER`.

        max_incomplete_event_size (int):
            The maximum number of bytes we're willing to buffer of an
            incomplete event. In practice this mostly sets a limit on the
            maximum size of the request/response line + headers. If this is
            exceeded, then :meth:`next_event` will raise
            :exc:`RemoteProtocolError`.

    our_rolemax_incomplete_event_sizer5   Nc                 C   s   || _ |ttfvrtd||| _|  |tu rt| _nt| _t | _| 	| jd t
| _| 	| jd t| _t | _d| _d | _d | _d| _d S )Nz#expected CLIENT or SERVER, not {!r}F)_max_incomplete_event_sizer   r!   
ValueErrorformatrP   
their_roler   _cstate_get_io_objectr&   _writerr   _readerr   _receive_buffer_receive_buffer_closedtheir_http_version_request_method"client_is_waiting_for_100_continue)selfrP   rQ   r0   r0   r1   __init__   s    
zConnection.__init__c                 C   s   t | jjS )zA dictionary like::

           {CLIENT: <client state>, SERVER: <server state>}

        See :ref:`state-machine` for details.

        )dictrV   statesr_   r0   r0   r1   rb      s   	zConnection.statesc                 C      | j j| j S )zjThe current state of whichever role we are playing. See
        :ref:`state-machine` for details.
        )rV   rb   rP   rc   r0   r0   r1   	our_state      zConnection.our_statec                 C   rd   )znThe current state of whichever role we are NOT playing. See
        :ref:`state-machine` for details.
        )rV   rb   rU   rc   r0   r0   r1   their_state   rf   zConnection.their_statec                 C   s   | j tu o| jS N)rU   r   r^   rc   r0   r0   r1   !they_are_waiting_for_100_continue   s   z,Connection.they_are_waiting_for_100_continuec                 C   s4   t | jj}| j  d| _| jrJ | | dS )a  Attempt to reset our connection state for a new request/response
        cycle.

        If both client and server are in :data:`DONE` state, then resets them
        both to :data:`IDLE` state in preparation for a new request/response
        cycle on this same connection. Otherwise, raises a
        :exc:`LocalProtocolError`.

        See :ref:`keepalive-and-pipelining`.

        N)ra   rV   rb   start_next_cycler]   r^   _respond_to_state_changes)r_   
old_statesr0   r0   r1   rj      s
   

zConnection.start_next_cyclerolec                 C   s&   t | jj}| j| | | d S rh   )ra   rV   rb   process_errorrk   )r_   rm   rl   r0   r0   r1   _process_error   s   zConnection._process_errorr4   c                 C   sT   t |tu r|jdkrtS t |tu r(t| jjv r(d|j  kr%dk r(tS  d S d S )Ne   rB   rC   )rJ   r   rK   r   r   r   rV   pending_switch_proposals)r_   r4   r0   r0   r1   _server_switch_event   s   zConnection._server_switch_eventc                 C   sR  t | jj}|tu r't|tu r'|jdkr| jt t	|j
dr'| jt d }|tu r2| |}| j|t|| t|tu rF|j| _|| ju rbt|tttfv rbtttttf |}|j| _t|ttfv rztttttf |sz| j  t|tu rt|rd| _t|ttfv rd| _|tu rt|ttfv rd| _| || d S )NrA   s   upgradeTF)ra   rV   rb   r   rJ   r   methodprocess_client_switch_proposalr   r   r:   r   r!   rr   process_eventr]   rU   r   r   r   r
   r8   r\   r=   process_keep_alive_disabledr   r^   r   r   rk   )r_   rm   r4   rl   server_switch_eventr0   r0   r1   _process_event  s<   


zConnection._process_eventio_dict.c                 C   sV   | j j| }|tu r$ttt| jtttt	f |\}}|t | | S |
||fS rh   )rV   rb   r    rO   r   bytesr]   r
   r   r   get)r_   rm   r4   ry   stateframing_typeargsr0   r0   r1   rW   4  s   zConnection._get_io_objectrl   c                 C   sL   | j || j kr| | j|t| _| j|| j kr$| | j|t| _d S d S rh   )	re   rP   rW   r&   rX   rg   rU   r   rY   )r_   rl   r4   r0   r0   r1   rk   J  s
   z$Connection._respond_to_state_changesc                 C   s   t | j| jfS )ab  Data that has been received, but not yet processed, represented as
        a tuple with two elements, where the first is a byte-string containing
        the unprocessed data itself, and the second is a bool that is True if
        the receive connection was closed.

        See :ref:`switching-protocols` for discussion of why you'd want this.
        )rz   rZ   r[   rc   r0   r0   r1   trailing_dataU  s   	zConnection.trailing_datadatac                 C   s.   |r| j r	td|  j|7  _dS d| _ dS )a  Add data to our internal receive buffer.

        This does not actually do any processing on the data, just stores
        it. To trigger processing, you have to call :meth:`next_event`.

        Args:
            data (:term:`bytes-like object`):
                The new data that was just received.

                Special case: If *data* is an empty byte-string like ``b""``,
                then this indicates that the remote side has closed the
                connection (end of file). Normally this is convenient, because
                standard Python APIs like :meth:`file.read` or
                :meth:`socket.recv` use ``b""`` to indicate end-of-file, while
                other failures to read are indicated using other mechanisms
                like raising :exc:`TimeoutError`. When using such an API you
                can just blindly pass through whatever you get from ``read``
                to :meth:`receive_data`, and everything will work.

                But, if you have an API where reading an empty string is a
                valid non-EOF condition, then you need to be aware of this and
                make sure to check for such strings and avoid passing them to
                :meth:`receive_data`.

        Returns:
            Nothing, but after calling this you should call :meth:`next_event`
            to parse the newly received data.

        Raises:
            RuntimeError:
                Raised if you pass an empty *data*, indicating EOF, and then
                pass a non-empty *data*, indicating more data that somehow
                arrived after the EOF.

                (Calling ``receive_data(b"")`` multiple times is fine,
                and equivalent to calling it once.)

        z(received close, then received more data?TN)r[   RuntimeErrorrZ   )r_   r   r0   r0   r1   receive_data`  s
   '
zConnection.receive_datac                 C   s   | j }|tu r| jrtS |tu s|tu rtS | jd usJ | | j}|d u r<| js<| jr<t| jdr9| j	 }nt
 }|d u rBt}|S )Nread_eof)rg   r   rZ   r*   r   r"   rY   r[   hasattrr   r   r)   )r_   r|   r4   r0   r0   r1   _extract_next_receive_event  s   z&Connection._extract_next_receive_eventc              
   C   s   | j tu r	tdz0|  }|ttfvr| | jtt	| |tu r7t
| j| jkr0tddd| jr7td|W S  ty] } z| | j t|trQ|  n W Y d}~dS d}~ww )aF  Parse the next event out of our receive buffer, update our internal
        state, and return it.

        This is a mutating operation -- think of it like calling :func:`next`
        on an iterator.

        Returns:
            : One of three things:

            1) An event object -- see :ref:`events`.

            2) The special constant :data:`NEED_DATA`, which indicates that
               you need to read more data from your socket and pass it to
               :meth:`receive_data` before this method will be able to return
               any more events.

            3) The special constant :data:`PAUSED`, which indicates that we
               are not in a state where we can process incoming data (usually
               because the peer has finished their part of the current
               request/response cycle, and you have not yet called
               :meth:`start_next_cycle`). See :ref:`flow-control` for details.

        Raises:
            RemoteProtocolError:
                The peer has misbehaved. You should close the connection
                (possibly after sending some kind of 4xx response).

        Once this method returns :class:`ConnectionClosed` once, then all
        subsequent calls will also return :class:`ConnectionClosed`.

        If this method raises any exception besides :exc:`RemoteProtocolError`
        then that's a bug -- if it happens please file a bug report!

        If this method raises any exception then it also sets
        :attr:`Connection.their_state` to :data:`ERROR` -- see
        :ref:`error-handling` for discussion.

        z+Can't receive data when peer state is ERRORzReceive buffer too longi  )error_status_hintz#peer unexpectedly closed connectionN)rg   r   r$   r   r)   r*   rx   rU   r   r   lenrZ   rR   r[   BaseExceptionro   
isinstancer#   !_reraise_as_remote_protocol_error)r_   r4   excr0   r0   r1   
next_event  s,   
(

zConnection.next_eventc                 C   s    |  |}|du rdS d|S )a  Convert a high-level event into bytes that can be sent to the peer,
        while updating our internal state machine.

        Args:
            event: The :ref:`event <events>` to send.

        Returns:
            If ``type(event) is ConnectionClosed``, then returns
            ``None``. Otherwise, returns a :term:`bytes-like object`.

        Raises:
            LocalProtocolError:
                Sending this event at this time would violate our
                understanding of the HTTP/1.1 protocol.

        If this method raises any exception then it also sets
        :attr:`Connection.our_state` to :data:`ERROR` -- see
        :ref:`error-handling` for discussion.

        N    )send_with_data_passthroughjoin)r_   r4   	data_listr0   r0   r1   send  s   

zConnection.sendc                 C   s   | j tu r	tdz/t|tu r| |}| j}| | j| t|t	u r(W dS |dus.J g }|||j
 |W S    | | j  )ah  Identical to :meth:`send`, except that in situations where
        :meth:`send` returns a single :term:`bytes-like object`, this instead
        returns a list of them -- and when sending a :class:`Data` event, this
        list is guaranteed to contain the exact object you passed in as
        :attr:`Data.data`. See :ref:`sendfile` for discussion.

        z'Can't send data when our state is ERRORN)re   r   r#   rJ   r   &_clean_up_response_headers_for_sendingrX   rx   rP   r   appendro   )r_   r4   writerr   r0   r0   r1   r     s    

z%Connection.send_with_data_passthroughc                 C   s   |  | j dS )zNotify the state machine that we failed to send the data it gave
        us.

        This causes :attr:`Connection.our_state` to immediately become
        :data:`ERROR` -- see :ref:`error-handling` for discussion.

        N)ro   rP   rc   r0   r0   r1   send_failed'  s   zConnection.send_failedresponsec                 C   s   t |tu sJ |j}d}tt| j}|dkrd}t||\}}|dv rIt|dg }| jd u s4| jdk rBt|dg }| jdkrAd}nt|dd	g}| j	j
rO|rhtt|d
}|d |d t|d
t|}t||j|j|jdS )NFr@   s   GET)rG   rI   rH   r9   rE   TrF   r6   s
   keep-aliver7   )r:   rK   r8   reason)rJ   r   r:   r   rz   r]   rO   r   r\   rV   
keep_alivesetr   discardaddsortedrK   r8   r   )r_   r   r:   
need_closemethod_for_choosing_headersr}   _r<   r0   r0   r1   r   @  s4   	


z1Connection._clean_up_response_headers_for_sending)r5   Nrh   )+r-   r.   r/   __doc__!DEFAULT_MAX_INCOMPLETE_EVENT_SIZEr	   r%   rL   r`   propertyr   rb   re   rg   boolri   rj   ro   r   r   rr   rx   r
   r   r'   r   r   rW   rk   r   rz   r   r   r)   r*   r   r   r   r   r   r   r   r   r0   r0   r0   r1   r(      sd    
' 

0



.
 A
!r(   N)8typingr   r   r   r   r   r   r   r	   r
   _eventsr   r   r   r   r   r   r   _headersr   r   r   _readersr   r   _receivebufferr   _stater   r   r   r   r   r   r   r    r!   r"   _utilr#   r$   r%   _writersr&   r'   __all__r)   r*   r   r   r=   rz   strrL   rO   r(   r0   r0   r0   r1   <module>   s*   ,$	0	

: