
    h_                    T   d Z ddlm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mZ ddlmZmZ erddlmZ  ej        e          ZdZdZdZ d  e!d          D             Z"dZ#d.dZ$d/dZ%d0d"Z&d1d&Z'd2d)Z( G d* d+          Z) G d, d-          Z*dS )3zL
Implements the HPACK header compression algorithm as detailed by RFC 7541.
    )annotationsN)TYPE_CHECKINGAny   )HPACKDecodingErrorInvalidTableSizeErrorOversizedHeaderListError)HuffmanEncoder)REQUEST_CODESREQUEST_CODES_LENGTH)decode_huffman)HeaderTupleHeaderWeaklyTypedNeverIndexedHeaderTuple)HeaderTabletable_entry_size)Iterable          @c                    g | ]
}d |z  dz
  S )   r    ).0is     O/var/www/html/e360mart/e360mart_env/lib/python3.11/site-packages/hpack/hpack.py
<listcomp>r      s     :::AAFa<:::    	   i   headerr   rawboolreturnr   c                    t          | d                   }t          | d                   }|s<|                     |                    d          |                    d                    S |                     ||          S )zj
    Provides a header as a unicode string if raw is False, otherwise returns
    it as a bytestring.
    r   r   utf-8)bytes	__class__decode)r    r!   namevalues       r   _unicode_if_neededr+   #   ss    
 D&)E MG 4 4ell76K6KLLLD%(((r   integerintprefix_bits	bytearrayc                   t                               d| |           | dk     rd|  }t          |          |dk     s|dk    rd| }t          |          t          |         }| |k     rt	          | g          S |g}| |z  } | dk    r&|                    | dz  dz              | d	z  } | dk    &|                    |            t	          |          S )
zi
    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 r      )Prefix bits must be between 1 and 8, got          )logdebug
ValueError_PREFIX_BIT_MAX_NUMBERSr/   append)r,   r.   msg
max_numberelementss        r   encode_integerr>   0   s    
 II(';???{{AAAooQ+//G+GGoo(5J'###|HzG
S..3#-...A S.. OOGXr   datar&   tuple[int, int]c                   |dk     s|dk    rd| }t          |          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}	d	| }t          |          |	d
}	~	ww xY wt                              d||           ||fS )z
    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   r1   r2   r      Tr3   r5   z3Unable to decode HPACK integer representation from NzDecoded %d, consumed %d bytes)r8   r9   
IndexErrorr   r6   r7   )
r?   r.   r;   r<   indexshiftmasknumber	next_byteerrs
             r   decode_integerrJ   O   s&    Q+//G+GGoo(5JEEQ_%D/a4Z	 K	
##y3588FFi500F
	  / / /LDLL %%3./ II-vu===5=s   A A< <
B BB header_dictdict[bytes | str, bytes | str])Iterable[tuple[bytes | str, bytes | str]]c              #     K   t          | t                    s!dt          |            }t          |          t	          |                                 d           }|D ]}|| |         fV  dS )z
    Converts a dictionary to an iterable of key-value tuples. This is a
    HPACK-specific function because it pulls "special-headers" out first and
    then emits them.
    zheader_dict not a dict, but 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type	TypeErrorsortedkeys)rK   r;   r[   rU   s       r   _dict_to_iterabler\   v   s       k4(( @T+->->@@nn77  D  $ $;s######$ $r   r*   bytes | str | Anyc                    t          |           }|t          u r| S |t          urt          |           } |                     d          S )zB
    Convert anything to bytes through a UTF-8 encoded string
    r%   )rX   r&   strencode)r*   ts     r   rQ   rQ      sC     	UAEzz||E

<<   r   c                      e Zd ZdZddZedd            Zej        dd            Z	 d d!dZd"d#dZ	d$dZ
d"d%dZd"d&dZd'dZdS )(Encoderzm
    An HPACK encoder object. This object takes HTTP headers and emits encoded
    HTTP/2 header blocks.
    r#   Nonec                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+/
 
 .0r   r-   c                    | j         j        S z>
        Controls the size of the HPACK header table.
        rg   maxsizerj   s    r   header_table_sizezEncoder.header_table_size       
  ((r   r*   c                n    || j         _        | j         j        r| j                            |           d S d S rf   )rg   rp   resizedri   r:   rk   r*   s     r   rq   zEncoder.header_table_size   sB    $)!$ 	2#**511111	2 	2r   TheadersIterable[HeaderTuple | tuple[bytes | str, bytes | str] | tuple[bytes | str, bytes | str, bool | None]] | dict[bytes | str, bytes | str]huffmanr"   r&   c                z   g }| j         j        r3|                    |                                            d| j         _        t	          |t
                    rt          |          }n	 t          |          }|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)rg   rt   r:   _encode_table_size_changerV   rW   r\   iterr   	indexablelenrQ   addjoinr6   r7   )	rk   rv   rx   header_blockhpack_headersr    	sensitive
