U
    ;g                  
   @   sz  d dl mZmZmZmZ d dlZd dlZd dlZd dl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 ddlmZ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 m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, dd
l-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZM ddlNmOZOmZ ddlPmQZQ ejRdk reSZTejRdk rejUZVnejVZVddgZWejXejYejZej[ej\dZ]ejXdejYdejZdej[dej\diZ^e_dZ`e_dZaeb Zci Zddd Zedd  Zfd!d" Zge#ed#eeZhe#ed$egZiG d%d dejZkG d&d dejZldS )'    )unicode_literalsdivisionabsolute_importprint_functionN   )Securityosx_version_infohandle_sec_errorSecurityConst)CoreFoundationhandle_cf_error	CFHelpers   )Certificateint_to_bytestimezone)pretty_message)array_from_pointer	array_setbuffer_from_bytesbytes_from_buffercallbackcastderefnewnullpointer_setstructstruct_bytesunwrapwrite_to_buffer)	type_namestr_clsbyte_cls	int_types)CIPHER_SUITE_MAP)
rand_bytes)TLSErrorTLSDisconnectErrorTLSGracefulDisconnectError)detect_client_auth_requestdetect_other_protocolextract_chainget_dh_params_lengthparse_session_inforaise_client_authraise_dh_paramsraise_disconnectionraise_expired_not_yet_validraise_handshakeraise_hostnameraise_lifetime_too_longraise_no_issuerraise_protocol_errorraise_protocol_versionraise_revokedraise_self_signedraise_verificationraise_weak_signature)load_certificater   )parse_certificate)   )r?      
TLSSession	TLSSocket)SSLv2SSLv3TLSv1TLSv1.1TLSv1.2rC   rD   rE   rF   rG   s   (
||
)zGanon|PSK|SEED|RC4|MD5|NULL|CAMELLIA|ARIA|SRP|KRB5|EXPORT|(?<!3)DES|IDEAc              
   C   sf  d}z t | }|s"t| }n|j}|s6|s6W dS t|}| }d}d}zt||k r|dk	r|dkrt|gg g |\}	}
}
t|	dkrt	t
jd||t| }||7 }|dkrPt|dkr|dkrtjW W S tjW W S qqPW n, tj	k
r } z
|j
}W 5 d}~X Y nX |dk	rZ|t
jkrZ|t
jksJ|t
jkrRtjW S tjW S |r|jst|dkrt|jdkr|dd tdd	gk}|dd td
ddddgk}|r|s| j|t| 7  _tjW S | j|7  _t|| t|t| t||kr"tjW S W dS  tk
r` } z|rF||_tj W Y S d}~X Y nX dS )a  
    Callback called by Secure Transport to actually read the socket

    :param connection_id:
        An integer identifying the connection

    :param data_buffer:
        A char pointer FFI type to write the data to

    :param data_length_pointer:
        A size_t pointer FFI type of the amount of data to read. Will be
        overwritten with the amount of data read on return.

    :return:
        An integer status code of the result - 0 for success
    Nr               z	timed outr?   r         s    s   s   s   s   )_connection_refsget_socket_refs_socketr   
gettimeoutlenselectsocket_errorerrnoEAGAINrecvr
   errSSLClosedNoNotifyerrSSLClosedAbort
ECONNRESETEPIPE_done_handshake_server_helloset_read_remainingerrSSLProtocolr    r   errSSLWouldBlockKeyboardInterrupt
_exception)connection_iddata_bufferdata_length_pointerselfsocketZbytes_requestedtimeoutrT   data
read_ready_chunkeZvalid_record_typeZvalid_protocol_version ro   5/tmp/pip-unpacked-wheel-x1gypflw/oscrypto/_mac/tls.py_read_callbackf   sn    



rq   c              	   C   sV   d}|   }z8z| d || d7 }W n tjk
r@   Y nX W 5 | | X |S )z
    Reads everything available from the socket - used for debugging when there
    is a protocol error

    :param socket:
        The socket to read from

    :return:
        A byte string of the remaining data
    rH   rI       )rP   
