| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
__all__ = [ 'Client', 'Listener', 'Pipe', 'wait' ] |
| 11 |
|
| 12 |
import errno |
| 13 |
import io |
| 14 |
import os |
| 15 |
import sys |
| 16 |
import socket |
| 17 |
import struct |
| 18 |
import time |
| 19 |
import tempfile |
| 20 |
import itertools |
| 21 |
|
| 22 |
import _multiprocessing |
| 23 |
|
| 24 |
from . import util |
| 25 |
|
| 26 |
from . import AuthenticationError, BufferTooShort |
| 27 |
from .context import reduction |
| 28 |
_ForkingPickler = reduction.ForkingPickler |
| 29 |
|
| 30 |
try: |
| 31 |
import _winapi |
| 32 |
from _winapi import WAIT_OBJECT_0, WAIT_ABANDONED_0, WAIT_TIMEOUT, INFINITE |
| 33 |
except ImportError: |
| 34 |
if sys.platform == 'win32': |
| 35 |
raise |
| 36 |
_winapi = None |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
BUFSIZE = 8192 |
| 43 |
|
| 44 |
CONNECTION_TIMEOUT = 20. |
| 45 |
|
| 46 |
_mmap_counter = itertools.count() |
| 47 |
|
| 48 |
default_family = 'AF_INET' |
| 49 |
families = ['AF_INET'] |
| 50 |
|
| 51 |
if hasattr(socket, 'AF_UNIX'): |
| 52 |
default_family = 'AF_UNIX' |
| 53 |
families += ['AF_UNIX'] |
| 54 |
|
| 55 |
if sys.platform == 'win32': |
| 56 |
default_family = 'AF_PIPE' |
| 57 |
families += ['AF_PIPE'] |
| 58 |
|
| 59 |
|
| 60 |
def _init_timeout(timeout=CONNECTION_TIMEOUT): |
| 61 |
return time.monotonic() + timeout |
| 62 |
|
| 63 |
def _check_timeout(t): |
| 64 |
return time.monotonic() > t |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
def arbitrary_address(family): |
| 71 |
''' |
| 72 |
Return an arbitrary free address for the given family |
| 73 |
''' |
| 74 |
if family == 'AF_INET': |
| 75 |
return ('localhost', 0) |
| 76 |
elif family == 'AF_UNIX': |
| 77 |
return tempfile.mktemp(prefix='listener-', dir=util.get_temp_dir()) |
| 78 |
elif family == 'AF_PIPE': |
| 79 |
return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' % |
| 80 |
(os.getpid(), next(_mmap_counter)), dir="") |
| 81 |
else: |
| 82 |
raise ValueError('unrecognized family') |
| 83 |
|
| 84 |
def _validate_family(family): |
| 85 |
''' |
| 86 |
Checks if the family is valid for the current environment. |
| 87 |
''' |
| 88 |
if sys.platform != 'win32' and family == 'AF_PIPE': |
| 89 |
raise ValueError('Family %s is not recognized.' % family) |
| 90 |
|
| 91 |
if sys.platform == 'win32' and family == 'AF_UNIX': |
| 92 |
|
| 93 |
if not hasattr(socket, family): |
| 94 |
raise ValueError('Family %s is not recognized.' % family) |
| 95 |
|
| 96 |
def address_type(address): |
| 97 |
''' |
| 98 |
Return the types of the address |
| 99 |
|
| 100 |
This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE' |
| 101 |
''' |
| 102 |
if type(address) == tuple: |
| 103 |
return 'AF_INET' |
| 104 |
elif type(address) is str and address.startswith('\\\\'): |
| 105 |
return 'AF_PIPE' |
| 106 |
elif type(address) is str or util.is_abstract_socket_namespace(address): |
| 107 |
return 'AF_UNIX' |
| 108 |
else: |
| 109 |
raise ValueError('address type of %r unrecognized' % address) |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
class _ConnectionBase: |
| 116 |
_handle = None |
| 117 |
|
| 118 |
def __init__(self, handle, readable=True, writable=True): |
| 119 |
handle = handle.__index__() |
| 120 |
if handle < 0: |
| 121 |
raise ValueError("invalid handle") |
| 122 |
if not readable and not writable: |
| 123 |
raise ValueError( |
| 124 |
"at least one of `readable` and `writable` must be True") |
| 125 |
self._handle = handle |
| 126 |
self._readable = readable |
| 127 |
self._writable = writable |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
def __del__(self): |
| 132 |
if self._handle is not None: |
| 133 |
self._close() |
| 134 |
|
| 135 |
def _check_closed(self): |
| 136 |
if self._handle is None: |
| 137 |
raise OSError("handle is closed") |
| 138 |
|
| 139 |
def _check_readable(self): |
| 140 |
if not self._readable: |
| 141 |
raise OSError("connection is write-only") |
| 142 |
|
| 143 |
def _check_writable(self): |
| 144 |
if not self._writable: |
| 145 |
raise OSError("connection is read-only") |
| 146 |
|
| 147 |
def _bad_message_length(self): |
| 148 |
if self._writable: |
| 149 |
self._readable = False |
| 150 |
else: |
| 151 |
self.close() |
| 152 |
raise OSError("bad message length") |
| 153 |
|
| 154 |
@property |
| 155 |
def closed(self): |
| 156 |
"""True if the connection is closed""" |
| 157 |
return self._handle is None |
| 158 |
|
| 159 |
@property |
| 160 |
def readable(self): |
| 161 |
"""True if the connection is readable""" |
| 162 |
return self._readable |
| 163 |
|
| 164 |
@property |
| 165 |
def writable(self): |
| 166 |
"""True if the connection is writable""" |
| 167 |
return self._writable |
| 168 |
|
| 169 |
def fileno(self): |
| 170 |
"""File descriptor or handle of the connection""" |
| 171 |
self._check_closed() |
| 172 |
return self._handle |
| 173 |
|
| 174 |
def close(self): |
| 175 |
"""Close the connection""" |
| 176 |
if self._handle is not None: |
| 177 |
try: |
| 178 |
self._close() |
| 179 |
finally: |
| 180 |
self._handle = None |
| 181 |
|
| 182 |
def send_bytes(self, buf, offset=0, size=None): |
| 183 |
"""Send the bytes data from a bytes-like object""" |
| 184 |
self._check_closed() |
| 185 |
self._check_writable() |
| 186 |
m = memoryview(buf) |
| 187 |
if m.itemsize > 1: |
| 188 |
m = m.cast('B') |
| 189 |
n = m.nbytes |
| 190 |
if offset < 0: |
| 191 |
raise ValueError("offset is negative") |
| 192 |
if n < offset: |
| 193 |
raise ValueError("buffer length < offset") |
| 194 |
if size is None: |
| 195 |
size = n - offset |
| 196 |
elif size < 0: |
| 197 |
raise ValueError("size is negative") |
| 198 |
elif offset + size > n: |
| 199 |
raise ValueError("buffer length < offset + size") |
| 200 |
self._send_bytes(m[offset:offset + size]) |
| 201 |
|
| 202 |
def send(self, obj): |
| 203 |
"""Send a (picklable) object""" |
| 204 |
self._check_closed() |
| 205 |
self._check_writable() |
| 206 |
self._send_bytes(_ForkingPickler.dumps(obj)) |
| 207 |
|
| 208 |
def recv_bytes(self, maxlength=None): |
| 209 |
""" |
| 210 |
Receive bytes data as a bytes object. |
| 211 |
""" |
| 212 |
self._check_closed() |
| 213 |
self._check_readable() |
| 214 |
if maxlength is not None and maxlength < 0: |
| 215 |
raise ValueError("negative maxlength") |
| 216 |
buf = self._recv_bytes(maxlength) |
| 217 |
if buf is None: |
| 218 |
self._bad_message_length() |
| 219 |
return buf.getvalue() |
| 220 |
|
| 221 |
def recv_bytes_into(self, buf, offset=0): |
| 222 |
""" |
| 223 |
Receive bytes data into a writeable bytes-like object. |
| 224 |
Return the number of bytes read. |
| 225 |
""" |
| 226 |
self._check_closed() |
| 227 |
self._check_readable() |
| 228 |
with memoryview(buf) as m: |
| 229 |
|
| 230 |
itemsize = m.itemsize |
| 231 |
bytesize = itemsize * len(m) |
| 232 |
if offset < 0: |
| 233 |
raise ValueError("negative offset") |
| 234 |
elif offset > bytesize: |
| 235 |
raise ValueError("offset too large") |
| 236 |
result = self._recv_bytes() |
| 237 |
size = result.tell() |
| 238 |
if bytesize < offset + size: |
| 239 |
raise BufferTooShort(result.getvalue()) |
| 240 |
|
| 241 |
result.seek(0) |
| 242 |
result.readinto(m[offset // itemsize : |
| 243 |
(offset + size) // itemsize]) |
| 244 |
return size |
| 245 |
|
| 246 |
def recv(self): |
| 247 |
"""Receive a (picklable) object""" |
| 248 |
self._check_closed() |
| 249 |
self._check_readable() |
| 250 |
buf = self._recv_bytes() |
| 251 |
return _ForkingPickler.loads(buf.getbuffer()) |
| 252 |
|
| 253 |
def poll(self, timeout=0.0): |
| 254 |
"""Whether there is any input available to be read""" |
| 255 |
self._check_closed() |
| 256 |
self._check_readable() |
| 257 |
return self._poll(timeout) |
| 258 |
|
| 259 |
def __enter__(self): |
| 260 |
return self |
| 261 |
|
| 262 |
def __exit__(self, exc_type, exc_value, exc_tb): |
| 263 |
self.close() |
| 264 |
|
| 265 |
|
| 266 |
if _winapi: |
| 267 |
|
| 268 |
class PipeConnection(_ConnectionBase): |
| 269 |
""" |
| 270 |
Connection class based on a Windows named pipe. |
| 271 |
Overlapped I/O is used, so the handles must have been created |
| 272 |
with FILE_FLAG_OVERLAPPED. |
| 273 |
""" |
| 274 |
_got_empty_message = False |
| 275 |
_send_ov = None |
| 276 |
|
| 277 |
def _close(self, _CloseHandle=_winapi.CloseHandle): |
| 278 |
ov = self._send_ov |
| 279 |
if ov is not None: |
| 280 |
|
| 281 |
ov.cancel() |
| 282 |
_CloseHandle(self._handle) |
| 283 |
|
| 284 |
def _send_bytes(self, buf): |
| 285 |
if self._send_ov is not None: |
| 286 |
|
| 287 |
raise ValueError("concurrent send_bytes() calls " |
| 288 |
"are not supported") |
| 289 |
ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True) |
| 290 |
self._send_ov = ov |
| 291 |
try: |
| 292 |
if err == _winapi.ERROR_IO_PENDING: |
| 293 |
waitres = _winapi.WaitForMultipleObjects( |
| 294 |
[ov.event], False, INFINITE) |
| 295 |
assert waitres == WAIT_OBJECT_0 |
| 296 |
except: |
| 297 |
ov.cancel() |
| 298 |
raise |
| 299 |
finally: |
| 300 |
self._send_ov = None |
| 301 |
nwritten, err = ov.GetOverlappedResult(True) |
| 302 |
if err == _winapi.ERROR_OPERATION_ABORTED: |
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
raise OSError(errno.EPIPE, "handle is closed") |
| 307 |
assert err == 0 |
| 308 |
assert nwritten == len(buf) |
| 309 |
|
| 310 |
def _recv_bytes(self, maxsize=None): |
| 311 |
if self._got_empty_message: |
| 312 |
self._got_empty_message = False |
| 313 |
return io.BytesIO() |
| 314 |
else: |
| 315 |
bsize = 128 if maxsize is None else min(maxsize, 128) |
| 316 |
try: |
| 317 |
ov, err = _winapi.ReadFile(self._handle, bsize, |
| 318 |
overlapped=True) |
| 319 |
try: |
| 320 |
if err == _winapi.ERROR_IO_PENDING: |
| 321 |
waitres = _winapi.WaitForMultipleObjects( |
| 322 |
[ov.event], False, INFINITE) |
| 323 |
assert waitres == WAIT_OBJECT_0 |
| 324 |
except: |
| 325 |
ov.cancel() |
| 326 |
raise |
| 327 |
finally: |
| 328 |
nread, err = ov.GetOverlappedResult(True) |
| 329 |
if err == 0: |
| 330 |
f = io.BytesIO() |
| 331 |
f.write(ov.getbuffer()) |
| 332 |
return f |
| 333 |
elif err == _winapi.ERROR_MORE_DATA: |
| 334 |
return self._get_more_data(ov, maxsize) |
| 335 |
except OSError as e: |
| 336 |
if e.winerror == _winapi.ERROR_BROKEN_PIPE: |
| 337 |
raise EOFError |
| 338 |
else: |
| 339 |
raise |
| 340 |
raise RuntimeError("shouldn't get here; expected KeyboardInterrupt") |
| 341 |
|
| 342 |
def _poll(self, timeout): |
| 343 |
if (self._got_empty_message or |
| 344 |
_winapi.PeekNamedPipe(self._handle)[0] != 0): |
| 345 |
return True |
| 346 |
return bool(wait([self], timeout)) |
| 347 |
|
| 348 |
def _get_more_data(self, ov, maxsize): |
| 349 |
buf = ov.getbuffer() |
| 350 |
f = io.BytesIO() |
| 351 |
f.write(buf) |
| 352 |
left = _winapi.PeekNamedPipe(self._handle)[1] |
| 353 |
assert left > 0 |
| 354 |
if maxsize is not None and len(buf) + left > maxsize: |
| 355 |
self._bad_message_length() |
| 356 |
ov, err = _winapi.ReadFile(self._handle, left, overlapped=True) |
| 357 |
rbytes, err = ov.GetOverlappedResult(True) |
| 358 |
assert err == 0 |
| 359 |
assert rbytes == left |
| 360 |
f.write(ov.getbuffer()) |
| 361 |
return f |
| 362 |
|
| 363 |
|
| 364 |
class Connection(_ConnectionBase): |
| 365 |
""" |
| 366 |
Connection class based on an arbitrary file descriptor (Unix only), or |
| 367 |
a socket handle (Windows). |
| 368 |
""" |
| 369 |
|
| 370 |
if _winapi: |
| 371 |
def _close(self, _close=_multiprocessing.closesocket): |
| 372 |
_close(self._handle) |
| 373 |
_write = _multiprocessing.send |
| 374 |
_read = _multiprocessing.recv |
| 375 |
else: |
| 376 |
def _close(self, _close=os.close): |
| 377 |
_close(self._handle) |
| 378 |
_write = os.write |
| 379 |
_read = os.read |
| 380 |
|
| 381 |
def _send(self, buf, write=_write): |
| 382 |
remaining = len(buf) |
| 383 |
while True: |
| 384 |
n = write(self._handle, buf) |
| 385 |
remaining -= n |
| 386 |
if remaining == 0: |
| 387 |
break |
| 388 |
buf = buf[n:] |
| 389 |
|
| 390 |
def _recv(self, size, read=_read): |
| 391 |
buf = io.BytesIO() |
| 392 |
handle = self._handle |
| 393 |
remaining = size |
| 394 |
while remaining > 0: |
| 395 |
chunk = read(handle, remaining) |
| 396 |
n = len(chunk) |
| 397 |
if n == 0: |
| 398 |
if remaining == size: |
| 399 |
raise EOFError |
| 400 |
else: |
| 401 |
raise OSError("got end of file during message") |
| 402 |
buf.write(chunk) |
| 403 |
remaining -= n |
| 404 |
return buf |
| 405 |
|
| 406 |
def _send_bytes(self, buf): |
| 407 |
n = len(buf) |
| 408 |
if n > 0x7fffffff: |
| 409 |
pre_header = struct.pack("!i", -1) |
| 410 |
header = struct.pack("!Q", n) |
| 411 |
self._send(pre_header) |
| 412 |
self._send(header) |
| 413 |
self._send(buf) |
| 414 |
else: |
| 415 |
|
| 416 |
header = struct.pack("!i", n) |
| 417 |
if n > 16384: |
| 418 |
|
| 419 |
|
| 420 |
self._send(header) |
| 421 |
self._send(buf) |
| 422 |
else: |
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
|
| 427 |
self._send(header + buf) |
| 428 |
|
| 429 |
def _recv_bytes(self, maxsize=None): |
| 430 |
buf = self._recv(4) |
| 431 |
size, = struct.unpack("!i", buf.getvalue()) |
| 432 |
if size == -1: |
| 433 |
buf = self._recv(8) |
| 434 |
size, = struct.unpack("!Q", buf.getvalue()) |
| 435 |
if maxsize is not None and size > maxsize: |
| 436 |
return None |
| 437 |
return self._recv(size) |
| 438 |
|
| 439 |
def _poll(self, timeout): |
| 440 |
r = wait([self], timeout) |
| 441 |
return bool(r) |
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
class Listener(object): |
| 449 |
''' |
| 450 |
Returns a listener object. |
| 451 |
|
| 452 |
This is a wrapper for a bound socket which is 'listening' for |
| 453 |
connections, or for a Windows named pipe. |
| 454 |
''' |
| 455 |
def __init__(self, address=None, family=None, backlog=1, authkey=None): |
| 456 |
family = family or (address and address_type(address)) \ |
| 457 |
or default_family |
| 458 |
address = address or arbitrary_address(family) |
| 459 |
|
| 460 |
_validate_family(family) |
| 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 |
if self._listener is None: |
| 478 |
raise OSError('listener is closed') |
| 479 |
|
| 480 |
c = self._listener.accept() |
| 481 |
if self._authkey is not None: |
| 482 |
deliver_challenge(c, self._authkey) |
| 483 |
answer_challenge(c, self._authkey) |
| 484 |
return c |
| 485 |
|
| 486 |
def close(self): |
| 487 |
''' |
| 488 |
Close the bound socket or named pipe of `self`. |
| 489 |
''' |
| 490 |
listener = self._listener |
| 491 |
if listener is not None: |
| 492 |
self._listener = None |
| 493 |
listener.close() |
| 494 |
|
| 495 |
@property |
| 496 |
def address(self): |
| 497 |
return self._listener._address |
| 498 |
|
| 499 |
@property |
| 500 |
def last_accepted(self): |
| 501 |
return self._listener._last_accepted |
| 502 |
|
| 503 |
def __enter__(self): |
| 504 |
return self |
| 505 |
|
| 506 |
def __exit__(self, exc_type, exc_value, exc_tb): |
| 507 |
self.close() |
| 508 |
|
| 509 |
|
| 510 |
def Client(address, family=None, authkey=None): |
| 511 |
''' |
| 512 |
Returns a connection to the address of a `Listener` |
| 513 |
''' |
| 514 |
family = family or address_type(address) |
| 515 |
_validate_family(family) |
| 516 |
if family == 'AF_PIPE': |
| 517 |
c = PipeClient(address) |
| 518 |
else: |
| 519 |
c = SocketClient(address) |
| 520 |
|
| 521 |
if authkey is not None and not isinstance(authkey, bytes): |
| 522 |
raise TypeError('authkey should be a byte string') |
| 523 |
|
| 524 |
if authkey is not None: |
| 525 |
answer_challenge(c, authkey) |
| 526 |
deliver_challenge(c, authkey) |
| 527 |
|
| 528 |
return c |
| 529 |
|
| 530 |
|
| 531 |
if sys.platform != 'win32': |
| 532 |
|
| 533 |
def Pipe(duplex=True): |
| 534 |
''' |
| 535 |
Returns pair of connection objects at either end of a pipe |
| 536 |
''' |
| 537 |
if duplex: |
| 538 |
s1, s2 = socket.socketpair() |
| 539 |
s1.setblocking(True) |
| 540 |
s2.setblocking(True) |
| 541 |
c1 = Connection(s1.detach()) |
| 542 |
c2 = Connection(s2.detach()) |
| 543 |
else: |
| 544 |
fd1, fd2 = os.pipe() |
| 545 |
c1 = Connection(fd1, writable=False) |
| 546 |
c2 = Connection(fd2, readable=False) |
| 547 |
|
| 548 |
return c1, c2 |
| 549 |
|
| 550 |
else: |
| 551 |
|
| 552 |
def Pipe(duplex=True): |
| 553 |
''' |
| 554 |
Returns pair of connection objects at either end of a pipe |
| 555 |
''' |
| 556 |
address = arbitrary_address('AF_PIPE') |
| 557 |
if duplex: |
| 558 |
openmode = _winapi.PIPE_ACCESS_DUPLEX |
| 559 |
access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE |
| 560 |
obsize, ibsize = BUFSIZE, BUFSIZE |
| 561 |
else: |
| 562 |
openmode = _winapi.PIPE_ACCESS_INBOUND |
| 563 |
access = _winapi.GENERIC_WRITE |
| 564 |
obsize, ibsize = 0, BUFSIZE |
| 565 |
|
| 566 |
h1 = _winapi.CreateNamedPipe( |
| 567 |
address, openmode | _winapi.FILE_FLAG_OVERLAPPED | |
| 568 |
_winapi.FILE_FLAG_FIRST_PIPE_INSTANCE, |
| 569 |
_winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE | |
| 570 |
_winapi.PIPE_WAIT, |
| 571 |
1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, |
| 572 |
|
| 573 |
_winapi.NULL |
| 574 |
) |
| 575 |
h2 = _winapi.CreateFile( |
| 576 |
address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING, |
| 577 |
_winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL |
| 578 |
) |
| 579 |
_winapi.SetNamedPipeHandleState( |
| 580 |
h2, _winapi.PIPE_READMODE_MESSAGE, None, None |
| 581 |
) |
| 582 |
|
| 583 |
overlapped = _winapi.ConnectNamedPipe(h1, overlapped=True) |
| 584 |
_, err = overlapped.GetOverlappedResult(True) |
| 585 |
assert err == 0 |
| 586 |
|
| 587 |
c1 = PipeConnection(h1, writable=duplex) |
| 588 |
c2 = PipeConnection(h2, readable=duplex) |
| 589 |
|
| 590 |
return c1, c2 |
| 591 |
|
| 592 |
|
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
class SocketListener(object): |
| 597 |
''' |
| 598 |
Representation of a socket which is bound to an address and listening |
| 599 |
''' |
| 600 |
def __init__(self, address, family, backlog=1): |
| 601 |
self._socket = socket.socket(getattr(socket, family)) |
| 602 |
try: |
| 603 |
|
| 604 |
if os.name == 'posix': |
| 605 |
self._socket.setsockopt(socket.SOL_SOCKET, |
| 606 |
socket.SO_REUSEADDR, 1) |
| 607 |
self._socket.setblocking(True) |
| 608 |
self._socket.bind(address) |
| 609 |
self._socket.listen(backlog) |
| 610 |
self._address = self._socket.getsockname() |
| 611 |
except OSError: |
| 612 |
self._socket.close() |
| 613 |
raise |
| 614 |
self._family = family |
| 615 |
self._last_accepted = None |
| 616 |
|
| 617 |
if family == 'AF_UNIX' and not util.is_abstract_socket_namespace(address): |
| 618 |
|
| 619 |
self._unlink = util.Finalize( |
| 620 |
self, os.unlink, args=(address,), exitpriority=0 |
| 621 |
) |
| 622 |
else: |
| 623 |
self._unlink = None |
| 624 |
|
| 625 |
def accept(self): |
| 626 |
s, self._last_accepted = self._socket.accept() |
| 627 |
s.setblocking(True) |
| 628 |
return Connection(s.detach()) |
| 629 |
|
| 630 |
def close(self): |
| 631 |
try: |
| 632 |
self._socket.close() |
| 633 |
finally: |
| 634 |
unlink = self._unlink |
| 635 |
if unlink is not None: |
| 636 |
self._unlink = None |
| 637 |
unlink() |
| 638 |
|
| 639 |
|
| 640 |
def SocketClient(address): |
| 641 |
''' |
| 642 |
Return a connection object connected to the socket given by `address` |
| 643 |
''' |
| 644 |
family = address_type(address) |
| 645 |
with socket.socket( getattr(socket, family) ) as s: |
| 646 |
s.setblocking(True) |
| 647 |
s.connect(address) |
| 648 |
return Connection(s.detach()) |
| 649 |
|
| 650 |
|
| 651 |
|
| 652 |
|
| 653 |
|
| 654 |
if sys.platform == 'win32': |
| 655 |
|
| 656 |
class PipeListener(object): |
| 657 |
''' |
| 658 |
Representation of a named pipe |
| 659 |
''' |
| 660 |
def __init__(self, address, backlog=None): |
| 661 |
self._address = address |
| 662 |
self._handle_queue = [self._new_handle(first=True)] |
| 663 |
|
| 664 |
self._last_accepted = None |
| 665 |
util.sub_debug('listener created with address=%r', self._address) |
| 666 |
self.close = util.Finalize( |
| 667 |
self, PipeListener._finalize_pipe_listener, |
| 668 |
args=(self._handle_queue, self._address), exitpriority=0 |
| 669 |
) |
| 670 |
|
| 671 |
def _new_handle(self, first=False): |
| 672 |
flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED |
| 673 |
if first: |
| 674 |
flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE |
| 675 |
return _winapi.CreateNamedPipe( |
| 676 |
self._address, flags, |
| 677 |
_winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE | |
| 678 |
_winapi.PIPE_WAIT, |
| 679 |
_winapi.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, |
| 680 |
_winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL |
| 681 |
) |
| 682 |
|
| 683 |
def accept(self): |
| 684 |
self._handle_queue.append(self._new_handle()) |
| 685 |
handle = self._handle_queue.pop(0) |
| 686 |
try: |
| 687 |
ov = _winapi.ConnectNamedPipe(handle, overlapped=True) |
| 688 |
except OSError as e: |
| 689 |
if e.winerror != _winapi.ERROR_NO_DATA: |
| 690 |
raise |
| 691 |
|
| 692 |
|
| 693 |
else: |
| 694 |
try: |
| 695 |
res = _winapi.WaitForMultipleObjects( |
| 696 |
[ov.event], False, INFINITE) |
| 697 |
except: |
| 698 |
ov.cancel() |
| 699 |
_winapi.CloseHandle(handle) |
| 700 |
raise |
| 701 |
finally: |
| 702 |
_, err = ov.GetOverlappedResult(True) |
| 703 |
assert err == 0 |
| 704 |
return PipeConnection(handle) |
| 705 |
|
| 706 |
@staticmethod |
| 707 |
def _finalize_pipe_listener(queue, address): |
| 708 |
util.sub_debug('closing listener with address=%r', address) |
| 709 |
for handle in queue: |
| 710 |
_winapi.CloseHandle(handle) |
| 711 |
|
| 712 |
def PipeClient(address): |
| 713 |
''' |
| 714 |
Return a connection object connected to the pipe given by `address` |
| 715 |
''' |
| 716 |
t = _init_timeout() |
| 717 |
while 1: |
| 718 |
try: |
| 719 |
_winapi.WaitNamedPipe(address, 1000) |
| 720 |
h = _winapi.CreateFile( |
| 721 |
address, _winapi.GENERIC_READ | _winapi.GENERIC_WRITE, |
| 722 |
0, _winapi.NULL, _winapi.OPEN_EXISTING, |
| 723 |
_winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL |
| 724 |
) |
| 725 |
except OSError as e: |
| 726 |
if e.winerror not in (_winapi.ERROR_SEM_TIMEOUT, |
| 727 |
_winapi.ERROR_PIPE_BUSY) or _check_timeout(t): |
| 728 |
raise |
| 729 |
else: |
| 730 |
break |
| 731 |
else: |
| 732 |
raise |
| 733 |
|
| 734 |
_winapi.SetNamedPipeHandleState( |
| 735 |
h, _winapi.PIPE_READMODE_MESSAGE, None, None |
| 736 |
) |
| 737 |
return PipeConnection(h) |
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
|
| 743 |
MESSAGE_LENGTH = 20 |
| 744 |
|
| 745 |
CHALLENGE = b'#CHALLENGE#' |
| 746 |
WELCOME = b'#WELCOME#' |
| 747 |
FAILURE = b'#FAILURE#' |
| 748 |
|
| 749 |
def deliver_challenge(connection, authkey): |
| 750 |
import hmac |
| 751 |
if not isinstance(authkey, bytes): |
| 752 |
raise ValueError( |
| 753 |
"Authkey must be bytes, not {0!s}".format(type(authkey))) |
| 754 |
message = os.urandom(MESSAGE_LENGTH) |
| 755 |
connection.send_bytes(CHALLENGE + message) |
| 756 |
digest = hmac.new(authkey, message, 'md5').digest() |
| 757 |
response = connection.recv_bytes(256) |
| 758 |
if response == digest: |
| 759 |
connection.send_bytes(WELCOME) |
| 760 |
else: |
| 761 |
connection.send_bytes(FAILURE) |
| 762 |
raise AuthenticationError('digest received was wrong') |
| 763 |
|
| 764 |
def answer_challenge(connection, authkey): |
| 765 |
import hmac |
| 766 |
if not isinstance(authkey, bytes): |
| 767 |
raise ValueError( |
| 768 |
"Authkey must be bytes, not {0!s}".format(type(authkey))) |
| 769 |
message = connection.recv_bytes(256) |
| 770 |
assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message |
| 771 |
message = message[len(CHALLENGE):] |
| 772 |
digest = hmac.new(authkey, message, 'md5').digest() |
| 773 |
connection.send_bytes(digest) |
| 774 |
response = connection.recv_bytes(256) |
| 775 |
if response != WELCOME: |
| 776 |
raise AuthenticationError('digest sent was rejected') |
| 777 |
|
| 778 |
|
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
class ConnectionWrapper(object): |
| 783 |
def __init__(self, conn, dumps, loads): |
| 784 |
self._conn = conn |
| 785 |
self._dumps = dumps |
| 786 |
self._loads = loads |
| 787 |
for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'): |
| 788 |
obj = getattr(conn, attr) |
| 789 |
setattr(self, attr, obj) |
| 790 |
def send(self, obj): |
| 791 |
s = self._dumps(obj) |
| 792 |
self._conn.send_bytes(s) |
| 793 |
def recv(self): |
| 794 |
s = self._conn.recv_bytes() |
| 795 |
return self._loads(s) |
| 796 |
|
| 797 |
def _xml_dumps(obj): |
| 798 |
return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf-8') |
| 799 |
|
| 800 |
def _xml_loads(s): |
| 801 |
(obj,), method = xmlrpclib.loads(s.decode('utf-8')) |
| 802 |
return obj |
| 803 |
|
| 804 |
class XmlListener(Listener): |
| 805 |
def accept(self): |
| 806 |
global xmlrpclib |
| 807 |
import xmlrpc.client as xmlrpclib |
| 808 |
obj = Listener.accept(self) |
| 809 |
return ConnectionWrapper(obj, _xml_dumps, _xml_loads) |
| 810 |
|
| 811 |
def XmlClient(*args, **kwds): |
| 812 |
global xmlrpclib |
| 813 |
import xmlrpc.client as xmlrpclib |
| 814 |
return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads) |
| 815 |
|
| 816 |
|
| 817 |
|
| 818 |
|
| 819 |
|
| 820 |
if sys.platform == 'win32': |
| 821 |
|
| 822 |
def _exhaustive_wait(handles, timeout): |
| 823 |
|
| 824 |
|
| 825 |
L = list(handles) |
| 826 |
ready = [] |
| 827 |
while L: |
| 828 |
res = _winapi.WaitForMultipleObjects(L, False, timeout) |
| 829 |
if res == WAIT_TIMEOUT: |
| 830 |
break |
| 831 |
elif WAIT_OBJECT_0 <= res < WAIT_OBJECT_0 + len(L): |
| 832 |
res -= WAIT_OBJECT_0 |
| 833 |
elif WAIT_ABANDONED_0 <= res < WAIT_ABANDONED_0 + len(L): |
| 834 |
res -= WAIT_ABANDONED_0 |
| 835 |
else: |
| 836 |
raise RuntimeError('Should not get here') |
| 837 |
ready.append(L[res]) |
| 838 |
L = L[res+1:] |
| 839 |
timeout = 0 |
| 840 |
return ready |
| 841 |
|
| 842 |
_ready_errors = {_winapi.ERROR_BROKEN_PIPE, _winapi.ERROR_NETNAME_DELETED} |
| 843 |
|
| 844 |
def wait(object_list, timeout=None): |
| 845 |
''' |
| 846 |
Wait till an object in object_list is ready/readable. |
| 847 |
|
| 848 |
Returns list of those objects in object_list which are ready/readable. |
| 849 |
''' |
| 850 |
if timeout is None: |
| 851 |
timeout = INFINITE |
| 852 |
elif timeout < 0: |
| 853 |
timeout = 0 |
| 854 |
else: |
| 855 |
timeout = int(timeout * 1000 + 0.5) |
| 856 |
|
| 857 |
object_list = list(object_list) |
| 858 |
waithandle_to_obj = {} |
| 859 |
ov_list = [] |
| 860 |
ready_objects = set() |
| 861 |
ready_handles = set() |
| 862 |
|
| 863 |
try: |
| 864 |
for o in object_list: |
| 865 |
try: |
| 866 |
fileno = getattr(o, 'fileno') |
| 867 |
except AttributeError: |
| 868 |
waithandle_to_obj[o.__index__()] = o |
| 869 |
else: |
| 870 |
|
| 871 |
try: |
| 872 |
ov, err = _winapi.ReadFile(fileno(), 0, True) |
| 873 |
except OSError as e: |
| 874 |
ov, err = None, e.winerror |
| 875 |
if err not in _ready_errors: |
| 876 |
raise |
| 877 |
if err == _winapi.ERROR_IO_PENDING: |
| 878 |
ov_list.append(ov) |
| 879 |
waithandle_to_obj[ov.event] = o |
| 880 |
else: |
| 881 |
|
| 882 |
|
| 883 |
|
| 884 |
if ov and sys.getwindowsversion()[:2] >= (6, 2): |
| 885 |
|
| 886 |
|
| 887 |
try: |
| 888 |
_, err = ov.GetOverlappedResult(False) |
| 889 |
except OSError as e: |
| 890 |
err = e.winerror |
| 891 |
if not err and hasattr(o, '_got_empty_message'): |
| 892 |
o._got_empty_message = True |
| 893 |
ready_objects.add(o) |
| 894 |
timeout = 0 |
| 895 |
|
| 896 |
ready_handles = _exhaustive_wait(waithandle_to_obj.keys(), timeout) |
| 897 |
finally: |
| 898 |
|
| 899 |
for ov in ov_list: |
| 900 |
ov.cancel() |
| 901 |
|
| 902 |
|
| 903 |
for ov in ov_list: |
| 904 |
try: |
| 905 |
_, err = ov.GetOverlappedResult(True) |
| 906 |
except OSError as e: |
| 907 |
err = e.winerror |
| 908 |
if err not in _ready_errors: |
| 909 |
raise |
| 910 |
if err != _winapi.ERROR_OPERATION_ABORTED: |
| 911 |
o = waithandle_to_obj[ov.event] |
| 912 |
ready_objects.add(o) |
| 913 |
if err == 0: |
| 914 |
|
| 915 |
|
| 916 |
if hasattr(o, '_got_empty_message'): |
| 917 |
o._got_empty_message = True |
| 918 |
|
| 919 |
ready_objects.update(waithandle_to_obj[h] for h in ready_handles) |
| 920 |
return [o for o in object_list if o in ready_objects] |
| 921 |
|
| 922 |
else: |
| 923 |
|
| 924 |
import selectors |
| 925 |
|
| 926 |
|
| 927 |
|
| 928 |
|
| 929 |
if hasattr(selectors, 'PollSelector'): |
| 930 |
_WaitSelector = selectors.PollSelector |
| 931 |
else: |
| 932 |
_WaitSelector = selectors.SelectSelector |
| 933 |
|
| 934 |
def wait(object_list, timeout=None): |
| 935 |
''' |
| 936 |
Wait till an object in object_list is ready/readable. |
| 937 |
|
| 938 |
Returns list of those objects in object_list which are ready/readable. |
| 939 |
''' |
| 940 |
with _WaitSelector() as selector: |
| 941 |
for obj in object_list: |
| 942 |
selector.register(obj, selectors.EVENT_READ) |
| 943 |
|
| 944 |
if timeout is not None: |
| 945 |
deadline = time.monotonic() + timeout |
| 946 |
|
| 947 |
while True: |
| 948 |
ready = selector.select(timeout) |
| 949 |
if ready: |
| 950 |
return [key.fileobj for (key, events) in ready] |
| 951 |
else: |
| 952 |
if timeout is not None: |
| 953 |
timeout = deadline - time.monotonic() |
| 954 |
if timeout < 0: |
| 955 |
return ready |
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
|
| 961 |
if sys.platform == 'win32': |
| 962 |
def reduce_connection(conn): |
| 963 |
handle = conn.fileno() |
| 964 |
with socket.fromfd(handle, socket.AF_INET, socket.SOCK_STREAM) as s: |
| 965 |
from . import resource_sharer |
| 966 |
ds = resource_sharer.DupSocket(s) |
| 967 |
return rebuild_connection, (ds, conn.readable, conn.writable) |
| 968 |
def rebuild_connection(ds, readable, writable): |
| 969 |
sock = ds.detach() |
| 970 |
return Connection(sock.detach(), readable, writable) |
| 971 |
reduction.register(Connection, reduce_connection) |
| 972 |
|
| 973 |
def reduce_pipe_connection(conn): |
| 974 |
access = ((_winapi.FILE_GENERIC_READ if conn.readable else 0) | |
| 975 |
(_winapi.FILE_GENERIC_WRITE if conn.writable else 0)) |
| 976 |
dh = reduction.DupHandle(conn.fileno(), access) |
| 977 |
return rebuild_pipe_connection, (dh, conn.readable, conn.writable) |
| 978 |
def rebuild_pipe_connection(dh, readable, writable): |
| 979 |
handle = dh.detach() |
| 980 |
return PipeConnection(handle, readable, writable) |
| 981 |
reduction.register(PipeConnection, reduce_pipe_connection) |
| 982 |
|
| 983 |
else: |
| 984 |
def reduce_connection(conn): |
| 985 |
df = reduction.DupFd(conn.fileno()) |
| 986 |
return rebuild_connection, (df, conn.readable, conn.writable) |
| 987 |
def rebuild_connection(df, readable, writable): |
| 988 |
fd = df.detach() |
| 989 |
return Connection(fd, readable, writable) |
| 990 |
reduction.register(Connection, reduce_connection) |