2
# A higher level module for using sockets (or Windows named pipes)
4
# multiprocessing/connection.py
6
# Copyright (c) 2006-2008, R Oudkerk
7
# Licensed to PSF under a Contributor Agreement.
10
__all__ = [ 'Client', 'Listener', 'Pipe', 'wait' ]
22
import _multiprocessing
24
from . import reduction
27
from . import AuthenticationError, BufferTooShort
28
from .reduction import ForkingPickler
32
from _winapi import WAIT_OBJECT_0, WAIT_TIMEOUT, INFINITE
34
if sys.platform == 'win32':
43
# A very generous timeout when it comes to local connections...
44
CONNECTION_TIMEOUT = 20.
46
_mmap_counter = itertools.count()
48
default_family = 'AF_INET'
49
families = ['AF_INET']
51
if hasattr(socket, 'AF_UNIX'):
52
default_family = 'AF_UNIX'
53
families += ['AF_UNIX']
55
if sys.platform == 'win32':
56
default_family = 'AF_PIPE'
57
families += ['AF_PIPE']
60
def _init_timeout(timeout=CONNECTION_TIMEOUT):
61
return time.time() + timeout
63
def _check_timeout(t):
64
return time.time() > t
70
def arbitrary_address(family):
72
Return an arbitrary free address for the given family
74
if family == 'AF_INET':
75
return ('localhost', 0)
76
elif family == 'AF_UNIX':
77
return tempfile.mktemp(prefix='listener-', dir=util.get_temp_dir())
78
elif family == 'AF_PIPE':
79
return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' %
80
(os.getpid(), next(_mmap_counter)))
82
raise ValueError('unrecognized family')
84
def _validate_family(family):
86
Checks if the family is valid for the current environment.
88
if sys.platform != 'win32' and family == 'AF_PIPE':
89
raise ValueError('Family %s is not recognized.' % family)
91
if sys.platform == 'win32' and family == 'AF_UNIX':
93
if not hasattr(socket, family):
94
raise ValueError('Family %s is not recognized.' % family)
96
def address_type(address):
98
Return the types of the address
100
This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
102
if type(address) == tuple:
104
elif type(address) is str and address.startswith('\\\\'):
106
elif type(address) is str:
109
raise ValueError('address type of %r unrecognized' % address)
115
class _ConnectionBase:
118
def __init__(self, handle, readable=True, writable=True):
119
handle = handle.__index__()
121
raise ValueError("invalid handle")
122
if not readable and not writable:
124
"at least one of `readable` and `writable` must be True")
125
self._handle = handle
126
self._readable = readable
127
self._writable = writable
129
# XXX should we use util.Finalize instead of a __del__?
132
if self._handle is not None:
135
def _check_closed(self):
136
if self._handle is None:
137
raise OSError("handle is closed")
139
def _check_readable(self):
140
if not self._readable:
141
raise OSError("connection is write-only")
143
def _check_writable(self):
144
if not self._writable:
145
raise OSError("connection is read-only")
147
def _bad_message_length(self):
149
self._readable = False
152
raise OSError("bad message length")
156
"""True if the connection is closed"""
157
return self._handle is None
161
"""True if the connection is readable"""
162
return self._readable
166
"""True if the connection is writable"""
167
return self._writable
170
"""File descriptor or handle of the connection"""
175
"""Close the connection"""
176
if self._handle is not None:
182
def send_bytes(self, buf, offset=0, size=None):
183
"""Send the bytes data from a bytes-like object"""
185
self._check_writable()
187
# HACK for byte-indexing of non-bytewise buffers (e.g. array.array)
189
m = memoryview(bytes(m))
192
raise ValueError("offset is negative")
194
raise ValueError("buffer length < offset")
198
raise ValueError("size is negative")
199
elif offset + size > n:
200
raise ValueError("buffer length < offset + size")
201
self._send_bytes(m[offset:offset + size])
204
"""Send a (picklable) object"""
206
self._check_writable()
207
self._send_bytes(ForkingPickler.dumps(obj))
209
def recv_bytes(self, maxlength=None):
211
Receive bytes data as a bytes object.
214
self._check_readable()
215
if maxlength is not None and maxlength < 0:
216
raise ValueError("negative maxlength")
217
buf = self._recv_bytes(maxlength)
219
self._bad_message_length()
220
return buf.getvalue()
222
def recv_bytes_into(self, buf, offset=0):
224
Receive bytes data into a writeable buffer-like object.
225
Return the number of bytes read.
228
self._check_readable()
229
with memoryview(buf) as m:
230
# Get bytesize of arbitrary buffer
231
itemsize = m.itemsize
232
bytesize = itemsize * len(m)
234
raise ValueError("negative offset")
235
elif offset > bytesize:
236
raise ValueError("offset too large")
237
result = self._recv_bytes()
239
if bytesize < offset + size:
240
raise BufferTooShort(result.getvalue())
241
# Message can fit in dest
243
result.readinto(m[offset // itemsize :
244
(offset + size) // itemsize])
248
"""Receive a (picklable) object"""
250
self._check_readable()
251
buf = self._recv_bytes()
252
return ForkingPickler.loads(buf.getbuffer())
254
def poll(self, timeout=0.0):
255
"""Whether there is any input available to be read"""
257
self._check_readable()
258
return self._poll(timeout)
263
def __exit__(self, exc_type, exc_value, exc_tb):
269
class PipeConnection(_ConnectionBase):
271
Connection class based on a Windows named pipe.
272
Overlapped I/O is used, so the handles must have been created
273
with FILE_FLAG_OVERLAPPED.
275
_got_empty_message = False
277
def _close(self, _CloseHandle=_winapi.CloseHandle):
278
_CloseHandle(self._handle)
280
def _send_bytes(self, buf):
281
ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True)
283
if err == _winapi.ERROR_IO_PENDING:
284
waitres = _winapi.WaitForMultipleObjects(
285
[ov.event], False, INFINITE)
286
assert waitres == WAIT_OBJECT_0
291
nwritten, err = ov.GetOverlappedResult(True)
293
assert nwritten == len(buf)
295
def _recv_bytes(self, maxsize=None):
296
if self._got_empty_message:
297
self._got_empty_message = False
300
bsize = 128 if maxsize is None else min(maxsize, 128)
302
ov, err = _winapi.ReadFile(self._handle, bsize,
305
if err == _winapi.ERROR_IO_PENDING:
306
waitres = _winapi.WaitForMultipleObjects(
307
[ov.event], False, INFINITE)
308
assert waitres == WAIT_OBJECT_0
313
nread, err = ov.GetOverlappedResult(True)
316
f.write(ov.getbuffer())
318
elif err == _winapi.ERROR_MORE_DATA:
319
return self._get_more_data(ov, maxsize)
321
if e.winerror == _winapi.ERROR_BROKEN_PIPE:
325
raise RuntimeError("shouldn't get here; expected KeyboardInterrupt")
327
def _poll(self, timeout):
328
if (self._got_empty_message or
329
_winapi.PeekNamedPipe(self._handle)[0] != 0):
331
return bool(wait([self], timeout))
333
def _get_more_data(self, ov, maxsize):
337
left = _winapi.PeekNamedPipe(self._handle)[1]
339
if maxsize is not None and len(buf) + left > maxsize:
340
self._bad_message_length()
341
ov, err = _winapi.ReadFile(self._handle, left, overlapped=True)
342
rbytes, err = ov.GetOverlappedResult(True)
344
assert rbytes == left
345
f.write(ov.getbuffer())
349
class Connection(_ConnectionBase):
351
Connection class based on an arbitrary file descriptor (Unix only), or
352
a socket handle (Windows).
356
def _close(self, _close=_multiprocessing.closesocket):
358
_write = _multiprocessing.send
359
_read = _multiprocessing.recv
361
def _close(self, _close=os.close):
366
def _send(self, buf, write=_write):
370
n = write(self._handle, buf)
371
except InterruptedError:
378
def _recv(self, size, read=_read):
380
handle = self._handle
384
chunk = read(handle, remaining)
385
except InterruptedError:
389
if remaining == size:
392
raise OSError("got end of file during message")
397
def _send_bytes(self, buf):
398
# For wire compatibility with 3.2 and lower
400
self._send(struct.pack("!i", n))
401
# The condition is necessary to avoid "broken pipe" errors
402
# when sending a 0-length buffer if the other end closed the pipe.
406
def _recv_bytes(self, maxsize=None):
408
size, = struct.unpack("!i", buf.getvalue())
409
if maxsize is not None and size > maxsize:
411
return self._recv(size)
413
def _poll(self, timeout):
414
r = wait([self], timeout)
422
class Listener(object):
424
Returns a listener object.
426
This is a wrapper for a bound socket which is 'listening' for
427
connections, or for a Windows named pipe.
429
def __init__(self, address=None, family=None, backlog=1, authkey=None):
430
family = family or (address and address_type(address)) \
432
address = address or arbitrary_address(family)
434
_validate_family(family)
435
if family == 'AF_PIPE':
436
self._listener = PipeListener(address, backlog)
438
self._listener = SocketListener(address, family, backlog)
440
if authkey is not None and not isinstance(authkey, bytes):
441
raise TypeError('authkey should be a byte string')
443
self._authkey = authkey
447
Accept a connection on the bound socket or named pipe of `self`.
449
Returns a `Connection` object.
451
if self._listener is None:
452
raise OSError('listener is closed')
453
c = self._listener.accept()
455
deliver_challenge(c, self._authkey)
456
answer_challenge(c, self._authkey)
461
Close the bound socket or named pipe of `self`.
463
if self._listener is not None:
464
self._listener.close()
465
self._listener = None
467
address = property(lambda self: self._listener._address)
468
last_accepted = property(lambda self: self._listener._last_accepted)
473
def __exit__(self, exc_type, exc_value, exc_tb):
477
def Client(address, family=None, authkey=None):
479
Returns a connection to the address of a `Listener`
481
family = family or address_type(address)
482
_validate_family(family)
483
if family == 'AF_PIPE':
484
c = PipeClient(address)
486
c = SocketClient(address)
488
if authkey is not None and not isinstance(authkey, bytes):
489
raise TypeError('authkey should be a byte string')
491
if authkey is not None:
492
answer_challenge(c, authkey)
493
deliver_challenge(c, authkey)
498
if sys.platform != 'win32':
500
def Pipe(duplex=True):
502
Returns pair of connection objects at either end of a pipe
505
s1, s2 = socket.socketpair()
508
c1 = Connection(s1.detach())
509
c2 = Connection(s2.detach())
512
c1 = Connection(fd1, writable=False)
513
c2 = Connection(fd2, readable=False)
519
def Pipe(duplex=True):
521
Returns pair of connection objects at either end of a pipe
523
address = arbitrary_address('AF_PIPE')
525
openmode = _winapi.PIPE_ACCESS_DUPLEX
526
access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
527
obsize, ibsize = BUFSIZE, BUFSIZE
529
openmode = _winapi.PIPE_ACCESS_INBOUND
530
access = _winapi.GENERIC_WRITE
531
obsize, ibsize = 0, BUFSIZE
533
h1 = _winapi.CreateNamedPipe(
534
address, openmode | _winapi.FILE_FLAG_OVERLAPPED |
535
_winapi.FILE_FLAG_FIRST_PIPE_INSTANCE,
536
_winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
538
1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER,
539
# default security descriptor: the handle cannot be inherited
542
h2 = _winapi.CreateFile(
543
address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
544
_winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
546
_winapi.SetNamedPipeHandleState(
547
h2, _winapi.PIPE_READMODE_MESSAGE, None, None
550
overlapped = _winapi.ConnectNamedPipe(h1, overlapped=True)
551
_, err = overlapped.GetOverlappedResult(True)
554
c1 = PipeConnection(h1, writable=duplex)
555
c2 = PipeConnection(h2, readable=duplex)
560
# Definitions for connections based on sockets
563
class SocketListener(object):
565
Representation of a socket which is bound to an address and listening
567
def __init__(self, address, family, backlog=1):
568
self._socket = socket.socket(getattr(socket, family))
570
# SO_REUSEADDR has different semantics on Windows (issue #2550).
571
if os.name == 'posix':
572
self._socket.setsockopt(socket.SOL_SOCKET,
573
socket.SO_REUSEADDR, 1)
574
self._socket.setblocking(True)
575
self._socket.bind(address)
576
self._socket.listen(backlog)
577
self._address = self._socket.getsockname()
581
self._family = family
582
self._last_accepted = None
584
if family == 'AF_UNIX':
585
self._unlink = util.Finalize(
586
self, os.unlink, args=(address,), exitpriority=0
594
s, self._last_accepted = self._socket.accept()
595
except InterruptedError:
600
return Connection(s.detach())
604
if self._unlink is not None:
608
def SocketClient(address):
610
Return a connection object connected to the socket given by `address`
612
family = address_type(address)
613
with socket.socket( getattr(socket, family) ) as s:
616
return Connection(s.detach())
619
# Definitions for connections based on named pipes
622
if sys.platform == 'win32':
624
class PipeListener(object):
626
Representation of a named pipe
628
def __init__(self, address, backlog=None):
629
self._address = address
630
self._handle_queue = [self._new_handle(first=True)]
632
self._last_accepted = None
633
util.sub_debug('listener created with address=%r', self._address)
634
self.close = util.Finalize(
635
self, PipeListener._finalize_pipe_listener,
636
args=(self._handle_queue, self._address), exitpriority=0
639
def _new_handle(self, first=False):
640
flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
642
flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
643
return _winapi.CreateNamedPipe(
644
self._address, flags,
645
_winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
647
_winapi.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
648
_winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL
652
self._handle_queue.append(self._new_handle())
653
handle = self._handle_queue.pop(0)
655
ov = _winapi.ConnectNamedPipe(handle, overlapped=True)
657
if e.winerror != _winapi.ERROR_NO_DATA:
659
# ERROR_NO_DATA can occur if a client has already connected,
660
# written data and then disconnected -- see Issue 14725.
663
res = _winapi.WaitForMultipleObjects(
664
[ov.event], False, INFINITE)
667
_winapi.CloseHandle(handle)
670
_, err = ov.GetOverlappedResult(True)
672
return PipeConnection(handle)
675
def _finalize_pipe_listener(queue, address):
676
util.sub_debug('closing listener with address=%r', address)
678
_winapi.CloseHandle(handle)
680
def PipeClient(address):
682
Return a connection object connected to the pipe given by `address`
687
_winapi.WaitNamedPipe(address, 1000)
688
h = _winapi.CreateFile(
689
address, _winapi.GENERIC_READ | _winapi.GENERIC_WRITE,
690
0, _winapi.NULL, _winapi.OPEN_EXISTING,
691
_winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
694
if e.winerror not in (_winapi.ERROR_SEM_TIMEOUT,
695
_winapi.ERROR_PIPE_BUSY) or _check_timeout(t):
702
_winapi.SetNamedPipeHandleState(
703
h, _winapi.PIPE_READMODE_MESSAGE, None, None
705
return PipeConnection(h)
708
# Authentication stuff
713
CHALLENGE = b'#CHALLENGE#'
714
WELCOME = b'#WELCOME#'
715
FAILURE = b'#FAILURE#'
717
def deliver_challenge(connection, authkey):
719
assert isinstance(authkey, bytes)
720
message = os.urandom(MESSAGE_LENGTH)
721
connection.send_bytes(CHALLENGE + message)
722
digest = hmac.new(authkey, message, 'md5').digest()
723
response = connection.recv_bytes(256) # reject large message
724
if response == digest:
725
connection.send_bytes(WELCOME)
727
connection.send_bytes(FAILURE)
728
raise AuthenticationError('digest received was wrong')
730
def answer_challenge(connection, authkey):
732
assert isinstance(authkey, bytes)
733
message = connection.recv_bytes(256) # reject large message
734
assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
735
message = message[len(CHALLENGE):]
736
digest = hmac.new(authkey, message, 'md5').digest()
737
connection.send_bytes(digest)
738
response = connection.recv_bytes(256) # reject large message
739
if response != WELCOME:
740
raise AuthenticationError('digest sent was rejected')
743
# Support for using xmlrpclib for serialization
746
class ConnectionWrapper(object):
747
def __init__(self, conn, dumps, loads):
751
for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'):
752
obj = getattr(conn, attr)
753
setattr(self, attr, obj)
756
self._conn.send_bytes(s)
758
s = self._conn.recv_bytes()
759
return self._loads(s)
762
return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf-8')
765
(obj,), method = xmlrpclib.loads(s.decode('utf-8'))
768
class XmlListener(Listener):
771
import xmlrpc.client as xmlrpclib
772
obj = Listener.accept(self)
773
return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
775
def XmlClient(*args, **kwds):
777
import xmlrpc.client as xmlrpclib
778
return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)
784
if sys.platform == 'win32':
786
def _exhaustive_wait(handles, timeout):
787
# Return ALL handles which are currently signalled. (Only
788
# returning the first signalled might create starvation issues.)
792
res = _winapi.WaitForMultipleObjects(L, False, timeout)
793
if res == WAIT_TIMEOUT:
795
elif WAIT_OBJECT_0 <= res < WAIT_OBJECT_0 + len(L):
797
elif WAIT_ABANDONED_0 <= res < WAIT_ABANDONED_0 + len(L):
798
res -= WAIT_ABANDONED_0
800
raise RuntimeError('Should not get here')
806
_ready_errors = {_winapi.ERROR_BROKEN_PIPE, _winapi.ERROR_NETNAME_DELETED}
808
def wait(object_list, timeout=None):
810
Wait till an object in object_list is ready/readable.
812
Returns list of those objects in object_list which are ready/readable.
819
timeout = int(timeout * 1000 + 0.5)
821
object_list = list(object_list)
822
waithandle_to_obj = {}
824
ready_objects = set()
825
ready_handles = set()
828
for o in object_list:
830
fileno = getattr(o, 'fileno')
831
except AttributeError:
832
waithandle_to_obj[o.__index__()] = o
834
# start an overlapped read of length zero
836
ov, err = _winapi.ReadFile(fileno(), 0, True)
839
if err not in _ready_errors:
841
if err == _winapi.ERROR_IO_PENDING:
843
waithandle_to_obj[ov.event] = o
845
# If o.fileno() is an overlapped pipe handle and
846
# err == 0 then there is a zero length message
847
# in the pipe, but it HAS NOT been consumed.
851
ready_handles = _exhaustive_wait(waithandle_to_obj.keys(), timeout)
853
# request that overlapped reads stop
857
# wait for all overlapped reads to stop
860
_, err = ov.GetOverlappedResult(True)
863
if err not in _ready_errors:
865
if err != _winapi.ERROR_OPERATION_ABORTED:
866
o = waithandle_to_obj[ov.event]
869
# If o.fileno() is an overlapped pipe handle then
870
# a zero length message HAS been consumed.
871
if hasattr(o, '_got_empty_message'):
872
o._got_empty_message = True
874
ready_objects.update(waithandle_to_obj[h] for h in ready_handles)
875
return [o for o in object_list if o in ready_objects]
881
# poll/select have the advantage of not requiring any extra file
882
# descriptor, contrarily to epoll/kqueue (also, they require a single
884
if hasattr(selectors, 'PollSelector'):
885
_WaitSelector = selectors.PollSelector
887
_WaitSelector = selectors.SelectSelector
889
def wait(object_list, timeout=None):
891
Wait till an object in object_list is ready/readable.
893
Returns list of those objects in object_list which are ready/readable.
895
with _WaitSelector() as selector:
896
for obj in object_list:
897
selector.register(obj, selectors.EVENT_READ)
899
if timeout is not None:
900
deadline = time.time() + timeout
903
ready = selector.select(timeout)
905
return [key.fileobj for (key, events) in ready]
907
if timeout is not None:
908
timeout = deadline - time.time()
913
# Make connection and socket objects sharable if possible
916
if sys.platform == 'win32':
917
def reduce_connection(conn):
918
handle = conn.fileno()
919
with socket.fromfd(handle, socket.AF_INET, socket.SOCK_STREAM) as s:
920
from . import resource_sharer
921
ds = resource_sharer.DupSocket(s)
922
return rebuild_connection, (ds, conn.readable, conn.writable)
923
def rebuild_connection(ds, readable, writable):
925
return Connection(sock.detach(), readable, writable)
926
reduction.register(Connection, reduce_connection)
928
def reduce_pipe_connection(conn):
929
access = ((_winapi.FILE_GENERIC_READ if conn.readable else 0) |
930
(_winapi.FILE_GENERIC_WRITE if conn.writable else 0))
931
dh = reduction.DupHandle(conn.fileno(), access)
932
return rebuild_pipe_connection, (dh, conn.readable, conn.writable)
933
def rebuild_pipe_connection(dh, readable, writable):
935
return PipeConnection(handle, readable, writable)
936
reduction.register(PipeConnection, reduce_pipe_connection)
939
def reduce_connection(conn):
940
df = reduction.DupFd(conn.fileno())
941
return rebuild_connection, (df, conn.readable, conn.writable)
942
def rebuild_connection(df, readable, writable):
944
return Connection(fd, readable, writable)
945
reduction.register(Connection, reduce_connection)