connection.py 27.9 KB
Newer Older
1 2 3 4 5
#
# A higher level module for using sockets (or Windows named pipes)
#
# multiprocessing/connection.py
#
6
# Copyright (c) 2006-2008, R Oudkerk
7
# Licensed to PSF under a Contributor Agreement.
8 9
#

10
__all__ = [ 'Client', 'Listener', 'Pipe', 'wait' ]
11

12
import io
13 14
import os
import sys
15 16
import pickle
import select
17
import socket
18
import struct
Georg Brandl's avatar
Georg Brandl committed
19
import errno
20 21 22 23 24
import time
import tempfile
import itertools

import _multiprocessing
25
from multiprocessing import current_process, AuthenticationError, BufferTooShort
26
from multiprocessing.util import get_temp_dir, Finalize, sub_debug, debug
27
from multiprocessing.forking import ForkingPickler
28
try:
29 30
    import _winapi
    from _winapi import WAIT_OBJECT_0, WAIT_TIMEOUT, INFINITE
31 32 33
except ImportError:
    if sys.platform == 'win32':
        raise
34
    _winapi = None
35 36 37 38 39 40

#
#
#

BUFSIZE = 8192
41 42
# A very generous timeout when it comes to local connections...
CONNECTION_TIMEOUT = 20.
43 44 45 46 47 48 49 50 51 52 53 54 55 56

_mmap_counter = itertools.count()

default_family = 'AF_INET'
families = ['AF_INET']

if hasattr(socket, 'AF_UNIX'):
    default_family = 'AF_UNIX'
    families += ['AF_UNIX']

if sys.platform == 'win32':
    default_family = 'AF_PIPE'
    families += ['AF_PIPE']

57 58 59 60 61 62 63

def _init_timeout(timeout=CONNECTION_TIMEOUT):
    return time.time() + timeout

def _check_timeout(t):
    return time.time() > t

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#
#
#

def arbitrary_address(family):
    '''
    Return an arbitrary free address for the given family
    '''
    if family == 'AF_INET':
        return ('localhost', 0)
    elif family == 'AF_UNIX':
        return tempfile.mktemp(prefix='listener-', dir=get_temp_dir())
    elif family == 'AF_PIPE':
        return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' %
                               (os.getpid(), next(_mmap_counter)))
    else:
        raise ValueError('unrecognized family')

82 83 84 85 86 87 88
def _validate_family(family):
    '''
    Checks if the family is valid for the current environment.
    '''
    if sys.platform != 'win32' and family == 'AF_PIPE':
        raise ValueError('Family %s is not recognized.' % family)

89 90 91 92
    if sys.platform == 'win32' and family == 'AF_UNIX':
        # double check
        if not hasattr(socket, family):
            raise ValueError('Family %s is not recognized.' % family)
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

def address_type(address):
    '''
    Return the types of the address

    This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
    '''
    if type(address) == tuple:
        return 'AF_INET'
    elif type(address) is str and address.startswith('\\\\'):
        return 'AF_PIPE'
    elif type(address) is str:
        return 'AF_UNIX'
    else:
        raise ValueError('address type of %r unrecognized' % address)

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
#
# Connection classes
#

class _ConnectionBase:
    _handle = None

    def __init__(self, handle, readable=True, writable=True):
        handle = handle.__index__()
        if handle < 0:
            raise ValueError("invalid handle")
        if not readable and not writable:
            raise ValueError(
                "at least one of `readable` and `writable` must be True")
        self._handle = handle
        self._readable = readable
        self._writable = writable

