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