
    nbiW                    .   d Z ddlmZ ddl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 dd
lmZmZ  ej        e          ZdZdZdZd  ed          D             ZeefZ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.
    )annotationsN   )HPACKDecodingErrorInvalidTableSizeErrorOversizedHeaderListError)HuffmanEncoder)REQUEST_CODESREQUEST_CODES_LENGTH)decode_huffman)HeaderTupleNeverIndexedHeaderTuple)HeaderTabletable_entry_size          @c                    g | ]
}d |z  dz
  S )   r    ).0is     _/var/www/html/mdtn/previsions/meteo_cartes/venv/lib/python3.11/site-packages/jh2/hpack/hpack.py
<listcomp>r       s     888!AqDA:888    	   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_integerr6   7   s    
 II(';???{{DwNOOOQ+//FTUUU(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-   )datar3   r4   indexshiftmasknumber	next_bytes           r   decode_integerr@   U   s    Q+//FTUUU(5JEEAO$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    	!8O8OPT8U8U4U r   )keyN)
isinstancedictsortedkeys)header_dictrL   rH   s      r   _dict_to_iterablerN   |   sr       k4(((((+""$$*U*UVVVD $ $;s######$ $r   c                    t          | t                    st          |           } t          | t                    r| n|                     d          S )z"
    Convert string to bytes.
    r   )rI   
basestringstrr   encode)strings    r   rD   rD      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__   s/    'MM+M;OPP"$r   c                    | j         j        S z>
        Controls the size of the HPACK header table.
        rX   maxsizer[   s    r   header_table_sizezEncoder.header_table_size       
  ((r   c                n    || j         _        | j         j        r| j                            |           d S d S rW   )rX   ra   resizedrZ   r1   r\   r$   s     r   rb   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)rI   rJ   rN   rX   re   r1   _encode_table_size_changer   	indexablelenrD   addjoinr,   r-   )r\   headershuffmanheader_blockr!   	sensitives         r   rR   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_NEVERrX   search_encode_literalrk   _encode_indexed_encode_indexed_literal)r\   to_addrp   rn   r#   r$   indexbitmatchencodedr;   perfects              r   rk   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25%7SSG 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)   )r6   r   )r\   r;   fields      r   rv   zEncoder._encode_indexed*  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   )rY   rR   r6   rj   rl   r   )r\   r#   r$   ry   rn   name_len	value_lens          r   ru   zEncoder._encode_literal2  s      	5%,,T22D&--e44E!#d))Q//"3u::q11	 	!QKKK4KKKaLLLD LLLxx5??D%	:J:JERSSSr   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   )rr   r6   ordrY   rR   rj   rl   r   )r\   r;   r$   ry   rn   prefixr   s          r   rw   zEncoder._encode_indexed_literalE  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       )rZ   r6   r   )r\   block
size_bytess      r   rh   z!Encoder._encode_table_size_change[  sa    
 1 	' 	'J'
A66JqMMMT!MMMU:&&&EE"$r   N)TF)__name__
__module____qualname____doc__r]   propertyrb   setterrR   rk   rv   ru   rw   rh   r   r   r   rU   rU      s         
% % %
 ) ) X) 2 2 2
O O O Ob- - - -^  T T T T&B B B B,    r   rU   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 rW   )r   rX   max_header_list_sizera   max_allowed_table_size)r\   r   s     r   r]   zDecoder.__init__  s.    'MM  %9! '+&7&?###r   c                    | j         j        S r_   r`   r[   s    r   rb   zDecoder.header_table_size  rc   r   c                    || j         _        d S rW   r`   rf   s     r   rb   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-   
memoryviewrj   _decode_indexed_decode_literal_indexr   _update_encoding_context_decode_literal_no_indexr1   r   r   r   _assert_valid_table_sizeUnicodeDecodeError)r\   r:   r"   data_memrm   data_leninflated_sizecurrent_indexcurrentindexedliteral_indexencoding_updater!   consumeds     `           r   r   zDecoder.decode  s2    			-&&&d##t99h&& =)G%n7dd%G %,dN=DDM '.n?dd%O #'#7#78P#Q#Q  #'#=#=h}~~>V#W#W     ,I    88-..9QRR $(#@#@]^^,$ $   v&&&!16!:: 4#<<<2H34  
 X%MY h&&b 	%%'''	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)rb   r   r   r[   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   rb   )r\   r:   new_sizer   s       r   r   z Decoder._update_encoding_context  sB    
 ,D!44(d111'(STTT!)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   rX   get_by_indexr,   r-   )r\   r:   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\   r:   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@   rX   r   rj   r   r   r   r   rk   r,   r-   )r\   r:   should_indextotal_consumedindexed_namer   not_indexable	high_byter;   r   r#   lengthr$   r!   s                 r   r   zDecoder._decode_literal  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8f#445D4yyF""()ABBBAw~ ,%d++%.2NHv%''( *$22X6 112u::$%=>>>7T> 	*"5))E 	&8++  	.,T599FF u--F  	/!!$...		=		
 	
 	
 ~%%r   Nr   )r   r   r   r   DEFAULT_MAX_HEADER_LIST_SIZEr]   r   rb   r   r   r   r   r   r   r   r   r   r   r   r   r   i  s         * -I @ @ @ @8 ) ) X) * * *MK MK MK MK^  	 	 	     1 1 10 0 0I& I& I& I& I&r   r   )(r   
__future__r   logging
exceptionsr   r   r   rn   r   huffman_constantsr	   r
   huffman_tabler   structr   r   tabler   r   	getLoggerr   r,   
INDEX_NONErs   rr   ranger/   rQ   r   rP   r   r%   r6   r@   rN   rD   rU   r   r   r   r   <module>r      s    # " " " " "          
 $ # # # # # B B B B B B B B ) ) ) ) ) ) 8 8 8 8 8 8 8 8 0 0 0 0 0 0 0 0g!!
 
 98uuQxx888 5\

  % 
) 
) 
)# # #<$ $ $N	$ 	$ 	$K K KT T T T T T T Tny& y& y& y& y& y& y& y& y& y&r   