
    NgX                     @   d Z ddlZddlmZmZ ddlmZmZmZ ddl	m
Z
 ddlmZmZ ddlmZ dd	lmZmZ  ej        e          Zd
ZdZdZd  ed          D             Z	 eZn# e$ r eefZY nw xY wdZd Z d Z!d Z"d Z#d Z$ G d d          Z% G d d          Z&dS )ze
hpack/hpack
~~~~~~~~~~~

Implements the HPACK header compression algorithm as detailed by the IETF.
    N   )HeaderTabletable_entry_size)HPACKDecodingErrorOversizedHeaderListErrorInvalidTableSizeError)HuffmanEncoder)REQUEST_CODESREQUEST_CODES_LENGTH)decode_huffman)HeaderTupleNeverIndexedHeaderTuple          @c                     g | ]
}d |z  dz
  S )   r    ).0is     G/var/www/html/ai-engine/env/lib/python3.11/site-packages/hpack/hpack.py
<listcomp>r      s     :::AAFa<:::    	   i   c                     t          | d                   }t          | d                   }|s*|                    d          }|                    d          }|                     ||          S )zj
    Provides a header as a unicode string if raw is False, otherwise returns
    it as a bytestring.
    r   r   utf-8)bytesdecode	__class__)headerrawnamevalues       r   _unicode_if_neededr$   +   sf    
 D&)E &{{7##W%%D%(((r   c                    t                               d| |           | dk     rt          d| z            |dk     s|dk    rt          d|z            t          |         }| |k     rt	          | g          S |g}| |z  } | dk    r&|                    | dz  dz              | d	z  } | dk    &|                    |            t	          |          S )
zn
    This encodes an integer according to the wacky integer encoding rules
    defined in the HPACK spec.
    zEncoding %d with %d bitsr   z)Can only encode positive integers, got %sr      +Prefix bits must be between 1 and 8, got %s         )logdebug
ValueError_PREFIX_BIT_MAX_NUMBERS	bytearrayappend)integerprefix_bits
max_numberelementss       r   encode_integerr5   8   s    
 II(';???{{7'A
 
 	
 Q+//9KG
 
 	
 )5J'###<:nnOOWs]c1222MG nn 	   """r   c                 t   |dk     s|dk    rt          d|z            t          |         }d}d}dd|z
  z	  }	 | d         |z  }||k    r/	 | |         }|dz  }|dk    r||dz
  |z  z  }n	|||z  z  }n|dz  }.n # t          $ r t          d	| z            w xY wt                              d
||           ||fS )z
    This decodes an integer according to the wacky integer encoding rules
    defined in the HPACK spec. Returns a tuple of the decoded integer and the
    number of bytes that were consumed from ``data`` in order to get that
    integer.
    r   r&   r'   r      Tr(   r*   z5Unable to decode HPACK integer representation from %rzDecoded %d, consumed %d bytes)r-   r.   
IndexErrorr   r+   r,   )datar2   r3   indexshiftmasknumber	next_bytes           r   decode_integerr?   Z   s"    Q+//9KG
 
 	
 )5JEEQ_%D
a4Z	 K	
##y3588FFi500F
	  
 
 
 CdJ
 
 	


 II-vu===5=s   A A: :Bc              #      K   t          | t                    sJ t          |                                 d           }|D ]}|| |         fV  dS )z
    This converts a dictionary to an iterable of two-tuples. This is a
    HPACK-specific function because it pulls "special-headers" out first and
    then emits them.
    c                 H    t          |                               d           S )N   :)	_to_bytes
