Re: IPv6 support at M2Crypto.httpslib

Christian Pinedo Zamalloa <[email protected]>
Newsgroups gmane.comp.python.cryptography
Message-ID <[email protected]>
Sorry. The attachment.

-- 
Christian Pinedo Zamalloa
[email protected]
PGP key: gpg --keyserver pgp.rediris.es --recv-key 78B39814
         http://www.rediris.es/servicios/cert/keyserver, keyID 0x78B39814
Fingerprint: 21E6 A55D 995D AC7A A497 B3A7 0B93 00DC 78B3 9814
httpslib.py (text/x-python, 6 KB)
"""M2Crypto support for Python 1.5.2 and Python 2.x's httplib. 

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved."""

RCS_id='$Id: httpslib.py,v 1.9 2004/03/25 06:35:20 ngps Exp$'

import string, sys, socket
from httplib import *
import SSL

if sys.version[0] == '2':
    
    if sys.version[:3] != '2.0':
        # In 2.1 and above, httplib exports "HTTP" only.
        from httplib import HTTPConnection, HTTPS_PORT

    class HTTPSConnection(HTTPConnection):
    
        """
        This class allows communication via SSL using M2Crypto.
        """
    
        default_port = HTTPS_PORT
    
        if (sys.version[:3] == '2.2' and sys.version_info[2] > 1) or (sys.version[:3] == '2.3'):
        
            # 2.2.2 and above have the 'strict' param.
            def __init__(self, host, port=None, strict=None, **ssl):
                keys = ssl.keys()
                try: 
                    keys.remove('key_file')
                except ValueError:
                    pass
                try:
                    keys.remove('cert_file')
                except ValueError:
                    pass
                try:
                    keys.remove('ssl_context')
                except ValueError:
                    pass
                if keys:
                    raise IllegalKeywordArgument()
                try:
                    self.ssl_ctx = ssl['ssl_context']
                    assert isinstance(self.ssl_ctx, SSL.Context)
                except KeyError:
                    self.ssl_ctx = SSL.Context('sslv23')
                HTTPConnection.__init__(self, host, port, strict)

        else:
            def __init__(self, host, port=None, **ssl):
                keys = ssl.keys()
                try: 
                    keys.remove('key_file')
                except ValueError:
                    pass
                try:
                    keys.remove('cert_file')
                except ValueError:
                    pass
                try:
                    keys.remove('ssl_context')
                except ValueError:
                    pass
                if keys:
                    raise IllegalKeywordArgument()
                try:
                    self.ssl_ctx = ssl['ssl_context']
                    assert isinstance(self.ssl_ctx, SSL.Context)
                except KeyError:
                    self.ssl_ctx = SSL.Context('sslv23')
                HTTPConnection.__init__(self, host, port)
    
        def connect(self):
            """Connect to the host and port specified in __init__."""
            msg = "getaddrinfo returns an empty list"
            for res in socket.getaddrinfo(self.host, self.port, 0,
                                          socket.SOCK_STREAM):
                af, socktype, proto, canonname, sa = res
                try:
                    self.socket = socket.socket(af, socktype, proto)
                    self.sock = SSL.Connection(self.ssl_ctx, self.socket)
                    if self.debuglevel > 0:
                        print "connect: (%s, %s)" % (self.host, self.port)
                    self.sock.connect(sa)
                except socket.error, msg:
                    if self.debuglevel > 0:
                        print 'connect fail:', (self.host, self.port)
                    if self.sock:
                        self.sock.close()
                    self.sock = None
                    continue
                break
            if not self.sock:
                raise socket.error, msg

        def close(self):
            # This kludges around line 545 of httplib.py,
            # which closes the connection in this object;
            # the connection remains open in the response
            # object.
            #
            # M2Crypto doesn't close-here-keep-open-there,
            # so, in effect, we don't close until the whole 
            # business is over and gc kicks in.
            #
            # Long-running callers beware leakage.
            #
            # 05-Jan-2002: This module works with Python 2.2,
            # but I've not investigated if the above conditions
            # remain.
            pass


    class HTTPS(HTTP):
        
        _connection_class = HTTPSConnection
    
        if (sys.version[:3] == '2.2' and sys.version_info[2] > 1) or (sys.version[:3] == '2.3'):
            # 2.2.2 and above have the 'strict' param.            
            def __init__(self, host='', port=None, strict=None, **ssl):
                HTTP.__init__(self, host, port, strict)
                try:
                    self.ssl_ctx = ssl['ssl_context']
                except KeyError:
                    self.ssl_ctx = SSL.Context('sslv23')
                assert isinstance(self._conn, HTTPSConnection)
                self._conn.ssl_ctx = self.ssl_ctx

        else:
            def __init__(self, host='', port=None, **ssl):
                HTTP.__init__(self, host, port)
                try:
                    self.ssl_ctx = ssl['ssl_context']
                except KeyError:
                    self.ssl_ctx = SSL.Context('sslv23')
                assert isinstance(self._conn, HTTPSConnection)
                self._conn.ssl_ctx = self.ssl_ctx


elif sys.version[:3] == '1.5':

    class HTTPS(HTTP):
    
        def __init__(self, ssl_context, host='', port=None):
            assert isinstance(ssl_context, SSL.Context)
            self.debuglevel=0
            self.file=None
            self.ssl_ctx=ssl_context
            if host:
                self.connect(host, port)
    
        def connect(self, host, port=None):
            # Cribbed from httplib.HTTP.
            if not port:
                i = string.find(host, ':')
                if i >= 0:
                    host, port = host[:i], host[i+1:]
                    try: port = string.atoi(port)
                    except string.atoi_error:
                        raise socket.error, "nonnumeric port"
            if not port: port = HTTPS_PORT
            self.sock = SSL.Connection(self.ssl_ctx)
            if self.debuglevel > 0: print 'connect:', (host, port)
            self.sock.connect((host, port))
signature.asc (application/pgp-signature, 189 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFBVTbGC5MA3HizmBQRAuA/AKDUPEukMVrSmIlUnrIb7mjzjLb7NQCg0351
DIW4OLV4SiFBsoGudTiZm2A=
=6dkm
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.