settimeoutrW   rS   rT   )rh   outputZold_timeoutro   ro   rp   r_      s    

r_   c           
   
   C   s&  zt | }|st| }n|j}|s0|s0W dS t|}t||}|rZ|jsZ| j|7  _d}z||}W n* t	j
k
r }	 z
|	j}W 5 d}	~	X Y nX |dk	r|tjkr|tjks|tjkrtjW S tjW S ||krt|| tjW S W dS  tk
r  }	 z|	|_tj W Y S d}	~	X Y nX dS )a  
    Callback called by Secure Transport to actually write to the socket

    :param connection_id:
        An integer identifying the connection

    :param data_buffer:
        A char pointer FFI type containing the data to write

    :param data_length_pointer:
        A size_t pointer FFI type of the amount of data to write. Will be
        overwritten with the amount of data actually written on return.

    :return:
        An integer status code of the result - 0 for success
    r   N)rL   rM   rN   rO   r   r   r\   _client_hellosendrS   rT   rU   rV   rZ   r[   r
   rX   rY   r   ra   rb   rc   ZerrSSLPeerUserCancelled)
rd   re   rf   rg   rh   data_lengthrj   rT   sentrn   ro   ro   rp   _write_callback   s6    



ry   ZSSLReadFuncZSSLWriteFuncc                   @   s.   e Zd ZdZdZdZdZdZdZdddZ	dS )rA   zj
    A TLS session object that multiple TLSSocket objects can share for the
    sake of session reuse
    NFc              
   C   s>  t |tsttdt||| _|dkr8tdddg}t |trNt|g}nt |tsjttdt||tddddg }|rttdt	||| _
g | _|r0|D ]}t |tr|j}nbt |trt|}nNt |trt|d	}t| }W 5 Q R X nt |ts"ttd
t|| j| qtd| _dS )a]  
        :param protocol:
            A unicode string or set of unicode strings representing allowable
            protocols to negotiate with the server:

             - "TLSv1.2"
             - "TLSv1.1"
             - "TLSv1"
             - "SSLv3"

            Default is: {"TLSv1", "TLSv1.1", "TLSv1.2"}

        :param manual_validation:
            If certificate and certificate path validation should be skipped
            and left to the developer to implement

        :param extra_trust_roots:
            A list containing one or more certificates to be treated as trust
            roots, in one of the following formats:
             - A byte string of the DER encoded certificate
             - A unicode string of the certificate filename
             - An asn1crypto.x509.Certificate object
             - An oscrypto.asymmetric.Certificate object

        :raises:
            ValueError - when any of the parameters contain an invalid value
            TypeError - when any of the parameters are of the wrong type
            OSError - when an error is returned by the OS crypto library
        zM
                manual_validation must be a boolean, not %s
                NrE   rF   rG   zu
                protocol must be a unicode string or set of unicode strings,
                not %s
                rD   z
                protocol must contain only the unicode strings "SSLv3", "TLSv1",
                "TLSv1.1", "TLSv1.2", not %s
                rbz
                        extra_trust_roots must be a list of byte strings, unicode
                        strings, asn1crypto.x509.Certificate objects or
                        oscrypto.asymmetric.Certificate objects, not %s
                           )
isinstancebool	TypeErrorr   r!   _manual_validationr^   r"   
ValueErrorrepr
_protocols_extra_trust_rootsr   asn1r#   r>   openreadAsn1Certificateappendr&   _peer_id)rg   protocolmanual_validationZextra_trust_rootsZunsupported_protocolsZextra_trust_rootfro   ro   rp   __init__   sN    





