Debian Codegraph @

rfc6555.py

raw symbols SCIP
1 """ Python implementation of the Happy Eyeballs Algorithm described in RFC 6555. """
2
3 # Copyright 2017 Seth Michael Larson
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import errno
18 import socket
19 try:
20 from selectors import DefaultSelector, EVENT_WRITE
21 except (ImportError, AttributeError):
22 from selectors2 import DefaultSelector, EVENT_WRITE
23
24 # time.perf_counter() is defined in Python 3.3
25 try:
26 from time import perf_counter
27 except (ImportError, AttributeError):
28 from time import time as perf_counter
29
30
31 # This list is due to socket.error and IOError not being a
32 # subclass of OSError until later versions of Python.
33 _SOCKET_ERRORS = (socket.error, OSError, IOError)
34
35
36 # Detects whether an IPv6 socket can be allocated.
37 def _detect_ipv6():
38 if getattr(socket, 'has_ipv6', False) and hasattr(socket, 'AF_INET6'):
39 _sock = None
40 try:
41 _sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
42 _sock.bind(('::1', 0))
43 return True
44 except _SOCKET_ERRORS:
45 if _sock:
46 _sock.close()
47 return False
48
49
50 _HAS_IPV6 = _detect_ipv6()
51
52 # These are error numbers for asynchronous operations which can
53 # be safely ignored by RFC 6555 as being non-errors.
54 _ASYNC_ERRNOS = set([errno.EINPROGRESS,
55 errno.EAGAIN,
56 errno.EWOULDBLOCK])
57 if hasattr(errno, 'WSAWOULDBLOCK'):
58 _ASYNC_ERRNOS.add(errno.WSAWOULDBLOCK)
59
60 _DEFAULT_CACHE_DURATION = 60 * 10 # 10 minutes according to the RFC.
61
62 # This value that can be used to disable RFC 6555 globally.
63 RFC6555_ENABLED = _HAS_IPV6
64
65 __all__ = ['RFC6555_ENABLED',
66 'create_connection',
67 'cache']
68
69 __version__ = '1.0.0'
70 __author__ = 'Seth Michael Larson'
71 __email__ = '[email protected]'
72 __license__ = 'Apache-2.0'
73
74
75 class _RFC6555CacheManager(object):
76 def __init__(self):
77 self.validity_duration = _DEFAULT_CACHE_DURATION
78 self.enabled = True
79 self.entries = {}
80
81 def add_entry(self, address, family):
82 if self.enabled:
83 current_time = perf_counter()
84
85 # Don't over-write old entries to reset their expiry.
86 if address not in self.entries or self.entries[address][1] > current_time:
87 self.entries[address] = (family, current_time + self.validity_duration)
88
89 def get_entry(self, address):
90 if not self.enabled or address not in self.entries:
91 return None
92
93 family, expiry = self.entries[address]
94 if perf_counter() > expiry:
95 del self.entries[address]
96 return None
97
98 return family
99
100
101 cache = _RFC6555CacheManager()
102
103
104 class _RFC6555ConnectionManager(object):
105 def __init__(self, address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
106 self.address = address
107 self.timeout = timeout
108 self.source_address = source_address
109
110 self._error = None
111 self._selector = DefaultSelector()
112 self._sockets = []
113 self._start_time = None
114
115 def create_connection(self):
116 self._start_time = perf_counter()
117
118 host, port = self.address
119 addr_info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
120 ret = self._connect_with_cached_family(addr_info)
121
122 # If it's a list, then these are the remaining values to try.
123 if isinstance(ret, list):
124 addr_info = ret
125 else:
126 cache.add_entry(self.address, ret.family)
127 return ret
128
129 # If we don't get any results back then just skip to the end.
130 if not addr_info:
131 raise socket.error('getaddrinfo returns an empty list')
132
133 sock = self._attempt_connect_with_addr_info(addr_info)
134
135 if sock:
136 cache.add_entry(self.address, sock.family)
137 return sock
138 elif self._error:
139 raise self._error
140 else:
141 raise socket.timeout()
142
143 def _attempt_connect_with_addr_info(self, addr_info):
144 sock = None
145 try:
146 for family, socktype, proto, _, sockaddr in addr_info:
147 self._create_socket(family, socktype, proto, sockaddr)
148 sock = self._wait_for_connection(False)
149 if sock:
150 break
151 if sock is None:
152 sock = self._wait_for_connection(True)
153 finally:
154 self._remove_all_sockets()
155 return sock
156
157 def _connect_with_cached_family(self, addr_info):
158 family = cache.get_entry(self.address)
159 if family is None:
160 return addr_info
161
162 is_family = []
163 not_family = []
164
165 for value in addr_info:
166 if value[0] == family:
167 is_family.append(value)
168 else:
169 not_family.append(value)
170
171 sock = self._attempt_connect_with_addr_info(is_family)
172 if sock is not None:
173 return sock
174
175 return not_family
176
177 def _create_socket(self, family, socktype, proto, sockaddr):
178 sock = None
179 try:
180 sock = socket.socket(family, socktype, proto)
181
182 # If we're using the 'default' socket timeout we have
183 # to set it to a real value here as this is the earliest
184 # opportunity to without pre-allocating a socket just for
185 # this purpose.
186 if self.timeout is socket._GLOBAL_DEFAULT_TIMEOUT:
187 self.timeout = sock.gettimeout()
188
189 if self.source_address:
190 sock.bind(self.source_address)
191
192 # Make the socket non-blocking so we can use our selector.
193 sock.settimeout(0.0)
194
195 if self._is_acceptable_errno(sock.connect_ex(sockaddr)):
196 self._selector.register(sock, EVENT_WRITE)
197 self._sockets.append(sock)
198
199 except _SOCKET_ERRORS as e:
200 self._error = e
201 if sock is not None:
202 _RFC6555ConnectionManager._close_socket(sock)
203
204 def _wait_for_connection(self, last_wait):
205 self._remove_all_errored_sockets()
206
207 # This is a safe-guard to make sure sock.gettimeout() is called in the
208 # case that the default socket timeout is used. If there are no
209 # sockets then we may not have called sock.gettimeout() yet.
210 if not self._sockets:
211 return None
212
213 # If this is the last time we're waiting for connections
214 # then we should wait until we should raise a timeout
215 # error, otherwise we should only wait >0.2 seconds as
216 # recommended by RFC 6555.
217 if last_wait:
218 if self.timeout is None:
219 select_timeout = None
220 else:
221 select_timeout = self._get_remaining_time()
222 else:
223 select_timeout = self._get_select_time()
224
225 # Wait for any socket to become writable as a sign of being connected.
226 for key, _ in self._selector.select(select_timeout):
227 sock = key.fileobj
228
229 if not self._is_socket_errored(sock):
230
231 # Restore the old proper timeout of the socket.
232 sock.settimeout(self.timeout)
233
234 # Remove it from this list to exempt the socket from cleanup.
235 self._sockets.remove(sock)
236 self._selector.unregister(sock)
237 return sock
238
239 return None
240
241 def _get_remaining_time(self):
242 if self.timeout is None:
243 return None
244 return max(self.timeout - (perf_counter() - self._start_time), 0.0)
245
246 def _get_select_time(self):
247 if self.timeout is None:
248 return 0.2
249 return min(0.2, self._get_remaining_time())
250
251 def _remove_all_errored_sockets(self):
252 socks = []
253 for sock in self._sockets:
254 if self._is_socket_errored(sock):
255 socks.append(sock)
256 for sock in socks:
257 self._selector.unregister(sock)
258 self._sockets.remove(sock)
259 _RFC6555ConnectionManager._close_socket(sock)
260
261 @staticmethod
262 def _close_socket(sock):
263 try:
264 sock.close()
265 except _SOCKET_ERRORS:
266 pass
267
268 def _is_acceptable_errno(self, errno):
269 if errno == 0 or errno in _ASYNC_ERRNOS:
270 return True
271 self._error = socket.error()
272 self._error.errno = errno
273 return False
274
275 def _is_socket_errored(self, sock):
276 errno = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
277 return not self._is_acceptable_errno(errno)
278
279 def _remove_all_sockets(self):
280 for sock in self._sockets:
281 self._selector.unregister(sock)
282 _RFC6555ConnectionManager._close_socket(sock)
283 self._sockets = []
284
285
286 def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
287 if RFC6555_ENABLED and _HAS_IPV6:
288 manager = _RFC6555ConnectionManager(address, timeout, source_address)
289 return manager.create_connection()
290 else:
291 # This code is the same as socket.create_connection() but is
292 # here to make sure the same code is used across all Python versions as
293 # the source_address parameter was added to socket.create_connection() in 3.2
294 # This segment of code is licensed under the Python Software Foundation License
295 # See LICENSE: https://github.com/python/cpython/blob/3.6/LICENSE
296 host, port = address
297 err = None
298 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
299 af, socktype, proto, canonname, sa = res
300 sock = None
301 try:
302 sock = socket.socket(af, socktype, proto)
303 if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
304 sock.settimeout(timeout)
305 if source_address:
306 sock.bind(source_address)
307 sock.connect(sa)
308 return sock
309
310 except socket.error as _:
311 err = _
312 if sock is not None:
313 sock.close()
314
315 if err is not None:
316 raise err
317 else:
318 raise socket.error("getaddrinfo returns an empty list")