##// END OF EJS Templates
httpclient: apply change df9aea1def3e: remove use of two-argument raise
Augie Fackler -
r18179:f6145437 default
parent child Browse files
Show More
@@ -1,127 +1,127 b''
1 # Copyright 2010, Google Inc.
1 # Copyright 2010, Google Inc.
2 # All rights reserved.
2 # All rights reserved.
3 #
3 #
4 # Redistribution and use in source and binary forms, with or without
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
5 # modification, are permitted provided that the following conditions are
6 # met:
6 # met:
7 #
7 #
8 # * Redistributions of source code must retain the above copyright
8 # * Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
9 # notice, this list of conditions and the following disclaimer.
10 # * Redistributions in binary form must reproduce the above
10 # * Redistributions in binary form must reproduce the above
11 # copyright notice, this list of conditions and the following disclaimer
11 # copyright notice, this list of conditions and the following disclaimer
12 # in the documentation and/or other materials provided with the
12 # in the documentation and/or other materials provided with the
13 # distribution.
13 # distribution.
14 # * Neither the name of Google Inc. nor the names of its
14 # * Neither the name of Google Inc. nor the names of its
15 # contributors may be used to endorse or promote products derived from
15 # contributors may be used to endorse or promote products derived from
16 # this software without specific prior written permission.
16 # this software without specific prior written permission.
17
17
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 """Abstraction to simplify socket use for Python < 2.6
29 """Abstraction to simplify socket use for Python < 2.6
30
30
31 This will attempt to use the ssl module and the new
31 This will attempt to use the ssl module and the new
32 socket.create_connection method, but fall back to the old
32 socket.create_connection method, but fall back to the old
33 methods if those are unavailable.
33 methods if those are unavailable.
34 """
34 """
35 import logging
35 import logging
36 import socket
36 import socket
37
37
38 logger = logging.getLogger(__name__)
38 logger = logging.getLogger(__name__)
39
39
40 try:
40 try:
41 import ssl
41 import ssl
42 ssl.wrap_socket # make demandimporters load the module
42 ssl.wrap_socket # make demandimporters load the module
43 have_ssl = True
43 have_ssl = True
44 except ImportError:
44 except ImportError:
45 import httplib
45 import httplib
46 import urllib2
46 import urllib2
47 have_ssl = getattr(urllib2, 'HTTPSHandler', False)
47 have_ssl = getattr(urllib2, 'HTTPSHandler', False)
48 ssl = False
48 ssl = False
49
49
50
50
51 try:
51 try:
52 create_connection = socket.create_connection
52 create_connection = socket.create_connection
53 except AttributeError:
53 except AttributeError:
54 def create_connection(address):
54 def create_connection(address):
55 host, port = address
55 host, port = address
56 msg = "getaddrinfo returns an empty list"
56 msg = "getaddrinfo returns an empty list"
57 sock = None
57 sock = None
58 for res in socket.getaddrinfo(host, port, 0,
58 for res in socket.getaddrinfo(host, port, 0,
59 socket.SOCK_STREAM):
59 socket.SOCK_STREAM):
60 af, socktype, proto, _canonname, sa = res
60 af, socktype, proto, _canonname, sa = res
61 try:
61 try:
62 sock = socket.socket(af, socktype, proto)
62 sock = socket.socket(af, socktype, proto)
63 logger.info("connect: (%s, %s)", host, port)
63 logger.info("connect: (%s, %s)", host, port)
64 sock.connect(sa)
64 sock.connect(sa)
65 except socket.error, msg:
65 except socket.error, msg:
66 logger.info('connect fail: %s %s', host, port)
66 logger.info('connect fail: %s %s', host, port)
67 if sock:
67 if sock:
68 sock.close()
68 sock.close()
69 sock = None
69 sock = None
70 continue
70 continue
71 break
71 break
72 if not sock:
72 if not sock:
73 raise socket.error, msg
73 raise socket.error(msg)
74 return sock
74 return sock
75
75
76 if ssl:
76 if ssl:
77 wrap_socket = ssl.wrap_socket
77 wrap_socket = ssl.wrap_socket
78 CERT_NONE = ssl.CERT_NONE
78 CERT_NONE = ssl.CERT_NONE
79 CERT_OPTIONAL = ssl.CERT_OPTIONAL
79 CERT_OPTIONAL = ssl.CERT_OPTIONAL
80 CERT_REQUIRED = ssl.CERT_REQUIRED
80 CERT_REQUIRED = ssl.CERT_REQUIRED
81 else:
81 else:
82 class FakeSocket(httplib.FakeSocket):
82 class FakeSocket(httplib.FakeSocket):
83 """Socket wrapper that supports SSL.
83 """Socket wrapper that supports SSL.
84 """
84 """
85 # backport the behavior from Python 2.6, which is to busy wait
85 # backport the behavior from Python 2.6, which is to busy wait
86 # on the socket instead of anything nice. Sigh.
86 # on the socket instead of anything nice. Sigh.
87 # See http://bugs.python.org/issue3890 for more info.
87 # See http://bugs.python.org/issue3890 for more info.
88 def recv(self, buflen=1024, flags=0):
88 def recv(self, buflen=1024, flags=0):
89 """ssl-aware wrapper around socket.recv
89 """ssl-aware wrapper around socket.recv
90 """
90 """
91 if flags != 0:
91 if flags != 0:
92 raise ValueError(
92 raise ValueError(
93 "non-zero flags not allowed in calls to recv() on %s" %
93 "non-zero flags not allowed in calls to recv() on %s" %
94 self.__class__)
94 self.__class__)
95 while True:
95 while True:
96 try:
96 try:
97 return self._ssl.read(buflen)
97 return self._ssl.read(buflen)
98 except socket.sslerror, x:
98 except socket.sslerror, x:
99 if x.args[0] == socket.SSL_ERROR_WANT_READ:
99 if x.args[0] == socket.SSL_ERROR_WANT_READ:
100 continue
100 continue
101 else:
101 else:
102 raise x
102 raise x
103
103
104 _PROTOCOL_SSLv23 = 2
104 _PROTOCOL_SSLv23 = 2
105
105
106 CERT_NONE = 0
106 CERT_NONE = 0
107 CERT_OPTIONAL = 1
107 CERT_OPTIONAL = 1
108 CERT_REQUIRED = 2
108 CERT_REQUIRED = 2
109
109
110 def wrap_socket(sock, keyfile=None, certfile=None,
110 def wrap_socket(sock, keyfile=None, certfile=None,
111 server_side=False, cert_reqs=CERT_NONE,
111 server_side=False, cert_reqs=CERT_NONE,
112 ssl_version=_PROTOCOL_SSLv23, ca_certs=None,
112 ssl_version=_PROTOCOL_SSLv23, ca_certs=None,
113 do_handshake_on_connect=True,
113 do_handshake_on_connect=True,
114 suppress_ragged_eofs=True):
114 suppress_ragged_eofs=True):
115 if cert_reqs != CERT_NONE and ca_certs:
115 if cert_reqs != CERT_NONE and ca_certs:
116 raise CertificateValidationUnsupported(
116 raise CertificateValidationUnsupported(
117 'SSL certificate validation requires the ssl module'
117 'SSL certificate validation requires the ssl module'
118 '(included in Python 2.6 and later.)')
118 '(included in Python 2.6 and later.)')
119 sslob = socket.ssl(sock)
119 sslob = socket.ssl(sock)
120 # borrow httplib's workaround for no ssl.wrap_socket
120 # borrow httplib's workaround for no ssl.wrap_socket
121 sock = FakeSocket(sock, sslob)
121 sock = FakeSocket(sock, sslob)
122 return sock
122 return sock
123
123
124
124
125 class CertificateValidationUnsupported(Exception):
125 class CertificateValidationUnsupported(Exception):
126 """Exception raised when cert validation is requested but unavailable."""
126 """Exception raised when cert validation is requested but unavailable."""
127 # no-check-code
127 # no-check-code
General Comments 0
You need to be logged in to leave comments. Login now