
    g-D                       d Z ddl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mZmZ ddlmZm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$m%Z%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8 ddl9m:Z:m;Z; ddl<m=Z=m>Z> ddl?m@Z@  G d de      ZA G d de      ZB G d de      ZC G d d      ZD G d d      ZEddZFd ZGy)zH
h2/connection
~~~~~~~~~~~~~

An implementation of a HTTP/2 connection.
    N)EnumIntEnum)InvalidPaddingError)GoAwayFrameWindowUpdateFrameHeadersFrame	DataFrame	PingFramePushPromiseFrameSettingsFrameRstStreamFramePriorityFrameContinuationFrameAltSvcFrameExtensionFrame)EncoderDecoder)
HPACKErrorOversizedHeaderListError   )H2Configuration)
ErrorCodes_error_code_from_int)	WindowUpdatedRemoteSettingsChangedPingReceivedPingAckReceivedSettingsAcknowledgedConnectionTerminatedPriorityUpdatedAlternativeServiceAvailableUnknownFrameReceived)
ProtocolErrorNoSuchStreamErrorFlowControlErrorFrameTooLargeErrorTooManyStreamsErrorStreamClosedErrorStreamIDTooLowErrorNoAvailableStreamIDErrorRFC1122ErrorDenialOfServiceError)FrameBuffer)SettingsSettingCodes)H2StreamStreamClosedBy)SizeLimitDictguard_increment_window)WindowManagerc                       e Zd ZdZdZdZdZy)ConnectionStater   r         N)__name__
__module____qualname__IDLECLIENT_OPENSERVER_OPENCLOSED     B/var/www/openai/venv/lib/python3.12/site-packages/h2/connection.pyr6   r6   (   s    DKKFrA   r6   c                   \    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZy)ConnectionInputsr   r   r7   r8                  	   
                              N)r9   r:   r;   SEND_HEADERSSEND_PUSH_PROMISE	SEND_DATASEND_GOAWAYSEND_WINDOW_UPDATE	SEND_PINGSEND_SETTINGSSEND_RST_STREAMSEND_PRIORITYRECV_HEADERSRECV_PUSH_PROMISE	RECV_DATARECV_GOAWAYRECV_WINDOW_UPDATE	RECV_PINGRECV_SETTINGSRECV_RST_STREAMRECV_PRIORITYSEND_ALTERNATIVE_SERVICERECV_ALTERNATIVE_SERVICEr@   rA   rB   rD   rD   /   sl    LIKIMOMLIKIMOM!!rA   rD   c                       e Zd ZdZdZy)AllowedStreamIDsr   r   N)r9   r:   r;   EVENODDr@   rA   rB   rj   rj   F   s    D
CrA   rj   c                   z   e Zd ZdZi ej
                  ej                  fdej                  fej
                  ej                  fdej                  fej
                  ej                  fdej
                  fej
                  ej                  fdej
                  fej
                  ej                  fdej
                  fej
                  ej                  fdej
                  fej
                  ej                  fdej
                  fej
                  ej                   fdej
                  fej
                  ej"                  fdej$                  fej
                  ej&                  fdej$                  fej
                  ej(                  fdej
                  fej
                  ej*                  fdej
                  fej
                  ej,                  fdej                  fej
                  ej.                  fdej                  fej                  ej                  fdej                  fej                  ej0                  fdej                  fej                  ej"                  fdej$                  fi ej                  ej                  fdej                  fej                  ej                  fdej                  fej                  ej                  fdej                  fej                  ej(                  fdej                  fej                  ej                  fdej                  fej                  ej2                  fdej                  fej                  ej4                  fdej                  fej                  ej&                  fdej$                  fej                  ej                  fdej                  fej                  ej                   fdej                  fej                  ej                  fdej                  fej                  ej6                  fdej                  fej                  ej8                  fdej                  fej                  ej*                  fdej                  fej                  ej.                  fdej                  fej                  ej                  fdej                  fej                  ej:                  fdej                  fi ej                  ej0                  fdej                  fej                  ej"                  fdej$                  fej                  ej                  fdej                  fej                  ej                  fdej                  fej                  ej                  fdej                  fej                  ej(                  fdej                  fej                  ej                  fdej                  fej                  ej4                  fdej                  fej                  ej&                  fdej$                  fej                  ej                  fdej                  fej                  ej                   fdej                  fej                  ej                  fdej                  fej                  ej*                  fdej                  fej                  ej6                  fdej                  fej                  ej8                  fdej                  fej                  ej,                  fdej                  fej                  ej.                  fdej                  fej$                  ej"                  fdej$                  fej$                  ej&                  fdej$                  fiZd Zd Z y)H2ConnectionStateMachinea7  
    A single HTTP/2 connection state machine.

    This state machine, while defined in its own class, is logically part of
    the H2Connection class also defined in this file. The state machine itself
    maintains very little state directly, instead focusing entirely on managing
    state transitions.
    Nc                 .    t         j                  | _        y N)r6   r<   stateselfs    rB   __init__z!H2ConnectionStateMachine.__init__   s    $))
rA   c                    t        |t              st        d      	 | j                  | j                  |f   \  }}|| _        | |       S g S # t
        $ r3 | j                  }t        j                  | _        t        d|d|      w xY w)z@
        Process a specific input in the state machine.
        z-Input must be an instance of ConnectionInputszInvalid input z
 in state )	
isinstancerD   
ValueError_transitionsrq   KeyErrorr6   r?   r#   )rs   input_functarget_state	old_states        rB   process_inputz&H2ConnectionStateMachine.process_input   s     &"23LMM	!%!2!2DJJ3G!HD, &DJvI  	