new_headerencodeds	            r   r`   zEncoder.encode   s=   p  $ 	. > > @ @AAA(-D%gt$$ 	* .g66MM& !MMM $ 		J 		JFI&+.. & & 00		Vq"1I	#F1I..	&)0D0DEJY H HIIII((<((		.888r   Fto_addtuple[bytes, bytes]r   c                   t                               d|||           |\  }}|st          nt          }| j                            ||          }|7|                     ||||          }|s| j                            ||           |S |\  }	}}
|
r|                     |	          }n5| 	                    |	|||          }|s| j                            ||           |S )z6
        Serializes a header key-value tuple.
        z7Adding %s to the header table, sensitive:%s, huffman:%s)
r6   r7   INDEX_INCREMENTALINDEX_NEVERrg   search_encode_literalr~   _encode_indexed_encode_indexed_literal)rk   r   r   rx   r)   r*   indexbitmatchr   rD   perfects              r   r~   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   rD   c                `    t          |d          }|dxx         dz  cc<   t          |          S )zD
        Encodes a header using the indexed representation.
        r5   r   r3   )r>   r&   )rk   rD   fields      r   r   zEncoder._encode_indexedM  s5     ua((aDU||r   r)   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.
        r5   r   r3   r   )rh   r`   r>   r}   r   r&   )rk   r)   r*   r   rx   name_len	value_lens          r   r   zEncoder._encode_literalU  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   r5   r3   r   )r   r>   ordrh   r`   r}   r   r&   )rk   rD   r*   r   rx   prefixr   s          r   r   zEncoder._encode_indexed_literalj  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       )ri   r>   r&   )rk   block
size_bytesbs       r   rz   z!Encoder._encode_table_size_change  s^    
 1 	 	Jz1--AaDDDDLDDDU1XXEE"$r   Nr#   rd   r#   r-   r*   r-   r#   rd   )T)rv   rw   rx   r"   r#   r&   F)r   r   r   r"   rx   r"   r#   r&   )rD   r-   r#   r&   )
r)   r&   r*   r&   r   r&   rx   r"   r#   r&   )
rD   r-   r*   r&   r   r&   rx   r"   r#   r&   )r#   r&   )__name__
__module____qualname____doc__rl   propertyrq   setterr`   r~   r   r   r   rz   r   r   r   rc   rc      s        
0 0 0 0 ) ) ) X) 2 2 2 2  $k k k k kZ/ / / / /b   
 
 
 
 
*B B B B B,     r   rc   c                      e Zd ZdZefddZedd            Zej        dd	            ZdddZ	ddZ
d dZd!dZd!dZd!dZd"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``
    max_header_list_sizer-   r#   rd   c                \    t                      | _        || _        | j        j        | _        d S rf   )r   rg   r   rp   max_allowed_table_size)rk   r   s     r   rl   zDecoder.__init__  s.    'MM  %9! '+&7&?###r   c                    | j         j        S rn   ro   rj   s    r   rq   zDecoder.header_table_size  rr   r   r*   c                    || j         _        d S rf   ro   ru   s     r   rq   zDecoder.header_table_size  s    $)!!!r   Fr?   r&   r!   r"   Iterable[HeaderTuple]c                   t                               d|           t          |          }g }t          |          }d}d}||k     r@||         }t	          |dz            }	t	          |dz            }
t	          |dz            }|	r!|                     ||d                   \  }}nx|
r!|                     ||d                   \  }}nU|r3|rd}t          |          |                     ||d                   }d}n | 	                    ||d                   \  }}|rY|
                    |           |t          |d         |d                   z  }|| j        k    rd	| j         d
}t          |          ||z  }||k     @|                                  	 fd|D             S # t          $ r}d}t          |          |d}~w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   r3   @   r   Nz/Table size update not at the start of the blockr   zA header list larger than z 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)r6   r7   
memoryviewr}   r"   _decode_indexed_decode_literal_indexr   _update_encoding_context_decode_literal_no_indexr:   r   r   r	   _assert_valid_table_sizeUnicodeDecodeError)rk   r?   r!   data_memrv   data_leninflated_sizecurrent_indexcurrentindexedliteral_indexencoding_updater    consumedr;   rI   s     `             r   r(   zDecoder.decode  sQ    			-&&&d##%'t99h&& =)G7T>**G !400M #7T>22O #'#7#7]^^,$ $   #'#=#=]^^,$ $  !   2KC,S11188]^^,   $(#@#@]^^,$ $   8v&&&!1&)VAY!G!GG 4#<<<dt7PdddC23777X%M_ h&&h 	%%'''	3@@@@@@@@! 	3 	3 	35C$S))s2	3s   F+ +
G5GGc                H    | j         | j        k    rd}t          |          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)rq   r   r   )rk   r;   s     r   r   z Decoder._assert_valid_table_size  s1    
 !D$???GC',,, @?r   c                r    t          |d          \  }}|| j        k    rd}t          |          || _        |S )zC
        Handles a byte that updates the encoding context.
        r   z)Encoder exceeded max allowable table size)rJ   r   r   rq   )rk   r?   new_sizer   r;   s        r   r   z Decoder._update_encoding_context'  sF    
 ,D!44(d111=C',,,!)r   tuple[HeaderTuple, int]c                    t          |d          \  }}t          | j                            |           }t                              d||           ||fS )zP
        Decodes a header represented using the indexed representation.
        r5   zDecoded %s, consumed %d)rJ   r   rg   get_by_indexr6   r7   )rk   r?   rD   r   r    s        r   r   zDecoder._decode_indexed3  sT     )q11xd/<<UCCD		+VX>>>xr   c                0    |                      |d          S )NFshould_index_decode_literalrk   r?   s     r   r   z Decoder._decode_literal_no_index<  s    ##Du#===r   c                0    |                      |d          S )NTr   r   r   s     r   r   zDecoder._decode_literal_index?  s    ##Dt#<<<r   r   c                h   d}|r|d         dz  }d}d}n!|d         }|dz  }d}t          |dz            }|r8t          ||          \  }}	| j                            |          d         }