zTLSSession.__init__)NFN)
__name__
__module____qualname____doc__r   Z_ciphersr   r   r   r   ro   ro   ro   rp   rA     s   c                   @   st  e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZdZdZdZdZdZdZdZdZdZdZed=ddZd>ddZd	d
 Zdd Zd?ddZdd Zdd Zdd Zdd Z dd Z!d@ddZ"dd Z#dd Z$dd  Z%d!d" Z&d#d$ Z'e(d%d& Z)e(d'd( Z*e(d)d* Z+e(d+d, Z,e(d-d. Z-e(d/d0 Z.e(d1d2 Z/e(d3d4 Z0e(d5d6 Z1e(d7d8 Z2e(d9d: Z3d;d< Z4dS )ArB   z8
    A wrapper around a socket.socket that adds TLS
    NFc                 C   s   t |tjsttdt|t |ts:ttdt||dk	r^t |ts^ttdt|| dd|d}||_||_	|
  |S )az  
        Takes an existing socket and adds TLS

        :param socket:
            A socket.socket object to wrap with TLS

        :param hostname:
            A unicode string of the hostname or IP the socket is connected to

        :param session:
            An existing TLSSession object to allow for session reuse, specific
            protocol or manual certificate validation

        :raises:
            ValueError - when any of the parameters contain an invalid value
            TypeError - when any of the parameters are of the wrong type
            OSError - when an error is returned by the OS crypto library
        zU
                socket must be an instance of socket.socket, not %s
                zK
                hostname must be a unicode string, not %s
                N`
                session must be an instance of oscrypto.tls.TLSSession, not %s
                )session)r|   rS   rh   r~   r   r!   r"   rA   rO   	_hostname
_handshake)clsrh   hostnamer   Z
new_socketro   ro   rp   wrap  s(    
zTLSSocket.wrap
   c                 C   s   d| _ d| _d| _d| _|dkr0|dkr0d| _n|t|tsLttdt	|t|t
shttdt	||dk	rt|tjsttdt	|t||f|| _| j| |dkrt }nt|tsttdt	||| _| jr|| _|   dS )a  
        :param address:
            A unicode string of the domain name or IP address to connect to

        :param port:
            An integer of the port number to connect to

        :param timeout:
            An integer timeout to use for the socket

        :param session:
            An oscrypto.tls.TLSSession object to allow for session reuse and
            controlling the protocols and validation performed
        FrH   NzR
                    address must be a unicode string, not %s
                    zI
                    port must be an integer, not %s
                    zJ
                    timeout must be a number, not %s
                    r   )r\   r]   ru   _decrypted_bytesrO   r|   r"   r~   r   r!   r$   numbersNumberrS   create_connectionrs   rA   _sessionr   r   )rg   addressportri   r   ro   ro   rp   r     sD    


zTLSSocket.__init__c           \   	   C   s  d}d}d}d}d}d}d}d}z
ztdk rXttd}
td|
}	t|	 t|
}nt	t
 tjtj}t|tt}	t|	 t| d | _| t| j< | jt| j< t|| j}	t|	 | jd}t||t|}	t|	 tdkr| jjp| jj}| jj o| jj}nd}| jj }tdk r|d	D ]0}t| }|| jjk}t |||}	t|	 q.|rt!|d}	t|	 nhd
d | jjD }t"|}t#|}t$||}	t|	 t%||}	t|	 |rt&|tj'd}	t|	 ttd}t(||}	t|	 t)|}t*|d }t+td|}t,|||}	t|	 t)|}t-td||}g }|D ]<}t.|dd}t/0||}t12|dk}|rV|3| qVt|}ttd|}t4|| t+td|} t5|| |}	t|	 | jj6| jd }!t7||!t|!}	t|	 t8|}"| j9dk	r(| j9}#d| _9|#|"tj:kr^t8|}"| j9dk	r(| j9}#d| _9|#q(tdk rtdkr|o~|"dk}$n|o|"tj;k}$|$rttd}%t<||%}	t|	 t|%}t=>| j}&t?d|&}t |&}	t|	 t@td}'t|'}(ttjA|(_Bt*tjA})t+td|)|(_Cttd}*tDtjE|'t
 |*}	t|	 t|*}ttd}+tF||+}	t|	 t|+}t@td},t|,}-tjG|-_HtjItjJB |-_KtL|,}.t@td}/t|/}0t|.|0_Bt*|.}1t+td|1|0_CtM||/}	t|	 t@td}2t|2}3ttjN|3_Bt*tjN}4t+td|4|3_Cttd}5tDtjE|2t
 |5}	t|	 t|5}ttd}6tF||6}	t|	 t|6}t@td}7t|7}8tjO|8_Hd|8_PtL|7}9t@td}/t|/}0t|9|0_Bt*|9}:t+td|:|0_CtM||/}	t|	 t=Q|||g}tR||}	t|	 | jjrvg };g }<| jjD ]$}=tS|=}>|<3|> |;3|>jT qtU|d}	t|	 t=Q|;}?tV||?}	t|	 ttd}@tW||@}	t|	 t)|@}AtXtjYtjZg}B|A|Bkrtj[}"n$t8|}"|"tj:krt8|}"qd| _\tXtj[tj]tj^tj_tj`tjatjbg}C|"|Ckr|r*t | d}ttd}%t<||%}	t|	 t|%}ttd}Dtc||D}	t)|D}Etd| je}Fd}Gd}Hd}Id}Jd}Kd}=d}L|Fr@|Fd }=tS|=}M|Mjf}G|Etjgk}H|G o|Etjhk}K|Etjik}I|Etjjk}J|Etjkk}L|Etjlk}Ntdkr@|=d  d! }O|Od" jmjn}P|Od# jmjn}Qtojoptqjr}R|Q|Rk }I|P|Rk}J|Frj|Fd jstXd$d%gkrjtt|Fd  |Hrxtu|= |Lrtv|=| j nD|Is|Jrtw|= n.|Krtx|= n|Grty|= n|Nrtz|= t{| jert|  t}|= |"tj~k	rt{| je	rt|  t  |"tjk	r t  |"tjk	r2t  |"tXtjtjgk	rf|  jet| j7  _et| je |"tXtjtjgk	r| j\	s|  jet| j7  _et| je	rt| je t  tdk 	rt| je}S|Sdk		r|Sd&k 	rt  |"tj:k}T|"tj;k}U| jj