I(//DJ28)D 	s   A <B	)!r9   r:   r;   __doc__r6   r<   rD   rU   r=   r^   r>   r[   rd   rY   rb   rZ   rc   rX   r?   ra   r]   rf   rg   rh   rW   r_   r`   r\   re   rV   rx   rt   r~   r@   rA   rB   rn   rn   K   sI	   $u			/<<=?../u 
		/<<=?../u 
		/==>?''(u 
		/==>?''(u 
		/BBC?''(u 
		/BBC?''(u 
		/99:?''(u  
		/99:?''(#u$ 
		/;;<?))*'u( 
		/;;<?))*+u, 
		/==>?''(/u0 
		/==>?''(3u4 
		/HHI?../7u8 
		/HHI?../;u@ 
	$	$&6&C&CD?../CuD 
	$	$&6&@&@A?../GuH 
	$	$&6&B&BC?))*KuL 
	$	$&6&I&IJ?../OuP 
	$	$&6&@&@A?../SuT 
	$	$&6&D&DE?../WuX 
	$	$&6&D&DE?../[u\ 
	$	$&6&C&CD?../_u` 
	$	$&6&H&HI?../cud 
	$	$&6&@&@A?../guh 
	$	$&6&B&BC?))*kul 
	$	$&6&I&IJ?../oup 
	$	$&6&@&@A?../sut 
	$	$&6&D&DE?../wux 
	$	$&6&F&FG?../{u| 
	$	$&6&F&FG?../u@ 
	$	$&6&D&DE?../CuD 
	$	$55	7223IuN 
	$	$&6&C&CD?../QuR 
	$	$&6&H&HI?../UuV 
	$	$&6&@&@A?../YuZ 
	$	$&6&B&BC?))*]u^ 
	$	$&6&I&IJ?../aub 
	$	$&6&@&@A?../euf 
	$	$&6&D&DE?../iuj 
	$	$&6&D&DE?../mun 
	$	$&6&C&CD?../qur 
	$	$&6&@&@A?../uuv 
	$	$&6&B&BC?))*yuz 
	$	$&6&I&IJ?../}u~ 
	$	$&6&@&@A?../AuB 
	$	$&6&D&DE?../EuF 
	$	$&6&D&DE?../IuJ 
	$	$&6&F&FG?../MuN 
	$	$&6&F&FG?../QuR 
	$	$55	7223WuX 
	$	$55	7223]ub 
		!1!=!=>?))*			!1!=!=>?))*iuLn*rA   rn   c                      e Zd ZdZdZdZdZdZdZdZ	d;dZ
d Zd	 Zed
        Zed        Zed        Zd Zd Zd;dZd Zd Zd Z	 	 	 d<dZd=dZd Zd;dZd Zd Zd>dZ	 	 d?dZd Z	 	 d@dZ 	 	 dAdZ!d Z"d Z#d  Z$d;d!Z%d" Z&d# Z'd$ Z(d% Z)d& Z*d' Z+d( Z,d) Z-d* Z.d+ Z/d, Z0d- Z1d. Z2d/ Z3d0 Z4d1 Z5d2 Z6d3 Z7d4 Z8d5 Z9d6 Z:d7 Z;d8 Z<d9 Z=d: Z>y)BH2Connectiona  
    A low-level HTTP/2 connection object. This handles building and receiving
    frames and maintains both connection and per-stream state for all streams
    on this connection.

    This wraps a HTTP/2 Connection state machine implementation, ensuring that
    frames can only be sent/received when the connection is in a valid state.
    It also builds stream state machines on demand to ensure that the
    constraints of those state machines are met as well. Attempts to create
    frames that cannot be sent will raise a ``ProtocolError``.

    .. versionchanged:: 2.3.0
       Added the ``header_encoding`` keyword argument.

    .. versionchanged:: 2.5.0
       Added the ``config`` keyword argument. Deprecated the ``client_side``
       and ``header_encoding`` parameters.

    .. versionchanged:: 3.0.0
       Removed deprecated parameters and properties.

    :param config: The configuration for the HTTP/2 connection.

        .. versionadded:: 2.5.0

    :type config: :class:`H2Configuration <h2.config.H2Configuration>`
    i  i   ii   Nc                    t               | _        i | _        d| _        d| _        t               | _        t               | _        | j                  | j                  _
        || _        | j                  t        d      | _        t        | j                  j                  t        j                   dt        j"                  | j                  i      | _        t        | j                  j                         | _        | j&                  j(                  | _        | j&                  j,                  | _        | j$                  j,                  | _        t3        | j                  j                         | _        g | _        t9               | _        t=        | j>                        | _         tC        | j$                  j(                  	      | _"        tF        | jH                  tJ        | jL                  tN        | jP                  tR        | jT                  tV        | jX                  tZ        | j\                  t^        | j`                  tb        | jd                  tf        | jh                  tj        | jl                  tn        | jp                  tr        | jt                  i| _;        y )
Nr   T)client_sided   )clientinitial_values)r   )server)
size_limit)max_window_size)<rn   state_machinestreamshighest_inbound_stream_idhighest_outbound_stream_idr   encoderr   decoderDEFAULT_MAX_HEADER_LIST_SIZEmax_header_list_sizeconfigr   r.   r   r/   MAX_CONCURRENT_STREAMSMAX_HEADER_LIST_SIZElocal_settingsremote_settingsinitial_window_sizeoutbound_flow_control_windowmax_frame_sizemax_outbound_frame_sizemax_inbound_frame_sizer-   incoming_buffer_header_frames	bytearray_data_to_sendr2   MAX_CLOSED_STREAMS_closed_streamsr4   $_inbound_flow_control_window_managerr   _receive_headers_framer   _receive_push_promise_framer   _receive_settings_framer	   _receive_data_framer   _receive_window_update_framer
   _receive_ping_framer   _receive_rst_stream_framer   _receive_priority_framer   _receive_goaway_framer   _receive_naked_continuationr   _receive_alt_svc_framer   _receive_unknown_frame_frame_dispatch_table)rs   r   s     rB   rt   zH2Connection.__init__  s   57)*&*+'yy -1,M,M)
 ;;) DK" ';;**33S1155
  (4;;3J3J/JK
   44 	) (,';';'J'J$ '+&9&9&H&H#  +dkk6M6M2MN ! '[  -.. 

 5B //CC5
1 $55d>>477t//t@@t//D::47733t??44D77&
"rA   c                      |sy  xj                   dj                  d |D              z  c_         t         fd|D              sJ y )NrA   c              3   <   K   | ]  }|j                           y wrp   )	serialize).0fs     rB   	<genexpr>z4H2Connection._prepare_for_sending.<locals>.<genexpr>  s     &Efq{{}fs   c              3   P   K   | ]  }|j                   j                  k    y wrp   )body_lenr   )r   r   rs   s     rB   r   z4H2Connection._prepare_for_sending.<locals>.<genexpr>  s!     Nv!1::!=!==vs   #&)r   joinall)rs   framess   ` rB   _prepare_for_sendingz!H2Connection._prepare_for_sending  s=    chh&Ef&EEENvNNNNrA   c                 8   d}g }| j                   j                         D ]=  \  }}|j                  r|dz  |k(  r|dz  } |j                  s-|j	                  |       ? |D ]6  }| j                   j                  |      }|j                  | j                  |<   8 |S )z
        A common method of counting number of open streams. Returns the number
        of streams that are open *and* that have (stream ID % 2) == remainder.
        While it iterates, also deletes any closed streams.
        r   r7   r   )r   itemsopenclosedappendpop	closed_byr   )rs   	remaindercount	to_delete	stream_idstreams         rB   _open_streamszH2Connection._open_streams  s     	!%!3!3!5Iv{{	A :
  +	 "6 #I\\%%i0F.4.>.>D  + # rA   c                 b    t        | j                  j                        }| j                  |      S )z>
        The current number of open outbound streams.
        intr   r   r   )rs   outbound_numberss     rB   open_outbound_streamsz"H2Connection.open_outbound_streams  s+    
 t{{667!!"233rA   c                 d    t        | j                  j                         }| j                  |      S )z=
        The current number of open inbound streams.
        r   )rs   inbound_numberss     rB   open_inbound_streamsz!H2Connection.open_inbound_streams  s,    
 $++"9"99:!!/22rA   c                 .    | j                   j                  S )a7  
        The size of the inbound flow control window for the connection. This is
        rarely publicly useful: instead, use :meth:`remote_flow_control_window
        <h2.connection.H2Connection.remote_flow_control_window>`. This
        shortcut is largely present to provide a shortcut to this data.
        )r   current_window_sizerr   s    rB   inbound_flow_control_windowz(H2Connection.inbound_flow_control_window  s     88LLLrA   c                    | j                   j                  j                  d|       | j                  |      }|r| j                  n| j
                  }||k  rt        ||      |dz  t        |      k7  rt        d      t        || j                   | j                  j                  | j                  j                        }| j                   j                  j                  d|       | j                  |_        | j                  |_        || j                  |<   | j                   j                  j                  d| j                  j!                                |r	|| _        |S || _        |S )z
        Initiate a new stream.

        .. versionchanged:: 2.0.0
           Removed this function from the public API.

        :param stream_id: The ID of the stream to open.
        :param allowed_ids: What kind of stream ID is allowed.
        z#Attempting to initiate stream ID %dr7   zInvalid stream ID for peer.)r   inbound_window_sizeoutbound_window_sizezStream ID %d createdzCurrent streams: %s)r   loggerdebug_stream_id_is_outboundr   r   r)   r   r#   r0   r   r   r   r   r   r   keys)rs   r   allowed_idsoutboundhighest_stream_idss         rB   _begin_new_streamzH2Connection._begin_new_stream  sJ    	  19	
 ..y9/7D++** 	
 ))%i1BCCMc+..-  ;; $ 3 3 G G!%!5!5!I!I	
 	  !7C#'#>#> $($@$@!"#Y  !68I8I8KL.7D+  .7D*rA   c                    | j                   j                  j                  d       | j                  j	                  t
        j                         | j                   j                  rd}nd}t        d      }| j                  j                         D ]  \  }}||j                  |<    | j                   j                  j                  d| j                         | xj                  ||j                         z   z  c_        y)z
        Provides any data that needs to be sent at the start of the connection.
        Must be called for both clients and servers.
        zInitializing connections   PRI * HTTP/2.0

SM

