Your IP : 18.217.14.208


Current Path : /usr/lib/python3.6/site-packages/OpenSSL/__pycache__/
Upload File :
Current File : //usr/lib/python3.6/site-packages/OpenSSL/__pycache__/SSL.cpython-36.opt-1.pyc

3

�F\�[�R@sddlZddlZddlmZddlmZmZddlmZm	Z	ddl
mZddlm
Z
ddlmZddlmZmZmZmZdd	lmZmZmZmZmZ m!Z"m#Z$m%Z&m'Z(dd
l)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\gRZ0ye1Z2Wn&e3k
�r�Gd]d^�d^e4�Z2YnXej5Z5ej6Z6ej7Z7ej8Z8ej9Z9ej:Z:ej;Z<ej=Z>d_Z?d`Z@daZAdbZBdcZCddZDejEZFejGZHejIZJejKZLejMZNejOZPejQZRejSZTejUZVejWZXejYZZej[Z\ej]Z^ej_Z`ejaZbejcZdejeZfejgZhejiZjejkZlejmZnejoZpejqZrejsZtejuZvejwZxejyZzej{Z|ej}Z~ejZ�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej��r$ej�Z�ej�Z�ej�Z�ej�Z�e0j�dedfdgdhg�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�ej�Z�didjdkdldmgZ�dngZ�doZ�dpZ�GdqdS�dSe��Z�eee��Z�e e��Z�GdrdT�dTe��Z�GdsdU�dUe��Z�GdtdV�dVe��Z�GdudW�dWe��Z�GdvdX�dXe��Z�Gdwdx�dxe4�Z�Gdydz�dze��Z�Gd{d|�d|e��Z�Gd}d~�d~e��Z�Gdd��d�e��Z�Gd�d��d�e��Z�Gd�d��d�e��Z�d�d��Z�d�dY�Z�d�d��Z�e�ej�d��Z�e�ej�d��Z�e�ej�d��Z�Gd�dZ�dZe4�Z�Gd�d[�d[e4�Z�ee�e�d�eσZ�Gd�d\�d\e4�Z�ee�e�d�eσZ�ejӃdS)��N)�platform)�wraps�partial)�count�chain)�WeakValueDictionary)�	errorcode)�
deprecated)�binary_type�
integer_types�int2byte�
indexbytes)	�UNSPECIFIED�exception_from_error_queue�ffi�lib�make_assert�native�path_string�text_to_bytes_and_warn�no_zero_allocator)�FILETYPE_PEM�_PassphraseHelper�PKey�X509Name�X509�	X509Store�OPENSSL_VERSION_NUMBER�SSLEAY_VERSION�
SSLEAY_CFLAGS�SSLEAY_PLATFORM�
SSLEAY_DIR�SSLEAY_BUILT_ON�
SENT_SHUTDOWN�RECEIVED_SHUTDOWN�SSLv2_METHOD�SSLv3_METHOD�
SSLv23_METHOD�TLSv1_METHOD�TLSv1_1_METHOD�TLSv1_2_METHOD�OP_NO_SSLv2�OP_NO_SSLv3�OP_NO_TLSv1�
OP_NO_TLSv1_1�
OP_NO_TLSv1_2�MODE_RELEASE_BUFFERS�OP_SINGLE_DH_USE�OP_SINGLE_ECDH_USE�OP_EPHEMERAL_RSA�OP_MICROSOFT_SESS_ID_BUG�OP_NETSCAPE_CHALLENGE_BUG�#OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG�OP_SSLREF2_REUSE_CERT_TYPE_BUG�OP_MICROSOFT_BIG_SSLV3_BUFFER�OP_MSIE_SSLV2_RSA_PADDING�OP_SSLEAY_080_CLIENT_DH_BUG�
OP_TLS_D5_BUG�OP_TLS_BLOCK_PADDING_BUG�OP_DONT_INSERT_EMPTY_FRAGMENTS�OP_CIPHER_SERVER_PREFERENCE�OP_TLS_ROLLBACK_BUG�OP_PKCS1_CHECK_1�OP_PKCS1_CHECK_2�OP_NETSCAPE_CA_DN_BUG�"OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG�OP_NO_COMPRESSION�OP_NO_QUERY_MTU�OP_COOKIE_EXCHANGE�OP_NO_TICKET�OP_ALL�VERIFY_PEER�VERIFY_FAIL_IF_NO_PEER_CERT�VERIFY_CLIENT_ONCE�VERIFY_NONE�SESS_CACHE_OFF�SESS_CACHE_CLIENT�SESS_CACHE_SERVER�SESS_CACHE_BOTH�SESS_CACHE_NO_AUTO_CLEAR�SESS_CACHE_NO_INTERNAL_LOOKUP�SESS_CACHE_NO_INTERNAL_STORE�SESS_CACHE_NO_INTERNAL�SSL_ST_CONNECT�
SSL_ST_ACCEPT�SSL_ST_MASK�SSL_CB_LOOP�SSL_CB_EXIT�SSL_CB_READ�SSL_CB_WRITE�SSL_CB_ALERT�SSL_CB_READ_ALERT�SSL_CB_WRITE_ALERT�SSL_CB_ACCEPT_LOOP�SSL_CB_ACCEPT_EXIT�SSL_CB_CONNECT_LOOP�SSL_CB_CONNECT_EXIT�SSL_CB_HANDSHAKE_START�SSL_CB_HANDSHAKE_DONE�Error�
WantReadError�WantWriteError�WantX509LookupError�ZeroReturnError�SysCallError�SSLeay_version�Session�Context�
Connectionc@seZdZdS)�_bufferN)�__name__�
__module__�__qualname__�rsrs�/usr/lib/python3.6/SSL.pyrovsro�������SSL_ST_INIT�
SSL_ST_BEFORE�	SSL_ST_OK�SSL_ST_RENEGOTIATEz"/etc/ssl/certs/ca-certificates.crtz /etc/pki/tls/certs/ca-bundle.crtz/etc/ssl/ca-bundle.pemz/etc/pki/tls/cacert.pemz1/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pemz/etc/ssl/certss$/opt/pyca/cryptography/openssl/certss'/opt/pyca/cryptography/openssl/cert.pemc@seZdZdZdS)rez4
    An error occurred in an `OpenSSL.SSL` API.
    N)rprqrr�__doc__rsrsrsrtre�sc@seZdZdS)rfN)rprqrrrsrsrsrtrf�sc@seZdZdS)rgN)rprqrrrsrsrsrtrg�sc@seZdZdS)rhN)rprqrrrsrsrsrtrhsc@seZdZdS)riN)rprqrrrsrsrsrtrisc@seZdZdS)rjN)rprqrrrsrsrsrtrj	sc@s eZdZdZdd�Zdd�ZdS)�_CallbackExceptionHelpera�
    A base class for wrapper classes that allow for intelligent exception
    handling in OpenSSL callbacks.

    :ivar list _problems: Any exceptions that occurred while executing in a
        context where they could not be raised in the normal way.  Typically
        this is because OpenSSL has called into some Python code and requires a
        return value.  The exceptions are saved to be raised later when it is
        possible to do so.
    cCs
g|_dS)N)�	_problems)�selfrsrsrt�__init__sz!_CallbackExceptionHelper.__init__cCs6|jr2y
t�Wntk
r$YnX|jjd��dS)z�
        Raise an exception from the OpenSSL error queue or that was previously
        captured whe running a callback.
        rN)r��_raise_current_errorre�pop)r�rsrsrt�raise_if_problems
z)_CallbackExceptionHelper.raise_if_problemN)rprqrrrr�r�rsrsrsrtr�
s
r�c@seZdZdZdd�ZdS)�
_VerifyHelperz^
    Wrap a callback such that it can be used as a certificate verification
    callback.
    cs2tj��t����fdd��}tjd|��_dS)Ncs�tj|�}tj|�tj|�}tj|�}tj|�}tj�}tj||�}t	j
|}y�|||||�}	Wn,tk
r�}
z�jj
|
�dSd}
~
XnX|	r�tj|tj�dSdSdS)Nrru)�_libZX509_STORE_CTX_get_current_cert�X509_up_refr�_from_raw_x509_ptrZX509_STORE_CTX_get_errorZX509_STORE_CTX_get_error_depthZ"SSL_get_ex_data_X509_STORE_CTX_idxZX509_STORE_CTX_get_ex_datarn�_reverse_mapping�	Exceptionr��appendZX509_STORE_CTX_set_errorZ	X509_V_OK)�okZ	store_ctxZx509�certZerror_numberZerror_depth�index�sslZ
connection�result�e)�callbackr�rsrt�wrapper2s$





z'_VerifyHelper.__init__.<locals>.wrapperzint (*)(int, X509_STORE_CTX *))r�r�r�_ffir�)r�r�r�rs)r�r�rtr�/s
z_VerifyHelper.__init__N)rprqrrrr�rsrsrsrtr�)sr�c@seZdZdZdd�ZdS)�_NpnAdvertiseHelperzT
    Wrap a callback such that it can be used as an NPN advertisement callback.
    cs2tj��t����fdd��}tjd|��_dS)Ncs�yntj|}�|�}djtjdd�|D���}tjdt|��tjd|�g|_|jdd|d<|jd|d<dSt	k
