from httplib import HTTPSConnection
from socket import socket, AF_INET, SOCK_STREAM
import config
from ssl import wrap_socket, CERT_REQUIRED

class SecureConnection(HTTPSConnection):
    '''
    This is an https connection that verifies that the server certificate is signed by
    a trusted ca_cert.

    NOTE that it does NOT validate that the hostname matches the one in the certificate,
    because multiple clients (with different hostnames) will use the same certificate.
    Thus, for us it's enough to know that a given client has the private key whose public
    key is trusted.
    '''
    def connect(self):
        # overrides the version in httplib so that we do certificate verification
        sock = socket(AF_INET, SOCK_STREAM)
        sock.connect((self.host, self.port))

        if not self.cert_file:
            self.cert_file = config.cert_file
        if not self.key_file:
            self.key_file = config.key_file
        self.ca_certs = (config.ca_cert)

        self.sock = wrap_socket(sock, self.key_file, self.cert_file,
            cert_reqs=CERT_REQUIRED, ca_certs=self.ca_certs)