|	}d}np|dd	         }t          |d
          \  }}	||	|	|z            }
t	          |
          |k    rd}t          |          |d         dz  rt          |
          }
|	|z   dz   }||	|z   d	         }t          |d
          \  }}	||	|	|z            }t	          |          |k    rd}t          |          |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   Nr5   zTruncated header blockr3   z/Decoded %s, total consumed %d bytes, indexed %s)r"   rJ   rg   r   r}   r   r   r   r   r~   r6   r7   )rk   r?   r   total_consumedindexed_namer   not_indexable	high_byterD   r   r)   lengthr;   r*   r    s                  r   r   zDecoder._decode_literalB  s,      	37T>LH!MMQI$t+LH T!122M 	3,T8<<OE8$11%88;D%NFF 8D-dA66FHF!223D4yyF"".(---Aw~ ,%d++%.2NHv%&&' *$22Xh//0u::*C$S)))7T> 	*"5))E 	&8++
  	.,T599FF u--F  	/!!$...		=		
 	
 	
 ~%%r   N)r   r-   r#   rd   r   r   r   )r?   r&   r!   r"   r#   r   r   )r?   r&   r#   r-   )r?   r&   r#   r   )r?   r&   r   r"   r#   r   )r   r   r   r   DEFAULT_MAX_HEADER_LIST_SIZErl   r   rq   r   r(   r   r   r   r   r   r   r   r   r   r   r     s#        * 4P @ @ @ @ @8 ) ) ) X) * * * *Q3 Q3 Q3 Q3 Q3f- - - -
 
 
 
       > > > >= = = =L& L& L& L& L& L&r   r   )r    r   r!   r"   r#   r   )r,   r-   r.   r-   r#   r/   )r?   r&   r.   r-   r#   r@   )rK   rL   r#   rM   )r*   r]   r#   r&   )+r   
__future__r   loggingtypingr   r   
exceptionsr   r   r	   rx   r
   huffman_constantsr   r   huffman_tabler   structr   r   r   tabler   r   collections.abcr   	getLoggerr   r6   
INDEX_NONEr   r   ranger9   r   r+   r>   rJ   r\   rQ   rc   r   r   r   r   <module>r      s    # " " " " "  % % % % % % % % [ [ [ [ [ [ [ [ [ [ # # # # # # B B B B B B B B ) ) ) ) ) ) K K K K K K K K K K 0 0 0 0 0 0 0 0 )((((((g!!
 
 ;:q:::   ' 
) 
) 
) 
)   >$ $ $ $N$ $ $ $&	! 	! 	! 	!v v v v v v v vr@& @& @& @& @& @& @& @& @& @&r   