startswith)ks    r   <lambda>z#_dict_to_iterable.<locals>.<lambda>   s    )A,,11$777 r   )keyN)
isinstancedictsortedkeys)header_dictrK   rG   s      r   _dict_to_iterablerM      s{       k4(((((77  D  $ $;s######$ $r   c                     t          | t                    st          |           } t          | t                    r| n|                     d          S )z"
    Convert string to bytes.
    r   )rH   
basestringstrr   encode)strings    r   rC   rC      sF     fj)) V..J66FMM'4J4JJr   c                   z    e Zd ZdZd Zed             Zej        d             ZddZddZ	d	 Z
dd
ZddZd ZdS )Encoderzm
    An HPACK encoder object. This object takes HTTP headers and emits encoded
    HTTP/2 header blocks.
    c                 x    t                      | _        t          t          t                    | _        g | _        d S N)r   header_tabler	   r
   r   huffman_codertable_size_changesselfs    r   __init__zEncoder.__init__   s6    'MM+/
 
 #%r   c                     | j         j        S z>
        Controls the size of the HPACK header table.
        rW   maxsizerZ   s    r   header_table_sizezEncoder.header_table_size       
  ((r   c                 n    || j         _        | j         j        r| j                            |           d S d S rV   )rW   r`   resizedrY   r0   r[   r#   s     r   ra   zEncoder.header_table_size   sB    $)!$ 	2#**511111	2 	2r   Tc                 X   g }t          |t                    rt          |          }| j        j        r3|                    |                                            d| j        _        |D ]}d}t          |t                    r	|j         }nt          |          dk    r|d         }t          |d                   t          |d                   f}|                    |                     |||                     d                    |          }t                              d|           |S )a	  
        Takes a set of headers and encodes them into a HPACK-encoded header
        block.

        :param headers: The headers to encode. Must be either an iterable of
                        tuples, an iterable of :class:`HeaderTuple
                        <hpack.HeaderTuple>`, or a ``dict``.

                        If an iterable of tuples, the tuples may be either
                        two-tuples or three-tuples. If they are two-tuples, the
                        tuples must be of the format ``(name, value)``. If they
                        are three-tuples, they must be of the format
                        ``(name, value, sensitive)``, where ``sensitive`` is a
                        boolean value indicating whether the header should be
                        added to header tables anywhere. If not present,
                        ``sensitive`` defaults to ``False``.

                        If an iterable of :class:`HeaderTuple
                        <hpack.HeaderTuple>`, the tuples must always be
                        two-tuples. Instead of using ``sensitive`` as a third
                        tuple entry, use :class:`NeverIndexedHeaderTuple
                        <hpack.NeverIndexedHeaderTuple>` to request that
                        the field never be indexed.

                        .. warning:: HTTP/2 requires that all special headers
                            (headers whose names begin with ``:`` characters)
                            appear at the *start* of the header block. While
                            this method will ensure that happens for ``dict``
                            subclasses, callers using any other iterable of
                            tuples **must** ensure they place their special
                            headers at the start of the iterable.

                            For efficiency reasons users should prefer to use
                            iterables of two-tuples: fixing the ordering of
                            dictionary headers is an expensive operation that
                            should be avoided if possible.

        :param huffman: (optional) Whether to Huffman-encode any header sent as
                        a literal value. Except for use when debugging, it is
                        recommended that this be left enabled.

        :returns: A bytestring containing the HPACK-encoded header block.
        Fr   r   r   r   zEncoded header block to %s)rH   rI   rM   rW   rd   r0   _encode_table_size_changer   	indexablelenrC   addjoinr+   r,   )r[   headershuffmanheader_blockr    	sensitives         r   rQ   zEncoder.encode   s*   d 
 gt$$ 	1'00G $ 	. > > @ @AAA(-D%  	F 	FFI&+.. & & 00		Vq"1I	q	**IfQi,@,@AFG D DEEEExx--		.===r   Fc                    t                               d|||           |\  }}|st          nt          }| j                            ||          }|7|                     ||||          }|s| j                            ||           |S |\  }	}}
|
r|                     |	          }n5| 	                    |	|||          }|s| j                            ||           |S )zQ
        This function takes a header key-value tuple and serializes it.
        z7Adding %s to the header table, sensitive:%s, huffman:%s)
r+   r,   INDEX_INCREMENTALINDEX_NEVERrW   search_encode_literalrj   _encode_indexed_encode_indexed_literal)r[   to_addro   rm   r"   r#   indexbitmatchencodedr:   perfects              r   rj   zEncoder.add  s    			E		
 	
 	
 e -6F$$; !((u55= **4'JJG 3!%%dE222N
  %tW 	3**511GG 22uh G  3!%%dE222r   c                 `    t          |d          }|dxx         dz  cc<   t          |          S )zD
        Encodes a header using the indexed representation.
        r*   r   r(   )r5   r   )r[   r:   fields      r   ru   zEncoder._encode_indexed8  s5     ua((aDU||r   c                    |r4| j                             |          }| j                             |          }t          t          |          d          }t          t          |          d          }|r |dxx         dz  cc<   |dxx         dz  cc<   d                    |t          |          |t          |          |g          S )z
        Encodes a header with a literal name and literal value. If ``indexing``
        is True, the header will be added to the header table: otherwise it
        will not.
        r*   r   r(   r   )rX   rQ   r5   ri   rk   r   )r[   r"   r#   rx   rm   name_len	value_lens          r   rt   zEncoder._encode_literal@  s      	5%,,T22D&--e44E!#d))Q//"3u::q11	 	!QKKK4KKKaLLLD LLLxxuXeI.>.>F
 
 	
r   c                    |t           k    rt          |d          }nt          |d          }|dxx         t          |          z  cc<   |r| j                            |          }t          t          |          d          }|r|dxx         dz  cc<   d                    t          |          t          |          |g          S )zv
        Encodes a header with an indexed name and a literal value and performs
        incremental indexing.
              r   r*   r(   r   )rq   r5   ordrX   rQ   ri   rk   r   )r[   r:   r#   rx   rm   prefixr   s          r   rv   zEncoder._encode_indexed_literalU  s    
 (((#E1--FF#E1--Fq			S]]"			 	5&--e44E"3u::q11	 	!aLLLD LLLxxvi(8(8%@AAAr   c                     d}| j         D ]4}t          |d          }|dxx         dz  cc<   |t          |          z  }5g | _         |S )zd
        Produces the encoded form of all header table size change context
        updates.
        r      r       )rY   r5   r   )r[   block
size_bytess      r   rg   z!Encoder._encode_table_size_changek  sa    
 1 	' 	'J'
A66JqMMMT!MMMU:&&&EE"$r   N)TF)__name__
__module____qualname____doc__r\   propertyra   setterrQ   rj   ru   rt   rv   rg   r   r   r   rT   rT      s         
% % % ) ) X) 2 2 2
O O O Ob/ / / /b  
 
 
 
