blob: 1eb1a8d89be1d34d83c677dfa07cb008e3d36549 [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# A higher level module for using sockets (or Windows named pipes)
3#
4# multiprocessing/connection.py
5#
R. David Murray3fc969a2010-12-14 01:38:16 +00006# Copyright (c) 2006-2008, R Oudkerk
Richard Oudkerk3e268aa2012-04-30 12:13:55 +01007# Licensed to PSF under a Contributor Agreement.
Benjamin Petersone711caf2008-06-11 16:44:04 +00008#
9
Antoine Pitroubdb1cf12012-03-05 19:28:37 +010010__all__ = [ 'Client', 'Listener', 'Pipe', 'wait' ]
Benjamin Petersone711caf2008-06-11 16:44:04 +000011
Antoine Pitrou87cf2202011-05-09 17:04:27 +020012import io
Benjamin Petersone711caf2008-06-11 16:44:04 +000013import os
14import sys
15import socket
Antoine Pitrou87cf2202011-05-09 17:04:27 +020016import struct
Benjamin Petersone711caf2008-06-11 16:44:04 +000017import time
18import tempfile
19import itertools
20
21import _multiprocessing
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010022
23from . import reduction
24from . import util
25
26from . import AuthenticationError, BufferTooShort
27from .reduction import ForkingPickler
28
Antoine Pitrou87cf2202011-05-09 17:04:27 +020029try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020030 import _winapi
Victor Stinner69b1e262014-03-20 08:50:52 +010031 from _winapi import WAIT_OBJECT_0, WAIT_ABANDONED_0, WAIT_TIMEOUT, INFINITE
Brett Cannoncd171c82013-07-04 17:43:24 -040032except ImportError:
Antoine Pitrou87cf2202011-05-09 17:04:27 +020033 if sys.platform == 'win32':
34 raise
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020035 _winapi = None
Benjamin Petersone711caf2008-06-11 16:44:04 +000036
37#
38#
39#
40
41BUFSIZE = 8192
Antoine Pitrou45d61a32009-11-13 22:35:18 +000042# A very generous timeout when it comes to local connections...
43CONNECTION_TIMEOUT = 20.
Benjamin Petersone711caf2008-06-11 16:44:04 +000044
45_mmap_counter = itertools.count()
46
47default_family = 'AF_INET'
48families = ['AF_INET']
49
50if hasattr(socket, 'AF_UNIX'):
51 default_family = 'AF_UNIX'
52 families += ['AF_UNIX']
53
54if sys.platform == 'win32':
55 default_family = 'AF_PIPE'
56 families += ['AF_PIPE']
57
Antoine Pitrou45d61a32009-11-13 22:35:18 +000058
59def _init_timeout(timeout=CONNECTION_TIMEOUT):
60 return time.time() + timeout
61
62def _check_timeout(t):
63 return time.time() > t
64
Benjamin Petersone711caf2008-06-11 16:44:04 +000065#
66#
67#
68
69def arbitrary_address(family):
70 '''
71 Return an arbitrary free address for the given family
72 '''
73 if family == 'AF_INET':
74 return ('localhost', 0)
75 elif family == 'AF_UNIX':
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010076 return tempfile.mktemp(prefix='listener-', dir=util.get_temp_dir())
Benjamin Petersone711caf2008-06-11 16:44:04 +000077 elif family == 'AF_PIPE':
78 return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' %
Benjamin Peterson40470e02014-04-14 12:24:37 -040079 (os.getpid(), next(_mmap_counter)), dir="")
Benjamin Petersone711caf2008-06-11 16:44:04 +000080 else:
81 raise ValueError('unrecognized family')
82
Antoine Pitrou709176f2012-04-01 17:19:09 +020083def _validate_family(family):
84 '''
85 Checks if the family is valid for the current environment.
86 '''
87 if sys.platform != 'win32' and family == 'AF_PIPE':
88 raise ValueError('Family %s is not recognized.' % family)
89
Antoine Pitrou6d20cba2012-04-03 20:12:23 +020090 if sys.platform == 'win32' and family == 'AF_UNIX':
91 # double check
92 if not hasattr(socket, family):
93 raise ValueError('Family %s is not recognized.' % family)
Benjamin Petersone711caf2008-06-11 16:44:04 +000094
95def address_type(address):
96 '''
97 Return the types of the address
98
99 This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
100 '''
101 if type(address) == tuple:
102 return 'AF_INET'
103 elif type(address) is str and address.startswith('\\\\'):
104 return 'AF_PIPE'
105 elif type(address) is str:
106 return 'AF_UNIX'
107 else:
108 raise ValueError('address type of %r unrecognized' % address)
109
110#
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200111# Connection classes
112#
113
114class _ConnectionBase:
115 _handle = None
116
117 def __init__(self, handle, readable=True, writable=True):
118 handle = handle.__index__()
119 if handle < 0:
120 raise ValueError("invalid handle")
121 if not readable and not writable:
122 raise ValueError(
123 "at least one of `readable` and `writable` must be True")
124 self._handle = handle
125 self._readable = readable
126 self._writable = writable
127
Antoine Pitrou60001202011-07-09 01:03:46 +0200128 # XXX should we use util.Finalize instead of a __del__?
129
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200130 def __del__(self):
131 if self._handle is not None:
132 self._close()
133
134 def _check_closed(self):
135 if self._handle is None:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200136 raise OSError("handle is closed")
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200137
138 def _check_readable(self):
139 if not self._readable:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200140 raise OSError("connection is write-only")
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200141
142 def _check_writable(self):
143 if not self._writable:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200144 raise OSError("connection is read-only")
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200145
146 def _bad_message_length(self):
147 if self._writable:
148 self._readable = False
149 else:
150 self.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200151 raise OSError("bad message length")
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200152
153 @property
154 def closed(self):
155 """True if the connection is closed"""
156 return self._handle is None
157
158 @property
159 def readable(self):
160 """True if the connection is readable"""
161 return self._readable
162
163 @property
164 def writable(self):
165 """True if the connection is writable"""
166 return self._writable
167
168 def fileno(self):
169 """File descriptor or handle of the connection"""
170 self._check_closed()
171 return self._handle
172
173 def close(self):
174 """Close the connection"""
175 if self._handle is not None:
176 try:
177 self._close()
178 finally:
179 self._handle = None
180
181 def send_bytes(self, buf, offset=0, size=None):
182 """Send the bytes data from a bytes-like object"""
183 self._check_closed()
184 self._check_writable()
185 m = memoryview(buf)
186 # HACK for byte-indexing of non-bytewise buffers (e.g. array.array)
187 if m.itemsize > 1:
188 m = memoryview(bytes(m))
189 n = len(m)
190 if offset < 0:
191 raise ValueError("offset is negative")
192 if n < offset:
193 raise ValueError("buffer length < offset")
194 if size is None:
195 size = n - offset
196 elif size < 0:
197 raise ValueError("size is negative")
198 elif offset + size > n:
199 raise ValueError("buffer length < offset + size")
200 self._send_bytes(m[offset:offset + size])
201
202 def send(self, obj):
203 """Send a (picklable) object"""
204 self._check_closed()
205 self._check_writable()
Charles-François Natalia6550752013-03-24 15:21:49 +0100206 self._send_bytes(ForkingPickler.dumps(obj))
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200207
208 def recv_bytes(self, maxlength=None):
209 """
210 Receive bytes data as a bytes object.
211 """
212 self._check_closed()
213 self._check_readable()
214 if maxlength is not None and maxlength < 0:
215 raise ValueError("negative maxlength")
216 buf = self._recv_bytes(maxlength)
217 if buf is None:
218 self._bad_message_length()
219 return buf.getvalue()
220
221 def recv_bytes_into(self, buf, offset=0):
222 """
Serhiy Storchakab757c832014-12-05 22:25:22 +0200223 Receive bytes data into a writeable bytes-like object.
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200224 Return the number of bytes read.
225 """
226 self._check_closed()
227 self._check_readable()
228 with memoryview(buf) as m:
229 # Get bytesize of arbitrary buffer
230 itemsize = m.itemsize
231 bytesize = itemsize * len(m)
232 if offset < 0:
233 raise ValueError("negative offset")
234 elif offset > bytesize:
235 raise ValueError("offset too large")
236 result = self._recv_bytes()
237 size = result.tell()
238 if bytesize < offset + size:
239 raise BufferTooShort(result.getvalue())
240 # Message can fit in dest
241 result.seek(0)
242 result.readinto(m[offset // itemsize :
243 (offset + size) // itemsize])
244 return size
245
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100246 def recv(self):
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200247 """Receive a (picklable) object"""
248 self._check_closed()
249 self._check_readable()
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100250 buf = self._recv_bytes()
Charles-François Natalia6550752013-03-24 15:21:49 +0100251 return ForkingPickler.loads(buf.getbuffer())
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200252
253 def poll(self, timeout=0.0):
254 """Whether there is any input available to be read"""
255 self._check_closed()
256 self._check_readable()
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200257 return self._poll(timeout)
258
Richard Oudkerkd69cfe82012-06-18 17:47:52 +0100259 def __enter__(self):
260 return self
261
262 def __exit__(self, exc_type, exc_value, exc_tb):
263 self.close()
264
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200265
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200266if _winapi:
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200267
268 class PipeConnection(_ConnectionBase):
269 """
270 Connection class based on a Windows named pipe.
Antoine Pitroudd696492011-06-08 17:21:55 +0200271 Overlapped I/O is used, so the handles must have been created
272 with FILE_FLAG_OVERLAPPED.
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200273 """
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100274 _got_empty_message = False
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200275
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200276 def _close(self, _CloseHandle=_winapi.CloseHandle):
Antoine Pitrou71a28a92011-07-09 01:03:00 +0200277 _CloseHandle(self._handle)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200278
279 def _send_bytes(self, buf):
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200280 ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100281 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200282 if err == _winapi.ERROR_IO_PENDING:
283 waitres = _winapi.WaitForMultipleObjects(
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100284 [ov.event], False, INFINITE)
285 assert waitres == WAIT_OBJECT_0
286 except:
287 ov.cancel()
288 raise
289 finally:
290 nwritten, err = ov.GetOverlappedResult(True)
291 assert err == 0
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200292 assert nwritten == len(buf)
293
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100294 def _recv_bytes(self, maxsize=None):
295 if self._got_empty_message:
296 self._got_empty_message = False
297 return io.BytesIO()
Antoine Pitroudd696492011-06-08 17:21:55 +0200298 else:
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100299 bsize = 128 if maxsize is None else min(maxsize, 128)
Antoine Pitroudd696492011-06-08 17:21:55 +0200300 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200301 ov, err = _winapi.ReadFile(self._handle, bsize,
302 overlapped=True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100303 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200304 if err == _winapi.ERROR_IO_PENDING:
305 waitres = _winapi.WaitForMultipleObjects(
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100306 [ov.event], False, INFINITE)
307 assert waitres == WAIT_OBJECT_0
308 except:
309 ov.cancel()
310 raise
311 finally:
312 nread, err = ov.GetOverlappedResult(True)
313 if err == 0:
314 f = io.BytesIO()
315 f.write(ov.getbuffer())
316 return f
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200317 elif err == _winapi.ERROR_MORE_DATA:
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100318 return self._get_more_data(ov, maxsize)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200319 except OSError as e:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200320 if e.winerror == _winapi.ERROR_BROKEN_PIPE:
Antoine Pitroudd696492011-06-08 17:21:55 +0200321 raise EOFError
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100322 else:
323 raise
324 raise RuntimeError("shouldn't get here; expected KeyboardInterrupt")
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200325
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100326 def _poll(self, timeout):
327 if (self._got_empty_message or
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200328 _winapi.PeekNamedPipe(self._handle)[0] != 0):
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200329 return True
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100330 return bool(wait([self], timeout))
331
332 def _get_more_data(self, ov, maxsize):
333 buf = ov.getbuffer()
334 f = io.BytesIO()
335 f.write(buf)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200336 left = _winapi.PeekNamedPipe(self._handle)[1]
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100337 assert left > 0
338 if maxsize is not None and len(buf) + left > maxsize:
339 self._bad_message_length()
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200340 ov, err = _winapi.ReadFile(self._handle, left, overlapped=True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100341 rbytes, err = ov.GetOverlappedResult(True)
342 assert err == 0
343 assert rbytes == left
344 f.write(ov.getbuffer())
345 return f
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200346
347
348class Connection(_ConnectionBase):
349 """
350 Connection class based on an arbitrary file descriptor (Unix only), or
351 a socket handle (Windows).
352 """
353
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200354 if _winapi:
355 def _close(self, _close=_multiprocessing.closesocket):
Antoine Pitrou71a28a92011-07-09 01:03:00 +0200356 _close(self._handle)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200357 _write = _multiprocessing.send
358 _read = _multiprocessing.recv
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200359 else:
Antoine Pitrou71a28a92011-07-09 01:03:00 +0200360 def _close(self, _close=os.close):
361 _close(self._handle)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200362 _write = os.write
363 _read = os.read
364
365 def _send(self, buf, write=_write):
366 remaining = len(buf)
367 while True:
Richard Oudkerkcca8c532013-07-01 18:59:26 +0100368 try:
369 n = write(self._handle, buf)
370 except InterruptedError:
371 continue
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200372 remaining -= n
373 if remaining == 0:
374 break
375 buf = buf[n:]
376
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100377 def _recv(self, size, read=_read):
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200378 buf = io.BytesIO()
Antoine Pitroudd696492011-06-08 17:21:55 +0200379 handle = self._handle
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200380 remaining = size
381 while remaining > 0:
Richard Oudkerkcca8c532013-07-01 18:59:26 +0100382 try:
383 chunk = read(handle, remaining)
384 except InterruptedError:
385 continue
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200386 n = len(chunk)
387 if n == 0:
388 if remaining == size:
389 raise EOFError
390 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200391 raise OSError("got end of file during message")
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200392 buf.write(chunk)
393 remaining -= n
394 return buf
395
396 def _send_bytes(self, buf):
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200397 n = len(buf)
Antoine Pitroub7d6d2a2014-02-08 23:03:56 +0100398 # For wire compatibility with 3.2 and lower
399 header = struct.pack("!i", n)
400 if n > 16384:
401 # The payload is large so Nagle's algorithm won't be triggered
402 # and we'd better avoid the cost of concatenation.
403 chunks = [header, buf]
404 elif n > 0:
405 # Issue # 20540: concatenate before sending, to avoid delays due
406 # to Nagle's algorithm on a TCP socket.
407 chunks = [header + buf]
408 else:
409 # This code path is necessary to avoid "broken pipe" errors
410 # when sending a 0-length buffer if the other end closed the pipe.
411 chunks = [header]
412 for chunk in chunks:
413 self._send(chunk)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200414
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100415 def _recv_bytes(self, maxsize=None):
416 buf = self._recv(4)
Charles-François Natali225aa4f2011-09-20 19:27:39 +0200417 size, = struct.unpack("!i", buf.getvalue())
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200418 if maxsize is not None and size > maxsize:
419 return None
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100420 return self._recv(size)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200421
422 def _poll(self, timeout):
Richard Oudkerked9e06c2013-01-13 22:46:48 +0000423 r = wait([self], timeout)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200424 return bool(r)
425
426
427#
Benjamin Petersone711caf2008-06-11 16:44:04 +0000428# Public functions
429#
430
431class Listener(object):
432 '''
433 Returns a listener object.
434
435 This is a wrapper for a bound socket which is 'listening' for
436 connections, or for a Windows named pipe.
437 '''
438 def __init__(self, address=None, family=None, backlog=1, authkey=None):
439 family = family or (address and address_type(address)) \
440 or default_family
441 address = address or arbitrary_address(family)
442
Antoine Pitrou709176f2012-04-01 17:19:09 +0200443 _validate_family(family)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000444 if family == 'AF_PIPE':
445 self._listener = PipeListener(address, backlog)
446 else:
447 self._listener = SocketListener(address, family, backlog)
448
449 if authkey is not None and not isinstance(authkey, bytes):
450 raise TypeError('authkey should be a byte string')
451
452 self._authkey = authkey
453
454 def accept(self):
455 '''
456 Accept a connection on the bound socket or named pipe of `self`.
457
458 Returns a `Connection` object.
459 '''
Richard Oudkerkd69cfe82012-06-18 17:47:52 +0100460 if self._listener is None:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200461 raise OSError('listener is closed')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000462 c = self._listener.accept()
463 if self._authkey:
464 deliver_challenge(c, self._authkey)
465 answer_challenge(c, self._authkey)
466 return c
467
468 def close(self):
469 '''
470 Close the bound socket or named pipe of `self`.
471 '''
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300472 listener = self._listener
473 if listener is not None:
Richard Oudkerkd69cfe82012-06-18 17:47:52 +0100474 self._listener = None
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300475 listener.close()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000476
477 address = property(lambda self: self._listener._address)
478 last_accepted = property(lambda self: self._listener._last_accepted)
479
Richard Oudkerkd69cfe82012-06-18 17:47:52 +0100480 def __enter__(self):
481 return self
482
483 def __exit__(self, exc_type, exc_value, exc_tb):
484 self.close()
485
Benjamin Petersone711caf2008-06-11 16:44:04 +0000486
487def Client(address, family=None, authkey=None):
488 '''
489 Returns a connection to the address of a `Listener`
490 '''
491 family = family or address_type(address)
Antoine Pitrou709176f2012-04-01 17:19:09 +0200492 _validate_family(family)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000493 if family == 'AF_PIPE':
494 c = PipeClient(address)
495 else:
496 c = SocketClient(address)
497
498 if authkey is not None and not isinstance(authkey, bytes):
499 raise TypeError('authkey should be a byte string')
500
501 if authkey is not None:
502 answer_challenge(c, authkey)
503 deliver_challenge(c, authkey)
504
505 return c
506
507
508if sys.platform != 'win32':
509
510 def Pipe(duplex=True):
511 '''
512 Returns pair of connection objects at either end of a pipe
513 '''
514 if duplex:
515 s1, s2 = socket.socketpair()
Richard Oudkerkb15e6222012-07-27 14:19:00 +0100516 s1.setblocking(True)
517 s2.setblocking(True)
Antoine Pitrou5aa878c2011-05-09 21:00:28 +0200518 c1 = Connection(s1.detach())
519 c2 = Connection(s2.detach())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000520 else:
Victor Stinnerdaf45552013-08-28 00:53:59 +0200521 fd1, fd2 = os.pipe()
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200522 c1 = Connection(fd1, writable=False)
523 c2 = Connection(fd2, readable=False)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000524
525 return c1, c2
526
527else:
528
Benjamin Petersone711caf2008-06-11 16:44:04 +0000529 def Pipe(duplex=True):
530 '''
531 Returns pair of connection objects at either end of a pipe
532 '''
533 address = arbitrary_address('AF_PIPE')
534 if duplex:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200535 openmode = _winapi.PIPE_ACCESS_DUPLEX
536 access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000537 obsize, ibsize = BUFSIZE, BUFSIZE
538 else:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200539 openmode = _winapi.PIPE_ACCESS_INBOUND
540 access = _winapi.GENERIC_WRITE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000541 obsize, ibsize = 0, BUFSIZE
542
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200543 h1 = _winapi.CreateNamedPipe(
544 address, openmode | _winapi.FILE_FLAG_OVERLAPPED |
545 _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE,
546 _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
547 _winapi.PIPE_WAIT,
Victor Stinnerdaf45552013-08-28 00:53:59 +0200548 1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER,
549 # default security descriptor: the handle cannot be inherited
550 _winapi.NULL
Benjamin Petersone711caf2008-06-11 16:44:04 +0000551 )
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200552 h2 = _winapi.CreateFile(
553 address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
554 _winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
Benjamin Petersone711caf2008-06-11 16:44:04 +0000555 )
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200556 _winapi.SetNamedPipeHandleState(
557 h2, _winapi.PIPE_READMODE_MESSAGE, None, None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000558 )
559
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200560 overlapped = _winapi.ConnectNamedPipe(h1, overlapped=True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100561 _, err = overlapped.GetOverlappedResult(True)
562 assert err == 0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000563
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200564 c1 = PipeConnection(h1, writable=duplex)
565 c2 = PipeConnection(h2, readable=duplex)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000566
567 return c1, c2
568
569#
570# Definitions for connections based on sockets
571#
572
573class SocketListener(object):
574 '''
Georg Brandl734e2682008-08-12 08:18:18 +0000575 Representation of a socket which is bound to an address and listening
Benjamin Petersone711caf2008-06-11 16:44:04 +0000576 '''
577 def __init__(self, address, family, backlog=1):
578 self._socket = socket.socket(getattr(socket, family))
Charles-François Nataliedc67fe2012-02-04 15:12:08 +0100579 try:
Charles-François Natalied4a8fc2012-02-08 21:15:58 +0100580 # SO_REUSEADDR has different semantics on Windows (issue #2550).
581 if os.name == 'posix':
582 self._socket.setsockopt(socket.SOL_SOCKET,
583 socket.SO_REUSEADDR, 1)
Richard Oudkerkb15e6222012-07-27 14:19:00 +0100584 self._socket.setblocking(True)
Charles-François Nataliedc67fe2012-02-04 15:12:08 +0100585 self._socket.bind(address)
586 self._socket.listen(backlog)
587 self._address = self._socket.getsockname()
588 except OSError:
589 self._socket.close()
590 raise
Benjamin Petersone711caf2008-06-11 16:44:04 +0000591 self._family = family
592 self._last_accepted = None
593
Benjamin Petersone711caf2008-06-11 16:44:04 +0000594 if family == 'AF_UNIX':
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100595 self._unlink = util.Finalize(
Georg Brandl2ee470f2008-07-16 12:55:28 +0000596 self, os.unlink, args=(address,), exitpriority=0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000597 )
598 else:
599 self._unlink = None
600
601 def accept(self):
Richard Oudkerkcca8c532013-07-01 18:59:26 +0100602 while True:
603 try:
604 s, self._last_accepted = self._socket.accept()
605 except InterruptedError:
606 pass
607 else:
608 break
Richard Oudkerkb15e6222012-07-27 14:19:00 +0100609 s.setblocking(True)
Antoine Pitroudf97cbe2012-04-07 22:38:52 +0200610 return Connection(s.detach())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000611
612 def close(self):
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300613 try:
614 self._socket.close()
615 finally:
616 unlink = self._unlink
617 if unlink is not None:
618 self._unlink = None
619 unlink()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000620
621
622def SocketClient(address):
623 '''
624 Return a connection object connected to the socket given by `address`
625 '''
626 family = address_type(address)
Victor Stinner2b695062011-01-03 15:47:59 +0000627 with socket.socket( getattr(socket, family) ) as s:
Richard Oudkerkb15e6222012-07-27 14:19:00 +0100628 s.setblocking(True)
Charles-François Natalie6eabd42011-11-19 09:59:43 +0100629 s.connect(address)
Antoine Pitroudf97cbe2012-04-07 22:38:52 +0200630 return Connection(s.detach())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000631
632#
633# Definitions for connections based on named pipes
634#
635
636if sys.platform == 'win32':
637
638 class PipeListener(object):
639 '''
640 Representation of a named pipe
641 '''
642 def __init__(self, address, backlog=None):
643 self._address = address
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100644 self._handle_queue = [self._new_handle(first=True)]
645
Benjamin Petersone711caf2008-06-11 16:44:04 +0000646 self._last_accepted = None
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100647 util.sub_debug('listener created with address=%r', self._address)
648 self.close = util.Finalize(
Benjamin Petersone711caf2008-06-11 16:44:04 +0000649 self, PipeListener._finalize_pipe_listener,
650 args=(self._handle_queue, self._address), exitpriority=0
651 )
652
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100653 def _new_handle(self, first=False):
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200654 flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100655 if first:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200656 flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
657 return _winapi.CreateNamedPipe(
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100658 self._address, flags,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200659 _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
660 _winapi.PIPE_WAIT,
661 _winapi.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
662 _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL
Benjamin Petersone711caf2008-06-11 16:44:04 +0000663 )
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100664
665 def accept(self):
666 self._handle_queue.append(self._new_handle())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000667 handle = self._handle_queue.pop(0)
668 try:
Richard Oudkerkfdb8dcf2012-05-05 19:45:37 +0100669 ov = _winapi.ConnectNamedPipe(handle, overlapped=True)
670 except OSError as e:
671 if e.winerror != _winapi.ERROR_NO_DATA:
672 raise
673 # ERROR_NO_DATA can occur if a client has already connected,
674 # written data and then disconnected -- see Issue 14725.
675 else:
676 try:
677 res = _winapi.WaitForMultipleObjects(
678 [ov.event], False, INFINITE)
679 except:
680 ov.cancel()
681 _winapi.CloseHandle(handle)
682 raise
683 finally:
684 _, err = ov.GetOverlappedResult(True)
685 assert err == 0
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200686 return PipeConnection(handle)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000687
688 @staticmethod
689 def _finalize_pipe_listener(queue, address):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100690 util.sub_debug('closing listener with address=%r', address)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000691 for handle in queue:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200692 _winapi.CloseHandle(handle)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000693
694 def PipeClient(address):
695 '''
696 Return a connection object connected to the pipe given by `address`
697 '''
Antoine Pitrou45d61a32009-11-13 22:35:18 +0000698 t = _init_timeout()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000699 while 1:
700 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200701 _winapi.WaitNamedPipe(address, 1000)
702 h = _winapi.CreateFile(
703 address, _winapi.GENERIC_READ | _winapi.GENERIC_WRITE,
704 0, _winapi.NULL, _winapi.OPEN_EXISTING,
705 _winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
Benjamin Petersone711caf2008-06-11 16:44:04 +0000706 )
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200707 except OSError as e:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200708 if e.winerror not in (_winapi.ERROR_SEM_TIMEOUT,
709 _winapi.ERROR_PIPE_BUSY) or _check_timeout(t):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000710 raise
711 else:
712 break
713 else:
714 raise
715
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200716 _winapi.SetNamedPipeHandleState(
717 h, _winapi.PIPE_READMODE_MESSAGE, None, None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000718 )
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200719 return PipeConnection(h)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000720
721#
722# Authentication stuff
723#
724
725MESSAGE_LENGTH = 20
726
Benjamin Peterson1fcfe212008-06-25 12:54:22 +0000727CHALLENGE = b'#CHALLENGE#'
728WELCOME = b'#WELCOME#'
729FAILURE = b'#FAILURE#'
Benjamin Petersone711caf2008-06-11 16:44:04 +0000730
731def deliver_challenge(connection, authkey):
732 import hmac
733 assert isinstance(authkey, bytes)
734 message = os.urandom(MESSAGE_LENGTH)
735 connection.send_bytes(CHALLENGE + message)
Christian Heimes634919a2013-11-20 17:23:06 +0100736 digest = hmac.new(authkey, message, 'md5').digest()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000737 response = connection.recv_bytes(256) # reject large message
738 if response == digest:
739 connection.send_bytes(WELCOME)
740 else:
741 connection.send_bytes(FAILURE)
742 raise AuthenticationError('digest received was wrong')
743
744def answer_challenge(connection, authkey):
745 import hmac
746 assert isinstance(authkey, bytes)
747 message = connection.recv_bytes(256) # reject large message
748 assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
749 message = message[len(CHALLENGE):]
Christian Heimes634919a2013-11-20 17:23:06 +0100750 digest = hmac.new(authkey, message, 'md5').digest()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000751 connection.send_bytes(digest)
752 response = connection.recv_bytes(256) # reject large message
753 if response != WELCOME:
754 raise AuthenticationError('digest sent was rejected')
755
756#
757# Support for using xmlrpclib for serialization
758#
759
760class ConnectionWrapper(object):
761 def __init__(self, conn, dumps, loads):
762 self._conn = conn
763 self._dumps = dumps
764 self._loads = loads
765 for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'):
766 obj = getattr(conn, attr)
767 setattr(self, attr, obj)
768 def send(self, obj):
769 s = self._dumps(obj)
770 self._conn.send_bytes(s)
771 def recv(self):
772 s = self._conn.recv_bytes()
773 return self._loads(s)
774
775def _xml_dumps(obj):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000776 return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf-8')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000777
778def _xml_loads(s):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000779 (obj,), method = xmlrpclib.loads(s.decode('utf-8'))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000780 return obj
781
782class XmlListener(Listener):
783 def accept(self):
784 global xmlrpclib
785 import xmlrpc.client as xmlrpclib
786 obj = Listener.accept(self)
787 return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
788
789def XmlClient(*args, **kwds):
790 global xmlrpclib
791 import xmlrpc.client as xmlrpclib
792 return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200793
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100794#
795# Wait
796#
797
798if sys.platform == 'win32':
799
800 def _exhaustive_wait(handles, timeout):
801 # Return ALL handles which are currently signalled. (Only
802 # returning the first signalled might create starvation issues.)
803 L = list(handles)
804 ready = []
805 while L:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200806 res = _winapi.WaitForMultipleObjects(L, False, timeout)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100807 if res == WAIT_TIMEOUT:
808 break
809 elif WAIT_OBJECT_0 <= res < WAIT_OBJECT_0 + len(L):
810 res -= WAIT_OBJECT_0
811 elif WAIT_ABANDONED_0 <= res < WAIT_ABANDONED_0 + len(L):
812 res -= WAIT_ABANDONED_0
813 else:
814 raise RuntimeError('Should not get here')
815 ready.append(L[res])
816 L = L[res+1:]
817 timeout = 0
818 return ready
819
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200820 _ready_errors = {_winapi.ERROR_BROKEN_PIPE, _winapi.ERROR_NETNAME_DELETED}
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100821
822 def wait(object_list, timeout=None):
823 '''
824 Wait till an object in object_list is ready/readable.
825
826 Returns list of those objects in object_list which are ready/readable.
827 '''
828 if timeout is None:
829 timeout = INFINITE
830 elif timeout < 0:
831 timeout = 0
832 else:
833 timeout = int(timeout * 1000 + 0.5)
834
835 object_list = list(object_list)
836 waithandle_to_obj = {}
837 ov_list = []
838 ready_objects = set()
839 ready_handles = set()
840
841 try:
842 for o in object_list:
843 try:
844 fileno = getattr(o, 'fileno')
845 except AttributeError:
846 waithandle_to_obj[o.__index__()] = o
847 else:
848 # start an overlapped read of length zero
849 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200850 ov, err = _winapi.ReadFile(fileno(), 0, True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100851 except OSError as e:
Steve Dower3f9e3812015-03-02 08:05:27 -0800852 ov, err = None, e.winerror
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100853 if err not in _ready_errors:
854 raise
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200855 if err == _winapi.ERROR_IO_PENDING:
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100856 ov_list.append(ov)
857 waithandle_to_obj[ov.event] = o
858 else:
859 # If o.fileno() is an overlapped pipe handle and
860 # err == 0 then there is a zero length message
Steve Dower3f9e3812015-03-02 08:05:27 -0800861 # in the pipe, but it HAS NOT been consumed...
862 if ov and sys.getwindowsversion()[:2] >= (6, 2):
863 # ... except on Windows 8 and later, where
864 # the message HAS been consumed.
865 try:
866 _, err = ov.GetOverlappedResult(False)
867 except OSError as e:
868 err = e.winerror
869 if not err and hasattr(o, '_got_empty_message'):
870 o._got_empty_message = True
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100871 ready_objects.add(o)
872 timeout = 0
873
874 ready_handles = _exhaustive_wait(waithandle_to_obj.keys(), timeout)
875 finally:
876 # request that overlapped reads stop
877 for ov in ov_list:
878 ov.cancel()
879
880 # wait for all overlapped reads to stop
881 for ov in ov_list:
882 try:
883 _, err = ov.GetOverlappedResult(True)
884 except OSError as e:
885 err = e.winerror
886 if err not in _ready_errors:
887 raise
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200888 if err != _winapi.ERROR_OPERATION_ABORTED:
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100889 o = waithandle_to_obj[ov.event]
890 ready_objects.add(o)
891 if err == 0:
892 # If o.fileno() is an overlapped pipe handle then
893 # a zero length message HAS been consumed.
894 if hasattr(o, '_got_empty_message'):
895 o._got_empty_message = True
896
897 ready_objects.update(waithandle_to_obj[h] for h in ready_handles)
898 return [o for o in object_list if o in ready_objects]
899
900else:
901
Charles-François Natalie241ac92013-09-05 20:46:49 +0200902 import selectors
Giampaolo Rodola'0c8ad612013-01-14 02:24:05 +0100903
Charles-François Natali45e25512013-09-08 11:30:53 +0200904 # poll/select have the advantage of not requiring any extra file
905 # descriptor, contrarily to epoll/kqueue (also, they require a single
906 # syscall).
907 if hasattr(selectors, 'PollSelector'):
908 _WaitSelector = selectors.PollSelector
909 else:
910 _WaitSelector = selectors.SelectSelector
911
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100912 def wait(object_list, timeout=None):
913 '''
914 Wait till an object in object_list is ready/readable.
915
916 Returns list of those objects in object_list which are ready/readable.
917 '''
Charles-François Natali45e25512013-09-08 11:30:53 +0200918 with _WaitSelector() as selector:
Charles-François Natalie241ac92013-09-05 20:46:49 +0200919 for obj in object_list:
920 selector.register(obj, selectors.EVENT_READ)
921
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100922 if timeout is not None:
Charles-François Natalie241ac92013-09-05 20:46:49 +0200923 deadline = time.time() + timeout
924
925 while True:
926 ready = selector.select(timeout)
927 if ready:
928 return [key.fileobj for (key, events) in ready]
929 else:
930 if timeout is not None:
931 timeout = deadline - time.time()
932 if timeout < 0:
933 return ready
Antoine Pitrou5438ed12012-04-24 22:56:57 +0200934
935#
936# Make connection and socket objects sharable if possible
937#
938
939if sys.platform == 'win32':
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100940 def reduce_connection(conn):
941 handle = conn.fileno()
942 with socket.fromfd(handle, socket.AF_INET, socket.SOCK_STREAM) as s:
943 from . import resource_sharer
944 ds = resource_sharer.DupSocket(s)
945 return rebuild_connection, (ds, conn.readable, conn.writable)
946 def rebuild_connection(ds, readable, writable):
947 sock = ds.detach()
948 return Connection(sock.detach(), readable, writable)
949 reduction.register(Connection, reduce_connection)
950
951 def reduce_pipe_connection(conn):
952 access = ((_winapi.FILE_GENERIC_READ if conn.readable else 0) |
953 (_winapi.FILE_GENERIC_WRITE if conn.writable else 0))
954 dh = reduction.DupHandle(conn.fileno(), access)
955 return rebuild_pipe_connection, (dh, conn.readable, conn.writable)
956 def rebuild_pipe_connection(dh, readable, writable):
957 handle = dh.detach()
958 return PipeConnection(handle, readable, writable)
959 reduction.register(PipeConnection, reduce_pipe_connection)
960
Antoine Pitrou5438ed12012-04-24 22:56:57 +0200961else:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100962 def reduce_connection(conn):
963 df = reduction.DupFd(conn.fileno())
964 return rebuild_connection, (df, conn.readable, conn.writable)
965 def rebuild_connection(df, readable, writable):
966 fd = df.detach()
967 return Connection(fd, readable, writable)
968 reduction.register(Connection, reduce_connection)