blob: 4421ac5cfd7a274279e489d3dd43603e0cfbb897 [file] [log] [blame]
Benjamin Peterson7f03ea72008-06-13 19:20:48 +00001#
2# A higher level module for using sockets (or Windows named pipes)
3#
4# multiprocessing/connection.py
5#
R. David Murray79af2452010-12-14 01:42:40 +00006# Copyright (c) 2006-2008, R Oudkerk
7# All rights reserved.
8#
9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions
11# are met:
12#
13# 1. Redistributions of source code must retain the above copyright
14# notice, this list of conditions and the following disclaimer.
15# 2. Redistributions in binary form must reproduce the above copyright
16# notice, this list of conditions and the following disclaimer in the
17# documentation and/or other materials provided with the distribution.
18# 3. Neither the name of author nor the names of any contributors may be
19# used to endorse or promote products derived from this software
20# without specific prior written permission.
21#
22# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
23# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32# SUCH DAMAGE.
Benjamin Peterson7f03ea72008-06-13 19:20:48 +000033#
34
35__all__ = [ 'Client', 'Listener', 'Pipe' ]
36
37import os
38import sys
39import socket
Jesse Noller5d353732008-08-11 19:00:15 +000040import errno
Benjamin Peterson7f03ea72008-06-13 19:20:48 +000041import time
42import tempfile
43import itertools
44
45import _multiprocessing
Neal Norwitz0c519b32008-08-25 01:50:24 +000046from multiprocessing import current_process, AuthenticationError
Benjamin Peterson7f03ea72008-06-13 19:20:48 +000047from multiprocessing.util import get_temp_dir, Finalize, sub_debug, debug
48from multiprocessing.forking import duplicate, close
49
50
51#
52#
53#
54
55BUFSIZE = 8192
Antoine Pitrouc562ca42009-11-13 22:31:18 +000056# A very generous timeout when it comes to local connections...
57CONNECTION_TIMEOUT = 20.
Benjamin Peterson7f03ea72008-06-13 19:20:48 +000058
59_mmap_counter = itertools.count()
60
61default_family = 'AF_INET'
62families = ['AF_INET']
63
64if hasattr(socket, 'AF_UNIX'):
65 default_family = 'AF_UNIX'
66 families += ['AF_UNIX']
67
68if sys.platform == 'win32':
69 default_family = 'AF_PIPE'
70 families += ['AF_PIPE']
71
Antoine Pitrouc562ca42009-11-13 22:31:18 +000072
73def _init_timeout(timeout=CONNECTION_TIMEOUT):
74 return time.time() + timeout
75
76def _check_timeout(t):
77 return time.time() > t
78
Benjamin Peterson7f03ea72008-06-13 19:20:48 +000079#
80#
81#
82
83def arbitrary_address(family):
84 '''
85 Return an arbitrary free address for the given family
86 '''
87 if family == 'AF_INET':
88 return ('localhost', 0)
89 elif family == 'AF_UNIX':
90 return tempfile.mktemp(prefix='listener-', dir=get_temp_dir())
91 elif family == 'AF_PIPE':
92 return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' %
93 (os.getpid(), _mmap_counter.next()))
94 else:
95 raise ValueError('unrecognized family')
96
97
98def address_type(address):
99 '''
100 Return the types of the address
101
102 This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
103 '''
104 if type(address) == tuple:
105 return 'AF_INET'
106 elif type(address) is str and address.startswith('\\\\'):
107 return 'AF_PIPE'
108 elif type(address) is str:
109 return 'AF_UNIX'
110 else:
111 raise ValueError('address type of %r unrecognized' % address)
112
113#
114# Public functions
115#
116
117class Listener(object):
118 '''
119 Returns a listener object.
120
121 This is a wrapper for a bound socket which is 'listening' for
122 connections, or for a Windows named pipe.
123 '''
124 def __init__(self, address=None, family=None, backlog=1, authkey=None):
125 family = family or (address and address_type(address)) \
126 or default_family
127 address = address or arbitrary_address(family)
128
129 if family == 'AF_PIPE':
130 self._listener = PipeListener(address, backlog)
131 else:
132 self._listener = SocketListener(address, family, backlog)
133
134 if authkey is not None and not isinstance(authkey, bytes):
135 raise TypeError, 'authkey should be a byte string'
136
137 self._authkey = authkey
138
139 def accept(self):
140 '''
141 Accept a connection on the bound socket or named pipe of `self`.
142
143 Returns a `Connection` object.
144 '''
145 c = self._listener.accept()
146 if self._authkey:
147 deliver_challenge(c, self._authkey)
148 answer_challenge(c, self._authkey)
149 return c
150
151 def close(self):
152 '''
153 Close the bound socket or named pipe of `self`.
154 '''
155 return self._listener.close()
156
157 address = property(lambda self: self._listener._address)
158 last_accepted = property(lambda self: self._listener._last_accepted)
159
160
161def Client(address, family=None, authkey=None):
162 '''
163 Returns a connection to the address of a `Listener`
164 '''
165 family = family or address_type(address)
166 if family == 'AF_PIPE':
167 c = PipeClient(address)
168 else:
169 c = SocketClient(address)
170
171 if authkey is not None and not isinstance(authkey, bytes):
172 raise TypeError, 'authkey should be a byte string'
173
174 if authkey is not None:
175 answer_challenge(c, authkey)
176 deliver_challenge(c, authkey)
177
178 return c
179
180
181if sys.platform != 'win32':
182
183 def Pipe(duplex=True):
184 '''
185 Returns pair of connection objects at either end of a pipe
186 '''
187 if duplex:
188 s1, s2 = socket.socketpair()
Richard Oudkerke4b99382012-07-27 14:05:46 +0100189 s1.setblocking(True)
190 s2.setblocking(True)
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000191 c1 = _multiprocessing.Connection(os.dup(s1.fileno()))
192 c2 = _multiprocessing.Connection(os.dup(s2.fileno()))
193 s1.close()
194 s2.close()
195 else:
196 fd1, fd2 = os.pipe()
197 c1 = _multiprocessing.Connection(fd1, writable=False)
198 c2 = _multiprocessing.Connection(fd2, readable=False)
199
200 return c1, c2
201
202else:
203
Jesse Noller2f8c8f42010-07-03 12:26:02 +0000204 from _multiprocessing import win32
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000205
206 def Pipe(duplex=True):
207 '''
208 Returns pair of connection objects at either end of a pipe
209 '''
210 address = arbitrary_address('AF_PIPE')
211 if duplex:
212 openmode = win32.PIPE_ACCESS_DUPLEX
213 access = win32.GENERIC_READ | win32.GENERIC_WRITE
214 obsize, ibsize = BUFSIZE, BUFSIZE
215 else:
216 openmode = win32.PIPE_ACCESS_INBOUND
217 access = win32.GENERIC_WRITE
218 obsize, ibsize = 0, BUFSIZE
219
220 h1 = win32.CreateNamedPipe(
221 address, openmode,
222 win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE |
223 win32.PIPE_WAIT,
224 1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, win32.NULL
225 )
226 h2 = win32.CreateFile(
227 address, access, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL
228 )
229 win32.SetNamedPipeHandleState(
230 h2, win32.PIPE_READMODE_MESSAGE, None, None
231 )
232
233 try:
234 win32.ConnectNamedPipe(h1, win32.NULL)
235 except WindowsError, e:
236 if e.args[0] != win32.ERROR_PIPE_CONNECTED:
237 raise
238
239 c1 = _multiprocessing.PipeConnection(h1, writable=duplex)
240 c2 = _multiprocessing.PipeConnection(h2, readable=duplex)
241
242 return c1, c2
243
244#
245# Definitions for connections based on sockets
246#
247
248class SocketListener(object):
249 '''
Mark Dickinson97521952008-08-06 20:12:30 +0000250 Representation of a socket which is bound to an address and listening
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000251 '''
252 def __init__(self, address, family, backlog=1):
253 self._socket = socket.socket(getattr(socket, family))
Charles-François Natali709aa352012-02-04 14:40:25 +0100254 try:
255 self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Richard Oudkerke4b99382012-07-27 14:05:46 +0100256 self._socket.setblocking(True)
Charles-François Natali709aa352012-02-04 14:40:25 +0100257 self._socket.bind(address)
258 self._socket.listen(backlog)
259 self._address = self._socket.getsockname()
260 except socket.error:
261 self._socket.close()
262 raise
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000263 self._family = family
264 self._last_accepted = None
265
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000266 if family == 'AF_UNIX':
267 self._unlink = Finalize(
Jesse Noller9949d6e2008-07-15 18:29:18 +0000268 self, os.unlink, args=(address,), exitpriority=0
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000269 )
270 else:
271 self._unlink = None
272
273 def accept(self):
274 s, self._last_accepted = self._socket.accept()
Richard Oudkerke4b99382012-07-27 14:05:46 +0100275 s.setblocking(True)
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000276 fd = duplicate(s.fileno())
277 conn = _multiprocessing.Connection(fd)
278 s.close()
279 return conn
280
281 def close(self):
282 self._socket.close()
283 if self._unlink is not None:
284 self._unlink()
285
286
287def SocketClient(address):
288 '''
289 Return a connection object connected to the socket given by `address`
290 '''
291 family = address_type(address)
292 s = socket.socket( getattr(socket, family) )
Richard Oudkerke4b99382012-07-27 14:05:46 +0100293 s.setblocking(True)
Antoine Pitrouc562ca42009-11-13 22:31:18 +0000294 t = _init_timeout()
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000295
296 while 1:
297 try:
298 s.connect(address)
299 except socket.error, e:
Antoine Pitrouc562ca42009-11-13 22:31:18 +0000300 if e.args[0] != errno.ECONNREFUSED or _check_timeout(t):
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000301 debug('failed to connect to address %s', address)
302 raise
303 time.sleep(0.01)
304 else:
305 break
306 else:
307 raise
308
309 fd = duplicate(s.fileno())
310 conn = _multiprocessing.Connection(fd)
311 s.close()
312 return conn
313
314#
315# Definitions for connections based on named pipes
316#
317
318if sys.platform == 'win32':
319
320 class PipeListener(object):
321 '''
322 Representation of a named pipe
323 '''
324 def __init__(self, address, backlog=None):
325 self._address = address
326 handle = win32.CreateNamedPipe(
327 address, win32.PIPE_ACCESS_DUPLEX,
328 win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE |
329 win32.PIPE_WAIT,
330 win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
331 win32.NMPWAIT_WAIT_FOREVER, win32.NULL
332 )
333 self._handle_queue = [handle]
334 self._last_accepted = None
335
336 sub_debug('listener created with address=%r', self._address)
337
338 self.close = Finalize(
339 self, PipeListener._finalize_pipe_listener,
340 args=(self._handle_queue, self._address), exitpriority=0
341 )
342
343 def accept(self):
344 newhandle = win32.CreateNamedPipe(
345 self._address, win32.PIPE_ACCESS_DUPLEX,
346 win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE |
347 win32.PIPE_WAIT,
348 win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
349 win32.NMPWAIT_WAIT_FOREVER, win32.NULL
350 )
351 self._handle_queue.append(newhandle)
352 handle = self._handle_queue.pop(0)
353 try:
354 win32.ConnectNamedPipe(handle, win32.NULL)
355 except WindowsError, e:
Richard Oudkerk9a16fa62012-05-05 20:41:08 +0100356 # ERROR_NO_DATA can occur if a client has already connected,
357 # written data and then disconnected -- see Issue 14725.
358 if e.args[0] not in (win32.ERROR_PIPE_CONNECTED,
359 win32.ERROR_NO_DATA):
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000360 raise
361 return _multiprocessing.PipeConnection(handle)
362
363 @staticmethod
364 def _finalize_pipe_listener(queue, address):
365 sub_debug('closing listener with address=%r', address)
366 for handle in queue:
367 close(handle)
368
369 def PipeClient(address):
370 '''
371 Return a connection object connected to the pipe given by `address`
372 '''
Antoine Pitrouc562ca42009-11-13 22:31:18 +0000373 t = _init_timeout()
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000374 while 1:
375 try:
376 win32.WaitNamedPipe(address, 1000)
377 h = win32.CreateFile(
378 address, win32.GENERIC_READ | win32.GENERIC_WRITE,
379 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL
380 )
381 except WindowsError, e:
382 if e.args[0] not in (win32.ERROR_SEM_TIMEOUT,
Antoine Pitrouc562ca42009-11-13 22:31:18 +0000383 win32.ERROR_PIPE_BUSY) or _check_timeout(t):
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000384 raise
385 else:
386 break
387 else:
388 raise
389
390 win32.SetNamedPipeHandleState(
391 h, win32.PIPE_READMODE_MESSAGE, None, None
392 )
393 return _multiprocessing.PipeConnection(h)
394
395#
396# Authentication stuff
397#
398
399MESSAGE_LENGTH = 20
400
Benjamin Petersonb09c9392008-06-25 12:39:05 +0000401CHALLENGE = b'#CHALLENGE#'
402WELCOME = b'#WELCOME#'
403FAILURE = b'#FAILURE#'
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000404
405def deliver_challenge(connection, authkey):
406 import hmac
407 assert isinstance(authkey, bytes)
408 message = os.urandom(MESSAGE_LENGTH)
409 connection.send_bytes(CHALLENGE + message)
410 digest = hmac.new(authkey, message).digest()
411 response = connection.recv_bytes(256) # reject large message
412 if response == digest:
413 connection.send_bytes(WELCOME)
414 else:
415 connection.send_bytes(FAILURE)
416 raise AuthenticationError('digest received was wrong')
417
418def answer_challenge(connection, authkey):
419 import hmac
420 assert isinstance(authkey, bytes)
421 message = connection.recv_bytes(256) # reject large message
422 assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
423 message = message[len(CHALLENGE):]
424 digest = hmac.new(authkey, message).digest()
425 connection.send_bytes(digest)
426 response = connection.recv_bytes(256) # reject large message
427 if response != WELCOME:
428 raise AuthenticationError('digest sent was rejected')
429
430#
431# Support for using xmlrpclib for serialization
432#
433
434class ConnectionWrapper(object):
435 def __init__(self, conn, dumps, loads):
436 self._conn = conn
437 self._dumps = dumps
438 self._loads = loads
439 for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'):
440 obj = getattr(conn, attr)
441 setattr(self, attr, obj)
442 def send(self, obj):
443 s = self._dumps(obj)
444 self._conn.send_bytes(s)
445 def recv(self):
446 s = self._conn.recv_bytes()
447 return self._loads(s)
448
449def _xml_dumps(obj):
450 return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf8')
451
452def _xml_loads(s):
453 (obj,), method = xmlrpclib.loads(s.decode('utf8'))
454 return obj
455
456class XmlListener(Listener):
457 def accept(self):
458 global xmlrpclib
459 import xmlrpclib
460 obj = Listener.accept(self)
461 return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
462
463def XmlClient(*args, **kwds):
464 global xmlrpclib
465 import xmlrpclib
466 return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)