r�}z�j
j|�dSd}~XnXdS)	N�css|]}tt|��|fVqdS)N)r�len)�.0�prsrsrt�	<genexpr>asz@_NpnAdvertiseHelper.__init__.<locals>.wrapper.<locals>.<genexpr>zunsigned int *zunsigned char[]rrurv)rnr��joinr�
from_iterabler��newr��_npn_advertise_callback_argsr�r�r�)r��out�outlen�arg�conn�protos�protostrr�)r�r�rsrtr�Xs
z-_NpnAdvertiseHelper.__init__.<locals>.wrapperz>int (*)(SSL *, const unsigned char **, unsigned int *, void *))r�r�rr�r�)r�r�r�rs)r�r�rtr�Us

z_NpnAdvertiseHelper.__init__N)rprqrrrr�rsrsrsrtr�Psr�c@seZdZdZdd�ZdS)�_NpnSelectHelperzP
    Wrap a callback such that it can be used as an NPN selection callback.
    cs2tj��t����fdd��}tjd|��_dS)Nc
s�y�tj|}tj||�dd�}g}x<|r`t|d�}	|d|	d�}
|j|
�||	dd�}q&W�||�}tjdt|��tjd|�g|_|jdd|d<|jd|d<dSt	k
r�}z�j
j|�dSd}~XnXdS)Nrruzunsigned char *zunsigned char[]rv)rnr�r��bufferr
r�r�r��_npn_select_callback_argsr�r�)
r�r�r��in_�inlenr�r��instr�	protolist�length�proto�outstrr�)r�r�rsrtr��s$



z*_NpnSelectHelper.__init__.<locals>.wrapperz^int (*)(SSL *, unsigned char **, unsigned char *, const unsigned char *, unsigned int, void *))r�r�rr�r�)r�r�r�rs)r�r�rtr�~s

"z_NpnSelectHelper.__init__N)rprqrrrr�rsrsrsrtr�ysr�c@seZdZdZdd�ZdS)�_ALPNSelectHelperzQ
    Wrap a callback such that it can be used as an ALPN selection callback.
    cs2tj��t����fdd��}tjd|��_dS)Nc
s�y�tj|}tj||�dd�}g}x<|r`t|d�}	|d|	d�}
|j|
�||	dd�}q&W�||�}t|t�s~td��tj	dt
|��tj	d|�g|_|jdd|d<|jd|d<dStk
r�}z�j
j|�dSd}~XnXdS)Nrruz'ALPN callback must return a bytestring.zunsigned char *zunsigned char[]rv)rnr�r�r�r
r��
isinstance�_binary_type�	TypeErrorr�r��_alpn_select_callback_argsr�r�)
r�r�r�r�r�r�r�r�r�Zencoded_lenr�r�r�)r�r�rsrtr��s(




z+_ALPNSelectHelper.__init__.<locals>.wrapperz^int (*)(SSL *, unsigned char **, unsigned char *, const unsigned char *, unsigned int, void *))r�r�rr�r�)r�r�r�rs)r�r�rtr��s

$z_ALPNSelectHelper.__init__N)rprqrrrr�rsrsrsrtr��sr�c@seZdZdZdd�ZdS)�_OCSPServerCallbackHelpera�
    Wrap a callback such that it can be used as an OCSP callback for the server
    side.

    Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
    ways. For servers, that callback is expected to retrieve some OCSP data and
    hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
    SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
    is expected to check the OCSP data, and returns a negative value on error,
    0 if the response is not acceptable, or positive if it is. These are
    mutually exclusive return code behaviours, and they mean that we need two
    helpers so that we always return an appropriate error code if the user's
    code throws an exception.

    Given that we have to have two helpers anyway, these helpers are a bit more
    helpery than most: specifically, they hide a few more of the OpenSSL
    functions so that the user has an easier time writing these callbacks.

    This helper implements the server side.
    cs2tj��t����fdd��}tjd|��_dS)Ncs�y�tj|}|tjkr"tj|�}nd}�||�}t|t�sBtd��|sJdSt|�}t	j
|�}|tj||�dd�<t	j|||�dSt
k
r�}z�jj|�dSd}~XnXdS)Nz'OCSP callback must return a bytestring.rwrrv)rnr�r��NULL�from_handler�r�r�r�r�ZOPENSSL_mallocr�ZSSL_set_tlsext_status_ocsp_respr�r�r�)r��cdatar��data�	ocsp_dataZocsp_data_lengthZdata_ptrr�)r�r�rsrtr��s&





z3_OCSPServerCallbackHelper.__init__.<locals>.wrapperzint (*)(SSL *, void *))r�r�rr�r�)r�r�r�rs)r�r�rtr��s
'z"_OCSPServerCallbackHelper.__init__N)rprqrrrr�rsrsrsrtr��sr�c@seZdZdZdd�ZdS)�_OCSPClientCallbackHelpera�
    Wrap a callback such that it can be used as an OCSP callback for the client
    side.

    Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
    ways. For servers, that callback is expected to retrieve some OCSP data and
    hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
    SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
    is expected to check the OCSP data, and returns a negative value on error,
    0 if the response is not acceptable, or positive if it is. These are
    mutually exclusive return code behaviours, and they mean that we need two
    helpers so that we always return an appropriate error code if the user's
    code throws an exception.

    Given that we have to have two helpers anyway, these helpers are a bit more
    helpery than most: specifically, they hide a few more of the OpenSSL
    functions so that the user has an easier time writing these callbacks.

    This helper implements the client side.
    cs2tj��t����fdd��}tjd|��_dS)Nc	s�yxtj|}|tjkr"tj|�}nd}tjd�}tj||�}|dkrJd}ntj|d|�dd�}�|||�}t	t
|��Stk
r�}z�jj
|�dSd}~XnXdS)Nzunsigned char **rr�ru���)rnr�r�r�r�r�r�ZSSL_get_tlsext_status_ocsp_respr��int�boolr�r�r�)	r�r�r�r�Zocsp_ptrZocsp_lenr�Zvalidr�)r�r�rsrtr�9s


z3_OCSPClientCallbackHelper.__init__.<locals>.wrapperzint (*)(SSL *, void *))r�r�rr�r�)r�r�r�rs)r�r�rtr�6s
z"_OCSPClientCallbackHelper.__init__N)rprqrrrr�rsrsrsrtr� sr�cCsdd}t|t�s(t|dd�}|dk	r(|�}t|t�r6|}t|t�sJtd��n|dkr`td|f��|S)N�filenoz3argument must be an int, or have a fileno() method.rz1file descriptor cannot be a negative integer (%i))r�r�getattrr��
ValueError)�obj�fd�methrsrsrt�_asFileDescriptor[s



r�cCstjtj|��S)z�
    Return a string describing the version of OpenSSL in use.

    :param type: One of the :const:`SSLEAY_` constants defined in this module.
    )r��stringr�rk)�typersrsrtrknscs��fdd�}|S)a�
    Builds a decorator that ensures that functions that rely on OpenSSL
    functions that are not present in this build raise NotImplementedError,
    rather than AttributeError coming out of cryptography.

    :param flag: A cryptography flag that guards the functions, e.g.
        ``Cryptography_HAS_NEXTPROTONEG``.
    :param error: The string to be used in the exception if the flag is false.
    cs$�st|��fdd��}|S|SdS)Ncst���dS)N)�NotImplementedError)�args�kwargs)�errorrsrt�explode�sz<_make_requires.<locals>._requires_decorator.<locals>.explode)r)�funcr�)r��flagrsrt�_requires_decorator�sz+_make_requires.<locals>._requires_decoratorrs)r�r�r�rs)r�r�rt�_make_requiresws
	r�zNPN not availablezALPN not availablezSNI not availablec@seZdZdZdS)rlz�
    A class representing an SSL session.  A session defines certain connection
    parameters which may be re-used to speed up the setup of subsequent
    connections.

    .. versionadded:: 0.14
    N)rprqrrrrsrsrsrtrl�sc@s�eZdZdZededededede	diZ
edd	�e
j�D��Z
d
d�Z
ded
d�Zdd�Zdfdd�Zdd�Zdd�Zdd�Zdd�Zefdd�Zdd�Zdd �Zd!d"�Zefd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Z d/d0�Z!d1d2�Z"d3d4�Z#d5d6�Z$d7d8�Z%d9d:�Z&d;d<�Z'd=d>�Z(d?d@�Z)dAdB�Z*dCdD�Z+dEdF�Z,dGdH�Z-dIdJ�Z.dKdL�Z/dMdN�Z0dOdP�Z1dQdR�Z2e3dSdT��Z4dUdV�Z5e6dWdX��Z7e6dYdZ��Z8e9d[d\��Z:e9d]d^��Z;d_d`�Z<dgdadb�Z=dhdcdd�Z>dS)irmz�
    :class:`OpenSSL.SSL.Context` instances define the parameters for setting
    up new SSL connections.

    :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
        TLSv1_METHOD.
    ZSSLv2_methodZSSLv3_methodZ
