1import contextlib 2import errno 3import socket 4import unittest 5import sys 6 7from .. import support 8from . import warnings_helper 9 10HOST = "localhost" 11HOSTv4 = "127.0.0.1" 12HOSTv6 = "::1" 13 14# WASI SDK 15.0 does not provide gethostname, stub raises OSError ENOTSUP. 15has_gethostname = not support.is_wasi 16 17 18def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): 19 """Returns an unused port that should be suitable for binding. This is 20 achieved by creating a temporary socket with the same family and type as 21 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to 22 the specified host address (defaults to 0.0.0.0) with the port set to 0, 23 eliciting an unused ephemeral port from the OS. The temporary socket is 24 then closed and deleted, and the ephemeral port is returned. 25 26 Either this method or bind_port() should be used for any tests where a 27 server socket needs to be bound to a particular port for the duration of 28 the test. Which one to use depends on whether the calling code is creating 29 a python socket, or if an unused port needs to be provided in a constructor 30 or passed to an external program (i.e. the -accept argument to openssl's 31 s_server mode). Always prefer bind_port() over find_unused_port() where 32 possible. Hard coded ports should *NEVER* be used. As soon as a server 33 socket is bound to a hard coded port, the ability to run multiple instances 34 of the test simultaneously on the same host is compromised, which makes the 35 test a ticking time bomb in a buildbot environment. On Unix buildbots, this 36 may simply manifest as a failed test, which can be recovered from without 37 intervention in most cases, but on Windows, the entire python process can 38 completely and utterly wedge, requiring someone to log in to the buildbot 39 and manually kill the affected process. 40 41 (This is easy to reproduce on Windows, unfortunately, and can be traced to 42 the SO_REUSEADDR socket option having different semantics on Windows versus 43 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, 44 listen and then accept connections on identical host/ports. An EADDRINUSE 45 OSError will be raised at some point (depending on the platform and 46 the order bind and listen were called on each socket). 47 48 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE 49 will ever be raised when attempting to bind two identical host/ports. When 50 accept() is called on each socket, the second caller's process will steal 51 the port from the first caller, leaving them both in an awkwardly wedged 52 state where they'll no longer respond to any signals or graceful kills, and 53 must be forcibly killed via OpenProcess()/TerminateProcess(). 54 55 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option 56 instead of SO_REUSEADDR, which effectively affords the same semantics as 57 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open 58 Source world compared to Windows ones, this is a common mistake. A quick 59 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when 60 openssl.exe is called with the 's_server' option, for example. See 61 http://bugs.python.org/issue2550 for more info. The following site also 62 has a very thorough description about the implications of both REUSEADDR 63 and EXCLUSIVEADDRUSE on Windows: 64 https://learn.microsoft.com/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse 65 66 XXX: although this approach is a vast improvement on previous attempts to 67 elicit unused ports, it rests heavily on the assumption that the ephemeral 68 port returned to us by the OS won't immediately be dished back out to some 69 other process when we close and delete our temporary socket but before our 70 calling code has a chance to bind the returned port. We can deal with this 71 issue if/when we come across it. 72 """ 73 74 with socket.socket(family, socktype) as tempsock: 75 port = bind_port(tempsock) 76 del tempsock 77 return port 78 79def bind_port(sock, host=HOST): 80 """Bind the socket to a free port and return the port number. Relies on 81 ephemeral ports in order to ensure we are using an unbound port. This is 82 important as many tests may be running simultaneously, especially in a 83 buildbot environment. This method raises an exception if the sock.family 84 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR 85 or SO_REUSEPORT set on it. Tests should *never* set these socket options 86 for TCP/IP sockets. The only case for setting these options is testing 87 multicasting via multiple UDP sockets. 88 89 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. 90 on Windows), it will be set on the socket. This will prevent anyone else 91 from bind()'ing to our host/port for the duration of the test. 92 """ 93 94 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: 95 if hasattr(socket, 'SO_REUSEADDR'): 96 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: 97 raise support.TestFailed("tests should never set the " 98 "SO_REUSEADDR socket option on " 99 "TCP/IP sockets!") 100 if hasattr(socket, 'SO_REUSEPORT'): 101 try: 102 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: 103 raise support.TestFailed("tests should never set the " 104 "SO_REUSEPORT socket option on " 105 "TCP/IP sockets!") 106 except OSError: 107 # Python's socket module was compiled using modern headers 108 # thus defining SO_REUSEPORT but this process is running 109 # under an older kernel that does not support SO_REUSEPORT. 110 pass 111 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): 112 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) 113 114 sock.bind((host, 0)) 115 port = sock.getsockname()[1] 116 return port 117 118def bind_unix_socket(sock, addr): 119 """Bind a unix socket, raising SkipTest if PermissionError is raised.""" 120 assert sock.family == socket.AF_UNIX 121 try: 122 sock.bind(addr) 123 except PermissionError: 124 sock.close() 125 raise unittest.SkipTest('cannot bind AF_UNIX sockets') 126 127def _is_ipv6_enabled(): 128 """Check whether IPv6 is enabled on this host.""" 129 if socket.has_ipv6: 130 sock = None 131 try: 132 sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) 133 sock.bind((HOSTv6, 0)) 134 return True 135 except OSError: 136 pass 137 finally: 138 if sock: 139 sock.close() 140 return False 141 142IPV6_ENABLED = _is_ipv6_enabled() 143 144 145_bind_nix_socket_error = None 146def skip_unless_bind_unix_socket(test): 147 """Decorator for tests requiring a functional bind() for unix sockets.""" 148 if not hasattr(socket, 'AF_UNIX'): 149 return unittest.skip('No UNIX Sockets')(test) 150 global _bind_nix_socket_error 151 if _bind_nix_socket_error is None: 152 from .os_helper import TESTFN, unlink 153 path = TESTFN + "can_bind_unix_socket" 154 with socket.socket(socket.AF_UNIX) as sock: 155 try: 156 sock.bind(path) 157 _bind_nix_socket_error = False 158 except OSError as e: 159 _bind_nix_socket_error = e 160 finally: 161 unlink(path) 162 if _bind_nix_socket_error: 163 msg = 'Requires a functional unix bind(): %s' % _bind_nix_socket_error 164 return unittest.skip(msg)(test) 165 else: 166 return test 167 168 169def get_socket_conn_refused_errs(): 170 """ 171 Get the different socket error numbers ('errno') which can be received 172 when a connection is refused. 173 """ 174 errors = [errno.ECONNREFUSED] 175 if hasattr(errno, 'ENETUNREACH'): 176 # On Solaris, ENETUNREACH is returned sometimes instead of ECONNREFUSED 177 errors.append(errno.ENETUNREACH) 178 if hasattr(errno, 'EADDRNOTAVAIL'): 179 # bpo-31910: socket.create_connection() fails randomly 180 # with EADDRNOTAVAIL on Travis CI 181 errors.append(errno.EADDRNOTAVAIL) 182 if hasattr(errno, 'EHOSTUNREACH'): 183 # bpo-37583: The destination host cannot be reached 184 errors.append(errno.EHOSTUNREACH) 185 if not IPV6_ENABLED: 186 errors.append(errno.EAFNOSUPPORT) 187 return errors 188 189 190_NOT_SET = object() 191 192@contextlib.contextmanager 193def transient_internet(resource_name, *, timeout=_NOT_SET, errnos=()): 194 """Return a context manager that raises ResourceDenied when various issues 195 with the internet connection manifest themselves as exceptions.""" 196 nntplib = warnings_helper.import_deprecated("nntplib") 197 import urllib.error 198 if timeout is _NOT_SET: 199 timeout = support.INTERNET_TIMEOUT 200 201 default_errnos = [ 202 ('ECONNREFUSED', 111), 203 ('ECONNRESET', 104), 204 ('EHOSTUNREACH', 113), 205 ('ENETUNREACH', 101), 206 ('ETIMEDOUT', 110), 207 # socket.create_connection() fails randomly with 208 # EADDRNOTAVAIL on Travis CI. 209 ('EADDRNOTAVAIL', 99), 210 ] 211 default_gai_errnos = [ 212 ('EAI_AGAIN', -3), 213 ('EAI_FAIL', -4), 214 ('EAI_NONAME', -2), 215 ('EAI_NODATA', -5), 216 # Encountered when trying to resolve IPv6-only hostnames 217 ('WSANO_DATA', 11004), 218 ] 219 220 denied = support.ResourceDenied("Resource %r is not available" % resource_name) 221 captured_errnos = errnos 222 gai_errnos = [] 223 if not captured_errnos: 224 captured_errnos = [getattr(errno, name, num) 225 for (name, num) in default_errnos] 226 gai_errnos = [getattr(socket, name, num) 227 for (name, num) in default_gai_errnos] 228 229 def filter_error(err): 230 n = getattr(err, 'errno', None) 231 if (isinstance(err, TimeoutError) or 232 (isinstance(err, socket.gaierror) and n in gai_errnos) or 233 (isinstance(err, urllib.error.HTTPError) and 234 500 <= err.code <= 599) or 235 (isinstance(err, urllib.error.URLError) and 236 (("ConnectionRefusedError" in err.reason) or 237 ("TimeoutError" in err.reason) or 238 ("EOFError" in err.reason))) or 239 n in captured_errnos): 240 if not support.verbose: 241 sys.stderr.write(denied.args[0] + "\n") 242 raise denied from err 243 244 old_timeout = socket.getdefaulttimeout() 245 try: 246 if timeout is not None: 247 socket.setdefaulttimeout(timeout) 248 yield 249 except nntplib.NNTPTemporaryError as err: 250 if support.verbose: 251 sys.stderr.write(denied.args[0] + "\n") 252 raise denied from err 253 except OSError as err: 254 # urllib can wrap original socket errors multiple times (!), we must 255 # unwrap to get at the original error. 256 while True: 257 a = err.args 258 if len(a) >= 1 and isinstance(a[0], OSError): 259 err = a[0] 260 # The error can also be wrapped as args[1]: 261 # except socket.error as msg: 262 # raise OSError('socket error', msg) from msg 263 elif len(a) >= 2 and isinstance(a[1], OSError): 264 err = a[1] 265 else: 266 break 267 filter_error(err) 268 raise 269 # XXX should we catch generic exceptions and look for their 270 # __cause__ or __context__? 271 finally: 272 socket.setdefaulttimeout(old_timeout) 273