Debian Codegraph @

Pyro5/socketutil.py

raw
1 """
2 Low level socket utilities.
3
4 Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]).
5 """
6
7 import os
8 import platform
9 import socket
10 import errno
11 import time
12 import select
13 import ipaddress
14 import weakref
15 import contextlib
16 from typing import Union, Optional, Tuple, Dict, Type, Any
17 try:
18 import ssl
19 except ImportError:
20 pass
21 from . import config
22 from .errors import CommunicationError, TimeoutError, ConnectionClosedError
23
24
25 # Note: other interesting errnos are EPERM, ENOBUFS, EMFILE
26 # but it seems to me that all these signify an unrecoverable situation.
27 # So I didn't include them in the list of retryable errors.
28 ERRNO_RETRIES = [errno.EINTR, errno.EAGAIN, errno.EWOULDBLOCK, errno.EINPROGRESS]
29 if hasattr(errno, "WSAEINTR"):
30 ERRNO_RETRIES.append(errno.WSAEINTR)
31 if hasattr(errno, "WSAEWOULDBLOCK"):
32 ERRNO_RETRIES.append(errno.WSAEWOULDBLOCK)
33 if hasattr(errno, "WSAEINPROGRESS"):
34 ERRNO_RETRIES.append(errno.WSAEINPROGRESS)
35
36 ERRNO_BADF = [errno.EBADF]
37 if hasattr(errno, "WSAEBADF"):
38 ERRNO_BADF.append(errno.WSAEBADF)
39
40 ERRNO_ENOTSOCK = [errno.ENOTSOCK]
41 if hasattr(errno, "WSAENOTSOCK"):
42 ERRNO_ENOTSOCK.append(errno.WSAENOTSOCK)
43 if not hasattr(socket, "SOL_TCP"):
44 socket.SOL_TCP = socket.IPPROTO_TCP
45
46 ERRNO_EADDRNOTAVAIL = [errno.EADDRNOTAVAIL]
47 if hasattr(errno, "WSAEADDRNOTAVAIL"):
48 ERRNO_EADDRNOTAVAIL.append(errno.WSAEADDRNOTAVAIL)
49
50 ERRNO_EADDRINUSE = [errno.EADDRINUSE]
51 if hasattr(errno, "WSAEADDRINUSE"):
52 ERRNO_EADDRINUSE.append(errno.WSAEADDRINUSE)
53
54 # msg_waitall has proven to be unreliable on windows
55 USE_MSG_WAITALL = hasattr(socket, "MSG_WAITALL") and platform.system() != "Windows"
56
57
58 def get_ip_address(hostname: str, workaround127: bool = False, version: int = None) \
59 -> Union[ipaddress.IPv4Address, ipaddress.IPv6Address]:
60 """
61 Returns the IP address for the given host. If you enable the workaround,
62 it will use a little hack if the ip address is found to be the loopback address.
63 The hack tries to discover an externally visible ip address instead (this only works for ipv4 addresses).
64 Set ipVersion=6 to return ipv6 addresses, 4 to return ipv4, 0 to let OS choose the best one or None to use config.PREFER_IP_VERSION.
65 """
66 if not workaround127:
67 with contextlib.suppress(ValueError):
68 addr = ipaddress.ip_address(hostname)
69 return addr
70
71 def getaddr(ip_version):
72 if ip_version == 6:
73 family = socket.AF_INET6
74 elif ip_version == 4:
75 family = socket.AF_INET
76 elif ip_version == 0:
77 family = socket.AF_UNSPEC
78 else:
79 raise ValueError("unknown value for argument ipVersion.")
80 ip = socket.getaddrinfo(hostname or socket.gethostname(), 80, family, socket.SOCK_STREAM, socket.SOL_TCP)[0][4][0]
81 if workaround127 and (ip.startswith("127.") or ip == "0.0.0.0"):
82 return get_interface("4.2.2.2").ip
83 return ipaddress.ip_address(ip)
84
85 try:
86 if hostname and ':' in hostname and version is None:
87 version = 0
88 return getaddr(config.PREFER_IP_VERSION) if version is None else getaddr(version)
89 except socket.gaierror:
90 if version == 6 or (version is None and config.PREFER_IP_VERSION == 6):
91 raise socket.error("unable to determine IPV6 address")
92 return getaddr(0)
93
94
95 def get_interface(ip_address: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address]) \
96 -> Union[ipaddress.IPv4Interface, ipaddress.IPv6Interface]:
97 """tries to find the network interface that connects to the given host's address"""
98 if isinstance(ip_address, str):
99 ip_address = get_ip_address(ip_address)
100 family = socket.AF_INET if ip_address.version == 4 else socket.AF_INET6
101 with socket.socket(family, socket.SOCK_DGRAM) as sock:
102 sock.connect((str(ip_address), 53)) # 53=dns
103 return ipaddress.ip_interface(sock.getsockname()[0])
104
105
106 def __retrydelays():
107 # first try a few very short delays,
108 # if that doesn't work, increase by 0.1 sec every time
109 yield 0.0001
110 yield 0.001
111 yield 0.01
112 d = 0.1
113 while True:
114 yield d
115 d += 0.1
116
117
118 def receive_data(sock: socket.socket, size: int) -> bytes:
119 """Retrieve a given number of bytes from a socket.
120 It is expected the socket is able to supply that number of bytes.
121 If it isn't, an exception is raised (you will not get a zero length result
122 or a result that is smaller than what you asked for). The partial data that
123 has been received however is stored in the 'partialData' attribute of
124 the exception object."""
125 try:
126 delays = __retrydelays()
127 msglen = 0
128 data = bytearray()
129 if USE_MSG_WAITALL and not hasattr(sock, "getpeercert"): # ssl doesn't support recv flags
130 while True:
131 try:
132 chunk = sock.recv(size, socket.MSG_WAITALL)
133 if len(chunk) == size:
134 return chunk
135 # less data than asked, drop down into normal receive loop to finish
136 msglen = len(chunk)
137 data.extend(chunk)
138 break
139 except socket.timeout:
140 raise TimeoutError("receiving: timeout")
141 except socket.error as x:
142 err = getattr(x, "errno", x.args[0])
143 if err not in ERRNO_RETRIES:
144 raise ConnectionClosedError("receiving: connection lost: " + str(x))
145 time.sleep(next(delays)) # a slight delay to wait before retrying
146 # old fashioned recv loop, we gather chunks until the message is complete
147 while True:
148 try:
149 while msglen < size:
150 # 60k buffer limit avoids problems on certain OSes like VMS, Windows
151 chunk = sock.recv(min(60000, size - msglen))
152 if not chunk:
153 break
154 data.extend(chunk)
155 msglen += len(chunk)
156 if len(data) != size:
157 err = ConnectionClosedError("receiving: not enough data")
158 err.partialData = data # store the message that was received until now
159 raise err
160 return data # yay, complete
161 except socket.timeout:
162 raise TimeoutError("receiving: timeout")
163 except socket.error as x:
164 err = getattr(x, "errno", x.args[0])
165 if err not in ERRNO_RETRIES:
166 raise ConnectionClosedError("receiving: connection lost: " + str(x))
167 time.sleep(next(delays)) # a slight delay to wait before retrying
168 except socket.timeout:
169 raise TimeoutError("receiving: timeout")
170
171
172 def send_data(sock: socket.socket, data: bytes) -> None:
173 """
174 Send some data over a socket.
175 Some systems have problems with ``sendall()`` when the socket is in non-blocking mode.
176 For instance, Mac OS X seems to be happy to throw EAGAIN errors too often.
177 This function falls back to using a regular send loop if needed.
178 """
179 if sock.gettimeout() is None:
180 # socket is in blocking mode, we can use sendall normally.
181 try:
182 sock.sendall(data)
183 return
184 except socket.timeout:
185 raise TimeoutError("sending: timeout")
186 except socket.error as x:
187 raise ConnectionClosedError("sending: connection lost: " + str(x))
188 else:
189 # Socket is in non-blocking mode, use regular send loop.
190 delays = __retrydelays()
191 while data:
192 try:
193 sent = sock.send(data)
194 data = data[sent:]
195 except socket.timeout:
196 raise TimeoutError("sending: timeout")
197 except socket.error as x:
198 err = getattr(x, "errno", x.args[0])
199 if err not in ERRNO_RETRIES:
200 raise ConnectionClosedError("sending: connection lost: " + str(x))
201 time.sleep(next(delays)) # a slight delay to wait before retrying
202
203
204 def create_socket(bind: Union[Tuple, str] = None,
205 connect: Union[Tuple, str] = None,
206 reuseaddr: bool = False, keepalive: bool = True,
207 timeout: Optional[float] = -1, noinherit: bool = False,
208 ipv6: bool = False, nodelay: bool = True, sslContext: ssl.SSLContext = None) -> socket.socket:
209 """
210 Create a socket. Default socket options are keepalive and IPv4 family, and nodelay (nagle disabled).
211 If 'bind' or 'connect' is a string, it is assumed a Unix domain socket is requested.
212 Otherwise, a normal tcp/ip socket tuple (addr, port, ...) is used.
213 Set ipv6=True to create an IPv6 socket rather than IPv4.
214 Set ipv6=None to use the PREFER_IP_VERSION config setting.
215 """
216 if bind and connect:
217 raise ValueError("bind and connect cannot both be specified at the same time")
218 forceIPv6 = ipv6 or (ipv6 is None and config.PREFER_IP_VERSION == 6)
219 if isinstance(bind, str) or isinstance(connect, str):
220 family = socket.AF_UNIX
221 elif not bind and not connect:
222 family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
223 elif isinstance(bind, tuple):
224 if not bind[0]:
225 family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
226 else:
227 addr = get_ip_address(bind[0])
228 if addr.version == 4:
229 if forceIPv6:
230 raise ValueError("IPv4 address is used bind argument with forceIPv6 argument:" + bind[0] + ".")
231 family = socket.AF_INET
232 elif addr.version == 6:
233 family = socket.AF_INET6
234 # replace bind addresses by their ipv6 counterparts (4-tuple)
235 bind = (bind[0], bind[1], 0, 0)
236 else:
237 raise ValueError("unknown bind format.")
238 elif isinstance(connect, tuple):
239 if not connect[0]:
240 family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
241 else:
242 addr = get_ip_address(connect[0])
243 if addr.version == 4:
244 if forceIPv6:
245 raise ValueError("IPv4 address is used in connect argument with forceIPv6 argument:" + connect[0] + ".")
246 family = socket.AF_INET
247 elif addr.version == 6:
248 family = socket.AF_INET6
249 # replace connect addresses by their ipv6 counterparts (4-tuple)
250 connect = (connect[0], connect[1], 0, 0)
251 else:
252 raise ValueError("unknown connect format.")
253 else:
254 raise ValueError("unknown bind or connect format.")
255 sock = socket.socket(family, socket.SOCK_STREAM)
256 if sslContext:
257 if bind:
258 sock = sslContext.wrap_socket(sock, server_side=True)
259 elif connect:
260 sock = sslContext.wrap_socket(sock, server_side=False, server_hostname=connect[0])
261 else:
262 sock = sslContext.wrap_socket(sock, server_side=False)
263 if nodelay:
264 set_nodelay(sock)
265 if reuseaddr:
266 set_reuseaddr(sock)
267 if noinherit:
268 set_noinherit(sock)
269 if timeout is not None:
270 if timeout == 0:
271 timeout = None
272 elif timeout >= 0:
273 sock.settimeout(timeout)
274 if bind:
275 if type(bind) is tuple and bind[1] == 0:
276 bind_unused_port(sock, bind[0])
277 else:
278 sock.bind(bind)
279 with contextlib.suppress(OSError, IOError):
280 sock.listen(100)
281 if connect:
282 try:
283 sock.connect(connect)
284 except socket.error as xv:
285 # This can happen when the socket is in non-blocking mode (or has a timeout configured).
286 # We check if it is a retryable errno (usually EINPROGRESS).
287 # If so, we use select() to wait until the socket is in writable state,
288 # essentially rebuilding a blocking connect() call.
289 errno = getattr(xv, "errno", 0)
290 if errno in ERRNO_RETRIES:
291 if timeout:
292 if timeout < 0:
293 timeout = None
294 elif timeout < 0.1:
295 timeout = 0.1
296 while True:
297 try:
298 sr, sw, se = select.select([], [sock], [sock], timeout)
299 except InterruptedError:
300 continue
301 if sock in sw:
302 break # yay, writable now, connect() completed
303 elif sock in se:
304 sock.close() # close the socket that refused to connect
305 raise socket.error("connect failed")
306 else:
307 sock.close() # close the socket that refused to connect
308 raise
309 if keepalive:
310 set_keepalive(sock)
311 return sock
312
313
314 def create_bc_socket(bind: Union[Tuple, str] = None, reuseaddr: bool = False,
315 timeout: Optional[float] = -1, ipv6: bool = False) -> socket.socket:
316 """
317 Create a udp broadcast socket.
318 Set ipv6=True to create an IPv6 socket rather than IPv4.
319 Set ipv6=None to use the PREFER_IP_VERSION config setting.
320 """
321 forceIPv6 = ipv6 or (ipv6 is None and config.PREFER_IP_VERSION == 6)
322 if not bind:
323 family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
324 elif isinstance(bind, tuple):
325 if not bind[0]:
326 family = socket.AF_INET6 if forceIPv6 else socket.AF_INET
327 else:
328 addr = get_ip_address(bind[0])
329 if addr.version == 4:
330 if forceIPv6:
331 raise ValueError("IPv4 address is used with forceIPv6 option:" + bind[0] + ".")
332 family = socket.AF_INET
333 elif addr.version == 6:
334 family = socket.AF_INET6
335 bind = (bind[0], bind[1], 0, 0)
336 else:
337 raise ValueError("unknown bind format: %r" % (bind,))
338 else:
339 raise ValueError("unknown bind format: %r" % (bind,))
340 sock = socket.socket(family, socket.SOCK_DGRAM)
341 if family == socket.AF_INET:
342 sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
343 if reuseaddr:
344 set_reuseaddr(sock)
345 if timeout is None:
346 sock.settimeout(None)
347 else:
348 if timeout >= 0:
349 sock.settimeout(timeout)
350 if bind:
351 host = bind[0] or ""
352 port = bind[1]
353 if port == 0:
354 bind_unused_port(sock, host)
355 else:
356 if len(bind) == 2:
357 sock.bind((host, port)) # ipv4
358 elif len(bind) == 4:
359 sock.bind((host, port, 0, 0)) # ipv6
360 else:
361 raise ValueError("bind must be None, 2-tuple or 4-tuple")
362 return sock
363
364
365 def set_reuseaddr(sock: socket.socket) -> None:
366 """sets the SO_REUSEADDR option on the socket, if possible."""
367 with contextlib.suppress(Exception):
368 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
369
370
371 def set_nodelay(sock: socket.socket) -> None:
372 """sets the TCP_NODELAY option on the socket (to disable Nagle's algorithm), if possible."""
373 with contextlib.suppress(Exception):
374 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
375
376
377 def set_keepalive(sock: socket.socket) -> None:
378 """sets the SO_KEEPALIVE option on the socket, if possible."""
379 with contextlib.suppress(Exception):
380 sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
381
382
383 try:
384 import fcntl
385
386 def set_noinherit(sock: socket.socket) -> None:
387 """Mark the given socket fd as non-inheritable to child processes"""
388 fd = sock.fileno()
389 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
390 fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
391
392 except ImportError:
393 # no fcntl available, try the windows version
394 try:
395 from ctypes import windll, WinError, wintypes
396 # help ctypes to set the proper args for this kernel32 call on 64-bit pythons
397 _SetHandleInformation = windll.kernel32.SetHandleInformation
398 _SetHandleInformation.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD]
399 _SetHandleInformation.restype = wintypes.BOOL # don't need this, but might as well
400
401 def set_noinherit(sock: socket.socket) -> None:
402 """Mark the given socket fd as non-inheritable to child processes"""
403 if not _SetHandleInformation(sock.fileno(), 1, 0):
404 raise WinError()
405
406 except (ImportError, NotImplementedError):
407 # nothing available, define a dummy function
408 def set_noinherit(sock: socket.socket) -> None:
409 """Mark the given socket fd as non-inheritable to child processes (dummy)"""
410 pass
411
412
413 class SocketConnection(object):
414 """A wrapper class for plain sockets, containing various methods such as :meth:`send` and :meth:`recv`"""
415 def __init__(self, sock: socket.socket, objectId: str = None, keep_open: bool = False) -> None:
416 self.sock = sock
417 self.objectId = objectId
418 self.pyroInstances = {} # type: Dict[Type, Any] # pyro objects for instance_mode=session
419 self.tracked_resources = weakref.WeakSet() # type: weakref.WeakSet[Any] # weakrefs to resources for this connection
420 self.keep_open = keep_open
421
422 def __del__(self):
423 self.close()
424
425 def __enter__(self):
426 return self
427
428 def __exit__(self, exc_type, exc_val, exc_tb):
429 self.close()
430
431 def send(self, data: bytes) -> None:
432 send_data(self.sock, data)
433
434 def recv(self, size: int) -> bytes:
435 return receive_data(self.sock, size)
436
437 def close(self) -> None:
438 if self.keep_open:
439 return
440 with contextlib.suppress(Exception):
441 self.sock.shutdown(socket.SHUT_RDWR)
442 with contextlib.suppress(Exception):
443 self.sock.close()
444 self.pyroInstances = {} # release the session instances
445 for rsc in self.tracked_resources:
446 with contextlib.suppress(Exception):
447 rsc.close() # it is assumed a 'resource' has a close method.
448 self.tracked_resources.clear()
449
450 def fileno(self) -> int:
451 return self.sock.fileno()
452
453 def family(self) -> str:
454 return family_str(self.sock)
455
456 def settimeout(self, timeout: Optional[float]) -> None:
457 self.sock.settimeout(timeout)
458
459 def gettimeout(self) -> Optional[float]:
460 return self.sock.gettimeout()
461
462 def getpeercert(self) -> Optional[dict]:
463 try:
464 return self.sock.getpeercert() # type: ignore
465 except AttributeError:
466 return None
467
468 timeout = property(gettimeout, settimeout)
469
470
471 def family_str(sock) -> str:
472 f = sock.family
473 if f == socket.AF_INET:
474 return "IPv4"
475 if f == socket.AF_INET6:
476 return "IPv6"
477 if hasattr(socket, "AF_UNIX") and f == socket.AF_UNIX:
478 return "Unix"
479 return "???"
480
481
482 def find_probably_unused_port(family: int = socket.AF_INET, socktype: int = socket.SOCK_STREAM) -> int:
483 """Returns an unused port that should be suitable for binding (likely, but not guaranteed).
484 This code is copied from the stdlib's test.test_support module."""
485 with socket.socket(family, socktype) as sock:
486 return bind_unused_port(sock)
487
488
489 def bind_unused_port(sock: socket.socket, host: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address] = 'localhost') -> int:
490 """Bind the socket to a free port and return the port number.
491 This code is based on the code in the stdlib's test.test_support module."""
492 if sock.family in (socket.AF_INET, socket.AF_INET6) and sock.type == socket.SOCK_STREAM:
493 if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
494 with contextlib.suppress(socket.error):
495 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
496 if not isinstance(host, str):
497 host = str(host)
498 if sock.family == socket.AF_INET:
499 if host == 'localhost':
500 sock.bind(('127.0.0.1', 0))
501 else:
502 sock.bind((host, 0))
503 elif sock.family == socket.AF_INET6:
504 if host == 'localhost':
505 sock.bind(('::1', 0, 0, 0))
506 else:
507 sock.bind((host, 0, 0, 0))
508 else:
509 raise CommunicationError("unsupported socket family: " + str(sock.family))
510 return sock.getsockname()[1]
511
512
513 def interrupt_socket(address: Tuple[str, int]) -> None:
514 """bit of a hack to trigger a blocking server to get out of the loop, useful at clean shutdowns"""
515 with contextlib.suppress(socket.error):
516 sock = create_socket(connect=address, keepalive=False, timeout=-1)
517 with contextlib.suppress(socket.error, AttributeError):
518 sock.sendall(b"!" * 16)
519 with contextlib.suppress(OSError, socket.error):
520 sock.shutdown(socket.SHUT_RDWR)
521 sock.close()
522
523
524 __ssl_server_context = None
525 __ssl_client_context = None
526
527
528 def get_ssl_context(servercert: str = "", serverkey: str = "", clientcert: str = "", clientkey: str = "",
529 cacerts: str = "", keypassword: str = "") -> ssl.SSLContext:
530 """creates an SSL context and caches it, so you have to set the parameters correctly before doing anything"""
531 global __ssl_client_context, __ssl_server_context
532 if servercert:
533 if clientcert:
534 raise ValueError("can't have both server cert and client cert")
535 # server context
536 if __ssl_server_context:
537 return __ssl_server_context
538 if not os.path.isfile(servercert):
539 raise IOError("server cert file not found")
540 if serverkey and not os.path.isfile(serverkey):
541 raise IOError("server key file not found")
542 __ssl_server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
543 __ssl_server_context.load_cert_chain(servercert, serverkey or None, keypassword or None) # type: ignore
544 if cacerts:
545 if os.path.isdir(cacerts):
546 __ssl_server_context.load_verify_locations(capath=cacerts)
547 else:
548 __ssl_server_context.load_verify_locations(cafile=cacerts)
549 if config.SSL_REQUIRECLIENTCERT:
550 __ssl_server_context.verify_mode = ssl.CERT_REQUIRED # 2-way ssl, server+client certs
551 else:
552 __ssl_server_context.verify_mode = ssl.CERT_NONE # 1-way ssl, server cert only
553 return __ssl_server_context
554 else:
555 # client context
556 if __ssl_client_context:
557 return __ssl_client_context
558 __ssl_client_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
559 if clientcert:
560 if not os.path.isfile(clientcert):
561 raise IOError("client cert file not found")
562 __ssl_client_context.load_cert_chain(clientcert, clientkey or None, keypassword or None) # type: ignore
563 if cacerts:
564 if os.path.isdir(cacerts):
565 __ssl_client_context.load_verify_locations(capath=cacerts)
566 else:
567 __ssl_client_context.load_verify_locations(cafile=cacerts)
568 return __ssl_client_context