SSLv23_methodZTLSv1_methodZTLSv1_1_methodZTLSv1_2_methodccs0|](\}}tt|d�dk	r|tt|�fVqdS)N)r�r�)r�Z
identifier�namersrsrtr��szContext.<genexpr>cCs&t|t�std��y|j|}Wntk
r<td��YnX|�}t|tjk�t	j
|�}t|tjk�tj|t	j�}yt	j
|d�}t|dk�Wntk
r�YnX||_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_ |j!t	j"�dS)Nzmethod must be an integerzNo such protocolru)#r�rr��_methods�KeyErrorr��_openssl_assertr�r�r�ZSSL_CTX_new�gcZSSL_CTX_freeZSSL_CTX_set_ecdh_auto�AttributeError�_context�_passphrase_helper�_passphrase_callback�_passphrase_userdata�_verify_helper�_verify_callback�_info_callback�_tlsext_servername_callback�	_app_data�_npn_advertise_helper�_npn_advertise_callback�_npn_select_helper�_npn_select_callback�_alpn_select_helper�_alpn_select_callback�_ocsp_helper�_ocsp_callback�
_ocsp_data�set_modeZSSL_MODE_ENABLE_PARTIAL_WRITE)r��methodZmethod_funcZ
method_obj�context�resrsrsrtr��sF

zContext.__init__NcCsN|dkrtj}nt|�}|dkr(tj}nt|�}tj|j||�}|sJt�dS)aU
        Let SSL know where we can find trusted certificates for the certificate
        chain.  Note that the certificates have to be in PEM format.

        If capath is passed, it must be a directory prepared using the
        ``c_rehash`` tool included with OpenSSL.  Either, but not both, of
        *pemfile* or *capath* may be :data:`None`.

        :param cafile: In which file we can find the certificates (``bytes`` or
            ``unicode``).
        :param capath: In which directory we can find the certificates
            (``bytes`` or ``unicode``).

        :return: None
        N)r�r��_path_stringr�ZSSL_CTX_load_verify_locationsr�r�)r��cafile�capathZload_resultrsrsrt�load_verify_locations�szContext.load_verify_locationscs&t����fdd��}tt|ddd�S)Ncs�||�j�S)N)r�)�sizeZverify�userdata)r�r�rsrtr�sz'Context._wrap_callback.<locals>.wrapperT)Z	more_args�truncate)rrr)r�r�r�rs)r�r�rt�_wrap_callback
szContext._wrap_callbackcCs@t|�std��|j|�|_|jj|_tj|j|j�||_	dS)a�
        Set the passphrase callback.  This function will be called
        when a private key with a passphrase is loaded.

        :param callback: The Python callback to use.  This must accept three
            positional arguments.  First, an integer giving the maximum length
            of the passphrase it may return.  If the returned passphrase is
            longer than this, it will be truncated.  Second, a boolean value
            which will be true if the user should be prompted for the
            passphrase twice and the callback should verify that the two values
            supplied are equal. Third, the value given as the *userdata*
            parameter to :meth:`set_passwd_cb`.  The *callback* must return
            a byte string. If an error occurs, *callback* should return a false
            value (e.g. an empty string).
        :param userdata: (optional) A Python object which will be given as
                         argument to the callback
        :return: None
        zcallback must be callableN)
�callabler�r�r�r�r�r�ZSSL_CTX_set_default_passwd_cbr�r�)r�r�r�rsrsrt�
set_passwd_cbs
zContext.set_passwd_cbcCs�tj|j�}t|dk�tjtj��jd�}tjtj��jd�}|j	||�s�tjtj
��}tjtj��}|tkr�|t
kr�|jtt�dS)a�
        Specify that the platform provided CA certificates are to be used for
        verification purposes. This method has some caveats related to the
        binary wheels that cryptography (pyOpenSSL's primary dependency) ships:

        *   macOS will only load certificates using this method if the user has
            the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
            in the default location.
        *   Windows will not work.
        *   manylinux1 cryptography wheels will work on most common Linux
            distributions in pyOpenSSL 17.1.0 and above.  pyOpenSSL detects the
            manylinux1 wheel and attempts to load roots via a fallback path.

        :return: None
        ru�asciiN)r�Z SSL_CTX_set_default_verify_pathsr�r�r�r�ZX509_get_default_cert_dir_env�decodeZX509_get_default_cert_file_env�_check_env_vars_setZX509_get_default_cert_dirZX509_get_default_cert_file�_CRYPTOGRAPHY_MANYLINUX1_CA_DIR� _CRYPTOGRAPHY_MANYLINUX1_CA_FILE�_fallback_default_verify_paths�_CERTIFICATE_FILE_LOCATIONS�_CERTIFICATE_PATH_LOCATIONS)r��
set_result�dir_env_var�file_env_varZdefault_dirZdefault_filersrsrt�set_default_verify_paths-s 

z Context.set_default_verify_pathscCs tjj|�dk	ptjj|�dk	S)zp
        Check to see if the default cert dir/file environment vars are present.

        :return: bool
        N)�os�environ�get)r�rrrsrsrtr�^szContext._check_env_vars_setcCsRx$|D]}tjj|�r|j|�PqWx&|D]}tjj|�r,|jd|�Pq,WdS)aW
        Default verify paths are based on the compiled version of OpenSSL.
        However, when pyca/cryptography is compiled as a manylinux1 wheel
        that compiled location can potentially be wrong. So, like Go, we
        will try a predefined set of paths and attempt to load roots
        from there.

        :return: None
        N)r�path�isfiler��isdir)r�Z	file_pathZdir_pathr�r�rsrsrtr�is



z&Context._fallback_default_verify_pathscCs$t|�}tj|j|�}|s t�dS)z�
        Load a certificate chain from a file.

        :param certfile: The name of the certificate chain file (``bytes`` or
            ``unicode``).  Must be PEM encoded.

        :return: None
        N)r�r�Z"SSL_CTX_use_certificate_chain_filer�r�)r��certfiler�rsrsrt�use_certificate_chain_file}s
	
z"Context.use_certificate_chain_filecCs8t|�}t|t�std��tj|j||�}|s4t�dS)ah
        Load a certificate from a file

        :param certfile: The name of the certificate file (``bytes`` or
            ``unicode``).
        :param filetype: (optional) The encoding of the file, which is either
            :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`.  The default is
            :const:`FILETYPE_PEM`.

        :return: None
        zfiletype must be an integerN)r�r�rr�r�ZSSL_CTX_use_certificate_filer�r�)r�r
�filetype�
use_resultrsrsrt�use_certificate_file�s
zContext.use_certificate_filecCs0t|t�std��tj|j|j�}|s,t�dS)zs
        Load a certificate from a X509 object

        :param cert: The X509 object
        :return: None
        zcert must be an X509 instanceN)r�rr�r�ZSSL_CTX_use_certificater��_x509r�)r�r�r
rsrsrt�use_certificate�s

zContext.use_certificatecCsDt|t�std��tj|j�}tj|j|�}|s@tj|�t	�dS)z�
        Add certificate to chain

        :param certobj: The X509 certificate object to add to the chain
        :return: None
        z certobj must be an X509 instanceN)
r�rr�r��X509_duprZSSL_CTX_add_extra_chain_certr�Z	X509_freer�)r�Zcertobj�copy�
add_resultrsrsrt�add_extra_chain_cert�s

zContext.add_extra_chain_certcCs |jdk	r|jjt�t�dS)N)r�r�rer�)r�rsrsrt�_raise_passphrase_exception�s
z#Context._raise_passphrase_exceptioncCsHt|�}|tkrt}nt|t�s(td��tj|j||�}|sD|j	�dS)aR
        Load a private key from a file

        :param keyfile: The name of the key file (``bytes`` or ``unicode``)
        :param filetype: (optional) The encoding of the file, which is either
            :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`.  The default is
            :const:`FILETYPE_PEM`.

        :return: None
        zfiletype must be an integerN)
r��_UNSPECIFIEDrr�rr�r�ZSSL_CTX_use_PrivateKey_filer�r)r�Zkeyfilerr
rsrsrt�use_privatekey_file�s
zContext.use_privatekey_filecCs2t|t�std��tj|j|j�}|s.|j�dS)zs
        Load a private key from a PKey object

        :param pkey: The PKey object
        :return: None
        zpkey must be a PKey instanceN)r�rr�r�ZSSL_CTX_use_PrivateKeyr�Z_pkeyr)r�Zpkeyr
rsrsrt�use_privatekey�s

