U
    Mf>                     @  s  d dl mZ d dlZd dlZd dlZd dlZd dlmZmZm	Z	m
Z
mZmZmZ ddlmZ ddlmZmZmZmZmZmZ ddd	d
dddddddgZedZdddddddZddddddZedZddddddZedZdddd d!d"d#Zed$Zed%Z dddd d!d&d'Z!ed(Z"ed)Z#ddd*d+d,Z$d-dddd.d/d0d1Z%dddd2d!d3d4Z&dd5d6d7dZ'ed8Z(dddd9d!d:d;Z)dd<d6d=d	Z*dddd>d!d?d@Z+ddddAd!dBdCZ,ddDd6dEd
Z-e-Z.dFdGddHdIdJZ/dKddLdMdZ0e0Z1ddddNd!dOdPZ2ddQd6dRdZ3e3Z4dSddTdUdZ5e5Z6dSdVdTdWdZ7dddXdYdZ8edZZ9dddd d!d[d\Z:ddddVd!d]d^Z;dd_d6d`dZ<ddddadbdZ=dS )c    )annotationsN)CallableListOptionalSequenceTupleTypeVarcast   )
exceptions)ConnectionOptionExtensionHeaderExtensionNameExtensionParameterSubprotocolUpgradeProtocol
build_hostparse_connectionparse_upgradeparse_extensionbuild_extensionparse_subprotocolbuild_subprotocolvalidate_subprotocolsbuild_www_authenticate_basicparse_authorization_basicbuild_authorization_basicTstrintbool)hostportsecurereturnc                 C  s\   zt | }W n tk
r"   Y nX |jdkr:d|  d} ||rDdndkrX|  d| } | S )z#
    Build a ``Host`` header.

       []i  P   :)	ipaddress
ip_address
ValueErrorversion)r!   r"   r#   address r/   6/tmp/pip-unpacked-wheel-yzabpfcc/websockets/headers.pyr   &   s    
zOptional[str])headerposr$   c                 C  s   |t | krdS | | S )z
    Return the next character from ``header`` at the given position.

    Return :obj:`None` at the end of ``header``.

    We never need to peek more than one character ahead.

    N)len)r1   r2   r/   r/   r0   
peek_aheadB   s    	r4   z[\t ]*c                 C  s    t | |}|dk	st| S )z
    Parse optional whitespace from ``header`` at the given position.

    Return the new position.

    The whitespace itself isn't returned because it isn't significant.

    N)_OWS_rematchAssertionErrorend)r1   r2   r6   r/   r/   r0   	parse_OWSQ   s    
r9   z[-!#$%&\'*+.^_`|~0-9a-zA-Z]+zTuple[str, int])r1   r2   header_namer$   c                 C  s4   t | |}|dkr$t|d| || | fS )z
    Parse a token from ``header`` at the given position.

    Return the token value and the new position.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    Nzexpected token)	_token_rer6   r   InvalidHeaderFormatgroupr8   r1   r2   r:   r6   r/   r/   r0   parse_tokenc   s    
r?   zC"(?:[\x09\x20-\x21\x23-\x5b\x5d-\x7e]|\\[\x09\x20-\x7e\x80-\xff])*"z\\([\x09\x20-\x7e\x80-\xff])c                 C  sD   t | |}|dkr$t|d| |td| dd | fS )z
    Parse a quoted string from ``header`` at the given position.

    Return the unquoted value and the new position.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    Nzexpected quoted stringz\1r
   )_quoted_string_rer6   r   r<   _unquote_resubr=   r8   r>   r/   r/   r0   parse_quoted_string{   s    
   rD   z[\x09\x20-\x7e\x80-\xff]*z([\x22\x5c]))valuer$   c                 C  s.   t | }|dkrtddtd|  d S )zh
    Format ``value`` as a quoted string.

    This is the reverse of :func:`parse_quoted_string`.

    Nz-invalid characters for quoted-string encoding"z\\\1)_quotable_re	fullmatchr,   	_quote_rerC   )rE   r6   r/   r/   r0   build_quoted_string   s    