rA   r   zSend Settings frame: %sN)r   r   r   r   r~   rD   r[   r   r   r   r   settingsr   r   )rs   preambler   settingvalues        rB   initiate_connectionz H2Connection.initiate_connection  s    
 	  !:;(()9)G)GH;;"":HH!"11779NGU"'AJJw :  %t':':	
 	h66rA   c                    | j                   j                  j                  d| j                         d}| j	                          | j                   j
                  rbt        d      }| j                  j                         D ]  \  }}||j                  |<    |j                         }t        j                  |      }nD|rBt        j                  |      }t        d      }|j                  |       | j                  |       | j                   j
                  rt        j                   nt        j"                  }| j                   j                  j                  d|       | j$                  j'                  |       | j)                  dt*        j,                         | j.                  d   j1                  | j                   j
                         |S )a  
        Call to initialise the connection object for use with an upgraded
        HTTP/2 connection (i.e. a connection negotiated using the
        ``Upgrade: h2c`` HTTP header).

        This method differs from :meth:`initiate_connection
        <h2.connection.H2Connection.initiate_connection>` in several ways.
        Firstly, it handles the additional SETTINGS frame that is sent in the
        ``HTTP2-Settings`` header field. When called on a client connection,
        this method will return a bytestring that the caller can put in the
        ``HTTP2-Settings`` field they send on their initial request. When
        called on a server connection, the user **must** provide the value they
        received from the client in the ``HTTP2-Settings`` header field to the
        ``settings_header`` argument, which will be used appropriately.

        Additionally, this method sets up stream 1 in a half-closed state
        appropriate for this side of the connection, to reflect the fact that
        the request is already complete.

        Finally, this method also prepares the appropriate preamble to be sent
        after the upgrade.

        .. versionadded:: 2.3.0

        :param settings_header: (optional, server-only): The value of the
             ``HTTP2-Settings`` header field received from the client.
        :type settings_header: ``bytes``

        :returns: For clients, a bytestring to put in the ``HTTP2-Settings``.
            For servers, returns nothing.
        :rtype: ``bytes`` or ``None``
        z(Upgrade connection. Current settings: %sNr   zProcess input %sr   )r   r   )r   r   r   r   r   r   r   r   r   serialize_bodybase64urlsafe_b64encodeurlsafe_b64decode
parse_bodyr   rD   rU   r^   r   r~   r   rj   rl   r   upgrade)rs   settings_header
frame_datar   r   r   connection_inputs          rB   initiate_upgrade_connectionz(H2Connection.initiate_upgrade_connection  sq   B 	  68K8K	
 
  ";;""a A"&"5"5";";"=&+

7# #> ))+J11*=J
 %66GOa ALL)((+ .2[[-D-D))!.. 	 	  !35EF(()9: 	8H8L8LMQ 7 78rA   c                 d    	 | j                   |   S # t        $ r | j                  ||      cY S w xY w)a  
        Gets a stream by its stream ID. Will create one if one does not already
        exist. Use allowed_ids to circumvent the usual stream ID rules for
        clients and servers.

        .. versionchanged:: 2.0.0
           Removed this function from the public API.
        )r   ry   r   )rs   r   r   s      rB   _get_or_create_streamz"H2Connection._get_or_create_streamD  s;    	B<<	** 	B)))[AA	Bs    //c                     	 | j                   |   S # t        $ rG | j                  |      }|r| j                  n| j                  }||kD  rt        |      t        |      w xY w)aB  
        Gets a stream by its stream ID. Raises NoSuchStreamError if the stream
        ID does not correspond to a known stream and is higher than the current
        maximum: raises if it is lower than the current maximum.

        .. versionchanged:: 2.0.0
           Removed this function from the public API.
        )r   ry   r   r   r   r$   r(   )rs   r   r   r   s       rB   _get_stream_by_idzH2Connection._get_stream_by_idR  so    	3<<	** 
	3229=H3;//.. 
 ,,'	22'	22
	3s
    AA!c                     | j                   s| j                  j                  rdnd}n| j                   dz   }| j                  j                  j	                  d|       || j
                  kD  rt        d      |S )a  
        Returns an integer suitable for use as the stream ID for the next
        stream created by this endpoint. For server endpoints, this stream ID
        will be even. For client endpoints, this stream ID will be odd. If no
        stream IDs are available, raises :class:`NoAvailableStreamIDError
        <h2.exceptions.NoAvailableStreamIDError>`.

        .. warning:: The return value from this function does not change until
                     the stream ID has actually been used by sending or pushing
                     headers on that stream. For that reason, it should be
                     called as close as possible to the actual use of the
                     stream ID.

        .. versionadded:: 2.0.0

        :raises: :class:`NoAvailableStreamIDError
            <h2.exceptions.NoAvailableStreamIDError>`
        :returns: The next free stream ID this peer can use to initiate a
            stream.
        :rtype: ``int``
        r   r7   zNext available stream ID %dzExhausted allowed stream IDs)r   r   r   r   r   HIGHEST_ALLOWED_STREAM_IDr*   )rs   next_stream_ids     rB   get_next_available_stream_idz)H2Connection.get_next_available_stream_idi  so    0 .."&++"9"9QqN!<<q@N  )>	
 D:::*+IJJrA   c                    | j                   j                  j                  d|       || j                  vrB| j                  j
                  }| j                  dz   |kD  rt        d|| j                  fz        | j                  j                  t        j                         | j                  |t        | j                   j                              }|j                  || j                   |      }	|duxs
 |duxs |du}