zContext.use_privatekeycCstj|j�st�dS)z�
        Check if the private key (loaded with :meth:`use_privatekey`) matches
        the certificate (loaded with :meth:`use_certificate`)

        :return: :data:`None` (raises :exc:`Error` if something's wrong)
        N)r�ZSSL_CTX_check_private_keyr�r�)r�rsrsrt�check_privatekey�szContext.check_privatekeycCs0tjtd|��}t|tjk�tj|j|�dS)a%
        Load the trusted certificates that will be sent to the client.  Does
        not actually imply any of the certificates are trusted; that must be
        configured separately.

        :param bytes cafile: The path to a certificates file in PEM format.
        :return: None
        r�N)r�ZSSL_load_client_CA_file�_text_to_bytes_and_warnr�r�r��SSL_CTX_set_client_CA_listr�)r�r�Zca_listrsrsrt�load_client_ca�s	zContext.load_client_cacCs*td|�}ttj|j|t|��dk�dS)aV
        Set the session id to *buf* within which a session can be reused for
        this Context object.  This is needed when doing session resumption,
        because there is no way for a stored session to know which Context
        object it is associated with.

        :param bytes buf: The session id.

        :returns: None
        �bufruN)rr�r�ZSSL_CTX_set_session_id_contextr�r�)r�rrsrsrt�set_session_ids
zContext.set_session_idcCs t|t�std��tj|j|�S)a�
        Set the behavior of the session cache used by all connections using
        this Context.  The previously set mode is returned.  See
        :const:`SESS_CACHE_*` for details about particular modes.

        :param mode: One or more of the SESS_CACHE_* flags (combine using
            bitwise or)
        :returns: The previously set caching mode.

        .. versionadded:: 0.14
        zmode must be an integer)r�rr�r�ZSSL_CTX_set_session_cache_moder�)r��modersrsrt�set_session_cache_modes
zContext.set_session_cache_modecCstj|j�S)z�
        Get the current session cache mode.

        :returns: The currently used cache mode.

        .. versionadded:: 0.14
        )r�ZSSL_CTX_get_session_cache_moder�)r�rsrsrt�get_session_cache_mode,szContext.get_session_cache_modecCsLt|t�std��t|�s"td��t|�|_|jj|_tj	|j
||j�dS)a�
        et the verification flags for this Context object to *mode* and specify
        that *callback* should be used for verification callbacks.

        :param mode: The verify mode, this should be one of
            :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
            :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
            :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
            :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
        :param callback: The Python callback to use.  This should take five
            arguments: A Connection object, an X509 object, and three integer
            variables, which are in turn potential error number, error depth
            and return code. *callback* should return True if verification
            passes and False otherwise.
        :return: None

        See SSL_CTX_set_verify(3SSL) for further details.
        zmode must be an integerzcallback must be callableN)r�rr�r�r�r�r�r�r�ZSSL_CTX_set_verifyr�)r�rr�rsrsrt�
set_verify6s


zContext.set_verifycCs$t|t�std��tj|j|�dS)z�
        Set the maximum depth for the certificate chain verification that shall
        be allowed for this Context object.

        :param depth: An integer specifying the verify depth
        :return: None
        zdepth must be an integerN)r�rr�r�ZSSL_CTX_set_verify_depthr�)r��depthrsrsrt�set_verify_depthSs
zContext.set_verify_depthcCstj|j�S)z�
        Retrieve the Context object's verify mode, as set by
        :meth:`set_verify`.

        :return: The verify mode
        )r�ZSSL_CTX_get_verify_moder�)r�rsrsrt�get_verify_mode`szContext.get_verify_modecCstj|j�S)z�
        Retrieve the Context object's verify depth, as set by
        :meth:`set_verify_depth`.

        :return: The verify depth
        )r�ZSSL_CTX_get_verify_depthr�)r�rsrsrt�get_verify_depthiszContext.get_verify_depthcCsht|�}tj|d�}|tjkr$t�tj|tj�}tj|tjtjtj�}tj|tj	�}tj
|j|�dS)z�
        Load parameters for Ephemeral Diffie-Hellman

        :param dhfile: The file to load EDH parameters from (``bytes`` or
            ``unicode``).

        :return: None
        �rN)r�r�ZBIO_new_filer�r�r�r�ZBIO_freeZPEM_read_bio_DHparamsZDH_freeZSSL_CTX_set_tmp_dhr�)r�Zdhfile�bioZdhrsrsrt�load_tmp_dhrs	
zContext.load_tmp_dhcCstj|j|j��dS)a

        Select a curve to use for ECDHE key exchange.

        :param curve: A curve object to use as returned by either
            :meth:`OpenSSL.crypto.get_elliptic_curve` or
            :meth:`OpenSSL.crypto.get_elliptic_curves`.

        :return: None
        N)r�ZSSL_CTX_set_tmp_ecdhr�Z
_to_EC_KEY)r�Zcurversrsrt�set_tmp_ecdh�s
zContext.set_tmp_ecdhcCsVtd|�}t|t�std��ttj|j|�dk�t|d�}t|j	�dddgk�dS)z�
        Set the list of ciphers to be used in this context.

        See the OpenSSL manual for more information (e.g.
        :manpage:`ciphers(1)`).

        :param bytes cipher_list: An OpenSSL cipher string.
        :return: None
        �cipher_listz"cipher_list must be a byte string.ruNZTLS_AES_256_GCM_SHA384ZTLS_CHACHA20_POLY1305_SHA256ZTLS_AES_128_GCM_SHA256)
rr��bytesr�r�r�ZSSL_CTX_set_cipher_listr�rn�get_cipher_list)r�r+Ztmpconnrsrsrt�set_cipher_list�s



zContext.set_cipher_listcCs�tj�}t|tjk�yjxd|D]\}t|t�s@tdt|�j	f��tj
|j�}t|tjk�tj||�}|stj
|�t�qWWn tk
r�tj|��YnXtj|j|�dS)a_
        Set the list of preferred client certificate signers for this server
        context.

        This list of certificate authorities will be sent to the client when
        the server requests a client certificate.

        :param certificate_authorities: a sequence of X509Names.
        :return: None

        .. versionadded:: 0.10
        z3client CAs must be X509Name objects, not %s objectsN)r�Zsk_X509_NAME_new_nullr�r�r�r�rr�r�rp�
X509_NAME_dup�_nameZsk_X509_NAME_push�X509_NAME_freer�r�Zsk_X509_NAME_freerr�)r�Zcertificate_authoritiesZ
name_stackZca_namerZpush_resultrsrsrt�set_client_ca_list�s$




zContext.set_client_ca_listcCs2t|t�std��tj|j|j�}t|dk�dS)ai
        Add the CA certificate to the list of preferred signers for this
        context.

        The list of certificate authorities will be sent to the client when the
        server requests a client certificate.

        :param certificate_authority: certificate authority's X509 certificate.
        :return: None

        .. versionadded:: 0.10
        z.certificate_authority must be an X509 instanceruN)r�rr�r�ZSSL_CTX_add_client_CAr�rr�)r�Zcertificate_authorityrrsrsrt�
add_client_ca�s

zContext.add_client_cacCs t|t�std��tj|j|�S)aQ
        Set the timeout for newly created sessions for this Context object to
        *timeout*.  The default value is 300 seconds. See the OpenSSL manual
        for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).

        :param timeout: The timeout in (whole) seconds
        :return: The previous session timeout
        ztimeout must be an integer)r�rr�r�ZSSL_CTX_set_timeoutr�)r�Ztimeoutrsrsrt�set_timeout�s	
zContext.set_timeoutcCstj|j�S)z�
        Retrieve session timeout, as set by :meth:`set_timeout`. The default
        is 300 seconds.

        :return: The session timeout
        )r�ZSSL_CTX_get_timeoutr�)r�rsrsrt�get_timeout�szContext.get_timeoutcs6t���fdd��}tjd|�|_tj|j|j�dS)a�
        Set the information callback to *callback*. This function will be
        called from time to time during SSL handshakes.

        :param callback: The Python callback to use.  This should take three
            arguments: a Connection object and two integers.  The first integer
            specifies where in the SSL handshake the function was called, and
            the other the return code from a (possibly failed) internal
            function call.
        :return: None
        cs�tj|||�dS)N)rnr�)r��whereZreturn_code)r�rsrtr�sz*Context.set_info_callback.<locals>.wrapperzvoid (*)(const SSL *, int, int)N)rr�r�r�r�ZSSL_CTX_set_info_callbackr�)r�r�r�rs)r�rt�set_info_callbacks
zContext.set_info_callbackcCs|jS)zw
        Get the application data (supplied via :meth:`set_app_data()`)

        :return: The application data
        )r�)r�rsrsrt�get_app_dataszContext.get_app_datacCs
||_dS)z�
        Set the application data (will be returned from get_app_data())

        :param data: Any Python object
        :return: None
        N)r�)r�r�rsrsrt�set_app_dataszContext.set_app_datacCs.tj|j�}|tjkrdStjt�}||_|S)z�
        Get the certificate store for the context.  This can be used to add
        "trusted" certificates without using the
        :meth:`load_verify_locations` method.

        :return: A X509Store object or None if it does not have one.
        N)r�ZSSL_CTX_get_cert_storer�r�r�r�__new__Z_store)r�ZstoreZpystorersrsrt�get_cert_store&s

zContext.get_cert_storecCs t|t�std��tj|j|�S)z�
        Add options. Options set before are not cleared!
        This method should be used with the :const:`OP_*` constants.

        :param options: The options to add.
        :return: The new option bitmask.
        zoptions must be an integer)r�rr�r�ZSSL_CTX_set_optionsr�)r�Zoptionsrsrsrt�set_options7s
zContext.set_optionscCs t|t�std��tj|j|�S)z�
        Add modes via bitmask. Modes set before are not cleared!  This method
        should be used with the :const:`MODE_*` constants.

        :param mode: The mode to add.
        :return: The new mode bitmask.
        zmode must be an integer)r�rr�r�ZSSL_CTX_set_moder�)r�rrsrsrtr�Ds
zContext.set_modecs6t���fdd��}tjd|�|_tj|j|j�dS)a
        Specify a callback function to be called when clients specify a server
        name.

        :param callback: The callback function.  It will be invoked with one
            argument, the Connection instance.

        .. versionadded:: 0.13
        cs�tj|�dS)Nr)rnr�)r�Zalertr�)r�rsrtr�\sz7Context.set_tlsext_servername_callback.<locals>.wrapperzint (*)(SSL *, int *, void *)N)rr�r�r�r�Z&SSL_CTX_set_tlsext_servername_callbackr�)r�r�r�rs)r�rt�set_tlsext_servername_callbackQs

z&Context.set_tlsext_servername_callbackcCs,t|t�std��ttj|j|�dk�dS)z�
        Enable support for negotiating SRTP keying material.

        :param bytes profiles: A colon delimited list of protection profile
            names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
        :return: None
        zprofiles must be a byte string.rN)r�r,r�r�r�ZSSL_CTX_set_tlsext_use_srtpr�)r�Zprofilesrsrsrt�set_tlsext_use_srtpfs
zContext.set_tlsext_use_srtpcCs,t|�|_|jj|_tj|j|jtj�dS)a�
        Specify a callback function that will be called when offering `Next
        Protocol Negotiation
        <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.

        :param callback: The callback function.  It will be invoked with one
            argument, the :class:`Connection` instance.  It should return a
            list of bytestrings representing the advertised protocols, like
            ``[b'http/1.1', b'spdy/2']``.

        .. versionadded:: 0.15
        N)	r�r�r�r�r�Z%SSL_CTX_set_next_protos_advertised_cbr�r�r�)r�r�rsrsrt�set_npn_advertise_callbackus

