Skip to content

ClientSSL Extension

Iury O. G. Figueiredo edited this page Dec 1, 2020 · 5 revisions

Untwisted provides a ClientSSL extension to deal with SSL connections. The ClientSSL extension works alike the Client one. It is meant to abstract away complexity when working with sockets in non blocking mode.

The ClientSSL spawns three events SSL_CONNECT, SSL_CONNECT_ERR.

from untwisted.client import ClientSSL, SSL_CONNECT, SSL_CONNECT_ERR
from socket import socket, AF_INET, SOCK_STREAM
from untwisted import core
from untwisted.core import die
from untwisted.network import SuperSocketSSL
import ssl

def handle_connect(con):
    print('Connected !')
    die()

def handle_connect_err(con, err):
    print('Connection refused.')
    die()

def handle_certificate_err(con, err):
    print('Certificate rr.')
    die()

if __name__ == '__main__':
    sock = socket(AF_INET, SOCK_STREAM)
    context = ssl.create_default_context()

    wrap = context.wrap_socket(sock, do_handshake_on_connect=False, 
    server_hostname='www.google.com.br')

    con = SuperSocketSSL(wrap)
    ClientSSL(con)
    
    con.add_map(SSL_CONNECT, handle_connect)
    con.add_map(SSL_CONNECT_ERR, handle_connect_err)
    con.connect_ex(('www.google.com.br', 443))
    core.gear.mainloop()    

The above code shows the ClientSSL usage, it is slightly cumbersome. There are helper functions to set up SSL connections alike with non secure connections. The above code merely connects to www.google.com.br.

It would output.

Connected !

Then it stops the reactor. The SSL is a SuperSocket that is used for SSL connections. It works alike SuperSocket in non secure connections.