blob: 2a0bc2fa726551049ef1df57d425800bb6770f7f [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
Antoine Pitrou87cf2202011-05-09 17:04:27 +020015import pickle
16import select
Benjamin Petersone711caf2008-06-11 16:44:04 +000017import socket
Antoine Pitrou87cf2202011-05-09 17:04:27 +020018import struct
Georg Brandl6aa2d1f2008-08-12 08:35:52 +000019import errno
Benjamin Petersone711caf2008-06-11 16:44:04 +000020import time
21import tempfile
22import itertools
23
24import _multiprocessing
Antoine Pitrou87cf2202011-05-09 17:04:27 +020025from multiprocessing import current_process, AuthenticationError, BufferTooShort
Richard Oudkerk59d54042012-05-10 16:11:12 +010026from multiprocessing.util import get_temp_dir, Finalize, sub_debug, debug
Antoine Pitrou5438ed12012-04-24 22:56:57 +020027from multiprocessing.forking import ForkingPickler
Antoine Pitrou87cf2202011-05-09 17:04:27 +020028try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020029 import _winapi
30 from _winapi import WAIT_OBJECT_0, WAIT_TIMEOUT, INFINITE
Antoine Pitrou87cf2202011-05-09 17:04:27 +020031except ImportError:
32 if sys.platform == 'win32':
33 raise
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020034 _winapi = None
Benjamin Petersone711caf2008-06-11 16:44:04 +000035
36#
37#
38#
39
40BUFSIZE = 8192
Antoine Pitrou45d61a32009-11-13 22:35:18 +000041# A very generous timeout when it comes to local connections...
42CONNECTION_TIMEOUT = 20.
Benjamin Petersone711caf2008-06-11 16:44:04 +000043
44_mmap_counter = itertools.count()
45
46default_family = 'AF_INET'
47families = ['AF_INET']
48
49if hasattr(socket, 'AF_UNIX'):
50 default_family = 'AF_UNIX'
51 families += ['AF_UNIX']
52
53if sys.platform == 'win32':
54 default_family = 'AF_PIPE'
55 families += ['AF_PIPE']
56
Antoine Pitrou45d61a32009-11-13 22:35:18 +000057
58def _init_timeout(timeout=CONNECTION_TIMEOUT):
59 return time.time() + timeout
60
61def _check_timeout(t):
62 return time.time() > t
63
Benjamin Petersone711caf2008-06-11 16:44:04 +000064#
65#
66#
67
68def arbitrary_address(family):
69 '''
70 Return an arbitrary free address for the given family
71 '''
72 if family == 'AF_INET':
73 return ('localhost', 0)
74 elif family == 'AF_UNIX':
75 return tempfile.mktemp(prefix='listener-', dir=get_temp_dir())
76 elif family == 'AF_PIPE':
77 return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' %
78 (os.getpid(), next(_mmap_counter)))
79 else:
80 raise ValueError('unrecognized family')
81
Antoine Pitrou709176f2012-04-01 17:19:09 +020082def _validate_family(family):
83 '''
84 Checks if the family is valid for the current environment.
85 '''
86 if sys.platform != 'win32' and family == 'AF_PIPE':
87 raise ValueError('Family %s is not recognized.' % family)
88
Antoine Pitrou6d20cba2012-04-03 20:12:23 +020089 if sys.platform == 'win32' and family == 'AF_UNIX':
90 # double check
91 if not hasattr(socket, family):
92 raise ValueError('Family %s is not recognized.' % family)
Benjamin Petersone711caf2008-06-11 16:44:04 +000093
94def address_type(address):
95 '''
96 Return the types of the address
97
98 This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
99 '''
100 if type(address) == tuple:
101 return 'AF_INET'
102 elif type(address) is str and address.startswith('\\\\'):
103 return 'AF_PIPE'
104 elif type(address) is str:
105 return 'AF_UNIX'
106 else:
107 raise ValueError('address type of %r unrecognized' % address)
108
109#
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200110# Connection classes
111#
112
113class _ConnectionBase:
114 _handle = None
115
116 def __init__(self, handle, readable=True, writable=True):
117 handle = handle.__index__()
118 if handle < 0:
119 raise ValueError("invalid handle")
120 if not readable and not writable:
121 raise ValueError(
122 "at least one of `readable` and `writable` must be True")
123 self._handle = handle
124 self._readable = readable
125 self._writable = writable
126
Antoine Pitrou60001202011-07-09 01:03:46 +0200127 # XXX should we use util.Finalize instead of a __del__?
128
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200129 def __del__(self):
130 if self._handle is not None:
131 self._close()
132
133 def _check_closed(self):
134 if self._handle is None:
135 raise IOError("handle is closed")
136
137 def _check_readable(self):
138 if not self._readable:
139 raise IOError("connection is write-only")
140
141 def _check_writable(self):
142 if not self._writable:
143 raise IOError("connection is read-only")
144
145 def _bad_message_length(self):
146 if self._writable:
147 self._readable = False
148 else:
149 self.close()
150 raise IOError("bad message length")
151
152 @property
153 def closed(self):
154 """True if the connection is closed"""
155 return self._handle is None
156
157 @property
158 def readable(self):
159 """True if the connection is readable"""
160 return self._readable
161
162 @property
163 def writable(self):
164 """True if the connection is writable"""
165 return self._writable
166
167 def fileno(self):
168 """File descriptor or handle of the connection"""
169 self._check_closed()
170 return self._handle
171
172 def close(self):
173 """Close the connection"""
174 if self._handle is not None:
175 try:
176 self._close()
177 finally:
178 self._handle = None
179
180 def send_bytes(self, buf, offset=0, size=None):
181 """Send the bytes data from a bytes-like object"""
182 self._check_closed()
183 self._check_writable()
184 m = memoryview(buf)
185 # HACK for byte-indexing of non-bytewise buffers (e.g. array.array)
186 if m.itemsize > 1:
187 m = memoryview(bytes(m))
188 n = len(m)
189 if offset < 0:
190 raise ValueError("offset is negative")
191 if n < offset:
192 raise ValueError("buffer length < offset")
193 if size is None:
194 size = n - offset
195 elif size < 0:
196 raise ValueError("size is negative")
197 elif offset + size > n:
198 raise ValueError("buffer length < offset + size")
199 self._send_bytes(m[offset:offset + size])
200
201 def send(self, obj):
202 """Send a (picklable) object"""
203 self._check_closed()
204 self._check_writable()
Antoine Pitrou5438ed12012-04-24 22:56:57 +0200205 buf = io.BytesIO()
206 ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj)
207 self._send_bytes(buf.getbuffer())
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200208
209 def recv_bytes(self, maxlength=None):
210 """
211 Receive bytes data as a bytes object.
212 """
213 self._check_closed()
214 self._check_readable()
215 if maxlength is not None and maxlength < 0:
216 raise ValueError("negative maxlength")
217 buf = self._recv_bytes(maxlength)
218 if buf is None:
219 self._bad_message_length()
220 return buf.getvalue()
221
222 def recv_bytes_into(self, buf, offset=0):
223 """
224 Receive bytes data into a writeable buffer-like object.
225 Return the number of bytes read.
226 """
227 self._check_closed()
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)
233 if offset < 0:
234 raise ValueError("negative offset")
235 elif offset > bytesize:
236 raise ValueError("offset too large")
237 result = self._recv_bytes()
238 size = result.tell()
239 if bytesize < offset + size:
240 raise BufferTooShort(result.getvalue())
241 # Message can fit in dest
242 result.seek(0)
243 result.readinto(m[offset // itemsize :
244 (offset + size) // itemsize])
245 return size
246
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100247 def recv(self):
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200248 """Receive a (picklable) object"""
249 self._check_closed()
250 self._check_readable()
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100251 buf = self._recv_bytes()
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200252 return pickle.loads(buf.getbuffer())
253
254 def poll(self, timeout=0.0):
255 """Whether there is any input available to be read"""
256 self._check_closed()
257 self._check_readable()
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200258 return self._poll(timeout)
259
Richard Oudkerkd69cfe82012-06-18 17:47:52 +0100260 def __enter__(self):
261 return self
262
263 def __exit__(self, exc_type, exc_value, exc_tb):
264 self.close()
265
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200266
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200267if _winapi:
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200268
269 class PipeConnection(_ConnectionBase):
270 """
271 Connection class based on a Windows named pipe.
Antoine Pitroudd696492011-06-08 17:21:55 +0200272 Overlapped I/O is used, so the handles must have been created
273 with FILE_FLAG_OVERLAPPED.
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200274 """
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100275 _got_empty_message = False
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200276
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200277 def _close(self, _CloseHandle=_winapi.CloseHandle):
Antoine Pitrou71a28a92011-07-09 01:03:00 +0200278 _CloseHandle(self._handle)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200279
280 def _send_bytes(self, buf):
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200281 ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100282 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200283 if err == _winapi.ERROR_IO_PENDING:
284 waitres = _winapi.WaitForMultipleObjects(
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100285 [ov.event], False, INFINITE)
286 assert waitres == WAIT_OBJECT_0
287 except:
288 ov.cancel()
289 raise
290 finally:
291 nwritten, err = ov.GetOverlappedResult(True)
292 assert err == 0
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200293 assert nwritten == len(buf)
294
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100295 def _recv_bytes(self, maxsize=None):
296 if self._got_empty_message:
297 self._got_empty_message = False
298 return io.BytesIO()
Antoine Pitroudd696492011-06-08 17:21:55 +0200299 else:
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100300 bsize = 128 if maxsize is None else min(maxsize, 128)
Antoine Pitroudd696492011-06-08 17:21:55 +0200301 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200302 ov, err = _winapi.ReadFile(self._handle, bsize,
303 overlapped=True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100304 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200305 if err == _winapi.ERROR_IO_PENDING:
306 waitres = _winapi.WaitForMultipleObjects(
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100307 [ov.event], False, INFINITE)
308 assert waitres == WAIT_OBJECT_0
309 except:
310 ov.cancel()
311 raise
312 finally:
313 nread, err = ov.GetOverlappedResult(True)
314 if err == 0:
315 f = io.BytesIO()
316 f.write(ov.getbuffer())
317 return f
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200318 elif err == _winapi.ERROR_MORE_DATA:
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100319 return self._get_more_data(ov, maxsize)
Antoine Pitroudd696492011-06-08 17:21:55 +0200320 except IOError as e:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200321 if e.winerror == _winapi.ERROR_BROKEN_PIPE:
Antoine Pitroudd696492011-06-08 17:21:55 +0200322 raise EOFError
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100323 else:
324 raise
325 raise RuntimeError("shouldn't get here; expected KeyboardInterrupt")
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200326
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100327 def _poll(self, timeout):
328 if (self._got_empty_message or
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200329 _winapi.PeekNamedPipe(self._handle)[0] != 0):
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200330 return True
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100331 return bool(wait([self], timeout))
332
333 def _get_more_data(self, ov, maxsize):
334 buf = ov.getbuffer()
335 f = io.BytesIO()
336 f.write(buf)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200337 left = _winapi.PeekNamedPipe(self._handle)[1]
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100338 assert left > 0
339 if maxsize is not None and len(buf) + left > maxsize:
340 self._bad_message_length()
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200341 ov, err = _winapi.ReadFile(self._handle, left, overlapped=True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100342 rbytes, err = ov.GetOverlappedResult(True)
343 assert err == 0
344 assert rbytes == left
345 f.write(ov.getbuffer())
346 return f
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200347
348
349class Connection(_ConnectionBase):
350 """
351 Connection class based on an arbitrary file descriptor (Unix only), or
352 a socket handle (Windows).
353 """
354
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200355 if _winapi:
356 def _close(self, _close=_multiprocessing.closesocket):
Antoine Pitrou71a28a92011-07-09 01:03:00 +0200357 _close(self._handle)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200358 _write = _multiprocessing.send
359 _read = _multiprocessing.recv
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200360 else:
Antoine Pitrou71a28a92011-07-09 01:03:00 +0200361 def _close(self, _close=os.close):
362 _close(self._handle)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200363 _write = os.write
364 _read = os.read
365
366 def _send(self, buf, write=_write):
367 remaining = len(buf)
368 while True:
Richard Oudkerkcca8c532013-07-01 18:59:26 +0100369 try:
370 n = write(self._handle, buf)
371 except InterruptedError:
372 continue
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200373 remaining -= n
374 if remaining == 0:
375 break
376 buf = buf[n:]
377
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100378 def _recv(self, size, read=_read):
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200379 buf = io.BytesIO()
Antoine Pitroudd696492011-06-08 17:21:55 +0200380 handle = self._handle
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200381 remaining = size
382 while remaining > 0:
Richard Oudkerkcca8c532013-07-01 18:59:26 +0100383 try:
384 chunk = read(handle, remaining)
385 except InterruptedError:
386 continue
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200387 n = len(chunk)
388 if n == 0:
389 if remaining == size:
390 raise EOFError
391 else:
392 raise IOError("got end of file during message")
393 buf.write(chunk)
394 remaining -= n
395 return buf
396
397 def _send_bytes(self, buf):
398 # For wire compatibility with 3.2 and lower
399 n = len(buf)
Charles-François Natali225aa4f2011-09-20 19:27:39 +0200400 self._send(struct.pack("!i", n))
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200401 # The condition is necessary to avoid "broken pipe" errors
402 # when sending a 0-length buffer if the other end closed the pipe.
403 if n > 0:
404 self._send(buf)
405
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100406 def _recv_bytes(self, maxsize=None):
407 buf = self._recv(4)
Charles-François Natali225aa4f2011-09-20 19:27:39 +0200408 size, = struct.unpack("!i", buf.getvalue())
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200409 if maxsize is not None and size > maxsize:
410 return None
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100411 return self._recv(size)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200412
413 def _poll(self, timeout):
Richard Oudkerked9e06c2013-01-13 22:46:48 +0000414 r = wait([self], timeout)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200415 return bool(r)
416
417
418#
Benjamin Petersone711caf2008-06-11 16:44:04 +0000419# Public functions
420#
421
422class Listener(object):
423 '''
424 Returns a listener object.
425
426 This is a wrapper for a bound socket which is 'listening' for
427 connections, or for a Windows named pipe.
428 '''
429 def __init__(self, address=None, family=None, backlog=1, authkey=None):
430 family = family or (address and address_type(address)) \
431 or default_family
432 address = address or arbitrary_address(family)
433
Antoine Pitrou709176f2012-04-01 17:19:09 +0200434 _validate_family(family)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000435 if family == 'AF_PIPE':
436 self._listener = PipeListener(address, backlog)
437 else:
438 self._listener = SocketListener(address, family, backlog)
439
440 if authkey is not None and not isinstance(authkey, bytes):
441 raise TypeError('authkey should be a byte string')
442
443 self._authkey = authkey
444
445 def accept(self):
446 '''
447 Accept a connection on the bound socket or named pipe of `self`.
448
449 Returns a `Connection` object.
450 '''
Richard Oudkerkd69cfe82012-06-18 17:47:52 +0100451 if self._listener is None:
452 raise IOError('listener is closed')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000453 c = self._listener.accept()
454 if self._authkey:
455 deliver_challenge(c, self._authkey)
456 answer_challenge(c, self._authkey)
457 return c
458
459 def close(self):
460 '''
461 Close the bound socket or named pipe of `self`.
462 '''
Richard Oudkerkd69cfe82012-06-18 17:47:52 +0100463 if self._listener is not None:
464 self._listener.close()
465 self._listener = None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000466
467 address = property(lambda self: self._listener._address)
468 last_accepted = property(lambda self: self._listener._last_accepted)
469
Richard Oudkerkd69cfe82012-06-18 17:47:52 +0100470 def __enter__(self):
471 return self
472
473 def __exit__(self, exc_type, exc_value, exc_tb):
474 self.close()
475
Benjamin Petersone711caf2008-06-11 16:44:04 +0000476
477def Client(address, family=None, authkey=None):
478 '''
479 Returns a connection to the address of a `Listener`
480 '''
481 family = family or address_type(address)
Antoine Pitrou709176f2012-04-01 17:19:09 +0200482 _validate_family(family)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000483 if family == 'AF_PIPE':
484 c = PipeClient(address)
485 else:
486 c = SocketClient(address)
487
488 if authkey is not None and not isinstance(authkey, bytes):
489 raise TypeError('authkey should be a byte string')
490
491 if authkey is not None:
492 answer_challenge(c, authkey)
493 deliver_challenge(c, authkey)
494
495 return c
496
497
498if sys.platform != 'win32':
499
500 def Pipe(duplex=True):
501 '''
502 Returns pair of connection objects at either end of a pipe
503 '''
504 if duplex:
505 s1, s2 = socket.socketpair()
Richard Oudkerkb15e6222012-07-27 14:19:00 +0100506 s1.setblocking(True)
507 s2.setblocking(True)
Antoine Pitrou5aa878c2011-05-09 21:00:28 +0200508 c1 = Connection(s1.detach())
509 c2 = Connection(s2.detach())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000510 else:
511 fd1, fd2 = os.pipe()
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200512 c1 = Connection(fd1, writable=False)
513 c2 = Connection(fd2, readable=False)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000514
515 return c1, c2
516
517else:
518
Benjamin Petersone711caf2008-06-11 16:44:04 +0000519 def Pipe(duplex=True):
520 '''
521 Returns pair of connection objects at either end of a pipe
522 '''
523 address = arbitrary_address('AF_PIPE')
524 if duplex:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200525 openmode = _winapi.PIPE_ACCESS_DUPLEX
526 access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000527 obsize, ibsize = BUFSIZE, BUFSIZE
528 else:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200529 openmode = _winapi.PIPE_ACCESS_INBOUND
530 access = _winapi.GENERIC_WRITE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000531 obsize, ibsize = 0, BUFSIZE
532
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200533 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 |
537 _winapi.PIPE_WAIT,
538 1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL
Benjamin Petersone711caf2008-06-11 16:44:04 +0000539 )
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200540 h2 = _winapi.CreateFile(
541 address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
542 _winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
Benjamin Petersone711caf2008-06-11 16:44:04 +0000543 )
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200544 _winapi.SetNamedPipeHandleState(
545 h2, _winapi.PIPE_READMODE_MESSAGE, None, None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000546 )
547
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200548 overlapped = _winapi.ConnectNamedPipe(h1, overlapped=True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100549 _, err = overlapped.GetOverlappedResult(True)
550 assert err == 0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000551
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200552 c1 = PipeConnection(h1, writable=duplex)
553 c2 = PipeConnection(h2, readable=duplex)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000554
555 return c1, c2
556
557#
558# Definitions for connections based on sockets
559#
560
561class SocketListener(object):
562 '''
Georg Brandl734e2682008-08-12 08:18:18 +0000563 Representation of a socket which is bound to an address and listening
Benjamin Petersone711caf2008-06-11 16:44:04 +0000564 '''
565 def __init__(self, address, family, backlog=1):
566 self._socket = socket.socket(getattr(socket, family))
Charles-François Nataliedc67fe2012-02-04 15:12:08 +0100567 try:
Charles-François Natalied4a8fc2012-02-08 21:15:58 +0100568 # SO_REUSEADDR has different semantics on Windows (issue #2550).
569 if os.name == 'posix':
570 self._socket.setsockopt(socket.SOL_SOCKET,
571 socket.SO_REUSEADDR, 1)
Richard Oudkerkb15e6222012-07-27 14:19:00 +0100572 self._socket.setblocking(True)
Charles-François Nataliedc67fe2012-02-04 15:12:08 +0100573 self._socket.bind(address)
574 self._socket.listen(backlog)
575 self._address = self._socket.getsockname()
576 except OSError:
577 self._socket.close()
578 raise
Benjamin Petersone711caf2008-06-11 16:44:04 +0000579 self._family = family
580 self._last_accepted = None
581
Benjamin Petersone711caf2008-06-11 16:44:04 +0000582 if family == 'AF_UNIX':
583 self._unlink = Finalize(
Georg Brandl2ee470f2008-07-16 12:55:28 +0000584 self, os.unlink, args=(address,), exitpriority=0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000585 )
586 else:
587 self._unlink = None
588
589 def accept(self):
Richard Oudkerkcca8c532013-07-01 18:59:26 +0100590 while True:
591 try:
592 s, self._last_accepted = self._socket.accept()
593 except InterruptedError:
594 pass
595 else:
596 break
Richard Oudkerkb15e6222012-07-27 14:19:00 +0100597 s.setblocking(True)
Antoine Pitroudf97cbe2012-04-07 22:38:52 +0200598 return Connection(s.detach())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000599
600 def close(self):
601 self._socket.close()
602 if self._unlink is not None:
603 self._unlink()
604
605
606def SocketClient(address):
607 '''
608 Return a connection object connected to the socket given by `address`
609 '''
610 family = address_type(address)
Victor Stinner2b695062011-01-03 15:47:59 +0000611 with socket.socket( getattr(socket, family) ) as s:
Richard Oudkerkb15e6222012-07-27 14:19:00 +0100612 s.setblocking(True)
Charles-François Natalie6eabd42011-11-19 09:59:43 +0100613 s.connect(address)
Antoine Pitroudf97cbe2012-04-07 22:38:52 +0200614 return Connection(s.detach())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000615
616#
617# Definitions for connections based on named pipes
618#
619
620if sys.platform == 'win32':
621
622 class PipeListener(object):
623 '''
624 Representation of a named pipe
625 '''
626 def __init__(self, address, backlog=None):
627 self._address = address
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100628 self._handle_queue = [self._new_handle(first=True)]
629
Benjamin Petersone711caf2008-06-11 16:44:04 +0000630 self._last_accepted = None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000631 sub_debug('listener created with address=%r', self._address)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000632 self.close = Finalize(
633 self, PipeListener._finalize_pipe_listener,
634 args=(self._handle_queue, self._address), exitpriority=0
635 )
636
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100637 def _new_handle(self, first=False):
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200638 flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100639 if first:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200640 flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
641 return _winapi.CreateNamedPipe(
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100642 self._address, flags,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200643 _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
644 _winapi.PIPE_WAIT,
645 _winapi.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
646 _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL
Benjamin Petersone711caf2008-06-11 16:44:04 +0000647 )
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100648
649 def accept(self):
650 self._handle_queue.append(self._new_handle())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000651 handle = self._handle_queue.pop(0)
652 try:
Richard Oudkerkfdb8dcf2012-05-05 19:45:37 +0100653 ov = _winapi.ConnectNamedPipe(handle, overlapped=True)
654 except OSError as e:
655 if e.winerror != _winapi.ERROR_NO_DATA:
656 raise
657 # ERROR_NO_DATA can occur if a client has already connected,
658 # written data and then disconnected -- see Issue 14725.
659 else:
660 try:
661 res = _winapi.WaitForMultipleObjects(
662 [ov.event], False, INFINITE)
663 except:
664 ov.cancel()
665 _winapi.CloseHandle(handle)
666 raise
667 finally:
668 _, err = ov.GetOverlappedResult(True)
669 assert err == 0
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200670 return PipeConnection(handle)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000671
672 @staticmethod
673 def _finalize_pipe_listener(queue, address):
674 sub_debug('closing listener with address=%r', address)
675 for handle in queue:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200676 _winapi.CloseHandle(handle)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000677
678 def PipeClient(address):
679 '''
680 Return a connection object connected to the pipe given by `address`
681 '''
Antoine Pitrou45d61a32009-11-13 22:35:18 +0000682 t = _init_timeout()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000683 while 1:
684 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200685 _winapi.WaitNamedPipe(address, 1000)
686 h = _winapi.CreateFile(
687 address, _winapi.GENERIC_READ | _winapi.GENERIC_WRITE,
688 0, _winapi.NULL, _winapi.OPEN_EXISTING,
689 _winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
Benjamin Petersone711caf2008-06-11 16:44:04 +0000690 )
691 except WindowsError as e:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200692 if e.winerror not in (_winapi.ERROR_SEM_TIMEOUT,
693 _winapi.ERROR_PIPE_BUSY) or _check_timeout(t):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000694 raise
695 else:
696 break
697 else:
698 raise
699
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200700 _winapi.SetNamedPipeHandleState(
701 h, _winapi.PIPE_READMODE_MESSAGE, None, None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000702 )
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200703 return PipeConnection(h)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000704
705#
706# Authentication stuff
707#
708
709MESSAGE_LENGTH = 20
710
Benjamin Peterson1fcfe212008-06-25 12:54:22 +0000711CHALLENGE = b'#CHALLENGE#'
712WELCOME = b'#WELCOME#'
713FAILURE = b'#FAILURE#'
Benjamin Petersone711caf2008-06-11 16:44:04 +0000714
715def deliver_challenge(connection, authkey):
716 import hmac
717 assert isinstance(authkey, bytes)
718 message = os.urandom(MESSAGE_LENGTH)
719 connection.send_bytes(CHALLENGE + message)
720 digest = hmac.new(authkey, message).digest()
721 response = connection.recv_bytes(256) # reject large message
722 if response == digest:
723 connection.send_bytes(WELCOME)
724 else:
725 connection.send_bytes(FAILURE)
726 raise AuthenticationError('digest received was wrong')
727
728def answer_challenge(connection, authkey):
729 import hmac
730 assert isinstance(authkey, bytes)
731 message = connection.recv_bytes(256) # reject large message
732 assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
733 message = message[len(CHALLENGE):]
734 digest = hmac.new(authkey, message).digest()
735 connection.send_bytes(digest)
736 response = connection.recv_bytes(256) # reject large message
737 if response != WELCOME:
738 raise AuthenticationError('digest sent was rejected')
739
740#
741# Support for using xmlrpclib for serialization
742#
743
744class ConnectionWrapper(object):
745 def __init__(self, conn, dumps, loads):
746 self._conn = conn
747 self._dumps = dumps
748 self._loads = loads
749 for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'):
750 obj = getattr(conn, attr)
751 setattr(self, attr, obj)
752 def send(self, obj):
753 s = self._dumps(obj)
754 self._conn.send_bytes(s)
755 def recv(self):
756 s = self._conn.recv_bytes()
757 return self._loads(s)
758
759def _xml_dumps(obj):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000760 return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf-8')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000761
762def _xml_loads(s):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000763 (obj,), method = xmlrpclib.loads(s.decode('utf-8'))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000764 return obj
765
766class XmlListener(Listener):
767 def accept(self):
768 global xmlrpclib
769 import xmlrpc.client as xmlrpclib
770 obj = Listener.accept(self)
771 return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
772
773def XmlClient(*args, **kwds):
774 global xmlrpclib
775 import xmlrpc.client as xmlrpclib
776 return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)
Antoine Pitrou87cf2202011-05-09 17:04:27 +0200777
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100778#
779# Wait
780#
781
782if sys.platform == 'win32':
783
784 def _exhaustive_wait(handles, timeout):
785 # Return ALL handles which are currently signalled. (Only
786 # returning the first signalled might create starvation issues.)
787 L = list(handles)
788 ready = []
789 while L:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200790 res = _winapi.WaitForMultipleObjects(L, False, timeout)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100791 if res == WAIT_TIMEOUT:
792 break
793 elif WAIT_OBJECT_0 <= res < WAIT_OBJECT_0 + len(L):
794 res -= WAIT_OBJECT_0
795 elif WAIT_ABANDONED_0 <= res < WAIT_ABANDONED_0 + len(L):
796 res -= WAIT_ABANDONED_0
797 else:
798 raise RuntimeError('Should not get here')
799 ready.append(L[res])
800 L = L[res+1:]
801 timeout = 0
802 return ready
803
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200804 _ready_errors = {_winapi.ERROR_BROKEN_PIPE, _winapi.ERROR_NETNAME_DELETED}
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100805
806 def wait(object_list, timeout=None):
807 '''
808 Wait till an object in object_list is ready/readable.
809
810 Returns list of those objects in object_list which are ready/readable.
811 '''
812 if timeout is None:
813 timeout = INFINITE
814 elif timeout < 0:
815 timeout = 0
816 else:
817 timeout = int(timeout * 1000 + 0.5)
818
819 object_list = list(object_list)
820 waithandle_to_obj = {}
821 ov_list = []
822 ready_objects = set()
823 ready_handles = set()
824
825 try:
826 for o in object_list:
827 try:
828 fileno = getattr(o, 'fileno')
829 except AttributeError:
830 waithandle_to_obj[o.__index__()] = o
831 else:
832 # start an overlapped read of length zero
833 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200834 ov, err = _winapi.ReadFile(fileno(), 0, True)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100835 except OSError as e:
836 err = e.winerror
837 if err not in _ready_errors:
838 raise
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200839 if err == _winapi.ERROR_IO_PENDING:
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100840 ov_list.append(ov)
841 waithandle_to_obj[ov.event] = o
842 else:
843 # If o.fileno() is an overlapped pipe handle and
844 # err == 0 then there is a zero length message
845 # in the pipe, but it HAS NOT been consumed.
846 ready_objects.add(o)
847 timeout = 0
848
849 ready_handles = _exhaustive_wait(waithandle_to_obj.keys(), timeout)
850 finally:
851 # request that overlapped reads stop
852 for ov in ov_list:
853 ov.cancel()
854
855 # wait for all overlapped reads to stop
856 for ov in ov_list:
857 try:
858 _, err = ov.GetOverlappedResult(True)
859 except OSError as e:
860 err = e.winerror
861 if err not in _ready_errors:
862 raise
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200863 if err != _winapi.ERROR_OPERATION_ABORTED:
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100864 o = waithandle_to_obj[ov.event]
865 ready_objects.add(o)
866 if err == 0:
867 # If o.fileno() is an overlapped pipe handle then
868 # a zero length message HAS been consumed.
869 if hasattr(o, '_got_empty_message'):
870 o._got_empty_message = True
871
872 ready_objects.update(waithandle_to_obj[h] for h in ready_handles)
873 return [o for o in object_list if o in ready_objects]
874
875else:
876
Giampaolo Rodola'67da8942013-01-14 02:24:25 +0100877 if hasattr(select, 'poll'):
878 def _poll(fds, timeout):
879 if timeout is not None:
Giampaolo Rodola'b38897f2013-04-17 13:08:59 +0200880 timeout = int(timeout * 1000) # timeout is in milliseconds
Giampaolo Rodola'67da8942013-01-14 02:24:25 +0100881 fd_map = {}
882 pollster = select.poll()
883 for fd in fds:
884 pollster.register(fd, select.POLLIN)
885 if hasattr(fd, 'fileno'):
886 fd_map[fd.fileno()] = fd
887 else:
888 fd_map[fd] = fd
889 ls = []
890 for fd, event in pollster.poll(timeout):
891 if event & select.POLLNVAL:
892 raise ValueError('invalid file descriptor %i' % fd)
893 ls.append(fd_map[fd])
894 return ls
895 else:
896 def _poll(fds, timeout):
897 return select.select(fds, [], [], timeout)[0]
898
899
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100900 def wait(object_list, timeout=None):
901 '''
902 Wait till an object in object_list is ready/readable.
903
904 Returns list of those objects in object_list which are ready/readable.
905 '''
906 if timeout is not None:
907 if timeout <= 0:
Giampaolo Rodola'67da8942013-01-14 02:24:25 +0100908 return _poll(object_list, 0)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100909 else:
910 deadline = time.time() + timeout
911 while True:
912 try:
Giampaolo Rodola'67da8942013-01-14 02:24:25 +0100913 return _poll(object_list, timeout)
Antoine Pitroubdb1cf12012-03-05 19:28:37 +0100914 except OSError as e:
915 if e.errno != errno.EINTR:
916 raise
917 if timeout is not None:
918 timeout = deadline - time.time()
Antoine Pitrou5438ed12012-04-24 22:56:57 +0200919
920#
921# Make connection and socket objects sharable if possible
922#
923
924if sys.platform == 'win32':
925 from . import reduction
926 ForkingPickler.register(socket.socket, reduction.reduce_socket)
927 ForkingPickler.register(Connection, reduction.reduce_connection)
928 ForkingPickler.register(PipeConnection, reduction.reduce_pipe_connection)
929else:
930 try:
931 from . import reduction
932 except ImportError:
933 pass
934 else:
935 ForkingPickler.register(socket.socket, reduction.reduce_socket)
936 ForkingPickler.register(Connection, reduction.reduce_connection)