z"Context.set_npn_advertise_callbackcCs,t|�|_|jj|_tj|j|jtj�dS)a�
        Specify a callback function that will be called when a server offers
        Next Protocol Negotiation options.

        :param callback: The callback function.  It will be invoked with two
            arguments: the Connection, and a list of offered protocols as
            bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``.  It should return
            one of those bytestrings, the chosen protocol.

        .. versionadded:: 0.15
        N)	r�r�r�r�r�Z SSL_CTX_set_next_proto_select_cbr�r�r�)r�r�rsrsrt�set_npn_select_callback�s

zContext.set_npn_select_callbackcCs>djtjdd�|D���}tjd|�}tj|j|t|��dS)a�
        Specify the protocols that the client is prepared to speak after the
        TLS connection has been negotiated using Application Layer Protocol
        Negotiation.

        :param protos: A list of the protocols to be offered to the server.
            This list should be a Python list of bytestrings representing the
            protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
        r�css|]}tt|��|fVqdS)N)rr�)r�r�rsrsrtr��sz*Context.set_alpn_protos.<locals>.<genexpr>zunsigned char[]N)	r�rr�r�r�r�ZSSL_CTX_set_alpn_protosr�r�)r�r�r��	input_strrsrsrt�set_alpn_protos�s
zContext.set_alpn_protoscCs,t|�|_|jj|_tj|j|jtj�dS)a�
        Specify a callback function that will be called on the server when a
        client offers protocols using ALPN.

        :param callback: The callback function.  It will be invoked with two
            arguments: the Connection, and a list of offered protocols as
            bytestrings, e.g ``[b'http/1.1', b'spdy/2']``.  It should return
            one of those bytestrings, the chosen protocol.
        N)	r�r�r�r�r�ZSSL_CTX_set_alpn_select_cbr�r�r�)r�r�rsrsrt�set_alpn_select_callback�s

z Context.set_alpn_select_callbackcCsh||_|j|_|dkr tj|_ntj|�|_tj|j	|j�}t
|dk�tj|j	|j�}t
|dk�dS)z�
        This internal helper does the common work for
        ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
        almost all of it.
        Nru)r�r�r�r�r�r�Z
new_handler�ZSSL_CTX_set_tlsext_status_cbr�r�ZSSL_CTX_set_tlsext_status_arg)r��helperr��rcrsrsrt�_set_ocsp_callback�s
zContext._set_ocsp_callbackcCst|�}|j||�dS)a�
        Set a callback to provide OCSP data to be stapled to the TLS handshake
        on the server side.

        :param callback: The callback function. It will be invoked with two
            arguments: the Connection, and the optional arbitrary data you have
            provided. The callback must return a bytestring that contains the
            OCSP data to staple to the handshake. If no OCSP data is available
            for this connection, return the empty bytestring.
        :param data: Some opaque data that will be passed into the callback
            function when called. This can be used to avoid needing to do
            complex data lookups or to keep track of what context is being
            used. This parameter is optional.
        N)r�rF)r�r�r�rDrsrsrt�set_ocsp_server_callback�sz Context.set_ocsp_server_callbackcCst|�}|j||�dS)a�
        Set a callback to validate OCSP data stapled to the TLS handshake on
        the client side.

        :param callback: The callback function. It will be invoked with three
            arguments: the Connection, a bytestring containing the stapled OCSP
            assertion, and the optional arbitrary data you have provided. The
            callback must return a boolean that indicates the result of
            validating the OCSP data: ``True`` if the OCSP data is valid and
            the certificate can be trusted, or ``False`` if either the OCSP
            data is invalid or the certificate has been revoked.
        :param data: Some opaque data that will be passed into the callback
            function when called. This can be used to avoid needing to do
            complex data lookups or to keep track of what context is being
            used. This parameter is optional.
        N)r�rF)r�r�r�rDrsrsrt�set_ocsp_client_callback�sz Context.set_ocsp_client_callback)N)N)N)N)?rprqrrrr%r&r'r(r)r*r��dict�itemsr�r�r�r�rr�r�rrrrrrrrrrrrr r!r"r$r%r&r)r*r.r2r3r4r5r7r8r9r;r<r��
_requires_snir=r>�
_requires_npnr?r@�_requires_alpnrBrCrFrGrHrsrsrsrtrm�sn.
 
1


		 %		


z4ContextType has been deprecated, use Context insteadc@seZdZdZe�Zdxdd�Zdd�Zdd�Zd	d
�Z	dd�Z
ed
d��Zedd��Z
dd�Zdydd�ZeZdzdd�Zd{dd�ZeZd|dd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Z d4d5�Z!d6d7�Z"d8d9�Z#d:d;�Z$d<d=�Z%d>d?�Z&d@dA�Z'dBdC�Z(dDdE�Z)dFdG�Z*dHdI�Z+d}dJdK�Z,dLdM�Z-dNdO�Z.dPdQ�Z/dRdS�Z0dTdU�Z1dVdW�Z2dXdY�Z3dZd[�Z4d\d]�Z5d^d_�Z6d`da�Z7dbdc�Z8ddde�Z9dfdg�Z:dhdi�Z;djdk�Z<dldm�Z=dndo�Z>e?dpdq��Z@eAdrds��ZBeAdtdu��ZCdvdw�ZDdS)~rnz
    NcCst|t�std��tj|j�}tj|tj�|_	tj
|j	tj�||_d|_d|_
d|_d|_||j|j	<|dkr�d|_tjtj��|_t|jtjk�tjtj��|_t|jtjk�tj|j	|j|j�n2d|_d|_||_tj|j	t|j��}t|dk�dS)z�
        Create a new Connection object, using the given OpenSSL.SSL.Context
        instance and socket.

        :param context: An SSL Context to use for this connection
        :param socket: The socket to use for transport layer
        z"context must be a Context instanceNru)r�rmr�r�ZSSL_newr�r�r�ZSSL_free�_sslZSSL_set_modeZSSL_MODE_AUTO_RETRYr�r�r�r�r��_socketZBIO_newZ	BIO_s_mem�	_into_sslr�r��	_from_sslZSSL_set_bioZ
SSL_set_fdr�)r�r��socketr�rrsrsrtr�s0
zConnection.__init__cCs0|jdkr td|jj|f��nt|j|�SdS)zy
        Look up attributes on the wrapped socket object if they are not found
        on the Connection object.
        Nz!'%s' object has no attribute '%s')rOr��	__class__rpr�)r�r�rsrsrt�__getattr__<s
