Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1 | # |
| 2 | # A higher level module for using sockets (or Windows named pipes) |
| 3 | # |
| 4 | # multiprocessing/connection.py |
| 5 | # |
R. David Murray | 3fc969a | 2010-12-14 01:38:16 +0000 | [diff] [blame] | 6 | # 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 Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 33 | # |
| 34 | |
| 35 | __all__ = [ 'Client', 'Listener', 'Pipe' ] |
| 36 | |
| 37 | import os |
| 38 | import sys |
| 39 | import socket |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 40 | import errno |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 41 | import time |
| 42 | import tempfile |
| 43 | import itertools |
| 44 | |
| 45 | import _multiprocessing |
Neal Norwitz | 5d6415e | 2008-08-25 01:53:32 +0000 | [diff] [blame] | 46 | from multiprocessing import current_process, AuthenticationError |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 47 | from multiprocessing.util import get_temp_dir, Finalize, sub_debug, debug |
| 48 | from multiprocessing.forking import duplicate, close |
| 49 | |
| 50 | |
| 51 | # |
| 52 | # |
| 53 | # |
| 54 | |
| 55 | BUFSIZE = 8192 |
Antoine Pitrou | 45d61a3 | 2009-11-13 22:35:18 +0000 | [diff] [blame] | 56 | # A very generous timeout when it comes to local connections... |
| 57 | CONNECTION_TIMEOUT = 20. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 58 | |
| 59 | _mmap_counter = itertools.count() |
| 60 | |
| 61 | default_family = 'AF_INET' |
| 62 | families = ['AF_INET'] |
| 63 | |
| 64 | if hasattr(socket, 'AF_UNIX'): |
| 65 | default_family = 'AF_UNIX' |
| 66 | families += ['AF_UNIX'] |
| 67 | |
| 68 | if sys.platform == 'win32': |
| 69 | default_family = 'AF_PIPE' |
| 70 | families += ['AF_PIPE'] |
| 71 | |
Antoine Pitrou | 45d61a3 | 2009-11-13 22:35:18 +0000 | [diff] [blame] | 72 | |
| 73 | def _init_timeout(timeout=CONNECTION_TIMEOUT): |
| 74 | return time.time() + timeout |
| 75 | |
| 76 | def _check_timeout(t): |
| 77 | return time.time() > t |
| 78 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 79 | # |
| 80 | # |
| 81 | # |
| 82 | |
| 83 | def 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(), next(_mmap_counter))) |
| 94 | else: |
| 95 | raise ValueError('unrecognized family') |
| 96 | |
| 97 | |
| 98 | def 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 | |
| 117 | class 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 | |
| 161 | def 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 | |
| 181 | if 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() |
| 189 | c1 = _multiprocessing.Connection(os.dup(s1.fileno())) |
| 190 | c2 = _multiprocessing.Connection(os.dup(s2.fileno())) |
| 191 | s1.close() |
| 192 | s2.close() |
| 193 | else: |
| 194 | fd1, fd2 = os.pipe() |
| 195 | c1 = _multiprocessing.Connection(fd1, writable=False) |
| 196 | c2 = _multiprocessing.Connection(fd2, readable=False) |
| 197 | |
| 198 | return c1, c2 |
| 199 | |
| 200 | else: |
| 201 | |
Brian Curtin | a6a3274 | 2010-08-04 15:47:24 +0000 | [diff] [blame] | 202 | from _multiprocessing import win32 |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 203 | |
| 204 | def Pipe(duplex=True): |
| 205 | ''' |
| 206 | Returns pair of connection objects at either end of a pipe |
| 207 | ''' |
| 208 | address = arbitrary_address('AF_PIPE') |
| 209 | if duplex: |
| 210 | openmode = win32.PIPE_ACCESS_DUPLEX |
| 211 | access = win32.GENERIC_READ | win32.GENERIC_WRITE |
| 212 | obsize, ibsize = BUFSIZE, BUFSIZE |
| 213 | else: |
| 214 | openmode = win32.PIPE_ACCESS_INBOUND |
| 215 | access = win32.GENERIC_WRITE |
| 216 | obsize, ibsize = 0, BUFSIZE |
| 217 | |
| 218 | h1 = win32.CreateNamedPipe( |
| 219 | address, openmode, |
| 220 | win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | |
| 221 | win32.PIPE_WAIT, |
| 222 | 1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, win32.NULL |
| 223 | ) |
| 224 | h2 = win32.CreateFile( |
| 225 | address, access, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL |
| 226 | ) |
| 227 | win32.SetNamedPipeHandleState( |
| 228 | h2, win32.PIPE_READMODE_MESSAGE, None, None |
| 229 | ) |
| 230 | |
| 231 | try: |
| 232 | win32.ConnectNamedPipe(h1, win32.NULL) |
| 233 | except WindowsError as e: |
| 234 | if e.args[0] != win32.ERROR_PIPE_CONNECTED: |
| 235 | raise |
| 236 | |
| 237 | c1 = _multiprocessing.PipeConnection(h1, writable=duplex) |
| 238 | c2 = _multiprocessing.PipeConnection(h2, readable=duplex) |
| 239 | |
| 240 | return c1, c2 |
| 241 | |
| 242 | # |
| 243 | # Definitions for connections based on sockets |
| 244 | # |
| 245 | |
| 246 | class SocketListener(object): |
| 247 | ''' |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 248 | Representation of a socket which is bound to an address and listening |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 249 | ''' |
| 250 | def __init__(self, address, family, backlog=1): |
| 251 | self._socket = socket.socket(getattr(socket, family)) |
Charles-François Natali | 992ca52 | 2012-02-04 14:55:53 +0100 | [diff] [blame] | 252 | try: |
| 253 | self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 254 | self._socket.bind(address) |
| 255 | self._socket.listen(backlog) |
| 256 | self._address = self._socket.getsockname() |
| 257 | except socket.error: |
| 258 | self._socket.close() |
| 259 | raise |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 260 | self._family = family |
| 261 | self._last_accepted = None |
| 262 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 263 | if family == 'AF_UNIX': |
| 264 | self._unlink = Finalize( |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 265 | self, os.unlink, args=(address,), exitpriority=0 |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 266 | ) |
| 267 | else: |
| 268 | self._unlink = None |
| 269 | |
| 270 | def accept(self): |
| 271 | s, self._last_accepted = self._socket.accept() |
| 272 | fd = duplicate(s.fileno()) |
| 273 | conn = _multiprocessing.Connection(fd) |
| 274 | s.close() |
| 275 | return conn |
| 276 | |
| 277 | def close(self): |
| 278 | self._socket.close() |
| 279 | if self._unlink is not None: |
| 280 | self._unlink() |
| 281 | |
| 282 | |
| 283 | def SocketClient(address): |
| 284 | ''' |
| 285 | Return a connection object connected to the socket given by `address` |
| 286 | ''' |
| 287 | family = address_type(address) |
Victor Stinner | 2b69506 | 2011-01-03 15:47:59 +0000 | [diff] [blame] | 288 | with socket.socket( getattr(socket, family) ) as s: |
| 289 | t = _init_timeout() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 290 | |
Victor Stinner | 2b69506 | 2011-01-03 15:47:59 +0000 | [diff] [blame] | 291 | while 1: |
| 292 | try: |
| 293 | s.connect(address) |
| 294 | except socket.error as e: |
| 295 | if e.args[0] != errno.ECONNREFUSED or _check_timeout(t): |
| 296 | debug('failed to connect to address %s', address) |
| 297 | raise |
| 298 | time.sleep(0.01) |
| 299 | else: |
| 300 | break |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 301 | else: |
Victor Stinner | 2b69506 | 2011-01-03 15:47:59 +0000 | [diff] [blame] | 302 | raise |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 303 | |
Victor Stinner | 2b69506 | 2011-01-03 15:47:59 +0000 | [diff] [blame] | 304 | fd = duplicate(s.fileno()) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 305 | conn = _multiprocessing.Connection(fd) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 306 | return conn |
| 307 | |
| 308 | # |
| 309 | # Definitions for connections based on named pipes |
| 310 | # |
| 311 | |
| 312 | if sys.platform == 'win32': |
| 313 | |
| 314 | class PipeListener(object): |
| 315 | ''' |
| 316 | Representation of a named pipe |
| 317 | ''' |
| 318 | def __init__(self, address, backlog=None): |
| 319 | self._address = address |
| 320 | handle = win32.CreateNamedPipe( |
| 321 | address, win32.PIPE_ACCESS_DUPLEX, |
| 322 | win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | |
| 323 | win32.PIPE_WAIT, |
| 324 | win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, |
| 325 | win32.NMPWAIT_WAIT_FOREVER, win32.NULL |
| 326 | ) |
| 327 | self._handle_queue = [handle] |
| 328 | self._last_accepted = None |
| 329 | |
| 330 | sub_debug('listener created with address=%r', self._address) |
| 331 | |
| 332 | self.close = Finalize( |
| 333 | self, PipeListener._finalize_pipe_listener, |
| 334 | args=(self._handle_queue, self._address), exitpriority=0 |
| 335 | ) |
| 336 | |
| 337 | def accept(self): |
| 338 | newhandle = win32.CreateNamedPipe( |
| 339 | self._address, win32.PIPE_ACCESS_DUPLEX, |
| 340 | win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | |
| 341 | win32.PIPE_WAIT, |
| 342 | win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, |
| 343 | win32.NMPWAIT_WAIT_FOREVER, win32.NULL |
| 344 | ) |
| 345 | self._handle_queue.append(newhandle) |
| 346 | handle = self._handle_queue.pop(0) |
| 347 | try: |
| 348 | win32.ConnectNamedPipe(handle, win32.NULL) |
| 349 | except WindowsError as e: |
| 350 | if e.args[0] != win32.ERROR_PIPE_CONNECTED: |
| 351 | raise |
| 352 | return _multiprocessing.PipeConnection(handle) |
| 353 | |
| 354 | @staticmethod |
| 355 | def _finalize_pipe_listener(queue, address): |
| 356 | sub_debug('closing listener with address=%r', address) |
| 357 | for handle in queue: |
| 358 | close(handle) |
| 359 | |
| 360 | def PipeClient(address): |
| 361 | ''' |
| 362 | Return a connection object connected to the pipe given by `address` |
| 363 | ''' |
Antoine Pitrou | 45d61a3 | 2009-11-13 22:35:18 +0000 | [diff] [blame] | 364 | t = _init_timeout() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 365 | while 1: |
| 366 | try: |
| 367 | win32.WaitNamedPipe(address, 1000) |
| 368 | h = win32.CreateFile( |
| 369 | address, win32.GENERIC_READ | win32.GENERIC_WRITE, |
| 370 | 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL |
| 371 | ) |
| 372 | except WindowsError as e: |
| 373 | if e.args[0] not in (win32.ERROR_SEM_TIMEOUT, |
Antoine Pitrou | 45d61a3 | 2009-11-13 22:35:18 +0000 | [diff] [blame] | 374 | win32.ERROR_PIPE_BUSY) or _check_timeout(t): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 375 | raise |
| 376 | else: |
| 377 | break |
| 378 | else: |
| 379 | raise |
| 380 | |
| 381 | win32.SetNamedPipeHandleState( |
| 382 | h, win32.PIPE_READMODE_MESSAGE, None, None |
| 383 | ) |
| 384 | return _multiprocessing.PipeConnection(h) |
| 385 | |
| 386 | # |
| 387 | # Authentication stuff |
| 388 | # |
| 389 | |
| 390 | MESSAGE_LENGTH = 20 |
| 391 | |
Benjamin Peterson | 1fcfe21 | 2008-06-25 12:54:22 +0000 | [diff] [blame] | 392 | CHALLENGE = b'#CHALLENGE#' |
| 393 | WELCOME = b'#WELCOME#' |
| 394 | FAILURE = b'#FAILURE#' |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 395 | |
| 396 | def deliver_challenge(connection, authkey): |
| 397 | import hmac |
| 398 | assert isinstance(authkey, bytes) |
| 399 | message = os.urandom(MESSAGE_LENGTH) |
| 400 | connection.send_bytes(CHALLENGE + message) |
| 401 | digest = hmac.new(authkey, message).digest() |
| 402 | response = connection.recv_bytes(256) # reject large message |
| 403 | if response == digest: |
| 404 | connection.send_bytes(WELCOME) |
| 405 | else: |
| 406 | connection.send_bytes(FAILURE) |
| 407 | raise AuthenticationError('digest received was wrong') |
| 408 | |
| 409 | def answer_challenge(connection, authkey): |
| 410 | import hmac |
| 411 | assert isinstance(authkey, bytes) |
| 412 | message = connection.recv_bytes(256) # reject large message |
| 413 | assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message |
| 414 | message = message[len(CHALLENGE):] |
| 415 | digest = hmac.new(authkey, message).digest() |
| 416 | connection.send_bytes(digest) |
| 417 | response = connection.recv_bytes(256) # reject large message |
| 418 | if response != WELCOME: |
| 419 | raise AuthenticationError('digest sent was rejected') |
| 420 | |
| 421 | # |
| 422 | # Support for using xmlrpclib for serialization |
| 423 | # |
| 424 | |
| 425 | class ConnectionWrapper(object): |
| 426 | def __init__(self, conn, dumps, loads): |
| 427 | self._conn = conn |
| 428 | self._dumps = dumps |
| 429 | self._loads = loads |
| 430 | for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'): |
| 431 | obj = getattr(conn, attr) |
| 432 | setattr(self, attr, obj) |
| 433 | def send(self, obj): |
| 434 | s = self._dumps(obj) |
| 435 | self._conn.send_bytes(s) |
| 436 | def recv(self): |
| 437 | s = self._conn.recv_bytes() |
| 438 | return self._loads(s) |
| 439 | |
| 440 | def _xml_dumps(obj): |
| 441 | return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf8') |
| 442 | |
| 443 | def _xml_loads(s): |
| 444 | (obj,), method = xmlrpclib.loads(s.decode('utf8')) |
| 445 | return obj |
| 446 | |
| 447 | class XmlListener(Listener): |
| 448 | def accept(self): |
| 449 | global xmlrpclib |
| 450 | import xmlrpc.client as xmlrpclib |
| 451 | obj = Listener.accept(self) |
| 452 | return ConnectionWrapper(obj, _xml_dumps, _xml_loads) |
| 453 | |
| 454 | def XmlClient(*args, **kwds): |
| 455 | global xmlrpclib |
| 456 | import xmlrpc.client as xmlrpclib |
| 457 | return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads) |