rJ   z(Callable[[str, int, str], Tuple[T, int]]zList[T])
parse_itemr1   r2   r:   r$   c                 C  s   t ||dkrt||d }q g }| |||\}}|| t||}|t|krTqt ||dkrrt||d }nt|d||t ||dkrt||d }q|t|kr"qq"|t|kst|S )a  
    Parse a comma-separated list from ``header`` at the given position.

    This is appropriate for parsing values with the following grammar:

        1#item

    ``parse_item`` parses one item.

    ``header`` is assumed not to start or end with whitespace.

    (This function is designed for parsing an entire header value and
    :func:`~websockets.http.read_headers` strips whitespace from values.)

    Return a list of items.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    ,r
   zexpected comma)r4   r9   appendr3   r   r<   r7   )rK   r1   r2   r:   itemsitemr/   r/   r0   
parse_list   s,    

   rP   zTuple[ConnectionOption, int]c                 C  s   t | ||\}}tt||fS )z
    Parse a Connection option from ``header`` at the given position.

    Return the protocol value and the new position.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    )r?   r	   r   r1   r2   r:   rO   r/   r/   r0   parse_connection_option   s    rR   zList[ConnectionOption])r1   r$   c                 C  s   t t| ddS )z
    Parse a ``Connection`` header.

    Return a list of HTTP connection options.

    Args
        header: value of the ``Connection`` header.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    r   
Connection)rP   rR   r1   r/   r/   r0   r      s    z>[-!#$%&\'*+.^_`|~0-9a-zA-Z]+(?:/[-!#$%&\'*+.^_`|~0-9a-zA-Z]+)?zTuple[UpgradeProtocol, int]c                 C  s:   t | |}|dkr$t|d| |tt| | fS )z
    Parse an Upgrade protocol from ``header`` at the given position.

    Return the protocol value and the new position.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    Nzexpected protocol)_protocol_rer6   r   r<   r	   r   r=   r8   r>   r/   r/   r0   parse_upgrade_protocol	  s       rV   zList[UpgradeProtocol]c                 C  s   t t| ddS )z
    Parse an ``Upgrade`` header.

    Return a list of HTTP protocols.

    Args:
        header: value of the ``Upgrade`` header.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    r   ZUpgrade)rP   rV   rT   r/   r/   r0   r     s    zTuple[ExtensionParameter, int]c                 C  s   t | ||\}}t| |}d}t| |dkrt| |d }t| |dkr||}t| ||\}}t|dkrt|d| |nt | ||\}}t| |}||f|fS )z
    Parse a single extension parameter from ``header`` at the given position.

    Return a ``(name, value)`` pair and the new position.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    N=r
   rF   zinvalid quoted header content)r?   r9   r4   rD   r;   rH   r   r<   )r1   r2   r:   namerE   Z
pos_beforer/   r/   r0   parse_extension_item_param-  s$    
   
rY   zTuple[ExtensionHeader, int]c                 C  sh   t | ||\}}t| |}g }t| |dkrVt| |d }t| ||\}}|| qtt||f|fS )a  
    Parse an extension definition from ``header`` at the given position.

    Return an ``(extension name, parameters)`` pair, where ``parameters`` is a
    list of ``(name, value)`` pairs, and the new position.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    ;r
   )r?   r9   r4   rY   rM   r	   r   )r1   r2   r:   rX   
parametersZ	parameterr/   r/   r0   parse_extension_itemQ  s    
r\   zList[ExtensionHeader]c                 C  s   t t| ddS )a  
    Parse a ``Sec-WebSocket-Extensions`` header.

    Return a list of WebSocket extensions and their parameters in this format::

        [
            (
                'extension name',
                [
                    ('parameter name', 'parameter value'),
                    ....
                ]
            ),
            ...
        ]

    Parameter values are :obj:`None` when no value is provided.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    r   zSec-WebSocket-Extensions)rP   r\   rT   r/   r/   r0   r   j  s    r   zList[ExtensionParameter])rX   r[   r$   c                 C  s    d tt| gdd |D  S )zc
    Build an extension definition.

    This is the reverse of :func:`parse_extension_item`.

    z; c                 S  s*   g | ]"\}}|d kr|n| d| qS )NrW   r/   ).0rX   rE   r/   r/   r0   