zConnection.__getattr__cCsT|jjdk	r|jjj�|jjdk	r0|jjj�|jjdk	rH|jjj�|jjdk	r`|jjj�|jjdk	rx|jjj�tj||�}|tj	kr�t
��n�|tjkr�t��n�|tj
kr�t��n�|tjkr�t��n�|tjk�r<tj�dk�r4|dk�r(tdk�rtj�d}ntj}|dk�r(t|tj|���tdd��nt�n|tjk�rJnt�dS)NrZwin32ruzUnexpected EOFr�)r�r�r�r�r�r�r�r�Z
SSL_get_errorZSSL_ERROR_WANT_READrfZSSL_ERROR_WANT_WRITErgZSSL_ERROR_ZERO_RETURNriZSSL_ERROR_WANT_X509_LOOKUPrhZSSL_ERROR_SYSCALLZERR_peek_errorrr�Zgetwinerror�errnorjrrr�ZSSL_ERROR_NONE)r�r�r�r�rUrsrsrt�_raise_ssl_errorHs@






zConnection._raise_ssl_errorcCs|jS)zh
        Retrieve the :class:`Context` object associated with this
        :class:`Connection`.
        )r�)r�rsrsrt�get_contextqszConnection.get_contextcCs,t|t�std��tj|j|j�||_dS)z�
        Switch this connection to a new session context.

        :param context: A :class:`Context` instance giving the new session
            context to use.
        z"context must be a Context instanceN)r�rmr�r�ZSSL_set_SSL_CTXrNr�)r�r�rsrsrt�set_contextxs
zConnection.set_contextcCs(tj|jtj�}|tjkrdStj|�S)z�
        Retrieve the servername extension value if provided in the client hello
        message, or None if there wasn't one.

        :return: A byte string giving the server name or :data:`None`.

        .. versionadded:: 0.13
        N)r�ZSSL_get_servernamerNZTLSEXT_NAMETYPE_host_namer�r�r�)r�r�rsrsrt�get_servername�s


zConnection.get_servernamecCs6t|t�std��nd|kr$td��tj|j|�dS)z�
        Set the value of the servername extension to send in the client hello.

        :param name: A byte string giving the name.

        .. versionadded:: 0.13
        zname must be a byte string�zname must not contain NUL byteN)r�r,r�r�ZSSL_set_tlsext_host_namerN)r�r�rsrsrt�set_tlsext_host_name�s
	

zConnection.set_tlsext_host_namecCstj|j�S)z�
        Get the number of bytes that can be safely read from the SSL buffer
        (**not** the underlying transport buffer).

        :return: The number of bytes available in the receive buffer.
        )r�ZSSL_pendingrN)r�rsrsrt�pending�szConnection.pendingrcCsztd|�}t|t�r|j�}t|t�r.t|�}t|t�s@td��t|�dkrTt	d��t
j|j|t|��}|j
|j|�|S)a�
        Send data on the connection. NOTE: If you get one of the WantRead,
        WantWrite or WantX509Lookup exceptions on this, you have to call the
        method again with the SAME buffer.

        :param buf: The string, buffer or memoryview to send
        :param flags: (optional) Included for compatibility with the socket
                      API, the value is ignored
        :return: The number of bytes written
        rz0data must be a memoryview, buffer or byte stringi���z,Cannot send more than 2**31-1 bytes at once.)rr��
memoryview�tobytesro�strr,r�r�r�r��	SSL_writerNrV)r�r�flagsr�rsrsrt�send�s



zConnection.sendcCs�td|�}t|t�r|j�}t|t�r.t|�}t|t�s@td��t|�}d}t	j
d|�}x@|r�tj|j
||t|d��}|j|j
|�||7}||8}qZWdS)a�
        Send "all" data on the connection. This calls send() repeatedly until
        all data is sent. If an error occurs, it's impossible to tell how much
        data has been sent.

        :param buf: The string, buffer or memoryview to send
        :param flags: (optional) Included for compatibility with the socket
                      API, the value is ignored
        :return: The number of bytes written
        rz/buf must be a memoryview, buffer or byte stringrzchar[]i���N)rr�r]r^ror_r,r�r�r�r�r�r`rN�minrV)r�rraZleft_to_sendZ
total_sentr�r�rsrsrt�sendall�s$