Antoine Pitrou's avatar
Antoine Pitrou committed
127 128
    # XXX should we use util.Finalize instead of a __del__?

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    def __del__(self):
        if self._handle is not None:
            self._close()

    def _check_closed(self):
        if self._handle is None:
            raise IOError("handle is closed")

    def _check_readable(self):
        if not self._readable:
            raise IOError("connection is write-only")

    def _check_writable(self):
        if not self._writable:
            raise IOError("connection is read-only")

    def _bad_message_length(self):
        if self._writable:
            self._readable = False
        else:
            self.close()
        raise IOError("bad message length")

    @property
    def closed(self):
        """True if the connection is closed"""
        return self._handle is None

    @property
    def readable(self):
        """True if the connection is readable"""
        return self._readable

    @property
    def writable(self):
        """True if the connection is writable"""
        return self._writable

    def fileno(self):
        """File descriptor or handle of the connection"""
        self._check_closed()
        return self._handle

    def close(self):
        """Close the connection"""
        if self._handle is not None:
            try:
                self._close()
            finally:
                self._handle = None

    def send_bytes(self, buf, offset=0, size=None):
        """Send the bytes data from a bytes-like object"""
        self._check_closed()
        self._check_writable()
        m = memoryview(buf)
        # HACK for byte-indexing of non-bytewise buffers (e.g. array.array)
        if m.itemsize > 1:
            m = memoryview(bytes(m))
        n = len(m)
        if offset < 0:
            raise ValueError("offset is negative")
        if n < offset:
            raise ValueError("buffer length < offset")
        if size is None:
            size = n - offset
        elif size < 0:
            raise ValueError("size is negative")
        elif offset + size > n:
            raise ValueError("buffer length < offset + size")
        self._send_bytes(m[offset:offset + size])

    def send(self, obj):
        """Send a (picklable) object"""
        self._check_closed()
        self._check_writable()
