fix timeout bug for python 2.6
[sfa.git] / sfa / util / httpsProtocol.py
1 import httplib
2 import socket
3 import sys
4
5
6 def is_python26():
7     return sys.version_info[0] == 2 and sys.version_info[1] == 6
8
9 # wrapper around standartd https modules. Properly supports timeouts.  
10
11 class HTTPSConnection(httplib.HTTPSConnection):
12     def __init__(self, host, port=None, key_file=None, cert_file=None,
13                  strict=None, timeout = None):
14         httplib.HTTPSConnection.__init__(self, host, port, key_file, cert_file, strict)
15         self.timeout = float(timeout)
16
17     def connect(self):
18         """Connect to a host on a given (SSL) port."""
19         if is_python26():
20             from sfa.util.ssl_socket import SSLSocket
21             sock = socket.create_connection((self.host, self.port), self.timeout)
22             if self._tunnel_host:
23                 self.sock = sock
24                 self._tunnel()
25             self.sock = SSLSocket(sock, self.key_file, self.cert_file)
26         else:
27             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
28             sock.settimeout(self.timeout)
29             sock.connect((self.host, self.port))
30             ssl = socket.ssl(sock, self.key_file, self.cert_file)
31             self.sock = httplib.FakeSocket(sock, ssl)
32
33 class HTTPS(httplib.HTTPS):
34     def __init__(self, host='', port=None, key_file=None, cert_file=None,
35                      strict=None, timeout = None):
36         # urf. compensate for bad input.
37         if port == 0:
38             port = None
39         self._setup(HTTPSConnection(host, port, key_file, cert_file, strict, timeout))
40
41         # we never actually use these for anything, but we keep them
42         # here for compatibility with post-1.5.2 CVS.
43         self.key_file = key_file
44         self.cert_file = cert_file
45     
46     def set_timeout(self, timeout):
47         if is_python26():
48             self._conn.timeout = timeout