Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_socket_helper.py

raw
1 # Copyright (c) 2019-2021, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import fcntl
11 import os
12 import os.path
13 import socket as pysocket
14 import typing as t
15 from collections.abc import Callable
16
17 if t.TYPE_CHECKING:
18 SocketLike = pysocket.socket
19
20
21 def make_file_unblocking(file: SocketLike) -> None:
22 fcntl.fcntl(
23 file.fileno(),
24 fcntl.F_SETFL,
25 fcntl.fcntl(file.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK,
26 )
27
28
29 def make_file_blocking(file: SocketLike) -> None:
30 fcntl.fcntl(
31 file.fileno(),
32 fcntl.F_SETFL,
33 fcntl.fcntl(file.fileno(), fcntl.F_GETFL) & ~os.O_NONBLOCK,
34 )
35
36
37 def make_unblocking(sock: SocketLike) -> None:
38 if hasattr(sock, "_sock"):
39 sock._sock.setblocking(0)
40 elif hasattr(sock, "setblocking"):
41 sock.setblocking(0) # type: ignore # TODO: CHECK!
42 else:
43 make_file_unblocking(sock)
44
45
46 def _empty_writer(msg: str) -> None:
47 pass
48
49
50 def shutdown_writing(
51 sock: SocketLike, log: Callable[[str], None] = _empty_writer
52 ) -> None:
53 # FIXME: This does **not work with SSLSocket**! Apparently SSLSocket does not allow to send
54 # a close_notify TLS alert without completely shutting down the connection.
55 # Calling sock.shutdown(pysocket.SHUT_WR) simply turns of TLS encryption and from that
56 # point on the raw encrypted data is returned when sock.recv() is called. :-(
57 if hasattr(sock, "shutdown_write"):
58 sock.shutdown_write()
59 elif hasattr(sock, "shutdown"):
60 try:
61 sock.shutdown(pysocket.SHUT_WR)
62 except TypeError as e:
63 # probably: "TypeError: shutdown() takes 1 positional argument but 2 were given"
64 log(f"Shutting down for writing not possible; trying shutdown instead: {e}")
65 sock.shutdown() # type: ignore
66 elif isinstance(sock, pysocket.SocketIO): # type: ignore
67 sock._sock.shutdown(pysocket.SHUT_WR) # type: ignore[unreachable]
68 else:
69 log("No idea how to signal end of writing")
70
71
72 def write_to_socket(sock: SocketLike, data: bytes) -> int:
73 if hasattr(sock, "_send_until_done"):
74 # WrappedSocket (urllib3/contrib/pyopenssl) does not have `send`, but
75 # only `sendall`, which uses `_send_until_done` under the hood.
76 return sock._send_until_done(data)
77 if hasattr(sock, "send"):
78 return sock.send(data)
79 return os.write(sock.fileno(), data)