205 206 207
        buf = io.BytesIO()
        ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj)
        self._send_bytes(buf.getbuffer())
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

    def recv_bytes(self, maxlength=None):
        """
        Receive bytes data as a bytes object.
        """
        self._check_closed()
        self._check_readable()
        if maxlength is not None and maxlength < 0:
            raise ValueError("negative maxlength")
        buf = self._recv_bytes(maxlength)
        if buf is None:
            self._bad_message_length()
        return buf.getvalue()

    def recv_bytes_into(self, buf, offset=0):
        """
        Receive bytes data into a writeable buffer-like object.
        Return the number of bytes read.
        """
        self._check_closed()
        self._check_readable()
        with memoryview(buf) as m:
            # Get bytesize of arbitrary buffer
            itemsize = m.itemsize
            bytesize = itemsize * len(m)
            if offset < 0:
                raise ValueError("negative offset")
            elif offset > bytesize:
                raise ValueError("offset too large")
            result = self._recv_bytes()
            size = result.tell()
            if bytesize < offset + size:
                raise BufferTooShort(result.getvalue())
            # Message can fit in dest
            result.seek(0)
            result.readinto(m[offset // itemsize :
                              (offset + size) // itemsize])
            return size

247
    def recv(self):
248 249 250
        """Receive a (picklable) object"""
        self._check_closed()
        self._check_readable()
251
        buf = self._recv_bytes()
252 253 254 255 256 257 258 259
        return pickle.loads(buf.getbuffer())

    def poll(self, timeout=0.0):
        """Whether there is any input available to be read"""
        self._check_closed()
        self._check_readable()
        return self._poll(timeout)

260 261 262 263 264 265
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        self.close()

266

267
if _winapi:
268 269 270 271

    class PipeConnection(_ConnectionBase):
        """
        Connection class based on a Windows named pipe.
272 273
        Overlapped I/O is used, so the handles must have been created
        with FILE_FLAG_OVERLAPPED.
274
        """
275
        _got_empty_message = False
276

277
        def _close(self, _CloseHandle=_winapi.CloseHandle):
278
            _CloseHandle(self._handle)
279 280

        def _send_bytes(self, buf):
281
            ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True)
282
            try:
283 284
                if err == _winapi.ERROR_IO_PENDING:
                    waitres = _winapi.WaitForMultipleObjects(
285 286 287 288 289 290 291 292
                        [ov.event], False, INFINITE)
                    assert waitres == WAIT_OBJECT_0
            except:
                ov.cancel()
                raise
            finally:
                nwritten, err = ov.GetOverlappedResult(True)
            assert err == 0
293 294
            assert nwritten == len(buf)

295 296 297 298
        def _recv_bytes(self, maxsize=None):
            if self._got_empty_message:
                self._got_empty_message = False
                return io.BytesIO()
299
            else:
300
                bsize = 128 if maxsize is None else min(maxsize, 128)
301
                try:
302 303
                    ov, err = _winapi.ReadFile(self._handle, bsize,
                                                overlapped=True)
304
                    try:
305 306
                        if err == _winapi.ERROR_IO_PENDING:
                            waitres = _winapi.WaitForMultipleObjects(
307 308 309 310 311 312 313 314 315 316 317
                                [ov.event], False, INFINITE)
                            assert waitres == WAIT_OBJECT_0
                    except:
                        ov.cancel()
                        raise
                    finally:
                        nread, err = ov.GetOverlappedResult(True)
                        if err == 0:
                            f = io.BytesIO()
                            f.write(ov.getbuffer())
                            return f
318
                        elif err == _winapi.ERROR_MORE_DATA:
319
                            return self._get_more_data(ov, maxsize)
320
                except IOError as e:
321
                    if e.winerror == _winapi.ERROR_BROKEN_PIPE:
322
                        raise EOFError
323 324 325 326 327 328
                    else:
                        raise
            raise RuntimeError("shouldn't get here; expected KeyboardInterrupt")

        def _poll(self, timeout):
            if (self._got_empty_message or
329
                        _winapi.PeekNamedPipe(self._handle)[0] != 0):
330
                return True
331 332 333 334 335 336
            return bool(wait([self], timeout))

        def _get_more_data(self, ov, maxsize):
            buf = ov.getbuffer()
            f = io.BytesIO()
            f.write(buf)
337
            left = _winapi.PeekNamedPipe(self._handle)[1]
338 339 340
            assert left > 0
            if maxsize is not None and len(buf) + left > maxsize:
                self._bad_message_length()
341
            ov, err = _winapi.ReadFile(self._handle, left, overlapped=True)
342 343 344 345 346
            rbytes, err = ov.GetOverlappedResult(True)
            assert err == 0
            assert rbytes == left
            f.write(ov.getbuffer())
            return f
347 348 349 350 351 352 353 354


class Connection(_ConnectionBase):
    """
    Connection class based on an arbitrary file descriptor (Unix only), or
    a socket handle (Windows).
    """

355 356
    if _winapi:
        def _close(self, _close=_multiprocessing.closesocket):
357
            _close(self._handle)
358 359
        _write = _multiprocessing.send
        _read = _multiprocessing.recv
360
    else:
361 362
        def _close(self, _close=os.close):
            _close(self._handle)
363 364 365 366 367 368 369 370 371 372 373 374
        _write = os.write
        _read = os.read

    def _send(self, buf, write=_write):
        remaining = len(buf)
        while True:
            n = write(self._handle, buf)
            remaining -= n
            if remaining == 0:
                break
            buf = buf[n:]

375
    def _recv(self, size, read=_read):
376
        buf = io.BytesIO()
377
        handle = self._handle
378 379
        remaining = size
        while remaining > 0:
380
            chunk = read(handle, remaining)
381 382 383 384 385 386 387 388 389 390 391 392 393
            n = len(chunk)
            if n == 0:
                if remaining == size:
                    raise EOFError
                else:
                    raise IOError("got end of file during message")
            buf.write(chunk)
            remaining -= n
        return buf

    def _send_bytes(self, buf):
        # For wire compatibility with 3.2 and lower
        n = len(buf)
394
        self._send(struct.pack("!i", n))
395 396 397 398 399
        # The condition is necessary to avoid "broken pipe" errors
        # when sending a 0-length buffer if the other end closed the pipe.
        if n > 0:
            self._send(buf)

400 401
    def _recv_bytes(self, maxsize=None):
        buf = self._recv(4)
402
        size, = struct.unpack("!i", buf.getvalue())
403 404
        if maxsize is not None and size > maxsize:
            return None
405
        return self._recv(size)
406 407

    def _poll(self, timeout):
408
        r = wait([self._handle], timeout)
409 410 411
        return bool(r)


412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
#
# Public functions
#

class Listener(object):
    '''
    Returns a listener object.

    This is a wrapper for a bound socket which is 'listening' for
    connections, or for a Windows named pipe.
    '''
    def __init__(self, address=None, family=None, backlog=1, authkey=None):
        family = family or (address and address_type(address)) \
                 or default_family
        address = address or arbitrary_address(family)

428
        _validate_family(family)
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
        if family == 'AF_PIPE':
            self._listener = PipeListener(address, backlog)
        else:
            self._listener = SocketListener(address, family, backlog)

        if authkey is not None and not isinstance(authkey, bytes):
            raise TypeError('authkey should be a byte string')

        self._authkey = authkey

    def accept(self):
        '''
        Accept a connection on the bound socket or named pipe of `self`.

        Returns a `Connection` object.
        '''
445 446
        if self._listener is None:
            raise IOError('listener is closed')
447 448 449 450 451 452 453 454 455 456
        c = self._listener.accept()
        if self._authkey:
            deliver_challenge(c, self._authkey)
            answer_challenge(c, self._authkey)
        return c

    def close(self):
        '''
        Close the bound socket or named pipe of `self`.
        '''
457 458 459
        if self._listener is not None:
            self._listener.close()
            self._listener = None
460 461 462 463

    address = property(lambda self: self._listener._address)
    last_accepted = property(lambda self: self._listener._last_accepted)

464 465 466 467 468 469
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        self.close()

470 471 472 473 474 475

def Client(address, family=None, authkey=None):
    '''
    Returns a connection to the address of a `Listener`
    '''
    family = family or address_type(address)
476
    _validate_family(family)
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
    if family == 'AF_PIPE':
        c = PipeClient(address)
    else:
        c = SocketClient(address)

    if authkey is not None and not isinstance(authkey, bytes):
        raise TypeError('authkey should be a byte string')

    if authkey is not None:
        answer_challenge(c, authkey)
        deliver_challenge(c, authkey)

    return c


if sys.platform != 'win32':

    def Pipe(duplex=True):
        '''
        Returns pair of connection objects at either end of a pipe
        '''
        if duplex:
            s1, s2 = socket.socketpair()
500 501
            s1.setblocking(True)
            s2.setblocking(True)
502 503
            c1 = Connection(s1.detach())
            c2 = Connection(s2.detach())
504 505
        else:
            fd1, fd2 = os.pipe()
506 507
            c1 = Connection(fd1, writable=False)
            c2 = Connection(fd2, readable=False)
508 509 510 511 512 513 514 515 516 517 518

        return c1, c2

else:

    def Pipe(duplex=True):
        '''
        Returns pair of connection objects at either end of a pipe
        '''
        address = arbitrary_address('AF_PIPE')
        if duplex:
519 520
            openmode = _winapi.PIPE_ACCESS_DUPLEX
            access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
521 522
            obsize, ibsize = BUFSIZE, BUFSIZE
        else:
523 524
            openmode = _winapi.PIPE_ACCESS_INBOUND
            access = _winapi.GENERIC_WRITE
525 526
            obsize, ibsize = 0, BUFSIZE

527 528 529 530 531 532
        h1 = _winapi.CreateNamedPipe(
            address, openmode | _winapi.FILE_FLAG_OVERLAPPED |
            _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE,
            _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
            _winapi.PIPE_WAIT,
            1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL
533
            )
534 535 536
        h2 = _winapi.CreateFile(
            address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
            _winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
537
            )
538 539
        _winapi.SetNamedPipeHandleState(
            h2, _winapi.PIPE_READMODE_MESSAGE, None, None
540 541
            )

542
        overlapped = _winapi.ConnectNamedPipe(h1, overlapped=True)
543 544
        _, err = overlapped.GetOverlappedResult(True)
        assert err == 0
545

546 547
        c1 = PipeConnection(h1, writable=duplex)
        c2 = PipeConnection(h2, readable=duplex)
548 549 550 551 552 553 554 555 556

        return c1, c2

#
# Definitions for connections based on sockets
#

class SocketListener(object):
    '''
Georg Brandl's avatar
Georg Brandl committed
557
    Representation of a socket which is bound to an address and listening
558 559 560
    '''
    def __init__(self, address, family, backlog=1):
        self._socket = socket.socket(getattr(socket, family))
561
        try:
562 563 564 565
            # SO_REUSEADDR has different semantics on Windows (issue #2550).
            if os.name == 'posix':
                self._socket.setsockopt(socket.SOL_SOCKET,
                                        socket.SO_REUSEADDR, 1)
566
            self._socket.setblocking(True)
567 568 569 570 571 572
            self._socket.bind(address)
            self._socket.listen(backlog)
            self._address = self._socket.getsockname()
        except OSError:
            self._socket.close()
            raise
573 574 575 576 577
        self._family = family
        self._last_accepted = None

        if family == 'AF_UNIX':
            self._unlink = Finalize(
Georg Brandl's avatar
Georg Brandl committed
578
                self, os.unlink, args=(address,), exitpriority=0
579 580 581 582 583 584
                )
        else:
            self._unlink = None

    def accept(self):
        s, self._last_accepted = self._socket.accept()
585
        s.setblocking(True)
586
        return Connection(s.detach())
587 588 589 590 591 592 593 594 595 596 597 598

    def close(self):
        self._socket.close()
        if self._unlink is not None:
            self._unlink()


def SocketClient(address):
    '''
    Return a connection object connected to the socket given by `address`
    '''
    family = address_type(address)
599
    with socket.socket( getattr(socket, family) ) as s:
600
        s.setblocking(True)
601
        s.connect(address)
602
        return Connection(s.detach())
603 604 605 606 607 608 609 610 611 612 613 614 615

#
# Definitions for connections based on named pipes
#

if sys.platform == 'win32':

    class PipeListener(object):
        '''
        Representation of a named pipe
        '''
        def __init__(self, address, backlog=None):
            self._address = address
616
            self._handle_queue = [self._new_handle(first=True)]
617

618
            self._last_accepted = None
619 620 621 622 623 624
            sub_debug('listener created with address=%r', self._address)
            self.close = Finalize(
                self, PipeListener._finalize_pipe_listener,
                args=(self._handle_queue, self._address), exitpriority=0
                )

625
        def _new_handle(self, first=False):
626
            flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
627
            if first:
628 629
                flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
            return _winapi.CreateNamedPipe(
630
                self._address, flags,
631 632 633 634
                _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
                _winapi.PIPE_WAIT,
                _winapi.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
                _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL
635
                )
636 637 638

        def accept(self):
            self._handle_queue.append(self._new_handle())
639 640
            handle = self._handle_queue.pop(0)
            try:
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
                ov = _winapi.ConnectNamedPipe(handle, overlapped=True)
            except OSError as e:
                if e.winerror != _winapi.ERROR_NO_DATA:
                    raise
                # ERROR_NO_DATA can occur if a client has already connected,
                # written data and then disconnected -- see Issue 14725.
            else:
                try:
                    res = _winapi.WaitForMultipleObjects(
                        [ov.event], False, INFINITE)
                except:
                    ov.cancel()
                    _winapi.CloseHandle(handle)
                    raise
                finally:
                    _, err = ov.GetOverlappedResult(True)
                    assert err == 0
658
            return PipeConnection(handle)
659 660 661 662 663

        @staticmethod
        def _finalize_pipe_listener(queue, address):
            sub_debug('closing listener with address=%r', address)
            for handle in queue:
664
                _winapi.CloseHandle(handle)
665 666 667 668 669

    def PipeClient(address):
        '''
        Return a connection object connected to the pipe given by `address`
        '''
670
        t = _init_timeout()
671 672
        while 1:
            try:
673 674 675 676 677
                _winapi.WaitNamedPipe(address, 1000)
                h = _winapi.CreateFile(
                    address, _winapi.GENERIC_READ | _winapi.GENERIC_WRITE,
                    0, _winapi.NULL, _winapi.OPEN_EXISTING,
                    _winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
678 679
                    )
            except WindowsError as e:
680 681
                if e.winerror not in (_winapi.ERROR_SEM_TIMEOUT,
                                      _winapi.ERROR_PIPE_BUSY) or _check_timeout(t):
682 683 684 685 686 687
                    raise
            else:
                break
        else:
            raise

688 689
        _winapi.SetNamedPipeHandleState(
            h, _winapi.PIPE_READMODE_MESSAGE, None, None
690
            )
691
        return PipeConnection(h)
692 693 694 695 696 697 698

#
# Authentication stuff
#

MESSAGE_LENGTH = 20

699 700 701
CHALLENGE = b'#CHALLENGE#'
WELCOME = b'#WELCOME#'
FAILURE = b'#FAILURE#'
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747

def deliver_challenge(connection, authkey):
    import hmac
    assert isinstance(authkey, bytes)
    message = os.urandom(MESSAGE_LENGTH)
    connection.send_bytes(CHALLENGE + message)
    digest = hmac.new(authkey, message).digest()
    response = connection.recv_bytes(256)        # reject large message
    if response == digest:
        connection.send_bytes(WELCOME)
    else:
        connection.send_bytes(FAILURE)
        raise AuthenticationError('digest received was wrong')

def answer_challenge(connection, authkey):
    import hmac
    assert isinstance(authkey, bytes)
    message = connection.recv_bytes(256)         # reject large message
    assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
    message = message[len(CHALLENGE):]
    digest = hmac.new(authkey, message).digest()
    connection.send_bytes(digest)
    response = connection.recv_bytes(256)        # reject large message
    if response != WELCOME:
        raise AuthenticationError('digest sent was rejected')

#
# Support for using xmlrpclib for serialization
#

class ConnectionWrapper(object):
    def __init__(self, conn, dumps, loads):
        self._conn = conn
        self._dumps = dumps
        self._loads = loads
        for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'):
            obj = getattr(conn, attr)
            setattr(self, attr, obj)
    def send(self, obj):
        s = self._dumps(obj)
        self._conn.send_bytes(s)
    def recv(self):
        s = self._conn.recv_bytes()
        return self._loads(s)

def _xml_dumps(obj):
748
    return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf-8')
749 750

def _xml_loads(s):
751
    (obj,), method = xmlrpclib.loads(s.decode('utf-8'))
752 753 754 755 756 757 758 759 760 761 762 763 764
    return obj

class XmlListener(Listener):
    def accept(self):
        global xmlrpclib
        import xmlrpc.client as xmlrpclib
        obj = Listener.accept(self)
        return ConnectionWrapper(obj, _xml_dumps, _xml_loads)

def XmlClient(*args, **kwds):
    global xmlrpclib
    import xmlrpc.client as xmlrpclib
    return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)
