#NEWLINE# def ssl_wrap_socket( sock , keyfile = None , certfile = None , cert_reqs = None , ca_certs = None , server_hostname = None , ssl_version = None , ca_cert_dir = None ) : #NEWLINE# #INDENT# ctx = OpenSSL . SSL . Context ( _openssl_versions [ ssl_version ] ) #NEWLINE# if ca_cert_dir : #NEWLINE# #INDENT# keyfile = ( keyfile or certfile ) #NEWLINE# ctx . use_certificate_file ( certfile ) #NEWLINE# #UNINDENT# if keyfile : #NEWLINE# #INDENT# ctx . use_privatekey_file ( keyfile ) #NEWLINE# #UNINDENT# if ( cert_reqs != ssl . CERT_NONE ) : #NEWLINE# #INDENT# ctx . set_verify ( _openssl_verify [ cert_reqs ] , _verify_callback ) #NEWLINE# #UNINDENT# if ( ca_certs or ca_cert_dir ) : #NEWLINE# #INDENT# try : #NEWLINE# #INDENT# ctx . load_verify_locations ( ca_certs , ca_cert_dir ) #NEWLINE# #UNINDENT# except OpenSSL . SSL . Error as e : #NEWLINE# #INDENT# raise ssl . SSLError ( ( 'bad ca_certs: %r' % ca_certs ) , e ) #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# ctx . set_default_verify_paths ( ) #NEWLINE# #UNINDENT# OP_NO_COMPRESSION = 131072 #NEWLINE# ctx . set_options ( OP_NO_COMPRESSION ) #NEWLINE# ctx . set_cipher_list ( DEFAULT_SSL_CIPHER_LIST ) #NEWLINE# cnx = OpenSSL . SSL . Connection ( ctx , sock ) #NEWLINE# cnx . set_tlsext_host_name ( server_hostname ) #NEWLINE# cnx . set_connect_state ( ) #NEWLINE# while True : #NEWLINE# #INDENT# try : #NEWLINE# #INDENT# cnx . do_handshake ( ) #NEWLINE# #UNINDENT# except OpenSSL . SSL . WantReadError : #NEWLINE# #INDENT# ( rd , _ , _ ) = select . select ( [ sock ] , [ ] , [ ] , sock . gettimeout ( ) ) #NEWLINE# if ( not rd ) : #NEWLINE# #INDENT# raise timeout ( 'select timed out' ) #NEWLINE# #UNINDENT# continue #NEWLINE# #UNINDENT# except OpenSSL . SSL . Error as e : #NEWLINE# #INDENT# raise ssl . SSLError ( ( 'bad handshake: %r' % e ) ) #NEWLINE# #UNINDENT# break #NEWLINE# #UNINDENT# return WrappedSocket ( cnx , sock )