o|U}V|T
s|V
st|"t || _ttd'}Wt||W}	t|	 t)|W}t| | _ttd(}Xt||X}	t|	 t)|X}Yt.|Ydd}Zt/0|Z|Z| _t| je| j}[|[d) | _|[d* | _|[d+ | _W nb ttjfk
r    |rtdk 
rt|}	t|	 nt |}	t|	 d| _|    Y nX W 5 |rBt |}	t|	 d}|r^t |}	t|	 d}|rzt |}	t|	 d}|rt |}	t|	 d}|rt | d}X dS ),z2
        Perform an initial TLS handshake
        Nr   r{   zSSLContextRef *Fizutf-8)r   r   T)rC   rD   rE   c                 S   s   g | ]}t | qS ro   )_PROTOCOL_STRING_CONST_MAP).0r   ro   ro   rp   
<listcomp>_  s     z(TLSSocket._handshake.<locals>.<listcomp>size_t *   z
uint32_t *Zuint32_tr   )widthz
uint32_t[])r   r@   r   SecTrustRef *ZCSSM_OIDzchar *zSecPolicySearchRef *zSecPolicyRef *ZCSSM_APPLE_TP_OCSP_OPTIONSZ	CSSM_DATAZCSSM_APPLE_TP_CRL_OPTIONSzSecTrustResultType *z
OSStatus *)r      Ztbs_certificatevalidity
not_before	not_aftermd5Zmd2i   zSSLProtocol *zSSLCipherSuite *compression
session_idsession_ticket)r   	CFReleaser   r   r   r   ZSSLNewContextr	   r   ZSSLCreateContextr   r
   ZkSSLClientSideZkSSLStreamTypeZSSLSetIOFuncs_read_callback_pointer_write_callback_pointerid_connection_idrL   rO   rN   ZSSLSetConnectionr   encodeZSSLSetPeerDomainNamerQ   r   r   r   r   r   ZSSLSetProtocolVersionEnabledZSSLSetEnableCertVerifyminmaxZSSLSetProtocolVersionMinZSSLSetProtocolVersionMaxZSSLSetSessionOptionZ"kSSLSessionOptionBreakOnServerAuthZSSLGetNumberSupportedCiphersr   r   r   ZSSLGetSupportedCiphersr   r   r%   rM   _cipher_blacklist_regexsearchr   r   ZSSLSetEnabledCiphersr   ZSSLSetPeerIDZSSLHandshakerc   ra   ZerrSSLServerAuthCompletedSSLCopyPeerTrustr   Zcf_string_from_unicodeZSecPolicyCreateSSLr   ZAPPLE_TP_REVOCATION_OCSPZLengthDataZSecPolicySearchCreateZCSSM_CERT_X_509v3ZSecPolicySearchCopyNextZCSSM_APPLE_TP_OCSP_OPTS_VERSIONVersionZCSSM_TP_ACTION_OCSP_DISABLE_NETZ&CSSM_TP_ACTION_OCSP_CACHE_READ_DISABLEZFlagsr   ZSecPolicySetValueZAPPLE_TP_REVOCATION_CRLZCSSM_APPLE_TP_CRL_OPTS_VERSIONZCrlFlagsZcf_array_from_listZSecTrustSetPoliciesr=   sec_certificate_refZ!SecTrustSetAnchorCertificatesOnlyZSecTrustSetAnchorCertificatesZSecTrustEvaluater^   ZkSecTrustResultProceedZkSecTrustResultUnspecifiedZerrSSLXCertChainInvalidr\   ZerrSSLCertExpiredZerrSSLCertNotYetValidZerrSSLUnknownRootCertZerrSSLNoRootCertZerrSSLHostNameMismatchZerrSSLInternalZSecTrustGetCssmResultCoder,   r]   self_signedZCSSMERR_TP_CERT_REVOKEDZCSSMERR_TP_NOT_TRUSTEDZCSSMERR_TP_CERT_EXPIREDZCSSMERR_TP_CERT_NOT_VALID_YETZ!CSSMERR_APPLETP_HOSTNAME_MISMATCHZCSSMERR_TP_CERT_SUSPENDEDZchosenZnativedatetimenowr   utcZ	hash_algor<   r9   r4   r2   r6   r:   r5   r*   r/   r;   ZerrSSLPeerHandshakeFailr3   ZerrSSLWeakPeerEphemeralDHKeyr0   ZerrSSLPeerProtocolVersionr8   ZerrSSLRecordOverflowr`   r_   r7   rX   rY   r+   r1   r-   r'   _session_contextZSSLGetNegotiatedProtocolVersion_PROTOCOL_CONST_STRING_MAP	_protocolZSSLGetNegotiatedCipher_cipher_suiter.   ru   _compression_session_id_session_ticketOSErrorrS   rT   SSLDisposeContextclose)\rg   Zsession_contextZssl_policy_refZcrl_search_refZcrl_policy_refZocsp_search_refZocsp_policy_refZpolicy_array_ref	trust_refresultZsession_context_pointerZutf8_domainZdisable_auto_validationZexplicit_validationr   Zprotocol_constZenabledZprotocol_constsZmin_protocolZmax_protocolZsupported_ciphers_pointerZsupported_ciphersZcipher_bufferZsupported_cipher_suites_pointerZsupported_cipher_suitesZgood_ciphersZsupported_cipher_suitecipher_suiteZcipher_suite_nameZgood_cipherZnum_good_ciphersZgood_ciphers_arrayZgood_ciphers_pointerZpeer_idZhandshake_result	exceptionZdo_validationtrust_ref_pointerZcf_string_hostnameZocsp_oid_pointerZocsp_oidZocsp_oid_bufferZocsp_search_ref_pointerZocsp_policy_ref_pointerZocsp_struct_pointerZocsp_structZocsp_struct_bytesZcssm_data_pointerZ	cssm_dataZocsp_struct_bufferZcrl_oid_pointerZcrl_oidZcrl_oid_bufferZcrl_search_ref_pointerZcrl_policy_ref_pointerZcrl_struct_pointerZ