|
rR| j                   j                  st#        d      |	d   }|j$                  j'                  d       t)        ||||      |	d<   | j+                  |	       y)a  
        Send headers on a given stream.

        This function can be used to send request or response headers: the kind
        that are sent depends on whether this connection has been opened as a
        client or server connection, and whether the stream was opened by the
        remote peer or not.

        If this is a client connection, calling ``send_headers`` will send the
        headers as a request. It will also implicitly open the stream being
        used. If this is a client connection and ``send_headers`` has *already*
        been called, this will send trailers instead.

        If this is a server connection, calling ``send_headers`` will send the
        headers as a response. It is a protocol error for a server to open a
        stream by sending headers. If this is a server connection and
        ``send_headers`` has *already* been called, this will send trailers
        instead.

        When acting as a server, you may call ``send_headers`` any number of
        times allowed by the following rules, in this order:

        - zero or more times with ``(':status', '1XX')`` (where ``1XX`` is a
          placeholder for any 100-level status code).
        - once with any other status header.
        - zero or one time for trailers.

        That is, you are allowed to send as many informational responses as you
        like, followed by one complete response and zero or one HTTP trailer
        blocks.

        Clients may send one or two header blocks: one request block, and
        optionally one trailer block.

        If it is important to send HPACK "never indexed" header fields (as
        defined in `RFC 7451 Section 7.1.3
        <https://tools.ietf.org/html/rfc7541#section-7.1.3>`_), the user may
        instead provide headers using the HPACK library's :class:`HeaderTuple
        <hpack:hpack.HeaderTuple>` and :class:`NeverIndexedHeaderTuple
        <hpack:hpack.NeverIndexedHeaderTuple>` objects.

        This method also allows users to prioritize the stream immediately,
        by sending priority information on the HEADERS frame directly. To do
        this, any one of ``priority_weight``, ``priority_depends_on``, or
        ``priority_exclusive`` must be set to a value that is not ``None``. For
        more information on the priority fields, see :meth:`prioritize
        <h2.connection.H2Connection.prioritize>`.

        .. warning:: In HTTP/2, it is mandatory that all the HTTP/2 special
            headers (that is, ones whose header keys begin with ``:``) appear
            at the start of the header block, before any normal headers.

        .. versionchanged:: 2.3.0
           Added support for using :class:`HeaderTuple
           <hpack:hpack.HeaderTuple>` objects to store headers.

        .. versionchanged:: 2.4.0
           Added the ability to provide priority keyword arguments:
           ``priority_weight``, ``priority_depends_on``, and
           ``priority_exclusive``.

        :param stream_id: The stream ID to send the headers on. If this stream
            does not currently exist, it will be created.
        :type stream_id: ``int``

        :param headers: The request/response headers to send.
        :type headers: An iterable of two tuples of bytestrings or
            :class:`HeaderTuple <hpack:hpack.HeaderTuple>` objects.

        :param end_stream: Whether this headers frame should end the stream
            immediately (that is, whether no more data will be sent after this
            frame). Defaults to ``False``.
        :type end_stream: ``bool``

        :param priority_weight: Sets the priority weight of the stream. See
            :meth:`prioritize <h2.connection.H2Connection.prioritize>` for more
            about how this field works. Defaults to ``None``, which means that
            no priority information will be sent.
        :type priority_weight: ``int`` or ``None``

        :param priority_depends_on: Sets which stream this one depends on for
            priority purposes. See :meth:`prioritize
            <h2.connection.H2Connection.prioritize>` for more about how this
            field works. Defaults to ``None``, which means that no priority
            information will be sent.
        :type priority_depends_on: ``int`` or ``None``

        :param priority_exclusive: Sets whether this stream exclusively depends
            on the stream given in ``priority_depends_on`` for priority
            purposes. See :meth:`prioritize
            <h2.connection.H2Connection.prioritize>` for more about how this
            field workds. Defaults to ``None``, which means that no priority
            information will be sent.
        :type priority_depends_on: ``bool`` or ``None``

        :returns: Nothing
        zSend headers on stream ID %dr   #Max outbound streams is %d, %d openN&Servers SHOULD NOT prioritize streams.r   PRIORITY)r   r   r   r   r   max_concurrent_streamsr   r'   r   r~   rD   rU   r   rj   r   send_headersr   r+   flagsadd_add_frame_priorityr   )rs   r   headers
end_streampriority_weightpriority_depends_onpriority_exclusivemax_open_streamsr   r   priority_presentheaders_frames               rB   r   zH2Connection.send_headers  sg   H 	  *I	

 DLL(#33JJ**Q.2BB)9%t'A'ABC 
 	(()9)F)FG++'(?(?@
 $$T\\:
 D( - ,-t+ 	 ;;**"#KLL"1IM##J/+#"	F1I 	!!&)rA   c                 V   | j                   j                  j                  d|t        |             t        |      }|8t	        |t
              st        d      |dk  s|dkD  rt        d      ||dz   z  }| j                   j                  j                  d||       || j                  |      kD  rt        d	|| j                  |      fz        || j                  kD  rt        d
|| j                  fz        | j                  j                  t        j                         | j                   |   j#                  |||      }| j%                  |       | xj&                  |z  c_        | j                   j                  j                  d| j&                         | j&                  dk\  sJ y)a  
        Send data on a given stream.

        This method does no breaking up of data: if the data is larger than the
        value returned by :meth:`local_flow_control_window
        <h2.connection.H2Connection.local_flow_control_window>` for this stream
        then a :class:`FlowControlError <h2.exceptions.FlowControlError>` will
        be raised. If the data is larger than :data:`max_outbound_frame_size
        <h2.connection.H2Connection.max_outbound_frame_size>` then a
        :class:`FrameTooLargeError <h2.exceptions.FrameTooLargeError>` will be
        raised.

        h2 does this to avoid buffering the data internally. If the user
        has more data to send than h2 will allow, consider breaking it up
        and buffering it externally.

        :param stream_id: The ID of the stream on which to send the data.
        :type stream_id: ``int``
        :param data: The data to send on the stream.
        :type data: ``bytes``
        :param end_stream: (optional) Whether this is the last data to be sent
            on the stream. Defaults to ``False``.
        :type end_stream: ``bool``
        :param pad_length: (optional) Length of the padding to apply to the
            data frame. Defaults to ``None`` for no use of padding. Note that
            a value of ``0`` results in padding of length ``0``
            (with the "padding" flag set on the frame).

            .. versionadded:: 2.6.0

        :type pad_length: ``int``
        :returns: Nothing
        z%Send data on stream ID %d with len %dNzpad_length must be an intr      z)pad_length must be within range: [0, 255]r   z Frame size on stream ID %d is %dz0Cannot send %d bytes, flow control window is %d.z/Cannot send frame size %d, max frame size is %d)
pad_lengthz'Outbound flow control window size is %d)r   r   r   lenrv   r   	TypeErrorrw   local_flow_control_windowr%   r   r&   r   r~   rD   rW   r   	send_datar   r   )rs   r   datar  r  
frame_sizer   s          rB   r  zH2Connection.send_data  s   D 	  3YD		
 Y
!j#. ;<<A~c!1 !LMM*q.(J  .	:	
 66yAA"BT;;IFGH  $666$AT99:; 
 	(()9)C)CDi(22* 3 
 	!!&)))Z7)  5--	
 00A555rA   c                     | j                   j                  j                  d|       | j                  j	                  t
        j                         | j                  |   j                         }| j                  |       y)a  
        Cleanly end a given stream.

        This method ends a stream by sending an empty DATA frame on that stream
        with the ``END_STREAM`` flag set.

        :param stream_id: The ID of the stream to end.
        :type stream_id: ``int``
        :returns: Nothing
        zEnd stream ID %dN)
r   r   r   r   r~   rD   rW   r   r  r   )rs   r   r   s      rB   r  zH2Connection.end_streamf  s_     	  !3Y?(()9)C)CDi(335!!&)rA   c                    d|cxk  r| j                   k  sn t        d| j                   z        | j                  j                  t        j
                         |H| j                  |   }|j                  |      }| j                  j                  j                  d||       nV| j                  j                  |       t        d      }||_        |g}| j                  j                  j                  d|       | j                  |       y)a  
        Increment a flow control window, optionally for a single stream. Allows
        the remote peer to send more data.

        .. versionchanged:: 2.0.0
           Rejects attempts to increment the flow control window by out of
           range values with a ``ValueError``.

        :param increment: The amount to increment the flow control window by.
        :type increment: ``int``
        :param stream_id: (optional) The ID of the stream that should have its
            flow control window opened. If not present or ``None``, the
            connection flow control window will be opened instead.
        :type stream_id: ``int`` or ``None``
        :returns: Nothing
        :raises: ``ValueError``
        r   z/Flow control increment must be between 1 and %dNz/Increase stream ID %d flow control window by %dr   z-Increase connection flow control window by %d)MAX_WINDOW_INCREMENTrw   r   r~   rD   rY   r   increase_flow_control_windowr   r   r   r   window_openedr   window_incrementr   )rs   	incrementr   r   r   r   s         rB   increment_flow_control_windowz*H2Connection.increment_flow_control_windowv  s    $ Y;$";";;A))* 
 	(()9)L)LM \\),F88F KK$$A9
 55CCIN!!$A!*ASFKK$$? 	!!&)rA   c                    | j                   j                  j                  d|       | j                  j                  st        d      | j                  j                  t        j                         | j                  |      }|dz  dk(  rt        d      | j                  |t        j                        }|| j                  |<   |j                  ||| j                         }|j#                         }| j%                  ||z          y)a  
        Push a response to the client by sending a PUSH_PROMISE frame.

        If it is important to send HPACK "never indexed" header fields (as
        defined in `RFC 7451 Section 7.1.3
        <https://tools.ietf.org/html/rfc7541#section-7.1.3>`_), the user may
        instead provide headers using the HPACK library's :class:`HeaderTuple
        <hpack:hpack.HeaderTuple>` and :class:`NeverIndexedHeaderTuple
        <hpack:hpack.NeverIndexedHeaderTuple>` objects.

        :param stream_id: The ID of the stream that this push is a response to.
        :type stream_id: ``int``
        :param promised_stream_id: The ID of the stream that the pushed
            response will be sent on.
        :type promised_stream_id: ``int``
        :param request_headers: The headers of the request that the pushed
            response will be responding to.
        :type request_headers: An iterable of two tuples of bytestrings or
            :class:`HeaderTuple <hpack:hpack.HeaderTuple>` objects.
        :returns: Nothing
        z'Send Push Promise frame on stream ID %dz$Remote peer has disabled stream pushr7   r    Cannot recursively push streams.N)r   r   r   r   enable_pushr#   r   r~   rD   rV   r   r   rj   rk   r   push_stream_in_bandr   locally_pushedr   )rs   r   promised_stream_idrequest_headersr   
new_streamr   
new_framess           rB   push_streamzH2Connection.push_stream  s    , 	  5y	
 ##// FGG(()9)K)KL''	2 Ma BCC++ 0 5 5

 ,6'(++
  ..0
!!&:"56rA   c                 @   | j                   j                  j                  d       t        |t              rt        |      dk7  rt        d|z        | j                  j                  t        j                         t        d      }||_        | j                  |g       y)z
        Send a PING frame.

        :param opaque_data: A bytestring of length 8 that will be sent in the
                            PING frame.
        :returns: Nothing
        zSend Ping framerI   zInvalid value for ping data: %rr   N)r   r   r   rv   bytesr  rw   r   r~   rD   rZ   r
   opaque_datar   )rs   r'  r   s      rB   pingzH2Connection.ping  s     	  !23+u-[1AQ1F>LMM(()9)C)CDaL#!!1#&rA   c                    | j                   j                  j                  d|       | j                  j	                  t
        j                         | j                  |      }|j                  |      }| j                  |       y)ai  
        Reset a stream.

        This method forcibly closes a stream by sending a RST_STREAM frame for
        a given stream. This is not a graceful closure. To gracefully end a
        stream, try the :meth:`end_stream
        <h2.connection.H2Connection.end_stream>` method.

        :param stream_id: The ID of the stream to reset.
        :type stream_id: ``int``
        :param error_code: (optional) The error code to use to reset the
            stream. Defaults to :data:`ErrorCodes.NO_ERROR
            <h2.errors.ErrorCodes.NO_ERROR>`.
        :type error_code: ``int``
        :returns: Nothing
        zReset stream ID %dN)
r   r   r   r   r~   rD   r\   r   reset_streamr   )rs   r   
error_coder   r   s        rB   r*  zH2Connection.reset_stream  sh    " 	  !5yA(()9)I)IJ''	2$$Z0!!&)rA   c                 .   | j                   j                  j                  d       | j                  j	                  t
        j                         |t        |t              sJ || j                  }t        d|||xs d      }| j                  |g       y)aH  
        Close a connection, emitting a GOAWAY frame.

        .. versionchanged:: 2.4.0
           Added ``additional_data`` and ``last_stream_id`` arguments.

        :param error_code: (optional) The error code to send in the GOAWAY
            frame.
        :param additional_data: (optional) Additional debug data indicating
            a reason for closing the connection. Must be a bytestring.
        :param last_stream_id: (optional) The last stream which was processed
            by the sender. Defaults to ``highest_inbound_stream_id``.
        :returns: Nothing
        zClose connectionNr   rA   )r   last_stream_idr+  additional_data)r   r   r   r   r~   rD   rX   rv   r&  r   r   r   )rs   r+  r.  r-  r   s        rB   close_connectionzH2Connection.close_connection  s    " 	  !34(()9)E)EF &ou555!!;;N)!,3	
 	!!1#&rA   c                     | j                   j                  j                  d|       | j                  j	                  t
        j                         | j                  j                  |       t        d      }||_
        | j                  |g       y)z
        Update the local settings. This will prepare and emit the appropriate
        SETTINGS frame.

        :param new_settings: A dictionary of {setting: new value}
        z Update connection settings to %sr   N)r   r   r   r   r~   rD   r[   r   updater   r   r   )rs   new_settingsr   s      rB   update_settingszH2Connection.update_settings%  ss     	  .	
 	(()9)G)GH""<0!!
!!1#&rA   c                 P   t        |t              st        d      ||t        d      | j                  j	                  t
        j                         |t        d      }||_        ||_	        |g}n"| j                  |      }|j                  |      }| j                  |       y)ai
  
        Notify a client about an available Alternative Service.

        An Alternative Service is defined in `RFC 7838
        <https://tools.ietf.org/html/rfc7838>`_. An Alternative Service
        notification informs a client that a given origin is also available
        elsewhere.

        Alternative Services can be advertised in two ways. Firstly, they can
        be advertised explicitly: that is, a server can say "origin X is also
        available at Y". To advertise like this, set the ``origin`` argument
        and not the ``stream_id`` argument. Alternatively, they can be
        advertised implicitly: that is, a server can say "the origin you're
        contacting on stream X is also available at Y". To advertise like this,
        set the ``stream_id`` argument and not the ``origin`` argument.

        The explicit method of advertising can be done as long as the
        connection is active. The implicit method can only be done after the
        client has sent the request headers and before the server has sent the
        response headers: outside of those points, h2 will forbid sending
        the Alternative Service advertisement by raising a ProtocolError.

        The ``field_value`` parameter is specified in RFC 7838. h2 does
        not validate or introspect this argument: the user is required to
        ensure that it's well-formed. ``field_value`` corresponds to RFC 7838's
        "Alternative Service Field Value".

        .. note:: It is strongly preferred to use the explicit method of
                  advertising Alternative Services. The implicit method of
                  advertising Alternative Services has a number of subtleties
                  and can lead to inconsistencies between the server and
                  client. h2 allows both mechanisms, but caution is
                  strongly advised.

        .. versionadded:: 2.3.0

        :param field_value: The RFC 7838 Alternative Service Field Value. This
            argument is not introspected by h2: the user is responsible
            for ensuring that it is well-formed.
        :type field_value: ``bytes``

        :param origin: The origin/authority to which the Alternative Service
            being advertised applies. Must not be provided at the same time as
            ``stream_id``.
        :type origin: ``bytes`` or ``None``

        :param stream_id: The ID of the stream which was sent to the authority
            for which this Alternative Service advertisement applies. Must not
            be provided at the same time as ``origin``.
        :type stream_id: ``int`` or ``None``

        :returns: Nothing.
        zField must be bytestring.Nz*Must not provide both origin and stream_idr   )r   )rv   r&  rw   r   r~   rD   rg   r   originfieldr   advertise_alternative_servicer   )rs   field_valuer5  r   r   r   r   s          rB   r7  z*H2Connection.advertise_alternative_service5  s    r +u-899)"7IJJ((55	
 a(AAH!AGSF++I6F99+FF!!&)rA   c                     | j                   j                  st        d      | j                  j	                  t
        j                         t        |      }t        ||||      }| j                  |g       y)a  
        Notify a server about the priority of a stream.

        Stream priorities are a form of guidance to a remote server: they
        inform the server about how important a given response is, so that the
        server may allocate its resources (e.g. bandwidth, CPU time, etc.)
        accordingly. This exists to allow clients to ensure that the most
        important data arrives earlier, while less important data does not
        starve out the more important data.

        Stream priorities are explained in depth in `RFC 7540 Section 5.3
        <https://tools.ietf.org/html/rfc7540#section-5.3>`_.

        This method updates the priority information of a single stream. It may
        be called well before a stream is actively in use, or well after a
        stream is closed.

        .. warning:: RFC 7540 allows for servers to change the priority of
                     streams. However, h2 **does not** allow server
                     stacks to do this. This is because most clients do not
                     adequately know how to respond when provided conflicting
                     priority information, and relatively little utility is
                     provided by making that functionality available.

        .. note:: h2 **does not** maintain any information about the
                  RFC 7540 priority tree. That means that h2 does not
                  prevent incautious users from creating invalid priority
                  trees, particularly by creating priority loops. While some
                  basic error checking is provided by h2, users are
                  strongly recommended to understand their prioritisation
                  strategies before using the priority tools here.

        .. note:: Priority information is strictly advisory. Servers are
                  allowed to disregard it entirely. Avoid relying on the idea
                  that your priority signaling will definitely be obeyed.

        .. versionadded:: 2.4.0

        :param stream_id: The ID of the stream to prioritize.
        :type stream_id: ``int``

        :param weight: The weight to give the stream. Defaults to ``16``, the
             default weight of any stream. May be any value between ``1`` and
             ``256`` inclusive. The relative weight of a stream indicates what
             proportion of available resources will be allocated to that
             stream.
        :type weight: ``int``

        :param depends_on: The ID of the stream on which this stream depends.
             This stream will only be progressed if it is impossible to
             progress the parent stream (the one on which this one depends).
             Passing the value ``0`` means that this stream does not depend on
             any other. Defaults to ``0``.
        :type depends_on: ``int``

        :param exclusive: Whether this stream is an exclusive dependency of its
            "parent" stream (i.e. the stream given by ``depends_on``). If a
            stream is an exclusive dependency of another, that means that all
            previously-set children of the parent are moved to become children
            of the new exclusively-dependent stream. Defaults to ``False``.
        :type exclusive: ``bool``
        r   N)