<listcomp>  s   z(build_extension_item.<locals>.<listcomp>)joinr	   r   )rX   r[   r/   r/   r0   build_extension_item  s    	
r`   zSequence[ExtensionHeader])
extensionsr$   c                 C  s   d dd | D S )zl
    Build a ``Sec-WebSocket-Extensions`` header.

    This is the reverse of :func:`parse_extension`.

    , c                 s  s   | ]\}}t ||V  qd S )N)r`   )r]   rX   r[   r/   r/   r0   	<genexpr>  s    z"build_extension.<locals>.<genexpr>r_   )ra   r/   r/   r0   r     s    
zTuple[Subprotocol, int]c                 C  s   t | ||\}}tt||fS )z
    Parse a subprotocol from ``header`` at the given position.

    Return the subprotocol value and the new position.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    )r?   r	   r   rQ   r/   r/   r0   parse_subprotocol_item  s    re   zList[Subprotocol]c                 C  s   t t| ddS )z
    Parse a ``Sec-WebSocket-Protocol`` header.

    Return a list of WebSocket subprotocols.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    r   zSec-WebSocket-Protocol)rP   re   rT   r/   r/   r0   r     s    
zSequence[Subprotocol])subprotocolsr$   c                 C  s
   d | S )zl
    Build a ``Sec-WebSocket-Protocol`` header.

    This is the reverse of :func:`parse_subprotocol`.

    rb   rd   )rf   r/   r/   r0   r     s    Nonec                 C  sJ   t | tstdt | tr$td| D ]}t|s(td| q(dS )zT
    Validate that ``subprotocols`` is suitable for :func:`build_subprotocol`.

    zsubprotocols must be a listz&subprotocols must be a list, not a strzinvalid subprotocol: N)
isinstancer   	TypeErrorr   r;   rH   r,   )rf   Zsubprotocolr/   r/   r0   r     s    


)realmr$   c                 C  s    t | } t d}d|  d| S )z
    Build a ``WWW-Authenticate`` header for HTTP Basic Auth.

    Args:
        realm: identifier of the protection space.

    zUTF-8zBasic realm=z
, charset=)rJ   )rj   charsetr/   r/   r0   r     s    	z[A-Za-z0-9-._~+/]+=*c                 C  s4   t | |}|dkr$t|d| || | fS )z
    Parse a token68 from ``header`` at the given position.

    Return the token value and the new position.

    Raises:
        InvalidHeaderFormat: on invalid inputs.

    Nzexpected token68)_token68_rer6   r   r<   r=   r8   r>   r/   r/   r0   parse_token68  s    
   rm   c                 C  s    |t | k rt|d| |dS )z8
    Check that parsing reached the end of header.

    ztrailing dataN)r3   r   r<   )r1   r2   r:   r/   r/   r0   	parse_end  s    rn   zTuple[str, str]c                 C  s   t | dd\}}| dkr.tdd| t| |dkrLtdd| ||d7 }t| |d\}}t| |d zt	|
  }W n$ tjk
r   tddd	Y nX z|d
d\}}W n" tk
r   tddd	Y nX ||fS )a!  
    Parse an ``Authorization`` header for HTTP Basic Auth.

    Return a ``(username, password)`` tuple.

    Args:
        header: value of the ``Authorization`` header.

    Raises:
        InvalidHeaderFormat: on invalid inputs.
        InvalidHeaderValue: on unsupported inputs.

    r   Authorizationbasiczunsupported scheme:  zexpected space after schemer
   z#expected base64-encoded credentialsNr)   z&expected username:password credentials)r?   lowerr   ZInvalidHeaderValuer4   r<   rm   rn   base64	b64decodeencodedecodebinasciiErrorsplitr,   )r1   schemer2   basic_credentials	user_passusernamepasswordr/   r/   r0   r     sF       )r}   r~   r$   c                 C  s4   d| kst |  d| }t|  }d| S )z
    Build an ``Authorization`` header for HTTP Basic Auth.

    This is the reverse of :func:`parse_authorization_basic`.

    r)   zBasic )r7   rs   	b64encoderu   rv   )r}   r~   r|   r{   r/   r/   r0   r   @  s    )>
__future__r   rs   rw   r*   retypingr   r   r   r   r   r   r	    r   r   r   r   r   r   r   __all__r   r   r4   compiler5   r9   r;   r?   rA   rB   rD   rG   rI   rJ   rP   rR   r   rU   rV   r   rY   r\   r   Zparse_extension_listr`   r   Zbuild_extension_listre   r   Zparse_subprotocol_listr   Zbuild_subprotocol_listr   r   rl   rm   rn   r   r   r/   r/   r/   r0   <module>   sz   $ 




D$

	0