crl_structZcrl_struct_bytesZcrl_struct_bufferZca_cert_refsca_certscertZca_certZ	array_refZresult_pointerZtrust_result_codeZinvalid_chain_error_codesZhandshake_error_codesZresult_code_pointerresult_codechainr   revokedZexpiredZnot_yet_validZ	no_issuerZbad_hostnameZoscrypto_certZvalidity_too_longr   r   r   utcnowZdh_params_lengthZwould_blockZserver_auth_completer   Zprotocol_const_pointerZcipher_int_pointerZ
cipher_intZcipher_bytesZsession_inforo   ro   rp   r     s   



































































zTLSSocket._handshakec           
      C   sl  t |tsttdt|| jdkrH| jdkr@| j}d| _|S |   t| j}||kr|| jd| }| j|d | _|S |dkr| 	ds| j}d| _|S |t| j }t
|}ttd}t| j|||}| jdk	r| j}d| _||r|ttjtjgkrt|t |r:|tjkr:d| _| d |   t|}	| jt||	 }||d | _|d| S )a  
        Reads data from the TLS-wrapped socket

        :param max_length:
            The number of bytes to read - output may be less than this

        :raises:
            socket.socket - when a non-TLS socket error occurs
            oscrypto.errors.TLSError - when a TLS-related error occurs
            oscrypto.errors.TLSDisconnectError - when the connection disconnects
            oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection
            ValueError - when any of the parameters contain an invalid value
            TypeError - when any of the parameters are of the wrong type
            OSError - when an error is returned by the OS crypto library

        :return:
            A byte string of the data read
        zG
                max_length must be an integer, not %s
                NrH   r   r   TF)r|   r$   r~   r   r!   r   r   _raise_closedrQ   select_readr   r   r   ZSSLReadrc   r^   r
   ra   ZerrSSLClosedGracefulr	   r'   _gracefully_closed	_shutdownr   r   )