765

766 767 768 769 770 771 772 773 774 775 776 777
#
# Wait
#

if sys.platform == 'win32':

    def _exhaustive_wait(handles, timeout):
        # Return ALL handles which are currently signalled.  (Only
        # returning the first signalled might create starvation issues.)
        L = list(handles)
        ready = []
        while L:
778
            res = _winapi.WaitForMultipleObjects(L, False, timeout)
779 780 781 782 783 784 785 786 787 788 789 790 791
            if res == WAIT_TIMEOUT:
                break
            elif WAIT_OBJECT_0 <= res < WAIT_OBJECT_0 + len(L):
                res -= WAIT_OBJECT_0
            elif WAIT_ABANDONED_0 <= res < WAIT_ABANDONED_0 + len(L):
                res -= WAIT_ABANDONED_0
            else:
                raise RuntimeError('Should not get here')
            ready.append(L[res])
            L = L[res+1:]
            timeout = 0
        return ready

792
    _ready_errors = {_winapi.ERROR_BROKEN_PIPE, _winapi.ERROR_NETNAME_DELETED}
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821

    def wait(object_list, timeout=None):
        '''
        Wait till an object in object_list is ready/readable.

        Returns list of those objects in object_list which are ready/readable.
        '''
        if timeout is None:
            timeout = INFINITE
        elif timeout < 0:
            timeout = 0
        else:
            timeout = int(timeout * 1000 + 0.5)

        object_list = list(object_list)
        waithandle_to_obj = {}
        ov_list = []
        ready_objects = set()
        ready_handles = set()

        try:
            for o in object_list:
                try:
                    fileno = getattr(o, 'fileno')
                except AttributeError:
                    waithandle_to_obj[o.__index__()] = o
                else:
                    # start an overlapped read of length zero
                    try:
822
                        ov, err = _winapi.ReadFile(fileno(), 0, True)
823 824 825 826
                    except OSError as e:
                        err = e.winerror
                        if err not in _ready_errors:
                            raise
827
                    if err == _winapi.ERROR_IO_PENDING:
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
                        ov_list.append(ov)
                        waithandle_to_obj[ov.event] = o
                    else:
                        # If o.fileno() is an overlapped pipe handle and
                        # err == 0 then there is a zero length message
                        # in the pipe, but it HAS NOT been consumed.
                        ready_objects.add(o)
                        timeout = 0

            ready_handles = _exhaustive_wait(waithandle_to_obj.keys(), timeout)
        finally:
            # request that overlapped reads stop
            for ov in ov_list:
                ov.cancel()

            # wait for all overlapped reads to stop
            for ov in ov_list:
                try:
                    _, err = ov.GetOverlappedResult(True)
                except OSError as e:
                    err = e.winerror
                    if err not in _ready_errors:
                        raise
851
                if err != _winapi.ERROR_OPERATION_ABORTED:
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
                    o = waithandle_to_obj[ov.event]
                    ready_objects.add(o)
                    if err == 0:
                        # If o.fileno() is an overlapped pipe handle then
                        # a zero length message HAS been consumed.
                        if hasattr(o, '_got_empty_message'):
                            o._got_empty_message = True

        ready_objects.update(waithandle_to_obj[h] for h in ready_handles)
        return [o for o in object_list if o in ready_objects]

else:

    def wait(object_list, timeout=None):
        '''
        Wait till an object in object_list is ready/readable.

        Returns list of those objects in object_list which are ready/readable.
        '''
        if timeout is not None:
            if timeout <= 0:
                return select.select(object_list, [], [], 0)[0]
            else:
                deadline = time.time() + timeout
        while True:
            try:
                return select.select(object_list, [], [], timeout)[0]
            except OSError as e:
                if e.errno != errno.EINTR:
                    raise
            if timeout is not None:
                timeout = deadline - time.time()
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901

#
# Make connection and socket objects sharable if possible
#

if sys.platform == 'win32':
    from . import reduction
    ForkingPickler.register(socket.socket, reduction.reduce_socket)
    ForkingPickler.register(Connection, reduction.reduce_connection)
    ForkingPickler.register(PipeConnection, reduction.reduce_pipe_connection)
else:
    try:
        from . import reduction
    except ImportError:
        pass
    else:
        ForkingPickler.register(socket.socket, reduction.reduce_socket)
        ForkingPickler.register(Connection, reduction.reduce_connection)