*B B B B,    r   rT   c                   ~    e Zd ZdZefdZed             Zej        d             ZddZ	d Z
d Zd	 Zd
 Zd Zd ZdS )Decodera  
    An HPACK decoder object.

    .. versionchanged:: 2.3.0
       Added ``max_header_list_size`` argument.

    :param max_header_list_size: The maximum decompressed size we will allow
        for any single header block. This is a protection against DoS attacks
        that attempt to force the application to expand a relatively small
        amount of data into a really large header list, allowing enormous
        amounts of memory to be allocated.

        If this amount of data is exceeded, a `OversizedHeaderListError
        <hpack.OversizedHeaderListError>` exception will be raised. At this
        point the connection should be shut down, as the HPACK state will no
        longer be usable.

        Defaults to 64kB.
    :type max_header_list_size: ``int``
    c                 \    t                      | _        || _        | j        j        | _        d S rV   )r   rW   max_header_list_sizer`   max_allowed_table_size)r[   r   s     r   r\   zDecoder.__init__  s.    'MM  %9! '+&7&?###r   c                     | j         j        S r^   r_   rZ   s    r   ra   zDecoder.header_table_size  rb   r   c                     || j         _        d S rV   r_   re   s     r   ra   zDecoder.header_table_size  s    $)!!!r   Fc                 *   t                               d|           t          |          }g }t          |          }d}d}||k     r||         }|dz  rdnd}	|dz  rdnd}
|dz  rdnd}|	r!|                     ||d                   \  }}nv|
r!|                     ||d                   \  }}nS|r1|rt          d	          |                     ||d                   }d}n |                     ||d                   \  }}|rC|	                    |           |t          | z  }|| j        k    rt          d
| j        z            ||z  }||k     |                                  	 fd|D             S # t          $ r t          d          w xY w)a  
        Takes an HPACK-encoded header block and decodes it into a header set.

        :param data: A bytestring representing a complete HPACK-encoded header
                     block.
        :param raw: (optional) Whether to return the headers as tuples of raw
                    byte strings or to decode them as UTF-8 before returning
                    them. The default value is False, which returns tuples of
                    Unicode strings
        :returns: A list of two-tuples of ``(name, value)`` representing the
                  HPACK-encoded headers, in the order they were decoded.
        :raises HPACKDecodingError: If an error is encountered while decoding
                                    the header block.
        zDecoding %sr   r(   TF@   r   Nz/Table size update not at the start of the blockz.A header list larger than %d has been receivedc                 0    g | ]}t          |          S r   )r$   )r   hr!   s     r   r   z"Decoder.decode.<locals>.<listcomp>  s$    @@@1&q#..@@@r   z"Unable to decode headers as UTF-8.)r+   r,   
memoryviewri   _decode_indexed_decode_literal_indexr   _update_encoding_context_decode_literal_no_indexr0   r   r   r   _assert_valid_table_sizeUnicodeDecodeError)r[   r9   r!   data_memrl   data_leninflated_sizecurrent_indexcurrentindexedliteral_indexencoding_updater    consumeds     `           r   r   zDecoder.decode  sG    			-&&&d##t99h&& =)G%n7dd%G %,dN=DDM '.n?dd%O #'#7#7]^^,$ $   #'#=#=]^^,$ $  !   ,I    88]^^,   $(#@#@]^^,$ $   v&&&!16!:: 4#<<<2H12  
 X%Me h&&n 	%%'''	K@@@@@@@@! 	K 	K 	K$%IJJJ	Ks   *E8 8Fc                 D    | j         | j        k    rt          d          dS )zs
        Check that the table size set by the encoder is lower than the maximum
        we expect to have.
        z3Encoder did not shrink table size to within the maxN)ra   r   r   rZ   s    r   r   z Decoder._assert_valid_table_size
  s3    
 !D$???'E   @?r   c                 n    t          |d          \  }}|| j        k    rt          d          || _        |S )zC
        Handles a byte that updates the encoding context.
        r   z)Encoder exceeded max allowable table size)r?   r   r   ra   )r[   r9   new_sizer   s       r   r   z Decoder._update_encoding_context  sJ    
 ,D!44(d111';   "*r   c                     t          |d          \  }}t          | j                            |           }t                              d||           ||fS )zP
        Decodes a header represented using the indexed representation.
        r*   zDecoded %s, consumed %d)r?   r   rW   get_by_indexr+   r,   )r[   r9   r:   r   r    s        r   r   zDecoder._decode_indexed!  sT     )q11xd/<<UCCD		+VX>>>xr   c                 .    |                      |d          S )NF_decode_literalr[   r9   s     r   r   z Decoder._decode_literal_no_index*  s    ##D%000r   c                 .    |                      |d          S )NTr   r   s     r   r   zDecoder._decode_literal_index-  s    ##D$///r   c                 F   d}|r|d         dz  }d}d}n|d         }|dz  }d}|dz  }|r8t          ||          \  }}	| j                            |          d         }
|	}d}nn|dd	         }t          |d
          \  }}	||	|	|z            }
t          |
          |k    rt	          d          |d         dz  rt          |
          }
|	|z   dz   }||	|z   d	         }t          |d
          \  }}	||	|	|z            }t          |          |k    rt	          d          |d         dz  rt          |          }|||	z   z  }|rt          |
|          }nt          |
|          }|r| j                            |
|           t          
                    d|||           ||fS )z>
        Decodes a header represented with a literal.
        r   ?   r   F   r      r   Nr*   zTruncated header blockr(   z/Decoded %s, total consumed %d bytes, indexed %s)r?   rW   r   ri   r   r   r   r   rj   r+   r,   )r[   r9   should_indextotal_consumedindexed_namer   not_indexable	high_byter:   r   r"   lengthr#   r    s                 r   r   zDecoder._decode_literal0  s      	-7T>LH!MMQI$t+LH%,M 	3,T8<<OE8$11%88;D%NFF 8D-dA66FHF!223D4yyF""()ABBBAw~ ,%d++%.2NHv%&&' *$22Xh//0u::$%=>>>7T> 	*"5))E 	&8++  	.,T599FF u--F  	/!!$...		=		
 	
 	
 ~%%r   Nr   )r   r   r   r   DEFAULT_MAX_HEADER_LIST_SIZEr\   r   ra   r   r   r   r   r   r   r   r   r   r   r   r   r   y  s         ( -I @ @ @ @8 ) ) X) * * *SK SK SK SKj         1 1 10 0 0I& I& I& I& I&r   r   )'r   loggingtabler   r   
exceptionsr   r   r   rm   r	   huffman_constantsr
   r   huffman_tabler   structr   r   	getLoggerr   r+   
INDEX_NONErr   rq   ranger.   rO   	NameErrorrP   r   r   r$   r5   r?   rM   rC   rT   r   r   r   r   <module>r      s     0 0 0 0 0 0 0 0          $ # # # # #        * ) ) ) ) ) 8 8 8 8 8 8 8 8g!!
 
 ;:q::: JJ   uJJJ  ' 
) 
) 
)# # #D& & &R$ $ $K K KZ Z Z Z Z Z Z Zz@& @& @& @& @& @& @& @& @& @&s   !A$ $	A0/A0