rg   
max_lengthrt   Zbuffered_lengthto_readZread_bufferprocessed_pointerr   r   
bytes_readro   ro   rp   r     sV    







zTLSSocket.readc                 C   s8   t | jdkrdS t| jgg g |\}}}t |dkS )aZ  
        Blocks until the socket is ready to be read from, or the timeout is hit

        :param timeout:
            A float - the period of time to wait for data to be read. None for
            no time limit.

        :return:
            A boolean - if data is ready to be read. Will only be False if
            timeout is not None.
        r   T)rQ   r   rR   rO   )rg   ri   rk   rl   ro   ro   rp   r   Q  s    zTLSSocket.select_readc           
      C   s   t |ts&t |ts&ttdt|d}t |t}t| jdkrP| j}d| _n|  pZd}| 	|}t|}||7 }|r|
|}|dk	r| }qq4td|t| d }	|||	}|dkr4|t| }qq4||d | j | _|d| S )a  
        Reads data from the socket until a marker is found. Data read includes
        the marker.

        :param marker:
            A byte string or regex object from re.compile(). Used to determine
            when to stop reading. Regex objects are more inefficient since
            they must scan the entire byte string of read data each time data
            is read off the socket.

        :return:
            A byte string of the data read, including the marker
        z_
                marker must be a byte string or compiled regex object, not %s
                rH   r   rr   Nr   )r|   r#   Patternr~   r   r!   rQ   r   _os_buffered_sizer   r   endr   find)
rg   markerrt   Zis_regexrm   r   offsetmatchr   startro   ro   rp   
read_untile  s4    