r   r   r+   r   r~   rD   r]   r   r  r   )rs   r   weight
depends_on	exclusiveframes         rB   
prioritizezH2Connection.prioritize  sg    @ {{&&GHH((**	
 i(#E6:yI!!5'*rA   c                 d    | j                  |      }t        | j                  |j                        S )a1  
        Returns the maximum amount of data that can be sent on stream
        ``stream_id``.

        This value will never be larger than the total data that can be sent on
        the connection: even if the given stream allows more data, the
        connection window provides a logical maximum to the amount of data that
        can be sent.

        The maximum data that can be sent in a single data frame on a stream
        is either this value, or the maximum frame size, whichever is
        *smaller*.

        :param stream_id: The ID of the stream whose flow control window is
            being queried.
        :type stream_id: ``int``
        :returns: The amount of data in bytes that can be sent on the stream
            before the flow control window is exhausted.
        :rtype: ``int``
        )r   minr   rs   r   r   s      rB   r  z&H2Connection.local_flow_control_window  s3    * ''	2--//
 	
rA   c                 d    | j                  |      }t        | j                  |j                        S )a=  
        Returns the maximum amount of data the remote peer can send on stream
        ``stream_id``.

        This value will never be larger than the total data that can be sent on
        the connection: even if the given stream allows more data, the
        connection window provides a logical maximum to the amount of data that
        can be sent.

        The maximum data that can be sent in a single data frame on a stream
        is either this value, or the maximum frame size, whichever is
        *smaller*.

        :param stream_id: The ID of the stream whose flow control window is
            being queried.
        :type stream_id: ``int``
        :returns: The amount of data in bytes that can be received on the
            stream before the flow control window is exhausted.
        :rtype: ``int``
        )r   r@  r   rA  s      rB   remote_flow_control_windowz'H2Connection.remote_flow_control_window  s3    * ''	2,,..
 	
rA   c                    | j                   j                  j                  d||       |dk  rt        d|z        |dk  rt        d      g }| j                  }|j                  |      }|r#t        d      }||_        |j                  |       	 | j                  |      }|j                  r!|j                  |j                  |             	 | j                  |       y# t        $ r Y w xY w)a  
        Inform the :class:`H2Connection <h2.connection.H2Connection>` that a
        certain number of flow-controlled bytes have been processed, and that
        the space should be handed back to the remote peer at an opportune
        time.

        .. versionadded:: 2.5.0

        :param acknowledged_size: The total *flow-controlled size* of the data
            that has been processed. Note that this must include the amount of
            padding that was sent with that data.
        :type acknowledged_size: ``int``
        :param stream_id: The ID of the stream on which this data was received.
        :type stream_id: ``int``
        :returns: Nothing
        :rtype: ``None``
        z.Ack received data on stream ID %d with size %dr   z7Stream ID %d is not valid for acknowledge_received_dataz Cannot acknowledge negative dataN)r   r   r   rw   r   process_bytesr   r  r   r   r   extendacknowledge_received_datar(   r   )rs   acknowledged_sizer   r   conn_managerconn_incrementr   r   s           rB   rG  z&H2Connection.acknowledge_received_data  s    $ 	  <(	
 >I  q ?@@@@%334EF!!$A!/AMM!	++I6F {{445FG 	!!&) ! 	 	s   C   	C,+C,c                     |&t        | j                        }t               | _        |S t        | j                  d|       }| j                  |d | _        |S )a|  
        Returns some data for sending out of the internal data buffer.

        This method is analogous to ``read`` on a file-like object, but it
        doesn't block. Instead, it returns as much data as the user asks for,
        or less if that much data is not available. It does not perform any
        I/O, and so uses a different name.

        :param amount: (optional) The maximum amount of data to return. If not
            set, or set to ``None``, will return as much data as possible.
        :type amount: ``int``
        :returns: A bytestring containing the data to send on the wire.
        :rtype: ``bytes``
        N)r&  r   r   )rs   amountr  s      rB   data_to_sendzH2Connection.data_to_send<  sY     >++,D!*DK++GV45D!%!3!3FG!<DKrA   c                 "    t               | _        y)aa  
        Clears the outbound data buffer, such that if this call was immediately
        followed by a call to
        :meth:`data_to_send <h2.connection.H2Connection.data_to_send>`, that
        call would return no data.

        This method should not normally be used, but is made available to avoid
        exposing implementation details.
        N)r   r   rr   s    rB   clear_outbound_data_bufferz'H2Connection.clear_outbound_data_bufferT  s     '[rA   c                    | j                   j                  t        j                         | j                  j                         }t        j                  |v r9|t        j                     }| j                  |j                  |j                         t        j                  |v r.|t        j                     }|j                  | j                  _        t        j                  |v rT|t        j                     }|j                  | _        | j                   j#                         D ]  }|j                  |_         t%        d      }|j&                  j)                  d       |gS )z
        Acknowledge settings that have been received.

        .. versionchanged:: 2.0.0
           Removed from public API, removed useless ``event`` parameter, made
           automatic.

        :returns: Nothing
        r   ACK)r   r~   rD   r[   r   acknowledger/   INITIAL_WINDOW_SIZE"_flow_control_change_from_settingsoriginal_value	new_valueHEADER_TABLE_SIZEr   header_table_sizeMAX_FRAME_SIZEr   r   valuesr   r   r   )rs   changesr   r   r   s        rB   _acknowledge_settingsz"H2Connection._acknowledge_settings`  s    	(()9)G)GH&&224++w6l>>?G33&&!! ))W4l<<=G-4->->DLL*&&'1l99:G+2+<+<D(,,--/181B1B. 0 !	Es
rA   c                     ||z
  }| j                   j                         D ]  }t        |j                  |      |_         y)av  
        Update flow control windows in response to a change in the value of
        SETTINGS_INITIAL_WINDOW_SIZE.

        When this setting is changed, it automatically updates all flow control
        windows by the delta in the settings values. Note that it does not
        increment the *connection* flow control window, per section 6.9.2 of
        RFC 7540.
        N)r   rZ  r3   r   rs   	old_valuerV  deltar   s        rB   rT  z/H2Connection._flow_control_change_from_settings  s>     I%ll))+F2H333F/ ,rA   c                 n    ||z
  }| j                   j                         D ]  }|j                  |        y)a  
        Update remote flow control windows in response to a change in the value
        of SETTINGS_INITIAL_WINDOW_SIZE.

        When this setting is changed, it automatically updates all remote flow
        control windows by the delta in the settings values.
        N)r   rZ  *_inbound_flow_control_change_from_settingsr^  s        rB   rb  z7H2Connection._inbound_flow_control_change_from_settings  s3     I%ll))+F==eD ,rA   c                    | j                   j                  j                  d|       g }| j                  j	                  |       | j
                  | j                  _        	 | j                  D ]"  }|j                  | j                  |             $ 	 |S # t        $ r+ | j                  t        j                         t        d      t        $ r!}| j                  |j                          d}~ww xY w)a  
        Pass some received HTTP/2 data to the connection for handling.

        :param data: The data received from the remote peer on the network.
        :type data: ``bytes``
        :returns: A list of events that the remote peer triggered by sending
            this data.
        z6Process received data on connection. Received data: %rz$Received frame with invalid padding.N)r   r   tracer   add_datar   r   rF  _receive_framer   _terminate_connectionr   PROTOCOL_ERRORr#   r+  )rs   r  eventsr=  es        rB   receive_datazH2Connection.receive_data  s     	  Dd	
 %%d+.2.I.I+	--d11%89 .  # 	H&&z'@'@A FGG 	
 &&q||4	s    1B ;C0C++C0c                    | j                   j                  j                  dt        |             	  | j                  |j
                     |      \  }}| j                  |       |S # t        $ rl}| j                  |j                        rEt        |j                        }|j                  |_        | j                  |g       |j                  }n Y d}~|S d}~wt        $ r}| j                  |j                        r?t        |j                        }t        j                  |_        | j                  |g       g }n1| j!                  |j                        rt        |j                         Y d}~|S d}~ww xY w)z
        Handle a frame received on the connection.

        .. versionchanged:: 2.0.0
           Removed from the public API.
        zReceived frame: %sN)r   r   rd  reprr   	__class__r   r(   _stream_is_closed_by_resetr   r   r+  _eventsr)   r   STREAM_CLOSED_stream_is_closed_by_end)rs   r=  r   ri  rj  r   s         rB   rf  zH2Connection._receive_frame  sF    	  !5tE{C$	.HT77HONFFD %%f-G ! 
	 ..q{{;"1;;/ ||))1#. 6 1 # 	 ..q{{;"1;;/)77))1#...q{{;'44   1	s%   "A& &	E8/A!CE8"BE33E8c                     t        d      }| j                  |_        ||_        | j                  j                  t        j                         | j                  |g       y)zn
        Terminate the connection early. Used in error handling blocks to send
        GOAWAY frames.
        r   N)	r   r   r-  r+  r   r~   rD   rX   r   )rs   r+  r   s      rB   rg  z"H2Connection._terminate_connection  sM    
 N99!(()9)E)EF!!1#&rA   c                    |j                   | j                  vrB| j                  j                  }| j                  dz   |kD  rt        d|| j                  fz        t        | j                  |j                        }| j                  j                  t        j                        }| j                  |j                   t        | j                   j"                               }|j%                  |d|j&                  v | j                   j(                        \  }}d|j&                  v r6| j+                  |      \  }}	|	d   |d   _        |j/                  |	       |rJ |||z   fS )z<
        Receive a headers frame on the connection.
        r   r   
END_STREAMr   r   )r   r   r   r   r   r'   r   _decode_headersr   r  r   r~   rD   r^   r   rj   r   r   receive_headersr   header_encodingr   priority_updatedrF  )
rs   r=  r  r  ri  r   r   stream_eventsp_framesp_eventss
             rB   r   z#H2Connection._receive_headers_frame   sN    ??$,,.#22II))A-1AA)9%t'A'ABC  "$,,

;##11))
 ++OO-$++2I2I.IJ
 !' 6 6EKK'KK''!
 $!%!=!=e!DHh08M!-  *<v---rA   c                    | j                   j                  st        d      t        | j                  |j
                        }| j                  j                  t        j                        }	 | j                  |j                        }|j                  dz  dk(  rt        d      	 |j+                  |j"                  || j,                  j.                        \  }}| j3                  |j"                  t4        j6                        }|| j8                  |j"                  <   |j;                  |       |||z   fS # t        $ ri | j                  |j                        t        j                  k(  r1t!        |j"                        }t$        j&                  |_        |g|fcY S t        d      w xY w# t0        $ r2 t!        |j"                        }t$        j&                  |_        |g|fcY S w xY w)zA
        Receive a push-promise frame on the connection.
        zReceived pushed streamz#Attempted to push on closed stream.r7   r   r  )r   r  r#   rv  r   r  r   r~   rD   r_   r   r   r$   _stream_closed_byr1   r\   r   r   r   REFUSED_STREAMr+  receive_push_promise_in_bandr   rx  r(   r   rj   rk   r   remotely_pushed)	rs   r=  pushed_headersri  r   r   r   rz  r"  s	            rB   r   z(H2Connection._receive_push_promise_frame'  s    "".. 899(uzzB##11..
	G++EOO<F0 OOaA% BCC	$*$G$G((++%!FM ++$$&6&;&;

 2<U--."">2v---] ! 	G &&u7"223"5#;#;<)88sF{" EFF!	G@ ! 	 u778A%44AL3;	s%   ,D4 %4F) 4A$F&F&)8G$#G$c                    g }| j                   }|j                  |j                        }|rTt        d      }||_        |j                  |       | j                  j                  j                  d|j                  |       t        |j                        }|j                  |_        |j                  |       | j                  j                  j                  d|j                  z         |||j                  z   fS )Nr   zLReceived DATA frame on closed stream %d - auto-emitted a WINDOW_UPDATE by %dzAStream %d already CLOSED or cleaned up - auto-emitted a RST_FRAME)r   rE  flow_controlled_lengthr   r  r   r   r   r   r   r   r+  rp  )rs   ri  excr=  r   rI  rJ  r   s           rB   _handle_data_on_closed_streamz*H2Connection._handle_data_on_closed_streamf  s     @@%33((
 !!$A!/AMM!KK$$5
 3==)~~a  ').9	
 v+++rA   c                    |j                   }| j                  j                  t        j                        }| j
                  j                  |       	 | j                  |j                        }|j                  |j                  d|j                  v |      \  }}|||z   fS # t        $ r}| j                  |||      cY d}~S d}~ww xY w)z9
        Receive a data frame on the connection.
        ru  N)r  r   r~   rD   r`   r   window_consumedr   r   rk  r  r   r(   r  )rs   r=  r  ri  r   r   rz  rj  s           rB   r   z H2Connection._receive_data_frame  s     "'!=!=##11&&
 	11AA"	

	H++EOO<F$*$7$7

+&%!FM v--- ! 	H 55faGG	Hs   AB   	C)C;CCc                    | j                   j                  t        j                        }d|j                  v r6| j                         }t               }||_        |j                  |       g |fS | j                  j                  |j                         |j                  t        j                  | j                  |j                               | j                         }||fS )z=
        Receive a SETTINGS frame on the connection.
        rQ  )r   r~   rD   rd   r   _local_settings_ackedr   changed_settingsr   r   r1  r   r   from_settingsr\  )rs   r=  ri  r  	ack_eventr   s         rB   r   z$H2Connection._receive_settings_frame  s     ##11**

 EKK#99;,.I)9I&MM)$v: 	##ENN3!//$$enn	

 ++-v~rA   c                    | j                   j                  t        j                        }|j                  r;	 | j                  |j                        }|j                  |j                        \  }}nLt        | j                  |j                        | _
        t               }d|_        |j                  |_        |g}g }|||z   fS # t        $ r g |fcY S w xY w)zB
        Receive a WINDOW_UPDATE frame on the connection.
        r   )r   r~   rD   rb   r   r   receive_window_updater  r(   r3   r   r   r`  )rs   r=  ri  r   r   rz  window_updated_events          rB   r   z)H2Connection._receive_window_update_frame  s     ##11//
 ??"//@(.(D(D**)% 1G11&&1D- $1? -. *).)?)? &12MFv---! % "6z!"s   9C CCc                 T   | j                   j                  t        j                        }g }d|j                  v rt               }n?t               }t        d      }dh|_        |j                  |_        |j                  |       |j                  |_
        |j                  |       ||fS )z9
        Receive a PING frame on the connection.
        rQ  r   )r   r~   rD   rc   r   r   r   r
   r'  r   	ping_data)rs   r=  ri  r   evtr   s         rB   r   z H2Connection._receive_ping_frame  s     ##11&&
 EKK!#C.C !AgAG!--AMLLO))cf}rA   c                     | j                   j                  t        j                        }	 | j	                  |j
                        }|j                  |      \  }}|||z   fS # t        $ r g }g }Y w xY w)z?
        Receive a RST_STREAM frame on the connection.
        )r   r~   rD   re   r   r   stream_resetr$   )rs   r=  ri  r   stream_framesrz  s         rB   r   z&H2Connection._receive_rst_stream_frame  s     ##11,,
	F++EOO<F ,2+>+>u+E(M=f}444 ! 	MM	s   A! !A10A1c                    | j                   j                  t        j                        }t	               }|j
                  |_        |j                  |_        |j                  |_        |j                  dz   |_	        |j                  |j
                  k(  rt        d|j
                  z        |j                  |       g |fS )z=
        Receive a PRIORITY frame on the connection.
        r   "Stream %d may not depend on itself)r   r~   rD   rf   r    r   r;  r<  stream_weightr:  r#   r   )rs   r=  ri  events       rB   r   z$H2Connection._receive_priority_frame  s     ##11**
  !// ++// **Q. u.4uF  	e6zrA   c                 F   | j                   j                  t        j                        }| j	                          t               }t        |j                        |_        |j                  |_        |j                  r|j                  nd|_	        |j                  |       g |fS )z;
        Receive a GOAWAY frame on the connection.
        N)r   r~   rD   ra   rO  r   r   r+  r-  r.  r   )rs   r=  ri  	new_events       rB   r   z"H2Connection._receive_goaway_frame!  s     ##11((

 	'') )*	3E4D4DE	#(#7#7	 (-(=(= &+%:%:CG 	!i 6zrA   c                 f    | j                  |j                        }|j                          J d       )a  
        A naked CONTINUATION frame has been received. This is always an error,
        but the type of error it is depends on the state of the stream and must
        transition the state of the stream, so we need to pass it to the
        appropriate stream.
        zShould not be reachable)r   r   receive_continuation)rs   r=  r   s      rB   r   z(H2Connection._receive_naked_continuation6  s/     ''8##%///urA   c                 "   | j                   j                  t        j                        }g }|j                  rV	 | j                  |j                        }|j                  |      \  }}|j                  |       |j                  |       ||fS |j                  s||fS | j                  j                  s||fS t               }|j                  |_
        |j                  |_        |j!                  |       ||fS # t        t        f$ r Y ||fS w xY w)a>  
        An ALTSVC frame has been received. This frame, specified in RFC 7838,
        is used to advertise alternative places where the same service can be
        reached.

        This frame can optionally be received either on a stream or on stream
        0, and its semantics are different in each case.
        )r   r~   rD   rh   r   r   receive_alt_svcrF  r$   r(   r5  r   r   r!   r6  r8  r   )rs   r=  ri  r   r   r  rz  r  s           rB   r   z#H2Connection._receive_alt_svc_frameA  s    ##1155
 ??
-//@ 06/E/Ee/L,}m,m," v~ <<v~% ;;**v~%/1E <<EL %EMM% v~- &'89 * v~-s   C9 9DDc                     | j                   j                  j                  d|j                         t	               }||_        g |gfS )u<  
        We have received a frame that we do not understand. This is almost
        certainly an extension frame, though it's impossible to be entirely
        sure.

        RFC 7540 § 5.5 says that we MUST ignore unknown frame types: so we
        do. We do notify the user that we received one, however.
        z(Received unknown extension frame (ID %d))r   r   r   r   r"   r=  )rs   r=  r  s      rB   r   z#H2Connection._receive_unknown_framen  sB     	  6	
 %&E7{rA   c                 <   | j                   j                         }t        j                  |v r9|t        j                     }| j	                  |j
                  |j                         t        j                  |v r.|t        j                     }|j                  | j                  _	        t        j                  |v r$|t        j                     }|j                  | _        t        j                  |v r.|t        j                     }|j                  | j                  _        |S )zO
        Handle the local settings being ACKed, update internal state.
        )r   rR  r/   rS  rb  rU  rV  r   r   r   rY  r   rW  max_allowed_table_size)rs   r[  r   s      rB   r  z"H2Connection._local_settings_acked  s     %%113++w6l>>?G;;&&!!
 ,,7l??@G070A0ADLL-&&'1l99:G*1*;*;D'))W4l<<=G 3:2C2CDLL/rA   c                 L    |dz  t        | j                  j                        k(  S )z
        Returns ``True`` if the stream ID corresponds to an outbound stream
        (one initiated by this peer), returns ``False`` otherwise.
        r7   )r   r   r   rs   r   s     rB   r   z#H2Connection._stream_id_is_outbound  s"    
 AT[[%<%<!==>rA   c                     || j                   v r| j                   |   j                  S || j                  v r| j                  |   S y)a'  
        Returns how the stream was closed.

        The return value will be either a member of
        ``h2.stream.StreamClosedBy`` or ``None``. If ``None``, the stream was
        closed implicitly by the peer opening a stream with a higher stream ID
        before opening this one.
        N)r   r   r   r  s     rB   r~  zH2Connection._stream_closed_by  sG     $<<	*444,,,''	22rA   c                 d    | j                  |      t        j                  t        j                  fv S )z
        Returns ``True`` if the stream was closed by sending or receiving a
        RST_STREAM frame. Returns ``False`` otherwise.
        )r~  r1   re   r\   r  s     rB   ro  z'H2Connection._stream_is_closed_by_reset  s2    
 %%i0**N,J,J5
 
 	
rA   c                 d    | j                  |      t        j                  t        j                  fv S )z
        Returns ``True`` if the stream was closed by sending or receiving an
        END_STREAM flag in a HEADERS or DATA frame. Returns ``False``
        otherwise.
        )r~  r1   RECV_END_STREAMSEND_END_STREAMr  s     rB   rr  z%H2Connection._stream_is_closed_by_end  s2     %%i0**N,J,J5
 
 	
rA   rp   )FNNN)FN)r   )r   NN)NNNNN)?r9   r:   r;   r   DEFAULT_MAX_OUTBOUND_FRAME_SIZEDEFAULT_MAX_INBOUND_FRAME_SIZEr   r  r   r   rt   r   r   propertyr   r   r   r   r   r   r   r   r   r   r  r  r  r$  r(  r*  r/  r3  r7  r>  r  rC  rG  rM  rO  r\  rT  rb  rk  rf  rg  r   r   r  r   r   r   r   r   r   r   r   r   r   r  r   r~  ro  rr  r@   rA   rB   r   r      s   : ',# &+" !* % $)  a
FO* 4 4 3 3 M M-^7*GRB3."H ;@?C(,M*^H6T* .*`17f'$*. >B(,!'F'$ .204M*^ =A!J+X
6
64*l0
)#J$EB.`	'%.N=.~,:.66!.F25$4*	0+Z":?

