Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 1 | #
|
| 2 | # A higher level module for using sockets (or Windows named pipes)
|
| 3 | #
|
| 4 | # multiprocessing/connection.py
|
| 5 | #
|
| 6 | # Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
|
| 7 | #
|
| 8 |
|
| 9 | __all__ = [ 'Client', 'Listener', 'Pipe' ]
|
| 10 |
|
| 11 | import os
|
| 12 | import sys
|
| 13 | import socket
|
| 14 | import time
|
| 15 | import tempfile
|
| 16 | import itertools
|
| 17 |
|
| 18 | import _multiprocessing
|
| 19 | from multiprocessing import current_process
|
| 20 | from multiprocessing.util import get_temp_dir, Finalize, sub_debug, debug
|
| 21 | from multiprocessing.forking import duplicate, close
|
| 22 |
|
| 23 |
|
| 24 | #
|
| 25 | #
|
| 26 | #
|
| 27 |
|
| 28 | BUFSIZE = 8192
|
| 29 |
|
| 30 | _mmap_counter = itertools.count()
|
| 31 |
|
| 32 | default_family = 'AF_INET'
|
| 33 | families = ['AF_INET']
|
| 34 |
|
| 35 | if hasattr(socket, 'AF_UNIX'):
|
| 36 | default_family = 'AF_UNIX'
|
| 37 | families += ['AF_UNIX']
|
| 38 |
|
| 39 | if sys.platform == 'win32':
|
| 40 | default_family = 'AF_PIPE'
|
| 41 | families += ['AF_PIPE']
|
| 42 |
|
| 43 | #
|
| 44 | #
|
| 45 | #
|
| 46 |
|
| 47 | def arbitrary_address(family):
|
| 48 | '''
|
| 49 | Return an arbitrary free address for the given family
|
| 50 | '''
|
| 51 | if family == 'AF_INET':
|
| 52 | return ('localhost', 0)
|
Benjamin Peterson | dfd7949 | 2008-06-13 19:13:39 +0000 | [diff] [blame^] | 53 | elif family == 'AF_UNIX':
|
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 54 | return tempfile.mktemp(prefix='listener-', dir=get_temp_dir())
|
| 55 | elif family == 'AF_PIPE':
|
| 56 | return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' %
|
| 57 | (os.getpid(), _mmap_counter.next()))
|
| 58 | else:
|
| 59 | raise ValueError('unrecognized family')
|
| 60 |
|
| 61 |
|
| 62 | def address_type(address):
|
| 63 | '''
|
| 64 | Return the types of the address
|
| 65 |
|
| 66 | This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
|
| 67 | '''
|
| 68 | if type(address) == tuple:
|
| 69 | return 'AF_INET'
|
| 70 | elif type(address) is str and address.startswith('\\\\'):
|
| 71 | return 'AF_PIPE'
|
| 72 | elif type(address) is str:
|
| 73 | return 'AF_UNIX'
|
| 74 | else:
|
| 75 | raise ValueError('address type of %r unrecognized' % address)
|
| 76 |
|
| 77 | #
|
| 78 | # Public functions
|
| 79 | #
|
| 80 |
|
| 81 | class Listener(object):
|
| 82 | '''
|
| 83 | Returns a listener object.
|
| 84 |
|
| 85 | This is a wrapper for a bound socket which is 'listening' for
|
| 86 | connections, or for a Windows named pipe.
|
| 87 | '''
|
| 88 | def __init__(self, address=None, family=None, backlog=1, authkey=None):
|
| 89 | family = family or (address and address_type(address)) \
|
| 90 | or default_family
|
| 91 | address = address or arbitrary_address(family)
|
| 92 |
|
| 93 | if family == 'AF_PIPE':
|
| 94 | self._listener = PipeListener(address, backlog)
|
| 95 | else:
|
| 96 | self._listener = SocketListener(address, family, backlog)
|
| 97 |
|
| 98 | if authkey is not None and not isinstance(authkey, bytes):
|
| 99 | raise TypeError, 'authkey should be a byte string'
|
| 100 |
|
| 101 | self._authkey = authkey
|
| 102 |
|
| 103 | def accept(self):
|
| 104 | '''
|
| 105 | Accept a connection on the bound socket or named pipe of `self`.
|
| 106 |
|
| 107 | Returns a `Connection` object.
|
| 108 | '''
|
| 109 | c = self._listener.accept()
|
| 110 | if self._authkey:
|
| 111 | deliver_challenge(c, self._authkey)
|
| 112 | answer_challenge(c, self._authkey)
|
| 113 | return c
|
| 114 |
|
| 115 | def close(self):
|
| 116 | '''
|
| 117 | Close the bound socket or named pipe of `self`.
|
| 118 | '''
|
| 119 | return self._listener.close()
|
| 120 |
|
| 121 | address = property(lambda self: self._listener._address)
|
| 122 | last_accepted = property(lambda self: self._listener._last_accepted)
|
| 123 |
|
| 124 |
|
| 125 | def Client(address, family=None, authkey=None):
|
| 126 | '''
|
| 127 | Returns a connection to the address of a `Listener`
|
| 128 | '''
|
| 129 | family = family or address_type(address)
|
| 130 | if family == 'AF_PIPE':
|
| 131 | c = PipeClient(address)
|
| 132 | else:
|
| 133 | c = SocketClient(address)
|
| 134 |
|
| 135 | if authkey is not None and not isinstance(authkey, bytes):
|
| 136 | raise TypeError, 'authkey should be a byte string'
|
| 137 |
|
| 138 | if authkey is not None:
|
| 139 | answer_challenge(c, authkey)
|
| 140 | deliver_challenge(c, authkey)
|
| 141 |
|
| 142 | return c
|
| 143 |
|
| 144 |
|
| 145 | if sys.platform != 'win32':
|
| 146 |
|
| 147 | def Pipe(duplex=True):
|
| 148 | '''
|
| 149 | Returns pair of connection objects at either end of a pipe
|
| 150 | '''
|
| 151 | if duplex:
|
| 152 | s1, s2 = socket.socketpair()
|
| 153 | c1 = _multiprocessing.Connection(os.dup(s1.fileno()))
|
| 154 | c2 = _multiprocessing.Connection(os.dup(s2.fileno()))
|
| 155 | s1.close()
|
| 156 | s2.close()
|
| 157 | else:
|
| 158 | fd1, fd2 = os.pipe()
|
| 159 | c1 = _multiprocessing.Connection(fd1, writable=False)
|
| 160 | c2 = _multiprocessing.Connection(fd2, readable=False)
|
| 161 |
|
| 162 | return c1, c2
|
Benjamin Peterson | dfd7949 | 2008-06-13 19:13:39 +0000 | [diff] [blame^] | 163 |
|
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 164 | else:
|
| 165 |
|
| 166 | from ._multiprocessing import win32
|
| 167 |
|
| 168 | def Pipe(duplex=True):
|
| 169 | '''
|
| 170 | Returns pair of connection objects at either end of a pipe
|
| 171 | '''
|
| 172 | address = arbitrary_address('AF_PIPE')
|
| 173 | if duplex:
|
| 174 | openmode = win32.PIPE_ACCESS_DUPLEX
|
| 175 | access = win32.GENERIC_READ | win32.GENERIC_WRITE
|
| 176 | obsize, ibsize = BUFSIZE, BUFSIZE
|
| 177 | else:
|
| 178 | openmode = win32.PIPE_ACCESS_INBOUND
|
| 179 | access = win32.GENERIC_WRITE
|
| 180 | obsize, ibsize = 0, BUFSIZE
|
| 181 |
|
| 182 | h1 = win32.CreateNamedPipe(
|
| 183 | address, openmode,
|
| 184 | win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE |
|
| 185 | win32.PIPE_WAIT,
|
| 186 | 1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, win32.NULL
|
| 187 | )
|
| 188 | h2 = win32.CreateFile(
|
| 189 | address, access, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL
|
| 190 | )
|
| 191 | win32.SetNamedPipeHandleState(
|
| 192 | h2, win32.PIPE_READMODE_MESSAGE, None, None
|
| 193 | )
|
| 194 |
|
| 195 | try:
|
| 196 | win32.ConnectNamedPipe(h1, win32.NULL)
|
| 197 | except WindowsError, e:
|
| 198 | if e.args[0] != win32.ERROR_PIPE_CONNECTED:
|
| 199 | raise
|
| 200 |
|
| 201 | c1 = _multiprocessing.PipeConnection(h1, writable=duplex)
|
| 202 | c2 = _multiprocessing.PipeConnection(h2, readable=duplex)
|
Benjamin Peterson | dfd7949 | 2008-06-13 19:13:39 +0000 | [diff] [blame^] | 203 |
|
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 204 | return c1, c2
|
| 205 |
|
| 206 | #
|
| 207 | # Definitions for connections based on sockets
|
| 208 | #
|
| 209 |
|
| 210 | class SocketListener(object):
|
| 211 | '''
|
| 212 | Represtation of a socket which is bound to an address and listening
|
| 213 | '''
|
| 214 | def __init__(self, address, family, backlog=1):
|
| 215 | self._socket = socket.socket(getattr(socket, family))
|
| 216 | self._socket.bind(address)
|
| 217 | self._socket.listen(backlog)
|
| 218 | address = self._socket.getsockname()
|
| 219 | if type(address) is tuple:
|
| 220 | address = (socket.getfqdn(address[0]),) + address[1:]
|
| 221 | self._address = address
|
| 222 | self._family = family
|
| 223 | self._last_accepted = None
|
| 224 |
|
| 225 | sub_debug('listener bound to address %r', self._address)
|
| 226 |
|
| 227 | if family == 'AF_UNIX':
|
| 228 | self._unlink = Finalize(
|
| 229 | self, os.unlink, args=(self._address,), exitpriority=0
|
| 230 | )
|
| 231 | else:
|
| 232 | self._unlink = None
|
| 233 |
|
| 234 | def accept(self):
|
| 235 | s, self._last_accepted = self._socket.accept()
|
| 236 | fd = duplicate(s.fileno())
|
| 237 | conn = _multiprocessing.Connection(fd)
|
| 238 | s.close()
|
| 239 | return conn
|
| 240 |
|
| 241 | def close(self):
|
| 242 | self._socket.close()
|
| 243 | if self._unlink is not None:
|
| 244 | self._unlink()
|
| 245 |
|
| 246 |
|
| 247 | def SocketClient(address):
|
| 248 | '''
|
| 249 | Return a connection object connected to the socket given by `address`
|
| 250 | '''
|
| 251 | family = address_type(address)
|
| 252 | s = socket.socket( getattr(socket, family) )
|
| 253 |
|
| 254 | while 1:
|
| 255 | try:
|
| 256 | s.connect(address)
|
| 257 | except socket.error, e:
|
| 258 | if e.args[0] != 10061: # 10061 => connection refused
|
| 259 | debug('failed to connect to address %s', address)
|
| 260 | raise
|
| 261 | time.sleep(0.01)
|
| 262 | else:
|
| 263 | break
|
| 264 | else:
|
| 265 | raise
|
| 266 |
|
| 267 | fd = duplicate(s.fileno())
|
| 268 | conn = _multiprocessing.Connection(fd)
|
| 269 | s.close()
|
| 270 | return conn
|
| 271 |
|
| 272 | #
|
| 273 | # Definitions for connections based on named pipes
|
| 274 | #
|
| 275 |
|
| 276 | if sys.platform == 'win32':
|
| 277 |
|
| 278 | class PipeListener(object):
|
| 279 | '''
|
| 280 | Representation of a named pipe
|
| 281 | '''
|
| 282 | def __init__(self, address, backlog=None):
|
| 283 | self._address = address
|
| 284 | handle = win32.CreateNamedPipe(
|
| 285 | address, win32.PIPE_ACCESS_DUPLEX,
|
| 286 | win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE |
|
| 287 | win32.PIPE_WAIT,
|
| 288 | win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
|
| 289 | win32.NMPWAIT_WAIT_FOREVER, win32.NULL
|
| 290 | )
|
| 291 | self._handle_queue = [handle]
|
| 292 | self._last_accepted = None
|
Benjamin Peterson | dfd7949 | 2008-06-13 19:13:39 +0000 | [diff] [blame^] | 293 |
|
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 294 | sub_debug('listener created with address=%r', self._address)
|
| 295 |
|
| 296 | self.close = Finalize(
|
| 297 | self, PipeListener._finalize_pipe_listener,
|
| 298 | args=(self._handle_queue, self._address), exitpriority=0
|
| 299 | )
|
Benjamin Peterson | dfd7949 | 2008-06-13 19:13:39 +0000 | [diff] [blame^] | 300 |
|
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 301 | def accept(self):
|
| 302 | newhandle = win32.CreateNamedPipe(
|
| 303 | self._address, win32.PIPE_ACCESS_DUPLEX,
|
| 304 | win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE |
|
| 305 | win32.PIPE_WAIT,
|
| 306 | win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
|
| 307 | win32.NMPWAIT_WAIT_FOREVER, win32.NULL
|
| 308 | )
|
| 309 | self._handle_queue.append(newhandle)
|
| 310 | handle = self._handle_queue.pop(0)
|
| 311 | try:
|
| 312 | win32.ConnectNamedPipe(handle, win32.NULL)
|
| 313 | except WindowsError, e:
|
| 314 | if e.args[0] != win32.ERROR_PIPE_CONNECTED:
|
| 315 | raise
|
| 316 | return _multiprocessing.PipeConnection(handle)
|
| 317 |
|
| 318 | @staticmethod
|
| 319 | def _finalize_pipe_listener(queue, address):
|
| 320 | sub_debug('closing listener with address=%r', address)
|
| 321 | for handle in queue:
|
| 322 | close(handle)
|
Benjamin Peterson | dfd7949 | 2008-06-13 19:13:39 +0000 | [diff] [blame^] | 323 |
|
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 324 | def PipeClient(address):
|
| 325 | '''
|
| 326 | Return a connection object connected to the pipe given by `address`
|
| 327 | '''
|
| 328 | while 1:
|
| 329 | try:
|
| 330 | win32.WaitNamedPipe(address, 1000)
|
| 331 | h = win32.CreateFile(
|
| 332 | address, win32.GENERIC_READ | win32.GENERIC_WRITE,
|
| 333 | 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL
|
| 334 | )
|
| 335 | except WindowsError, e:
|
| 336 | if e.args[0] not in (win32.ERROR_SEM_TIMEOUT,
|
| 337 | win32.ERROR_PIPE_BUSY):
|
| 338 | raise
|
| 339 | else:
|
| 340 | break
|
| 341 | else:
|
| 342 | raise
|
| 343 |
|
| 344 | win32.SetNamedPipeHandleState(
|
| 345 | h, win32.PIPE_READMODE_MESSAGE, None, None
|
| 346 | )
|
| 347 | return _multiprocessing.PipeConnection(h)
|
| 348 |
|
| 349 | #
|
| 350 | # Authentication stuff
|
| 351 | #
|
| 352 |
|
| 353 | MESSAGE_LENGTH = 20
|
| 354 |
|
| 355 | CHALLENGE = '#CHALLENGE#'
|
| 356 | WELCOME = '#WELCOME#'
|
| 357 | FAILURE = '#FAILURE#'
|
| 358 |
|
| 359 | if sys.version_info >= (3, 0): # XXX can use bytes literals in 2.6/3.0
|
| 360 | CHALLENGE = CHALLENGE.encode('ascii')
|
| 361 | WELCOME = WELCOME.encode('ascii')
|
| 362 | FAILURE = FAILURE.encode('ascii')
|
| 363 |
|
| 364 | def deliver_challenge(connection, authkey):
|
| 365 | import hmac
|
| 366 | assert isinstance(authkey, bytes)
|
| 367 | message = os.urandom(MESSAGE_LENGTH)
|
| 368 | connection.send_bytes(CHALLENGE + message)
|
| 369 | digest = hmac.new(authkey, message).digest()
|
| 370 | response = connection.recv_bytes(256) # reject large message
|
| 371 | if response == digest:
|
| 372 | connection.send_bytes(WELCOME)
|
| 373 | else:
|
| 374 | connection.send_bytes(FAILURE)
|
| 375 | raise AuthenticationError('digest received was wrong')
|
| 376 |
|
| 377 | def answer_challenge(connection, authkey):
|
| 378 | import hmac
|
| 379 | assert isinstance(authkey, bytes)
|
| 380 | message = connection.recv_bytes(256) # reject large message
|
| 381 | assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
|
| 382 | message = message[len(CHALLENGE):]
|
| 383 | digest = hmac.new(authkey, message).digest()
|
| 384 | connection.send_bytes(digest)
|
| 385 | response = connection.recv_bytes(256) # reject large message
|
| 386 | if response != WELCOME:
|
| 387 | raise AuthenticationError('digest sent was rejected')
|
| 388 |
|
| 389 | #
|
| 390 | # Support for using xmlrpclib for serialization
|
| 391 | #
|
| 392 |
|
| 393 | class ConnectionWrapper(object):
|
| 394 | def __init__(self, conn, dumps, loads):
|
| 395 | self._conn = conn
|
| 396 | self._dumps = dumps
|
| 397 | self._loads = loads
|
| 398 | for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'):
|
| 399 | obj = getattr(conn, attr)
|
Benjamin Peterson | dfd7949 | 2008-06-13 19:13:39 +0000 | [diff] [blame^] | 400 | setattr(self, attr, obj)
|
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 401 | def send(self, obj):
|
| 402 | s = self._dumps(obj)
|
| 403 | self._conn.send_bytes(s)
|
| 404 | def recv(self):
|
| 405 | s = self._conn.recv_bytes()
|
| 406 | return self._loads(s)
|
| 407 |
|
| 408 | def _xml_dumps(obj):
|
| 409 | return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf8')
|
| 410 |
|
| 411 | def _xml_loads(s):
|
| 412 | (obj,), method = xmlrpclib.loads(s.decode('utf8'))
|
| 413 | return obj
|
| 414 |
|
| 415 | class XmlListener(Listener):
|
| 416 | def accept(self):
|
| 417 | global xmlrpclib
|
| 418 | import xmlrpclib
|
| 419 | obj = Listener.accept(self)
|
| 420 | return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
|
| 421 |
|
| 422 | def XmlClient(*args, **kwds):
|
| 423 | global xmlrpclib
|
| 424 | import xmlrpclib
|
| 425 | return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)
|