zTLSSocket.read_untilc                 C   s(   t td}t| j|}t| t|S )a  
        Returns the number of bytes of decrypted data stored in the Secure
        Transport read buffer. This amount of data can be read from SSLRead()
        without calling self._socket.recv().

        :return:
            An integer - the number of available bytes
        r   )r   r   ZSSLGetBufferedReadSizer   r	   r   )rg   Znum_bytes_pointerr   ro   ro   rp   r     s    

zTLSSocket._os_buffered_sizec                 C   s
   |  tS )z
        Reads a line from the socket, including the line ending of "\r\n", "\r",
        or "\n"

        :return:
            A byte string of the next line from the socket
        )r   _line_regexrg   ro   ro   rp   	read_line  s    	zTLSSocket.read_linec                 C   s0   d}|}|dkr,||  |7 }|t| }q|S )z
        Reads exactly the specified number of bytes from the socket

        :param num_bytes:
            An integer - the exact number of bytes to read

        :return:
            A byte string of the data that was read
        rH   r   )r   rQ   )rg   	num_bytesrt   	remainingro   ro   rp   read_exactly  s    zTLSSocket.read_exactlyc                 C   s   | j dkr|   ttd}t|}|rt|}t| j |||}| jdk	r\| j}d| _|t|t	 t
|}||d }t|}|dkr$|   q$dS )a  
        Writes data to the TLS-wrapped socket

        :param data:
            A byte string to write to the socket

        :raises:
            socket.socket - when a non-TLS socket error occurs
            oscrypto.errors.TLSError - when a TLS-related error occurs
            oscrypto.errors.TLSDisconnectError - when the connection disconnects
            oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection
            ValueError - when any of the parameters contain an invalid value
            TypeError - when any of the parameters are of the wrong type
            OSError - when an error is returned by the OS crypto library
        Nr   r   )r   r   r   r   rQ   r   ZSSLWriterc   r	   r'   r   select_write)rg   rj   r   data_lenZwrite_bufferr   r   Zbytes_writtenro   ro   rp   write  s,    



zTLSSocket.writec                 C   s&   t  g | jgg |\}}}t|dkS )aw  
        Blocks until the socket is ready to be written to, or the timeout is hit

        :param timeout:
            A float - the period of time to wait for the socket to be ready to
            written to. None for no time limit.

        :return:
            A boolean - if the socket is ready for writing. Will only be False
            if timeout is not None.
        r   )rR   rO   rQ   )rg   ri   rl   Zwrite_readyro   ro   rp   r     s    zTLSSocket.select_writec                 C   s   | j dkrdS t| j }tdk r8t| j }t| nt| j }t| d| _ |r\d| _	z| j
tj W n tjk
r   Y nX dS )z
        Shuts down the TLS session and then shuts down the underlying socket

        :param manual:
            A boolean if the connection was manually shutdown
        Nr   T)r   r   ZSSLCloser   r   r	   r   r   r   _local_closedrO   shutdownrS   	SHUT_RDWRrT   )rg   Zmanualr   ro   ro   rp   r   	  s    

zTLSSocket._shutdownc                 C   s   |  d dS )zV
        Shuts down the TLS session and then shuts down the underlying socket
        TN)r   r   ro   ro   rp   r   (  s    zTLSSocket.shutdownc                 C   sX   z|   W 5 | j r@z| j   W n tjk
r8   Y nX d| _ | jtkrRt| j= X dS )zN
        Shuts down the TLS session and socket and forcibly closes it
        N)rO   r   rS   rT   r   rN   r   r   ro   ro   rp   r   /  s    
zTLSSocket.closec           
   	   C   s   d}d}d}zttd}t| j|}t| t|}t	|}g | _