zConnection.sendallcCs`td|�}|dk	r.|tj@r.tj|j||�}ntj|j||�}|j|j|�tj	||�dd�S)a
        Receive data on the connection.

        :param bufsiz: The maximum number of bytes to read
        :param flags: (optional) The only supported flag is ``MSG_PEEK``,
            all other flags are ignored.
        :return: The string read from the Connection
        zchar[]N)
�_no_zero_allocatorrR�MSG_PEEKr��SSL_peekrN�SSL_readrVr�r�)r��bufsizrarr�rsrsrt�recv�s	
zConnection.recvcCs�|dkrt|�}nt|t|��}td|�}|dk	rN|tj@rNtj|j||�}ntj|j||�}|j	|j|�t
tj||��|d|�<|S)ae
        Receive data on the connection and copy it directly into the provided
        buffer, rather than creating a new string.

        :param buffer: The buffer to copy into.
        :param nbytes: (optional) The maximum number of bytes to read into the
            buffer. If not present, defaults to the size of the buffer. If
            larger than the size of the buffer, is reduced to the size of the
            buffer.
        :param flags: (optional) The only supported flag is ``MSG_PEEK``,
            all other flags are ignored.
        :return: The number of bytes read into the buffer.
        Nzchar[])
r�rcrerRrfr�rgrNrhrVr]r�r�)r�r��nbytesrarr�rsrsrt�	recv_intos

zConnection.recv_intocCsVtj|�rLtj|�rt��qRtj|�r.t��qRtj|�rBtd��qRtd��nt�dS)N�BIO_should_io_specialzunknown bio failure)	r�ZBIO_should_retryZBIO_should_readrfZBIO_should_writergrmr�r�)r�r(r�rsrsrt�_handle_bio_errors(s





zConnection._handle_bio_errorscCsh|jdkrtd��t|t�s$td��td|�}tj|j||�}|dkrT|j|j|�tj	||�dd�S)a�
        If the Connection was created with a memory BIO, this method can be
        used to read bytes from the write end of that memory BIO.  Many
        Connection methods will add bytes which must be read in this manner or
        the buffer will eventually fill up and the Connection will be able to
        take no further actions.

        :param bufsiz: The maximum number of bytes to read
        :return: The string read.
        NzConnection sock was not Nonezbufsiz must be an integerzchar[]r)
rQr�r�rrer�ZBIO_readrnr�r�)r�rirr�rsrsrt�bio_read:s


zConnection.bio_readcCsJtd|�}|jdkrtd��tj|j|t|��}|dkrF|j|j|�|S)aj
        If the Connection was created with a memory BIO, this method can be
        used to add bytes to the read end of that memory BIO.  The Connection
        can then read the bytes (for example, in response to a call to
        :meth:`recv`).

        :param buf: The string to put into the memory BIO.
        :return: The number of bytes written
        rNzConnection sock was not Noner)rrPr�r�Z	BIO_writer�rn)r�rr�rsrsrt�	bio_writeRs


zConnection.bio_writecCs$|j�s ttj|j�dk�dSdS)z�
        Renegotiate the session.

        :return: True if the renegotiation can be started, False otherwise
        :rtype: bool
        ruTF)�renegotiate_pendingr�r�ZSSL_renegotiaterN)r�rsrsrt�renegotiatefszConnection.renegotiatecCstj|j�}|j|j|�dS)a
        Perform an SSL handshake (usually called after :meth:`renegotiate` or
        one of :meth:`set_accept_state` or :meth:`set_accept_state`). This can
        raise the same exceptions as :meth:`send` and :meth:`recv`.

        :return: None.
        N)r�ZSSL_do_handshakerNrV)r�r�rsrsrt�do_handshakerszConnection.do_handshakecCstj|j�dkS)z�
        Check if there's a renegotiation in progress, it will return False once
        a renegotiation is finished.

        :return: Whether there's a renegotiation in progress
        :rtype: bool
        ru)r�ZSSL_renegotiate_pendingrN)r�rsrsrtrq}szConnection.renegotiate_pendingcCstj|j�S)z�
        Find out the total number of renegotiations.

        :return: The number of renegotiations.
        :rtype: int
        )r�ZSSL_total_renegotiationsrN)r�rsrsrt�total_renegotiations�szConnection.total_renegotiationscCstj|j�|jj|�S)a4
        Call the :meth:`connect` method of the underlying socket and set up SSL
        on the socket, using the :class:`Context` object supplied to this
        :class:`Connection` object at creation.

        :param addr: A remote address
        :return: What the socket's connect method returns
        )r��SSL_set_connect_staterNrO�connect)r��addrrsrsrtrv�s	zConnection.connectcCs|jj}|j�||�S)a�
        Call the :meth:`connect_ex` method of the underlying socket and set up
        SSL on the socket, using the Context object supplied to this Connection
        object at creation. Note that if the :meth:`connect_ex` method of the
        socket doesn't return 0, SSL won't be initialized.

        :param addr: A remove address
        :return: What the socket's connect_ex method returns
        )rO�
connect_ex�set_connect_state)r�rwrxrsrsrtrx�s
zConnection.connect_excCs*|jj�\}}t|j|�}|j�||fS)a�
        Call the :meth:`accept` method of the underlying socket and set up SSL
        on the returned socket, using the Context object supplied to this
        :class:`Connection` object at creation.

        :return: A *(conn, addr)* pair where *conn* is the new
            :class:`Connection` object created, and *address* is as returned by
            the socket's :meth:`accept`.
        )rO�acceptrnr��set_accept_state)r�Zclientrwr�rsrsrtrz�s
zConnection.acceptcCs$|jdkrtd��tj|jd�dS)z�
        If the Connection was created with a memory BIO, this method can be
        used to indicate that *end of file* has been reached on the read end of
        that memory BIO.

        :return: None
        NzConnection sock was not Noner)rQr�r�ZBIO_set_mem_eof_returnrP)r�rsrsrt�bio_shutdown�s
zConnection.bio_shutdowncCs8tj|j�}|dkr$|j|j|�n|dkr0dSdSdS)aQ
        Send the shutdown message to the Connection.

        :return: True if the shutdown completed successfully (i.e. both sides
                 have sent closure alerts), False otherwise (in which case you
                 call :meth:`recv` or :meth:`send` when the connection becomes
                 readable/writeable).
        rTFN)r�ZSSL_shutdownrNrV)r�r�rsrsrt�shutdown�s	zConnection.shutdowncCsFg}x<t�D]2}tj|j|�}|tjkr*P|jttj|���qW|S)z�
        Retrieve the list of ciphers used by the Connection object.

        :return: A list of native cipher strings.
        )	rr�ZSSL_get_cipher_listrNr�r�r��_nativer�)r�Zciphers�ir�rsrsrtr-�s
zConnection.get_cipher_listcCs�tj|j�}|tjkrgSg}x^ttj|��D]L}tj||�}tj|�}t	|tjk�t
jt
�}tj|tj
�|_|j|�q.W|S)a�
        Get CAs whose certificates are suggested for client authentication.

        :return: If this is a server connection, the list of certificate
            authorities that will be sent or has been sent to the client, as
            controlled by this :class:`Connection`'s :class:`Context`.

            If this is a client connection, the list will be empty until the
            connection with the server is established.

        .. versionadded:: 0.10
        )r�ZSSL_get_client_CA_listrNr�r��rangeZsk_X509_NAME_numZsk_X509_NAME_valuer/r�rr:r�r1r0r�)r�Zca_namesr�rr�rZpynamersrsrt�get_client_ca_list�s



zConnection.get_client_ca_listcOstd��dS)z�
        The makefile() method is not implemented, since there is no dup
        semantics for SSL connections

        :raise: NotImplementedError
        z1Cannot make file object of OpenSSL.SSL.ConnectionN)r�)r�r�r�rsrsrt�makefileszConnection.makefilecCs|jS)zr
        Retrieve application data as set by :meth:`set_app_data`.

        :return: The application data
        )r�)r�rsrsrtr8szConnection.get_app_datacCs
||_dS)zg
        Set application data

        :param data: The application data
        :return: None
        N)r�)r�r�rsrsrtr9szConnection.set_app_datacCstj|j�S)z�
        Get the shutdown state of the Connection.

        :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
            RECEIVED_SHUTDOWN.
        )r�ZSSL_get_shutdownrN)r�rsrsrt�get_shutdownszConnection.get_shutdowncCs$t|t�std��tj|j|�dS)z�
        Set the shutdown state of the Connection.

        :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
        :return: None
        zstate must be an integerN)r�rr�r�ZSSL_set_shutdownrN)r��statersrsrt�set_shutdown&s
zConnection.set_shutdowncCstjtj|j��S)z�
        Retrieve a verbose string detailing the state of the Connection.

        :return: A string representing the state
        :rtype: bytes
        )r�r�r�ZSSL_state_string_longrN)r�rsrsrt�get_state_string2szConnection.get_state_stringcCsZtj|j�}|tjkrdStj|jtjd�}td|�}tj|j||�tj||�dd�S)z�
        Retrieve the random value used with the server hello message.

        :return: A string representing the state
        Nrzunsigned char[])r��SSL_get_sessionrNr�r�ZSSL_get_server_randomrer�)r��sessionr��outprsrsrt�
server_random;s

zConnection.server_randomcCsZtj|j�}|tjkrdStj|jtjd�}td|�}tj|j||�tj||�dd�S)z�
        Retrieve the random value used with the client hello message.

        :return: A string representing the state
        Nrzunsigned char[])r�r�rNr�r�ZSSL_get_client_randomrer�)r�r�r�r�rsrsrt�
client_randomJs

zConnection.client_randomcCsVtj|j�}|tjkrdStj|tjd�}td|�}tj|||�tj||�dd�S)zz
        Retrieve the value of the master key for this session.

        :return: A string representing the state
        Nrzunsigned char[])r�r�rNr�r�ZSSL_SESSION_get_master_keyrer�)r�r�r�r�rsrsrt�
master_keyZs

zConnection.master_keyc		Csntd|�}tj}d}d}|dk	r0|}t|�}d}tj|j|||t|�|||�}t|dk�tj||�dd�S)aH
        Obtain keying material for application use.

        :param: label - a disambiguating label string as described in RFC 5705
        :param: olen - the length of the exported key material in bytes
        :param: context - a per-association context value
        :return: the exported key material bytes or None
        zunsigned char[]rNru)	rer�r�r�r�ZSSL_export_keying_materialrNr�r�)	r�ZlabelZolenr�r�Zcontext_bufZcontext_lenZuse_context�successrsrsrt�export_keying_materialjs	
z!Connection.export_keying_materialcOs|jj||�S)z�
        Call the :meth:`shutdown` method of the underlying socket.
        See :manpage:`shutdown(2)`.

        :return: What the socket's shutdown() method returns
        )rOr})r�r�r�rsrsrt�
sock_shutdown�szConnection.sock_shutdowncCs.tj|j�}|tjkr*tj|�tj|�SdS)za
        Retrieve the local certificate (if any)

        :return: The local certificate
        N)r�ZSSL_get_certificaterNr�r�r�rr�)r�r�rsrsrt�get_certificate�s



zConnection.get_certificatecCs$tj|j�}|tjkr tj|�SdS)zi
        Retrieve the other side's certificate (if any)

        :return: The peer's certificate
        N)r�ZSSL_get_peer_certificaterNr�r�rr�)r�r�rsrsrt�get_peer_certificate�s

zConnection.get_peer_certificatecCs`tj|j�}|tjkrdSg}x<ttj|��D]*}tjtj||��}t	j
|�}|j|�q.W|S)z�
        Retrieve the other side's certificate (if any)

        :return: A list of X509 instances giving the peer's certificate chain,
                 or None if it does not have one.
        N)r�ZSSL_get_peer_cert_chainrNr�r�r�Zsk_X509_numrZ
sk_X509_valuerr�r�)r�Z
cert_stackr�rr�Zpycertrsrsrt�get_peer_cert_chain�s

zConnection.get_peer_cert_chaincCstj|j�S)z�
        Checks if more data has to be read from the transport layer to complete
        an operation.

        :return: True iff more data has to be read
        )r�Z
SSL_want_readrN)r�rsrsrt�	want_read�szConnection.want_readcCstj|j�S)z�
        Checks if there is data to write to the transport layer to complete an
        operation.

        :return: True iff there is data to write
        )r�ZSSL_want_writerN)r�rsrsrt�
want_write�szConnection.want_writecCstj|j�dS)z�
        Set the connection to work in server mode. The handshake will be
        handled automatically by read/write.

        :return: None
        N)r�ZSSL_set_accept_staterN)r�rsrsrtr{�szConnection.set_accept_statecCstj|j�dS)z�
        Set the connection to work in client mode. The handshake will be
        handled automatically by read/write.

        :return: None
        N)r�rurN)r�rsrsrtry�szConnection.set_connect_statecCs8tj|j�}|tjkrdStjt�}tj|tj�|_	|S)z�
        Returns the Session currently used.

        :return: An instance of :class:`OpenSSL.SSL.Session` or
            :obj:`None` if no session exists.

        .. versionadded:: 0.14
        N)
r�ZSSL_get1_sessionrNr�r�rlr:r�ZSSL_SESSION_free�_session)r�r�Z	pysessionrsrsrt�get_session�s	

zConnection.get_sessioncCs0t|t�std��tj|j|j�}|s,t�dS)z�
        Set the session to be used when the TLS/SSL connection is established.

        :param session: A Session instance representing the session to use.
        :returns: None

        .. versionadded:: 0.14
        z"session must be a Session instanceN)r�rlr�r�ZSSL_set_sessionrNr�r�)r�r�r�rsrsrt�set_session�s
	
zConnection.set_sessioncCsRtjdd�}||j|d�}|dkr&dStd|�}||j||�tj||�dd�S)a�
        Helper to implement :meth:`get_finished` and
        :meth:`get_peer_finished`.

        :param function: Either :data:`SSL_get_finished`: or
            :data:`SSL_get_peer_finished`.

        :return: :data:`None` if the desired message has not yet been
            received, otherwise the contents of the message.
        :rtype: :class:`bytes` or :class:`NoneType`
        zchar[]rN)r�r�rNrer�)r�Zfunction�emptyr�rrsrsrt�_get_finished_message�s
