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 | |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 37 | import io |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 38 | import os |
| 39 | import sys |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 40 | import pickle |
| 41 | import select |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 42 | import socket |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 43 | import struct |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 44 | import errno |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 45 | import time |
| 46 | import tempfile |
| 47 | import itertools |
| 48 | |
| 49 | import _multiprocessing |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 50 | from multiprocessing import current_process, AuthenticationError, BufferTooShort |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 51 | from multiprocessing.util import ( |
| 52 | get_temp_dir, Finalize, sub_debug, debug, _eintr_retry) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 53 | try: |
| 54 | from _multiprocessing import win32 |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 55 | from _subprocess import WAIT_OBJECT_0, WAIT_TIMEOUT, INFINITE |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 56 | except ImportError: |
| 57 | if sys.platform == 'win32': |
| 58 | raise |
| 59 | win32 = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 60 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 61 | _select = _eintr_retry(select.select) |
| 62 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 63 | # |
| 64 | # |
| 65 | # |
| 66 | |
| 67 | BUFSIZE = 8192 |
Antoine Pitrou | 45d61a3 | 2009-11-13 22:35:18 +0000 | [diff] [blame] | 68 | # A very generous timeout when it comes to local connections... |
| 69 | CONNECTION_TIMEOUT = 20. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 70 | |
| 71 | _mmap_counter = itertools.count() |
| 72 | |
| 73 | default_family = 'AF_INET' |
| 74 | families = ['AF_INET'] |
| 75 | |
| 76 | if hasattr(socket, 'AF_UNIX'): |
| 77 | default_family = 'AF_UNIX' |
| 78 | families += ['AF_UNIX'] |
| 79 | |
| 80 | if sys.platform == 'win32': |
| 81 | default_family = 'AF_PIPE' |
| 82 | families += ['AF_PIPE'] |
| 83 | |
Antoine Pitrou | 45d61a3 | 2009-11-13 22:35:18 +0000 | [diff] [blame] | 84 | |
| 85 | def _init_timeout(timeout=CONNECTION_TIMEOUT): |
| 86 | return time.time() + timeout |
| 87 | |
| 88 | def _check_timeout(t): |
| 89 | return time.time() > t |
| 90 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 91 | # |
| 92 | # |
| 93 | # |
| 94 | |
| 95 | def arbitrary_address(family): |
| 96 | ''' |
| 97 | Return an arbitrary free address for the given family |
| 98 | ''' |
| 99 | if family == 'AF_INET': |
| 100 | return ('localhost', 0) |
| 101 | elif family == 'AF_UNIX': |
| 102 | return tempfile.mktemp(prefix='listener-', dir=get_temp_dir()) |
| 103 | elif family == 'AF_PIPE': |
| 104 | return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' % |
| 105 | (os.getpid(), next(_mmap_counter))) |
| 106 | else: |
| 107 | raise ValueError('unrecognized family') |
| 108 | |
| 109 | |
| 110 | def address_type(address): |
| 111 | ''' |
| 112 | Return the types of the address |
| 113 | |
| 114 | This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE' |
| 115 | ''' |
| 116 | if type(address) == tuple: |
| 117 | return 'AF_INET' |
| 118 | elif type(address) is str and address.startswith('\\\\'): |
| 119 | return 'AF_PIPE' |
| 120 | elif type(address) is str: |
| 121 | return 'AF_UNIX' |
| 122 | else: |
| 123 | raise ValueError('address type of %r unrecognized' % address) |
| 124 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 125 | |
| 126 | class SentinelReady(Exception): |
| 127 | """ |
| 128 | Raised when a sentinel is ready when polling. |
| 129 | """ |
| 130 | def __init__(self, *args): |
| 131 | Exception.__init__(self, *args) |
| 132 | self.sentinels = args[0] |
| 133 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 134 | # |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 135 | # Connection classes |
| 136 | # |
| 137 | |
| 138 | class _ConnectionBase: |
| 139 | _handle = None |
| 140 | |
| 141 | def __init__(self, handle, readable=True, writable=True): |
| 142 | handle = handle.__index__() |
| 143 | if handle < 0: |
| 144 | raise ValueError("invalid handle") |
| 145 | if not readable and not writable: |
| 146 | raise ValueError( |
| 147 | "at least one of `readable` and `writable` must be True") |
| 148 | self._handle = handle |
| 149 | self._readable = readable |
| 150 | self._writable = writable |
| 151 | |
Antoine Pitrou | 6000120 | 2011-07-09 01:03:46 +0200 | [diff] [blame] | 152 | # XXX should we use util.Finalize instead of a __del__? |
| 153 | |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 154 | def __del__(self): |
| 155 | if self._handle is not None: |
| 156 | self._close() |
| 157 | |
| 158 | def _check_closed(self): |
| 159 | if self._handle is None: |
| 160 | raise IOError("handle is closed") |
| 161 | |
| 162 | def _check_readable(self): |
| 163 | if not self._readable: |
| 164 | raise IOError("connection is write-only") |
| 165 | |
| 166 | def _check_writable(self): |
| 167 | if not self._writable: |
| 168 | raise IOError("connection is read-only") |
| 169 | |
| 170 | def _bad_message_length(self): |
| 171 | if self._writable: |
| 172 | self._readable = False |
| 173 | else: |
| 174 | self.close() |
| 175 | raise IOError("bad message length") |
| 176 | |
| 177 | @property |
| 178 | def closed(self): |
| 179 | """True if the connection is closed""" |
| 180 | return self._handle is None |
| 181 | |
| 182 | @property |
| 183 | def readable(self): |
| 184 | """True if the connection is readable""" |
| 185 | return self._readable |
| 186 | |
| 187 | @property |
| 188 | def writable(self): |
| 189 | """True if the connection is writable""" |
| 190 | return self._writable |
| 191 | |
| 192 | def fileno(self): |
| 193 | """File descriptor or handle of the connection""" |
| 194 | self._check_closed() |
| 195 | return self._handle |
| 196 | |
| 197 | def close(self): |
| 198 | """Close the connection""" |
| 199 | if self._handle is not None: |
| 200 | try: |
| 201 | self._close() |
| 202 | finally: |
| 203 | self._handle = None |
| 204 | |
| 205 | def send_bytes(self, buf, offset=0, size=None): |
| 206 | """Send the bytes data from a bytes-like object""" |
| 207 | self._check_closed() |
| 208 | self._check_writable() |
| 209 | m = memoryview(buf) |
| 210 | # HACK for byte-indexing of non-bytewise buffers (e.g. array.array) |
| 211 | if m.itemsize > 1: |
| 212 | m = memoryview(bytes(m)) |
| 213 | n = len(m) |
| 214 | if offset < 0: |
| 215 | raise ValueError("offset is negative") |
| 216 | if n < offset: |
| 217 | raise ValueError("buffer length < offset") |
| 218 | if size is None: |
| 219 | size = n - offset |
| 220 | elif size < 0: |
| 221 | raise ValueError("size is negative") |
| 222 | elif offset + size > n: |
| 223 | raise ValueError("buffer length < offset + size") |
| 224 | self._send_bytes(m[offset:offset + size]) |
| 225 | |
| 226 | def send(self, obj): |
| 227 | """Send a (picklable) object""" |
| 228 | self._check_closed() |
| 229 | self._check_writable() |
| 230 | buf = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) |
| 231 | self._send_bytes(memoryview(buf)) |
| 232 | |
| 233 | def recv_bytes(self, maxlength=None): |
| 234 | """ |
| 235 | Receive bytes data as a bytes object. |
| 236 | """ |
| 237 | self._check_closed() |
| 238 | self._check_readable() |
| 239 | if maxlength is not None and maxlength < 0: |
| 240 | raise ValueError("negative maxlength") |
| 241 | buf = self._recv_bytes(maxlength) |
| 242 | if buf is None: |
| 243 | self._bad_message_length() |
| 244 | return buf.getvalue() |
| 245 | |
| 246 | def recv_bytes_into(self, buf, offset=0): |
| 247 | """ |
| 248 | Receive bytes data into a writeable buffer-like object. |
| 249 | Return the number of bytes read. |
| 250 | """ |
| 251 | self._check_closed() |
| 252 | self._check_readable() |
| 253 | with memoryview(buf) as m: |
| 254 | # Get bytesize of arbitrary buffer |
| 255 | itemsize = m.itemsize |
| 256 | bytesize = itemsize * len(m) |
| 257 | if offset < 0: |
| 258 | raise ValueError("negative offset") |
| 259 | elif offset > bytesize: |
| 260 | raise ValueError("offset too large") |
| 261 | result = self._recv_bytes() |
| 262 | size = result.tell() |
| 263 | if bytesize < offset + size: |
| 264 | raise BufferTooShort(result.getvalue()) |
| 265 | # Message can fit in dest |
| 266 | result.seek(0) |
| 267 | result.readinto(m[offset // itemsize : |
| 268 | (offset + size) // itemsize]) |
| 269 | return size |
| 270 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 271 | def recv(self, sentinels=None): |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 272 | """Receive a (picklable) object""" |
| 273 | self._check_closed() |
| 274 | self._check_readable() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 275 | buf = self._recv_bytes(sentinels=sentinels) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 276 | return pickle.loads(buf.getbuffer()) |
| 277 | |
| 278 | def poll(self, timeout=0.0): |
| 279 | """Whether there is any input available to be read""" |
| 280 | self._check_closed() |
| 281 | self._check_readable() |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 282 | return self._poll(timeout) |
| 283 | |
| 284 | |
| 285 | if win32: |
| 286 | |
| 287 | class PipeConnection(_ConnectionBase): |
| 288 | """ |
| 289 | Connection class based on a Windows named pipe. |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 290 | Overlapped I/O is used, so the handles must have been created |
| 291 | with FILE_FLAG_OVERLAPPED. |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 292 | """ |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 293 | _buffered = b'' |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 294 | |
Antoine Pitrou | 71a28a9 | 2011-07-09 01:03:00 +0200 | [diff] [blame] | 295 | def _close(self, _CloseHandle=win32.CloseHandle): |
| 296 | _CloseHandle(self._handle) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 297 | |
| 298 | def _send_bytes(self, buf): |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 299 | overlapped = win32.WriteFile(self._handle, buf, overlapped=True) |
| 300 | nwritten, complete = overlapped.GetOverlappedResult(True) |
| 301 | assert complete |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 302 | assert nwritten == len(buf) |
| 303 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 304 | def _recv_bytes(self, maxsize=None, sentinels=()): |
| 305 | if sentinels: |
| 306 | self._poll(-1.0, sentinels) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 307 | buf = io.BytesIO() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 308 | firstchunk = self._buffered |
| 309 | if firstchunk: |
| 310 | lenfirstchunk = len(firstchunk) |
| 311 | buf.write(firstchunk) |
| 312 | self._buffered = b'' |
| 313 | else: |
| 314 | # A reasonable size for the first chunk transfer |
| 315 | bufsize = 128 |
| 316 | if maxsize is not None and maxsize < bufsize: |
| 317 | bufsize = maxsize |
| 318 | try: |
| 319 | overlapped = win32.ReadFile(self._handle, bufsize, overlapped=True) |
| 320 | lenfirstchunk, complete = overlapped.GetOverlappedResult(True) |
| 321 | firstchunk = overlapped.getbuffer() |
| 322 | assert lenfirstchunk == len(firstchunk) |
| 323 | except IOError as e: |
| 324 | if e.errno == win32.ERROR_BROKEN_PIPE: |
| 325 | raise EOFError |
| 326 | raise |
| 327 | buf.write(firstchunk) |
| 328 | if complete: |
| 329 | return buf |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 330 | navail, nleft = win32.PeekNamedPipe(self._handle) |
| 331 | if maxsize is not None and lenfirstchunk + nleft > maxsize: |
| 332 | return None |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 333 | if nleft > 0: |
| 334 | overlapped = win32.ReadFile(self._handle, nleft, overlapped=True) |
| 335 | res, complete = overlapped.GetOverlappedResult(True) |
| 336 | assert res == nleft |
| 337 | assert complete |
| 338 | buf.write(overlapped.getbuffer()) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 339 | return buf |
| 340 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 341 | def _poll(self, timeout, sentinels=()): |
| 342 | # Fast non-blocking path |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 343 | navail, nleft = win32.PeekNamedPipe(self._handle) |
| 344 | if navail > 0: |
| 345 | return True |
| 346 | elif timeout == 0.0: |
| 347 | return False |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 348 | # Blocking: use overlapped I/O |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 349 | if timeout < 0.0: |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 350 | timeout = INFINITE |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 351 | else: |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 352 | timeout = int(timeout * 1000 + 0.5) |
| 353 | overlapped = win32.ReadFile(self._handle, 1, overlapped=True) |
| 354 | try: |
| 355 | handles = [overlapped.event] |
| 356 | handles += sentinels |
| 357 | res = win32.WaitForMultipleObjects(handles, False, timeout) |
| 358 | finally: |
| 359 | # Always cancel overlapped I/O in the same thread |
| 360 | # (because CancelIoEx() appears only in Vista) |
| 361 | overlapped.cancel() |
| 362 | if res == WAIT_TIMEOUT: |
| 363 | return False |
| 364 | idx = res - WAIT_OBJECT_0 |
| 365 | if idx == 0: |
| 366 | # I/O was successful, store received data |
| 367 | overlapped.GetOverlappedResult(True) |
| 368 | self._buffered += overlapped.getbuffer() |
| 369 | return True |
| 370 | assert 0 < idx < len(handles) |
| 371 | raise SentinelReady([handles[idx]]) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 372 | |
| 373 | |
| 374 | class Connection(_ConnectionBase): |
| 375 | """ |
| 376 | Connection class based on an arbitrary file descriptor (Unix only), or |
| 377 | a socket handle (Windows). |
| 378 | """ |
| 379 | |
| 380 | if win32: |
Antoine Pitrou | 71a28a9 | 2011-07-09 01:03:00 +0200 | [diff] [blame] | 381 | def _close(self, _close=win32.closesocket): |
| 382 | _close(self._handle) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 383 | _write = win32.send |
| 384 | _read = win32.recv |
| 385 | else: |
Antoine Pitrou | 71a28a9 | 2011-07-09 01:03:00 +0200 | [diff] [blame] | 386 | def _close(self, _close=os.close): |
| 387 | _close(self._handle) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 388 | _write = os.write |
| 389 | _read = os.read |
| 390 | |
| 391 | def _send(self, buf, write=_write): |
| 392 | remaining = len(buf) |
| 393 | while True: |
| 394 | n = write(self._handle, buf) |
| 395 | remaining -= n |
| 396 | if remaining == 0: |
| 397 | break |
| 398 | buf = buf[n:] |
| 399 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 400 | def _recv(self, size, sentinels=(), read=_read): |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 401 | buf = io.BytesIO() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 402 | handle = self._handle |
| 403 | if sentinels: |
| 404 | handles = [handle] + sentinels |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 405 | remaining = size |
| 406 | while remaining > 0: |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 407 | if sentinels: |
| 408 | r = _select(handles, [], [])[0] |
| 409 | if handle not in r: |
| 410 | raise SentinelReady(r) |
| 411 | chunk = read(handle, remaining) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 412 | n = len(chunk) |
| 413 | if n == 0: |
| 414 | if remaining == size: |
| 415 | raise EOFError |
| 416 | else: |
| 417 | raise IOError("got end of file during message") |
| 418 | buf.write(chunk) |
| 419 | remaining -= n |
| 420 | return buf |
| 421 | |
| 422 | def _send_bytes(self, buf): |
| 423 | # For wire compatibility with 3.2 and lower |
| 424 | n = len(buf) |
Charles-François Natali | 225aa4f | 2011-09-20 19:27:39 +0200 | [diff] [blame^] | 425 | self._send(struct.pack("!i", n)) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 426 | # The condition is necessary to avoid "broken pipe" errors |
| 427 | # when sending a 0-length buffer if the other end closed the pipe. |
| 428 | if n > 0: |
| 429 | self._send(buf) |
| 430 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 431 | def _recv_bytes(self, maxsize=None, sentinels=()): |
| 432 | buf = self._recv(4, sentinels) |
Charles-François Natali | 225aa4f | 2011-09-20 19:27:39 +0200 | [diff] [blame^] | 433 | size, = struct.unpack("!i", buf.getvalue()) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 434 | if maxsize is not None and size > maxsize: |
| 435 | return None |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 436 | return self._recv(size, sentinels) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 437 | |
| 438 | def _poll(self, timeout): |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 439 | if timeout < 0.0: |
| 440 | timeout = None |
| 441 | r = _select([self._handle], [], [], timeout)[0] |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 442 | return bool(r) |
| 443 | |
| 444 | |
| 445 | # |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 446 | # Public functions |
| 447 | # |
| 448 | |
| 449 | class Listener(object): |
| 450 | ''' |
| 451 | Returns a listener object. |
| 452 | |
| 453 | This is a wrapper for a bound socket which is 'listening' for |
| 454 | connections, or for a Windows named pipe. |
| 455 | ''' |
| 456 | def __init__(self, address=None, family=None, backlog=1, authkey=None): |
| 457 | family = family or (address and address_type(address)) \ |
| 458 | or default_family |
| 459 | address = address or arbitrary_address(family) |
| 460 | |
| 461 | if family == 'AF_PIPE': |
| 462 | self._listener = PipeListener(address, backlog) |
| 463 | else: |
| 464 | self._listener = SocketListener(address, family, backlog) |
| 465 | |
| 466 | if authkey is not None and not isinstance(authkey, bytes): |
| 467 | raise TypeError('authkey should be a byte string') |
| 468 | |
| 469 | self._authkey = authkey |
| 470 | |
| 471 | def accept(self): |
| 472 | ''' |
| 473 | Accept a connection on the bound socket or named pipe of `self`. |
| 474 | |
| 475 | Returns a `Connection` object. |
| 476 | ''' |
| 477 | c = self._listener.accept() |
| 478 | if self._authkey: |
| 479 | deliver_challenge(c, self._authkey) |
| 480 | answer_challenge(c, self._authkey) |
| 481 | return c |
| 482 | |
| 483 | def close(self): |
| 484 | ''' |
| 485 | Close the bound socket or named pipe of `self`. |
| 486 | ''' |
| 487 | return self._listener.close() |
| 488 | |
| 489 | address = property(lambda self: self._listener._address) |
| 490 | last_accepted = property(lambda self: self._listener._last_accepted) |
| 491 | |
| 492 | |
| 493 | def Client(address, family=None, authkey=None): |
| 494 | ''' |
| 495 | Returns a connection to the address of a `Listener` |
| 496 | ''' |
| 497 | family = family or address_type(address) |
| 498 | if family == 'AF_PIPE': |
| 499 | c = PipeClient(address) |
| 500 | else: |
| 501 | c = SocketClient(address) |
| 502 | |
| 503 | if authkey is not None and not isinstance(authkey, bytes): |
| 504 | raise TypeError('authkey should be a byte string') |
| 505 | |
| 506 | if authkey is not None: |
| 507 | answer_challenge(c, authkey) |
| 508 | deliver_challenge(c, authkey) |
| 509 | |
| 510 | return c |
| 511 | |
| 512 | |
| 513 | if sys.platform != 'win32': |
| 514 | |
| 515 | def Pipe(duplex=True): |
| 516 | ''' |
| 517 | Returns pair of connection objects at either end of a pipe |
| 518 | ''' |
| 519 | if duplex: |
| 520 | s1, s2 = socket.socketpair() |
Antoine Pitrou | 5aa878c | 2011-05-09 21:00:28 +0200 | [diff] [blame] | 521 | c1 = Connection(s1.detach()) |
| 522 | c2 = Connection(s2.detach()) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 523 | else: |
| 524 | fd1, fd2 = os.pipe() |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 525 | c1 = Connection(fd1, writable=False) |
| 526 | c2 = Connection(fd2, readable=False) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 527 | |
| 528 | return c1, c2 |
| 529 | |
| 530 | else: |
| 531 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 532 | def Pipe(duplex=True): |
| 533 | ''' |
| 534 | Returns pair of connection objects at either end of a pipe |
| 535 | ''' |
| 536 | address = arbitrary_address('AF_PIPE') |
| 537 | if duplex: |
| 538 | openmode = win32.PIPE_ACCESS_DUPLEX |
| 539 | access = win32.GENERIC_READ | win32.GENERIC_WRITE |
| 540 | obsize, ibsize = BUFSIZE, BUFSIZE |
| 541 | else: |
| 542 | openmode = win32.PIPE_ACCESS_INBOUND |
| 543 | access = win32.GENERIC_WRITE |
| 544 | obsize, ibsize = 0, BUFSIZE |
| 545 | |
| 546 | h1 = win32.CreateNamedPipe( |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 547 | address, openmode | win32.FILE_FLAG_OVERLAPPED, |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 548 | win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | |
| 549 | win32.PIPE_WAIT, |
| 550 | 1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, win32.NULL |
| 551 | ) |
| 552 | h2 = win32.CreateFile( |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 553 | address, access, 0, win32.NULL, win32.OPEN_EXISTING, |
| 554 | win32.FILE_FLAG_OVERLAPPED, win32.NULL |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 555 | ) |
| 556 | win32.SetNamedPipeHandleState( |
| 557 | h2, win32.PIPE_READMODE_MESSAGE, None, None |
| 558 | ) |
| 559 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 560 | overlapped = win32.ConnectNamedPipe(h1, overlapped=True) |
| 561 | overlapped.GetOverlappedResult(True) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 562 | |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 563 | c1 = PipeConnection(h1, writable=duplex) |
| 564 | c2 = PipeConnection(h2, readable=duplex) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 565 | |
| 566 | return c1, c2 |
| 567 | |
| 568 | # |
| 569 | # Definitions for connections based on sockets |
| 570 | # |
| 571 | |
| 572 | class SocketListener(object): |
| 573 | ''' |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 574 | Representation of a socket which is bound to an address and listening |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 575 | ''' |
| 576 | def __init__(self, address, family, backlog=1): |
| 577 | self._socket = socket.socket(getattr(socket, family)) |
Jesse Noller | c5d28a0 | 2009-03-30 16:37:36 +0000 | [diff] [blame] | 578 | self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 579 | self._socket.bind(address) |
| 580 | self._socket.listen(backlog) |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 581 | self._address = self._socket.getsockname() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 582 | self._family = family |
| 583 | self._last_accepted = None |
| 584 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 585 | if family == 'AF_UNIX': |
| 586 | self._unlink = Finalize( |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 587 | self, os.unlink, args=(address,), exitpriority=0 |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 588 | ) |
| 589 | else: |
| 590 | self._unlink = None |
| 591 | |
| 592 | def accept(self): |
| 593 | s, self._last_accepted = self._socket.accept() |
| 594 | fd = duplicate(s.fileno()) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 595 | conn = Connection(fd) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 596 | s.close() |
| 597 | return conn |
| 598 | |
| 599 | def close(self): |
| 600 | self._socket.close() |
| 601 | if self._unlink is not None: |
| 602 | self._unlink() |
| 603 | |
| 604 | |
| 605 | def SocketClient(address): |
| 606 | ''' |
| 607 | Return a connection object connected to the socket given by `address` |
| 608 | ''' |
| 609 | family = address_type(address) |
Victor Stinner | 2b69506 | 2011-01-03 15:47:59 +0000 | [diff] [blame] | 610 | with socket.socket( getattr(socket, family) ) as s: |
| 611 | t = _init_timeout() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 612 | |
Victor Stinner | 2b69506 | 2011-01-03 15:47:59 +0000 | [diff] [blame] | 613 | while 1: |
| 614 | try: |
| 615 | s.connect(address) |
| 616 | except socket.error as e: |
| 617 | if e.args[0] != errno.ECONNREFUSED or _check_timeout(t): |
| 618 | debug('failed to connect to address %s', address) |
| 619 | raise |
| 620 | time.sleep(0.01) |
| 621 | else: |
| 622 | break |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 623 | else: |
Victor Stinner | 2b69506 | 2011-01-03 15:47:59 +0000 | [diff] [blame] | 624 | raise |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 625 | |
Victor Stinner | 2b69506 | 2011-01-03 15:47:59 +0000 | [diff] [blame] | 626 | fd = duplicate(s.fileno()) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 627 | conn = Connection(fd) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 628 | return conn |
| 629 | |
| 630 | # |
| 631 | # Definitions for connections based on named pipes |
| 632 | # |
| 633 | |
| 634 | if sys.platform == 'win32': |
| 635 | |
| 636 | class PipeListener(object): |
| 637 | ''' |
| 638 | Representation of a named pipe |
| 639 | ''' |
| 640 | def __init__(self, address, backlog=None): |
| 641 | self._address = address |
| 642 | handle = win32.CreateNamedPipe( |
| 643 | address, win32.PIPE_ACCESS_DUPLEX, |
| 644 | win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | |
| 645 | win32.PIPE_WAIT, |
| 646 | win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, |
| 647 | win32.NMPWAIT_WAIT_FOREVER, win32.NULL |
| 648 | ) |
| 649 | self._handle_queue = [handle] |
| 650 | self._last_accepted = None |
| 651 | |
| 652 | sub_debug('listener created with address=%r', self._address) |
| 653 | |
| 654 | self.close = Finalize( |
| 655 | self, PipeListener._finalize_pipe_listener, |
| 656 | args=(self._handle_queue, self._address), exitpriority=0 |
| 657 | ) |
| 658 | |
| 659 | def accept(self): |
| 660 | newhandle = win32.CreateNamedPipe( |
| 661 | self._address, win32.PIPE_ACCESS_DUPLEX, |
| 662 | win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | |
| 663 | win32.PIPE_WAIT, |
| 664 | win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, |
| 665 | win32.NMPWAIT_WAIT_FOREVER, win32.NULL |
| 666 | ) |
| 667 | self._handle_queue.append(newhandle) |
| 668 | handle = self._handle_queue.pop(0) |
| 669 | try: |
| 670 | win32.ConnectNamedPipe(handle, win32.NULL) |
| 671 | except WindowsError as e: |
| 672 | if e.args[0] != win32.ERROR_PIPE_CONNECTED: |
| 673 | raise |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 674 | return PipeConnection(handle) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 675 | |
| 676 | @staticmethod |
| 677 | def _finalize_pipe_listener(queue, address): |
| 678 | sub_debug('closing listener with address=%r', address) |
| 679 | for handle in queue: |
| 680 | close(handle) |
| 681 | |
| 682 | def PipeClient(address): |
| 683 | ''' |
| 684 | Return a connection object connected to the pipe given by `address` |
| 685 | ''' |
Antoine Pitrou | 45d61a3 | 2009-11-13 22:35:18 +0000 | [diff] [blame] | 686 | t = _init_timeout() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 687 | while 1: |
| 688 | try: |
| 689 | win32.WaitNamedPipe(address, 1000) |
| 690 | h = win32.CreateFile( |
| 691 | address, win32.GENERIC_READ | win32.GENERIC_WRITE, |
| 692 | 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL |
| 693 | ) |
| 694 | except WindowsError as e: |
| 695 | if e.args[0] not in (win32.ERROR_SEM_TIMEOUT, |
Antoine Pitrou | 45d61a3 | 2009-11-13 22:35:18 +0000 | [diff] [blame] | 696 | win32.ERROR_PIPE_BUSY) or _check_timeout(t): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 697 | raise |
| 698 | else: |
| 699 | break |
| 700 | else: |
| 701 | raise |
| 702 | |
| 703 | win32.SetNamedPipeHandleState( |
| 704 | h, win32.PIPE_READMODE_MESSAGE, None, None |
| 705 | ) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 706 | return PipeConnection(h) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 707 | |
| 708 | # |
| 709 | # Authentication stuff |
| 710 | # |
| 711 | |
| 712 | MESSAGE_LENGTH = 20 |
| 713 | |
Benjamin Peterson | 1fcfe21 | 2008-06-25 12:54:22 +0000 | [diff] [blame] | 714 | CHALLENGE = b'#CHALLENGE#' |
| 715 | WELCOME = b'#WELCOME#' |
| 716 | FAILURE = b'#FAILURE#' |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 717 | |
| 718 | def deliver_challenge(connection, authkey): |
| 719 | import hmac |
| 720 | assert isinstance(authkey, bytes) |
| 721 | message = os.urandom(MESSAGE_LENGTH) |
| 722 | connection.send_bytes(CHALLENGE + message) |
| 723 | digest = hmac.new(authkey, message).digest() |
| 724 | response = connection.recv_bytes(256) # reject large message |
| 725 | if response == digest: |
| 726 | connection.send_bytes(WELCOME) |
| 727 | else: |
| 728 | connection.send_bytes(FAILURE) |
| 729 | raise AuthenticationError('digest received was wrong') |
| 730 | |
| 731 | def answer_challenge(connection, authkey): |
| 732 | import hmac |
| 733 | assert isinstance(authkey, bytes) |
| 734 | message = connection.recv_bytes(256) # reject large message |
| 735 | assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message |
| 736 | message = message[len(CHALLENGE):] |
| 737 | digest = hmac.new(authkey, message).digest() |
| 738 | connection.send_bytes(digest) |
| 739 | response = connection.recv_bytes(256) # reject large message |
| 740 | if response != WELCOME: |
| 741 | raise AuthenticationError('digest sent was rejected') |
| 742 | |
| 743 | # |
| 744 | # Support for using xmlrpclib for serialization |
| 745 | # |
| 746 | |
| 747 | class ConnectionWrapper(object): |
| 748 | def __init__(self, conn, dumps, loads): |
| 749 | self._conn = conn |
| 750 | self._dumps = dumps |
| 751 | self._loads = loads |
| 752 | for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'): |
| 753 | obj = getattr(conn, attr) |
| 754 | setattr(self, attr, obj) |
| 755 | def send(self, obj): |
| 756 | s = self._dumps(obj) |
| 757 | self._conn.send_bytes(s) |
| 758 | def recv(self): |
| 759 | s = self._conn.recv_bytes() |
| 760 | return self._loads(s) |
| 761 | |
| 762 | def _xml_dumps(obj): |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 763 | return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf-8') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 764 | |
| 765 | def _xml_loads(s): |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 766 | (obj,), method = xmlrpclib.loads(s.decode('utf-8')) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 767 | return obj |
| 768 | |
| 769 | class XmlListener(Listener): |
| 770 | def accept(self): |
| 771 | global xmlrpclib |
| 772 | import xmlrpc.client as xmlrpclib |
| 773 | obj = Listener.accept(self) |
| 774 | return ConnectionWrapper(obj, _xml_dumps, _xml_loads) |
| 775 | |
| 776 | def XmlClient(*args, **kwds): |
| 777 | global xmlrpclib |
| 778 | import xmlrpc.client as xmlrpclib |
| 779 | return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads) |
Antoine Pitrou | 87cf220 | 2011-05-09 17:04:27 +0200 | [diff] [blame] | 780 | |
| 781 | |
| 782 | # Late import because of circular import |
| 783 | from multiprocessing.forking import duplicate, close |