forked from ssh-mitm/ssh-mitm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultisocket.py
More file actions
332 lines (287 loc) · 11 KB
/
multisocket.py
File metadata and controls
332 lines (287 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
"""
Utility functions to create server sockets able to listen on both
IPv4 and IPv6.
Source: https://code.activestate.com/recipes/578504-server-supporting-ipv4-and-ipv6/
Inspired by: http://bugs.python.org/issue17561
Expected usage:
>>> sock = create_server_sock(("", 8000))
>>> if not has_dual_stack(sock):
... sock.close()
... sock = MultipleSocketsListener([("0.0.0.0", 8000), ("::", 8000)])
>>>
From here on you have a socket which listens on port 8000,
all interfaces, serving both IPv4 and IPv6.
You can start accepting new connections as usual:
>>> while True:
... conn, addr = sock.accept()
... # handle new connection
Supports UNIX, Windows, non-blocking sockets and socket timeouts.
Works with Python >= 2.6 and 3.X.
"""
import os
import sys
import socket
import select
import contextlib
from typing import (
Any,
Dict,
Tuple,
Optional,
Text,
List,
Union,
overload
)
from typeguard import typechecked
__author__ = "Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>"
__license__ = "MIT"
@typechecked
def has_dual_stack(sock: Optional[socket.socket] = None) -> bool:
"""Return True if kernel allows creating a socket which is able to
listen for both IPv4 and IPv6 connections.
If *sock* is provided the check is made against it.
"""
if not hasattr(socket, 'AF_INET6') or not hasattr(socket, 'IPPROTO_IPV6') or not hasattr(socket, 'IPV6_V6ONLY'):
return False
try:
if sock is not None:
return not sock.getsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY)
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
with contextlib.closing(sock):
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False)
return True
except socket.error:
return False
@typechecked
def create_server_sock(
address: Tuple[Text, int],
family: Optional[socket.AddressFamily] = None,
reuse_addr: Optional[bool] = None,
transparent: bool = False,
queue_size: int = 5,
dual_stack: bool = has_dual_stack()
) -> socket.socket:
"""Convenience function which creates a TCP server bound to
*address* and return the socket object.
Internally it takes care of choosing the right address family
(IPv4 or IPv6) depending on the host specified in *address*
(a (host, port) tuple.
If host is an empty string or None all interfaces are assumed
and if dual stack is supported by kernel the socket will be
able to listen for both IPv4 and IPv6 connections.
*family* can be set to either AF_INET or AF_INET6 to force the
socket to use IPv4 or IPv6. If not set it will be determined
from host.
*reuse_addr* tells the kernel to reuse a local socket in TIME_WAIT
state, without waiting for its natural timeout to expire.
If not set will default to True on POSIX.
*queue_size* is the maximum number of queued connections passed to
listen() (defaults to 5).
If *dual_stack* if True it will force the socket to listen on both
IPv4 and IPv6 connections (defaults to True on all platforms
natively supporting this functionality).
The returned socket can be used to accept() new connections as in:
>>> server = create_server_sock((None, 8000))
>>> while True:
... sock, addr = server.accept()
... # handle new sock connection
"""
AF_INET6 = getattr(socket, 'AF_INET6', 0)
host: Optional[Text]
port: int
host, port = address
if host == "" or host == "0.0.0.0": # nosec
# http://mail.python.org/pipermail/python-ideas/2013-March/019937.html
host = None
if host is None and dual_stack:
host = "::"
if family is None:
family = socket.AF_UNSPEC
if reuse_addr is None:
reuse_addr = os.name == 'posix' and sys.platform != 'cygwin'
err = None
info = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM,
0, socket.AI_PASSIVE)
if not dual_stack:
# in case dual stack is not supported we want IPv4 to be
# preferred over IPv6
info.sort(key=lambda x: x[0] == socket.AF_INET, reverse=True)
for res in info:
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket.socket(af, socktype, proto)
if reuse_addr:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if transparent:
if hasattr(socket, 'IP_TRANSPARENT'):
sock.setsockopt(socket.SOL_IP, socket.IP_TRANSPARENT, 1)
else:
IP_TRANSPARENT = 19
sock.setsockopt(socket.SOL_IP, IP_TRANSPARENT, 1)
if af == AF_INET6:
if dual_stack:
# enable
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
elif has_dual_stack(sock):
# disable
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
sock.bind(sa)
sock.listen(queue_size)
return sock
except socket.error as _:
err = _
if sock is not None:
sock.close()
if err is not None:
raise err
raise socket.error("getaddrinfo returns an empty list")
class MultipleSocketsListener:
"""Listen on multiple addresses specified as a list of
(host, port) tuples.
Useful to listen on both IPv4 and IPv6 on those systems where
a dual stack is not supported natively (Windows and many UNIXes).
The returned instance is a socket-like object which can be used to
accept() new connections, as with a common socket.
Calls like settimeout() and setsockopt() will be applied to all
sockets.
Calls like gettimeout() or getsockopt() will refer to the first
socket in the list.
"""
@typechecked
def __init__(
self,
addresses: List[Tuple[Text, int]],
family: Optional[socket.AddressFamily] = None,
reuse_addr: Optional[bool] = None,
transparent: bool = False,
queue_size: int = 5
) -> None:
self._pollster: Optional[select.poll]
self._socks: List[socket.socket] = []
self._sockmap: Dict[int, socket.socket] = {}
if hasattr(select, 'poll'):
self._pollster = select.poll()
else:
self._pollster = None
completed = False
try:
for addr in addresses:
sock = create_server_sock(
addr,
family=family,
reuse_addr=reuse_addr,
transparent=transparent,
queue_size=queue_size,
dual_stack=False
)
self._socks.append(sock)
fd = sock.fileno()
if self._pollster is not None:
self._pollster.register(fd, select.POLLIN)
self._sockmap[fd] = sock
completed = True
finally:
if not completed:
self.close()
@typechecked
def __enter__(self) -> 'MultipleSocketsListener':
return self
@typechecked
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
self.close()
@typechecked
def __repr__(self) -> Text:
addrs = []
for sock in self._socks:
try:
addrs.append(sock.getsockname())
except socket.error:
addrs.append(())
return '<%s (%r) at %#x>' % (self.__class__.__name__, addrs, id(self))
@typechecked
def _poll(self) -> Optional[Any]:
"""Return the first readable fd."""
fds_select: Optional[Tuple[List[Any], List[Any], List[Any]]] = None
fds_poll: Optional[List[Tuple[int, int]]] = None
timeout = self.gettimeout()
if self._pollster is None:
fds_select = select.select(self._sockmap.keys(), [], [], timeout)
if timeout and fds_select == ([], [], []):
raise TimeoutError('timed out')
else:
if timeout is not None:
timeout *= 1000
fds_poll = self._pollster.poll(timeout)
if timeout and fds_poll == []:
raise TimeoutError('timed out')
try:
if fds_select is not None:
return fds_select[0][0]
if fds_poll is not None:
return fds_poll[0][0]
except IndexError:
pass # non-blocking socket
return None
@typechecked
def _multicall(self, name: Text, *args: Any, **kwargs: Any) -> None:
for sock in self._socks:
meth = getattr(sock, name)
meth(*args, **kwargs)
@typechecked
def accept(self) -> Tuple[socket.socket, Any]:
"""Accept a connection from the first socket which is ready
to do so.
"""
fd = self._poll()
sock = self._sockmap[fd] if fd else self._socks[0]
return sock.accept()
@typechecked
def filenos(self) -> List[int]:
"""Return sockets' file descriptors as a list of integers.
This is useful with select().
"""
return list(self._sockmap.keys())
@typechecked
def getsockname(self) -> Any:
"""Return first registered socket's own address."""
return self._socks[0].getsockname()
@overload
def getsockopt(self, level: int, optname: int) -> int: ...
@overload
def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ...
@typechecked
def getsockopt(self, level: int, optname: int, buflen: int = 0) -> Union[int, bytes]:
"""Return first registered socket's options."""
return self._socks[0].getsockopt(level, optname, buflen)
@typechecked
def gettimeout(self) -> Optional[float]:
"""Return first registered socket's timeout."""
return self._socks[0].gettimeout()
@typechecked
def settimeout(self, timeout: float) -> None:
"""Set timeout for all registered sockets."""
self._multicall('settimeout', timeout)
@typechecked
def setblocking(self, flag: bool) -> None:
"""Set non/blocking mode for all registered sockets."""
self._multicall('setblocking', flag)
@overload
def setsockopt(self, level: int, optname: int, value: Union[int, bytes], optlen: None) -> None: ...
@overload
def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ...
@typechecked
def setsockopt(self, level: int, optname: int, value: Optional[Union[int, bytes]], optlen: Optional[int]) -> None:
"""Set option for all registered sockets."""
self._multicall('setsockopt', level, optname, value, optlen)
@typechecked
def shutdown(self, how: int) -> None:
"""Shut down all registered sockets."""
self._multicall('shutdown', how)
@typechecked
def close(self) -> None:
"""Close all registered sockets."""
self._multicall('close')
self._socks = []
self._sockmap.clear()