rA   r   c                     || j                   k(  rt        d| j                   z        ||dkD  s|dk  rt        d|z        |dz  }||nd}||nd}||nd}|| _        || _        || _        | S )a6  
    Adds priority data to a given frame. Does not change any flags set on that
    frame: if the caller is adding priority information to a HEADERS frame they
    must set that themselves.

    This method also deliberately sets defaults for anything missing.

    This method validates the input values.
    r     r   z(Weight must be between 1 and 256, not %drP   r   F)r   r#   r  r;  r<  )r=  r:  r;  r<  s       rB   r  r    s     U__$05??B
 	

 C<6A::VC  aKF )VrF)51J&2	I E!EEOLrA   c                     	 | j                  |d      S # t        $ r}t        d|z        d}~wt        t        t
        t        f$ r}t        d|z        d}~ww xY w)z
    Decode a HPACK-encoded header block, translating HPACK exceptions into
    sensible h2 errors.

    This only ever returns bytestring headers: h2 may emit them as
    unicode later, but internally it processes them as bytestrings only.
    T)rawzOversized header block: %sNzError decoding header block: %s)decoder   r,   r   
IndexErrorr  UnicodeDecodeErrorr#   )r   encoded_header_blockrj  s      rB   rv  rv    sh    C~~2~==# E ##?!#CDD
I/AB C =ABB	Cs    	A,AAAr  )Hr   r   enumr   r   hyperframe.exceptionsr   hyperframe.framer   r   r   r	   r
   r   r   r   r   r   r   r   hpack.hpackr   r   hpack.exceptionsr   r   r   r   errorsr   r   ri  r   r   r   r   r   r   r    r!   r"   
exceptionsr#   r$   r%   r&   r'   r(   r)   r*   r+   r,   frame_bufferr-   r   r.   r/   r   r0   r1   	utilitiesr2   r3   windowsr4   r6   rD   rj   rn   r   r  rv  r@   rA   rB   <module>r     s      5   
 ) A # 4  
  
 & , , < "d "t ".w 
a aHT
 T
n6$NCrA   