td|D ]`}t||}t|}t|}t |}t| d}t|}	|dkr|	| _qP| j
|	 qPW 5 |rt |}t| |rt |}t| X dS )zh
        Reads end-entity and intermediate certificate information from the
        TLS session
        Nr   r   )r   r   r   r   r   r   r   r	   r   ZSecTrustGetCertificateCount_intermediatesrangeZSecTrustGetCertificateAtIndexZSecCertificateCopyDatar   Zcf_data_to_bytesr   load_certificater   )
rg   r   Zcf_data_refr   r   Znumber_certsindexr   	cert_datar   ro   ro   rp   _read_certificatesB  sB    







zTLSSocket._read_certificatesc                 C   s,   | j rtdn| jr tdntddS )zi
        Raises an exception describing if the local or remote end closed the
        connection
        z!The connection was already closedz$The remote end closed the connectionzThe connection was closedN)r   r(   r   r)   r   ro   ro   rp   r   v  s
    

zTLSSocket._raise_closedc                 C   s*   | j dkr|   | jdkr$|   | jS )zu
        An asn1crypto.x509.Certificate object of the end-entity certificate
        presented by the server
        N)r   r   r   r   r   ro   ro   rp   certificate  s
    

zTLSSocket.certificatec                 C   s*   | j dkr|   | jdkr$|   | jS )zz
        A list of asn1crypto.x509.Certificate objects that were presented as
        intermediates by the server
        N)r   r   r   r   r   r   ro   ro   rp   intermediates  s
    

zTLSSocket.intermediatesc                 C   s   | j S )zg
        A unicode string of the IANA cipher suite name of the negotiated
        cipher suite
        )r   r   ro   ro   rp   r     s    zTLSSocket.cipher_suitec                 C   s   | j S )zM
        A unicode string of: "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"
        )r   r   ro   ro   rp   r     s    zTLSSocket.protocolc                 C   s   | j S )z5
        A boolean if compression is enabled
        )r   r   ro   ro   rp   r     s    zTLSSocket.compressionc                 C   s   | j S zM
        A unicode string of "new" or "reused" or None for no ticket
        )r   r   ro   ro   rp   r     s    zTLSSocket.session_idc                 C   s   | j S r   )r   r   ro   ro   rp   r     s    zTLSSocket.session_ticketc                 C   s   | j S )zM
        The oscrypto.tls.TLSSession object used for this connection
        )r   r   ro   ro   rp   r     s    zTLSSocket.sessionc                 C   s   | j S )zN
        A unicode string of the TLS server domain name or IP address
        )r   r   ro   ro   rp   r     s    zTLSSocket.hostnamec                 C   s   | j  d S )zJ
        An integer of the port number the socket is connected to
        r   )rh   getpeernamer   ro   ro   rp   r     s    zTLSSocket.portc                 C   s   | j dkr|   | jS )z9
        The underlying socket.socket connection
        N)r   r   rO   r   ro   ro   rp   rh     s    
zTLSSocket.socketc                 C   s   |    d S )N)r   r   ro   ro   rp   __del__  s    zTLSSocket.__del__)N)r   N)N)N)5r   r   r   r   rO   r   rc   r   r   r   r   r   r   r   r   r   r   r\   r]   ru   r   r   r   classmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r   r   r   r   rh   r  ro   ro   ro   rp   rB   {  s~   3
F   kS
8+
4











)m
__future__r   r   r   r   r   sysrerh   rS   rR   r   rU   weakrefZ	_securityr   r   r	   r
   Z_core_foundationr   r   r   Z_asn1r   r   r   r   _errorsr   _ffir   r   r   r   r   r   r   r   r   r   r   r   r   r    _typesr!   r"   r#   r$   Z_cipher_suitesr%   utilr&   errorsr'   r(   r)   Z_tlsr*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   
asymmetricr=   keysr>   version_infoxranger   Z_pattern_typer   __all__ZkSSLProtocol2ZkSSLProtocol3ZkTLSProtocol1ZkTLSProtocol11ZkTLSProtocol12r   r   compiler   r   WeakValueDictionaryrL   rN   rq   r_   ry   r   r   objectrA   rB   ro   ro   ro   rp   <module>   sp   @T	     

[7g