z Connection._get_finished_messagecCs|jtj�S)a
        Obtain the latest TLS Finished message that we sent.

        :return: The contents of the message or :obj:`None` if the TLS
            handshake has not yet completed.
        :rtype: :class:`bytes` or :class:`NoneType`

        .. versionadded:: 0.15
        )r�r�ZSSL_get_finished)r�rsrsrt�get_finished	s
zConnection.get_finishedcCs|jtj�S)a!
        Obtain the latest TLS Finished message that we received from the peer.

        :return: The contents of the message or :obj:`None` if the TLS
            handshake has not yet completed.
        :rtype: :class:`bytes` or :class:`NoneType`

        .. versionadded:: 0.15
        )r�r�ZSSL_get_peer_finished)r�rsrsrt�get_peer_finished(	s
zConnection.get_peer_finishedcCs8tj|j�}|tjkrdStjtj|��}|jd�SdS)a
        Obtain the name of the currently used cipher.

        :returns: The name of the currently used cipher or :obj:`None`
            if no connection has been established.
        :rtype: :class:`unicode` or :class:`NoneType`

        .. versionadded:: 0.15
        Nzutf-8)r��SSL_get_current_cipherrNr�r�r�ZSSL_CIPHER_get_namer�)r��cipherr�rsrsrt�get_cipher_name4	s


zConnection.get_cipher_namecCs,tj|j�}|tjkrdStj|tj�SdS)a.
        Obtain the number of secret bits of the currently used cipher.

        :returns: The number of secret bits of the currently used cipher
            or :obj:`None` if no connection has been established.
        :rtype: :class:`int` or :class:`NoneType`

        .. versionadded:: 0.15
        N)r�r�rNr�r�ZSSL_CIPHER_get_bits)r�r�rsrsrt�get_cipher_bitsE	s

zConnection.get_cipher_bitscCs8tj|j�}|tjkrdStjtj|��}|jd�SdS)a%
        Obtain the protocol version of the currently used cipher.

        :returns: The protocol name of the currently used cipher
            or :obj:`None` if no connection has been established.
        :rtype: :class:`unicode` or :class:`NoneType`

        .. versionadded:: 0.15
        Nzutf-8)r�r�rNr�r�r�ZSSL_CIPHER_get_versionr�)r�r��versionrsrsrt�get_cipher_versionU	s


zConnection.get_cipher_versioncCstjtj|j��}|jd�S)a>
        Retrieve the protocol version of the current connection.

        :returns: The TLS version of the current connection, for example
            the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
            for connections that were not successfully established.
        :rtype: :class:`unicode`
        zutf-8)r�r�r�ZSSL_get_versionrNr�)r�r�rsrsrt�get_protocol_version_namef	s	z$Connection.get_protocol_version_namecCstj|j�}|S)a
        Retrieve the SSL or TLS protocol version of the current connection.

        :returns: The TLS version of the current connection.  For example,
            it will return ``0x769`` for connections made over TLS version 1.
        :rtype: :class:`int`
        )r�ZSSL_versionrN)r�r�rsrsrt�get_protocol_versionr	szConnection.get_protocol_versioncCs@tjd�}tjd�}tj|j||�tj|d|d�dd�S)z�
        Get the protocol that was negotiated by NPN.

        :returns: A bytestring of the protocol name.  If no protocol has been
            negotiated yet, returns an empty string.

        .. versionadded:: 0.15
        zunsigned char **zunsigned int *rN)r�r�r�ZSSL_get0_next_proto_negotiatedrNr�)r�r��data_lenrsrsrt�get_next_proto_negotiated}	s


z$Connection.get_next_proto_negotiatedcCs>djtjdd�|D���}tjd|�}tj|j|t|��dS)ah
        Specify the client's ALPN protocol list.

        These protocols are offered to the server during protocol negotiation.

        :param protos: A list of the protocols to be offered to the server.
            This list should be a Python list of bytestrings representing the
            protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
        r�css|]}tt|��|fVqdS)N)rr�)r�r�rsrsrtr��	sz-Connection.set_alpn_protos.<locals>.<genexpr>zunsigned char[]N)	r�rr�r�r�r�ZSSL_set_alpn_protosrNr�)r�r�r�rArsrsrtrB�	s
zConnection.set_alpn_protoscCsHtjd�}tjd�}tj|j||�|s,dStj|d|d�dd�S)z�
        Get the protocol that was negotiated by ALPN.

        :returns: A bytestring of the protocol name.  If no protocol has been
            negotiated yet, returns an empty string.
        zunsigned char **zunsigned int *r�rN)r�r�r�ZSSL_get0_alpn_selectedrNr�)r�r�r�rsrsrt�get_alpn_proto_negotiated�	s

z$Connection.get_alpn_proto_negotiatedcCs tj|jtj�}t|dk�dS)a
        Called to request that the server sends stapled OCSP data, if
        available. If this is not called on the client side then the server
        will not send OCSP data. Should be used in conjunction with
        :meth:`Context.set_ocsp_client_callback`.
        ruN)r�ZSSL_set_tlsext_status_typerNZTLSEXT_STATUSTYPE_ocspr�)r�rErsrsrt�request_ocsp�	szConnection.request_ocsp)N)r)r)N)NN)N)Erprqrrrrr�r�rTrVrWrXrKrYr[r\rb�writerdrj�readrlrnrorprrrsrqrtrvrxrzr|r}r-r�r�r8r9r�r�r�r�r�r�r�r�r�r�r�r�r�r{ryr�r�r�r�r�r�r�r�r�r�rLr�rMrBr�r�rsrsrsrtrns|
6)
	

$

%
	

			
					"z:ConnectionType has been deprecated, use Connection instead)�rrR�sysr�	functoolsrr�	itertoolsrr�weakrefrrUrZcryptography.utilsr	Zsixr
r�rrr
Z
OpenSSL._utilrrrZ_exception_from_error_queuerr�rr�rZ_make_assertrr~rr�rrrreZOpenSSL.cryptorrrrrr�__all__r�ro�	NameError�objectrrrr r!r"ZSSL_SENT_SHUTDOWNr#ZSSL_RECEIVED_SHUTDOWNr$r%r&r'r(r)r*ZSSL_OP_NO_SSLv2r+ZSSL_OP_NO_SSLv3r,ZSSL_OP_NO_TLSv1r-ZSSL_OP_NO_TLSv1_1r.ZSSL_OP_NO_TLSv1_2r/ZSSL_MODE_RELEASE_BUFFERSr0ZSSL_OP_SINGLE_DH_USEr1ZSSL_OP_SINGLE_ECDH_USEr2ZSSL_OP_EPHEMERAL_RSAr3ZSSL_OP_MICROSOFT_SESS_ID_BUGr4ZSSL_OP_NETSCAPE_CHALLENGE_BUGr5Z'SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUGr6Z"SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUGr7Z!SSL_OP_MICROSOFT_BIG_SSLV3_BUFFERr8ZSSL_OP_MSIE_SSLV2_RSA_PADDINGr9ZSSL_OP_SSLEAY_080_CLIENT_DH_BUGr:ZSSL_OP_TLS_D5_BUGr;ZSSL_OP_TLS_BLOCK_PADDING_BUGr<Z"SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSr=ZSSL_OP_CIPHER_SERVER_PREFERENCEr>ZSSL_OP_TLS_ROLLBACK_BUGr?ZSSL_OP_PKCS1_CHECK_1r@ZSSL_OP_PKCS1_CHECK_2rAZSSL_OP_NETSCAPE_CA_DN_BUGrBZ&SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUGrCZSSL_OP_NO_COMPRESSIONrDZSSL_OP_NO_QUERY_MTUrEZSSL_OP_COOKIE_EXCHANGErFZSSL_OP_NO_TICKETrGZ
SSL_OP_ALLrHZSSL_VERIFY_PEERrIZSSL_VERIFY_FAIL_IF_NO_PEER_CERTrJZSSL_VERIFY_CLIENT_ONCErKZSSL_VERIFY_NONErLZSSL_SESS_CACHE_OFFrMZSSL_SESS_CACHE_CLIENTrNZSSL_SESS_CACHE_SERVERrOZSSL_SESS_CACHE_BOTHrPZSSL_SESS_CACHE_NO_AUTO_CLEARrQZ!SSL_SESS_CACHE_NO_INTERNAL_LOOKUPrRZ SSL_SESS_CACHE_NO_INTERNAL_STORErSZSSL_SESS_CACHE_NO_INTERNALrTrUrVrWZCryptography_HAS_SSL_STr{r|r}r~�extendrXrYrZr[r\r]r^r_r`rarbrcrdr�r�r�r�r�rer�r�rfrgrhrirjr�r�r�r�r�r�r�r�rkr�ZCryptography_HAS_NEXTPROTONEGrLZCryptography_HAS_ALPNrMZ Cryptography_HAS_TLSEXT_HOSTNAMErKrlrmrp�DeprecationWarningZContextTypernZConnectionTypeZSSL_library_initrsrsrsrt�<module>s�, 
')13C;	


ZI

?>