2018-10-10 12:23:21 +02:00
|
|
|
"""
|
|
|
|
Basic infrastructure for asynchronous socket service clients and servers.
|
2017-03-10 23:11:57 +01:00
|
|
|
"""
|
2020-01-06 12:44:47 +01:00
|
|
|
# -*- Mode: Python -*-
|
|
|
|
# Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp
|
|
|
|
# Author: Sam Rushing <rushing@nightmare.com>
|
|
|
|
# pylint: disable=too-many-branches,too-many-lines,global-statement
|
|
|
|
# pylint: disable=redefined-builtin,no-self-use
|
2018-10-10 12:23:21 +02:00
|
|
|
import os
|
2017-03-10 23:11:57 +01:00
|
|
|
import select
|
|
|
|
import socket
|
|
|
|
import sys
|
|
|
|
import time
|
|
|
|
import warnings
|
2018-10-10 12:23:21 +02:00
|
|
|
from errno import (
|
2020-01-06 12:44:47 +01:00
|
|
|
EADDRINUSE, EAGAIN, EALREADY, EBADF, ECONNABORTED, ECONNREFUSED,
|
|
|
|
ECONNRESET, EHOSTUNREACH, EINPROGRESS, EINTR, EINVAL, EISCONN, ENETUNREACH,
|
|
|
|
ENOTCONN, ENOTSOCK, EPIPE, ESHUTDOWN, ETIMEDOUT, EWOULDBLOCK, errorcode
|
2018-10-10 12:23:21 +02:00
|
|
|
)
|
|
|
|
from threading import current_thread
|
2017-03-10 23:11:57 +01:00
|
|
|
|
2018-03-21 14:56:27 +01:00
|
|
|
import helper_random
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-05-24 16:51:49 +02:00
|
|
|
try:
|
|
|
|
from errno import WSAEWOULDBLOCK
|
2017-05-29 12:56:59 +02:00
|
|
|
except (ImportError, AttributeError):
|
|
|
|
WSAEWOULDBLOCK = EWOULDBLOCK
|
2017-05-29 13:14:25 +02:00
|
|
|
try:
|
|
|
|
from errno import WSAENOTSOCK
|
|
|
|
except (ImportError, AttributeError):
|
|
|
|
WSAENOTSOCK = ENOTSOCK
|
2017-08-06 20:39:14 +02:00
|
|
|
try:
|
|
|
|
from errno import WSAECONNRESET
|
|
|
|
except (ImportError, AttributeError):
|
2017-08-06 21:26:25 +02:00
|
|
|
WSAECONNRESET = ECONNRESET
|
2017-08-09 17:29:23 +02:00
|
|
|
try:
|
2018-10-10 12:23:21 +02:00
|
|
|
# Desirable side-effects on Windows; imports winsock error numbers
|
|
|
|
from errno import WSAEADDRINUSE # pylint: disable=unused-import
|
2017-08-09 17:29:23 +02:00
|
|
|
except (ImportError, AttributeError):
|
|
|
|
WSAEADDRINUSE = EADDRINUSE
|
2017-05-29 12:56:59 +02:00
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
|
|
|
_DISCONNECTED = frozenset((
|
|
|
|
ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED, EPIPE, EBADF, ECONNREFUSED,
|
|
|
|
EHOSTUNREACH, ENETUNREACH, ETIMEDOUT, WSAECONNRESET))
|
2017-03-10 23:11:57 +01:00
|
|
|
|
2017-04-16 18:27:15 +02:00
|
|
|
OP_READ = 1
|
|
|
|
OP_WRITE = 2
|
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
|
|
|
socket_map
|
|
|
|
except NameError:
|
|
|
|
socket_map = {}
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def _strerror(err):
|
|
|
|
try:
|
|
|
|
return os.strerror(err)
|
|
|
|
except (ValueError, OverflowError, NameError):
|
|
|
|
if err in errorcode:
|
|
|
|
return errorcode[err]
|
2018-10-10 12:23:21 +02:00
|
|
|
return "Unknown error %s" % err
|
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
class ExitNow(Exception):
|
2020-01-06 12:44:47 +01:00
|
|
|
"""We don't use directly but may be necessary as we replace
|
|
|
|
asyncore due to some library raising or expecting it"""
|
2017-03-10 23:11:57 +01:00
|
|
|
pass
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
_reraised_exceptions = (ExitNow, KeyboardInterrupt, SystemExit)
|
|
|
|
|
2017-05-24 16:51:49 +02:00
|
|
|
maxDownloadRate = 0
|
|
|
|
downloadTimestamp = 0
|
|
|
|
downloadBucket = 0
|
2017-05-25 14:59:18 +02:00
|
|
|
receivedBytes = 0
|
2017-05-24 16:51:49 +02:00
|
|
|
maxUploadRate = 0
|
|
|
|
uploadTimestamp = 0
|
|
|
|
uploadBucket = 0
|
2017-05-25 14:59:18 +02:00
|
|
|
sentBytes = 0
|
2017-05-24 16:51:49 +02:00
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def read(obj):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Event to read from the object, i.e. its network socket."""
|
|
|
|
|
2018-01-02 15:24:47 +01:00
|
|
|
if not can_receive():
|
|
|
|
return
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
|
|
|
obj.handle_read_event()
|
|
|
|
except _reraised_exceptions:
|
|
|
|
raise
|
2018-10-10 12:23:21 +02:00
|
|
|
except BaseException:
|
2017-03-10 23:11:57 +01:00
|
|
|
obj.handle_error()
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def write(obj):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Event to write to the object, i.e. its network socket."""
|
|
|
|
|
2018-01-02 15:24:47 +01:00
|
|
|
if not can_send():
|
|
|
|
return
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
|
|
|
obj.handle_write_event()
|
|
|
|
except _reraised_exceptions:
|
|
|
|
raise
|
2018-10-10 12:23:21 +02:00
|
|
|
except BaseException:
|
2017-03-10 23:11:57 +01:00
|
|
|
obj.handle_error()
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-05-24 16:51:49 +02:00
|
|
|
def set_rates(download, upload):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Set throttling rates"""
|
|
|
|
|
2020-01-06 12:44:47 +01:00
|
|
|
global maxDownloadRate, maxUploadRate, downloadBucket
|
|
|
|
global uploadBucket, downloadTimestamp, uploadTimestamp
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2018-01-01 12:49:08 +01:00
|
|
|
maxDownloadRate = float(download) * 1024
|
|
|
|
maxUploadRate = float(upload) * 1024
|
2017-05-24 16:51:49 +02:00
|
|
|
downloadBucket = maxDownloadRate
|
|
|
|
uploadBucket = maxUploadRate
|
|
|
|
downloadTimestamp = time.time()
|
|
|
|
uploadTimestamp = time.time()
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2018-01-02 15:24:47 +01:00
|
|
|
def can_receive():
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Predicate indicating whether the download throttle is in effect"""
|
|
|
|
|
2018-01-02 15:24:47 +01:00
|
|
|
return maxDownloadRate == 0 or downloadBucket > 0
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2018-01-02 15:24:47 +01:00
|
|
|
def can_send():
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Predicate indicating whether the upload throttle is in effect"""
|
|
|
|
|
2018-01-02 15:24:47 +01:00
|
|
|
return maxUploadRate == 0 or uploadBucket > 0
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-05-29 00:24:07 +02:00
|
|
|
def update_received(download=0):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Update the receiving throttle"""
|
|
|
|
|
2017-08-22 13:49:27 +02:00
|
|
|
global receivedBytes, downloadBucket, downloadTimestamp
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-05-29 00:24:07 +02:00
|
|
|
currentTimestamp = time.time()
|
2017-05-25 14:59:18 +02:00
|
|
|
receivedBytes += download
|
2017-05-29 00:24:07 +02:00
|
|
|
if maxDownloadRate > 0:
|
2020-01-06 12:44:47 +01:00
|
|
|
bucketIncrease = \
|
|
|
|
maxDownloadRate * (currentTimestamp - downloadTimestamp)
|
2017-05-29 00:24:07 +02:00
|
|
|
downloadBucket += bucketIncrease
|
|
|
|
if downloadBucket > maxDownloadRate:
|
|
|
|
downloadBucket = int(maxDownloadRate)
|
|
|
|
downloadBucket -= download
|
|
|
|
downloadTimestamp = currentTimestamp
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-05-29 00:24:07 +02:00
|
|
|
def update_sent(upload=0):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Update the sending throttle"""
|
|
|
|
|
2017-08-22 13:49:27 +02:00
|
|
|
global sentBytes, uploadBucket, uploadTimestamp
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-05-29 00:24:07 +02:00
|
|
|
currentTimestamp = time.time()
|
2017-05-25 14:59:18 +02:00
|
|
|
sentBytes += upload
|
2017-05-29 00:24:07 +02:00
|
|
|
if maxUploadRate > 0:
|
2018-01-02 15:24:47 +01:00
|
|
|
bucketIncrease = maxUploadRate * (currentTimestamp - uploadTimestamp)
|
2017-05-29 00:24:07 +02:00
|
|
|
uploadBucket += bucketIncrease
|
|
|
|
if uploadBucket > maxUploadRate:
|
|
|
|
uploadBucket = int(maxUploadRate)
|
|
|
|
uploadBucket -= upload
|
|
|
|
uploadTimestamp = currentTimestamp
|
2017-05-24 16:51:49 +02:00
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def _exception(obj):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Handle exceptions as appropriate"""
|
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
|
|
|
obj.handle_expt_event()
|
|
|
|
except _reraised_exceptions:
|
|
|
|
raise
|
2018-10-10 12:23:21 +02:00
|
|
|
except BaseException:
|
2017-03-10 23:11:57 +01:00
|
|
|
obj.handle_error()
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def readwrite(obj, flags):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Read and write any pending data to/from the object"""
|
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
2018-01-02 15:24:47 +01:00
|
|
|
if flags & select.POLLIN and can_receive():
|
2017-03-10 23:11:57 +01:00
|
|
|
obj.handle_read_event()
|
2018-01-02 15:24:47 +01:00
|
|
|
if flags & select.POLLOUT and can_send():
|
2017-03-10 23:11:57 +01:00
|
|
|
obj.handle_write_event()
|
|
|
|
if flags & select.POLLPRI:
|
|
|
|
obj.handle_expt_event()
|
|
|
|
if flags & (select.POLLHUP | select.POLLERR | select.POLLNVAL):
|
|
|
|
obj.handle_close()
|
|
|
|
except socket.error as e:
|
|
|
|
if e.args[0] not in _DISCONNECTED:
|
|
|
|
obj.handle_error()
|
|
|
|
else:
|
|
|
|
obj.handle_close()
|
|
|
|
except _reraised_exceptions:
|
|
|
|
raise
|
2018-10-10 12:23:21 +02:00
|
|
|
except BaseException:
|
2017-03-10 23:11:57 +01:00
|
|
|
obj.handle_error()
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def select_poller(timeout=0.0, map=None):
|
|
|
|
"""A poller which uses select(), available on most platforms."""
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
if map is None:
|
|
|
|
map = socket_map
|
|
|
|
if map:
|
2018-10-10 12:23:21 +02:00
|
|
|
r = []
|
|
|
|
w = []
|
|
|
|
e = []
|
2017-03-10 23:11:57 +01:00
|
|
|
for fd, obj in list(map.items()):
|
|
|
|
is_r = obj.readable()
|
|
|
|
is_w = obj.writable()
|
|
|
|
if is_r:
|
|
|
|
r.append(fd)
|
|
|
|
# accepting sockets should not be writable
|
|
|
|
if is_w and not obj.accepting:
|
|
|
|
w.append(fd)
|
|
|
|
if is_r or is_w:
|
|
|
|
e.append(fd)
|
|
|
|
if [] == r == w == e:
|
|
|
|
time.sleep(timeout)
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
r, w, e = select.select(r, w, e, timeout)
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
return
|
2017-05-29 12:56:59 +02:00
|
|
|
except socket.error as err:
|
2017-08-06 20:40:35 +02:00
|
|
|
if err.args[0] in (EBADF, EINTR):
|
2017-08-06 20:39:14 +02:00
|
|
|
return
|
|
|
|
except Exception as err:
|
|
|
|
if err.args[0] in (WSAENOTSOCK, ):
|
2017-05-29 12:56:59 +02:00
|
|
|
return
|
2017-03-10 23:11:57 +01:00
|
|
|
|
2018-03-21 14:56:27 +01:00
|
|
|
for fd in helper_random.randomsample(r, len(r)):
|
2017-03-10 23:11:57 +01:00
|
|
|
obj = map.get(fd)
|
|
|
|
if obj is None:
|
|
|
|
continue
|
|
|
|
read(obj)
|
|
|
|
|
2018-03-21 14:56:27 +01:00
|
|
|
for fd in helper_random.randomsample(w, len(w)):
|
2017-03-10 23:11:57 +01:00
|
|
|
obj = map.get(fd)
|
|
|
|
if obj is None:
|
|
|
|
continue
|
|
|
|
write(obj)
|
|
|
|
|
|
|
|
for fd in e:
|
|
|
|
obj = map.get(fd)
|
|
|
|
if obj is None:
|
|
|
|
continue
|
|
|
|
_exception(obj)
|
2018-01-22 22:37:29 +01:00
|
|
|
else:
|
|
|
|
current_thread().stop.wait(timeout)
|
2017-03-10 23:11:57 +01:00
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def poll_poller(timeout=0.0, map=None):
|
|
|
|
"""A poller which uses poll(), available on most UNIXen."""
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
if map is None:
|
|
|
|
map = socket_map
|
|
|
|
if timeout is not None:
|
|
|
|
# timeout is in milliseconds
|
2018-10-10 12:23:21 +02:00
|
|
|
timeout = int(timeout * 1000)
|
2017-03-10 23:56:38 +01:00
|
|
|
try:
|
|
|
|
poll_poller.pollster
|
|
|
|
except AttributeError:
|
|
|
|
poll_poller.pollster = select.poll()
|
2017-03-10 23:11:57 +01:00
|
|
|
if map:
|
|
|
|
for fd, obj in list(map.items()):
|
2017-04-16 18:27:15 +02:00
|
|
|
flags = newflags = 0
|
2017-03-10 23:11:57 +01:00
|
|
|
if obj.readable():
|
|
|
|
flags |= select.POLLIN | select.POLLPRI
|
2017-04-16 18:27:15 +02:00
|
|
|
newflags |= OP_READ
|
|
|
|
else:
|
|
|
|
newflags &= ~ OP_READ
|
2017-03-10 23:11:57 +01:00
|
|
|
# accepting sockets should not be writable
|
|
|
|
if obj.writable() and not obj.accepting:
|
|
|
|
flags |= select.POLLOUT
|
2017-04-16 18:27:15 +02:00
|
|
|
newflags |= OP_WRITE
|
|
|
|
else:
|
|
|
|
newflags &= ~ OP_WRITE
|
2017-07-06 19:45:36 +02:00
|
|
|
if newflags != obj.poller_flags:
|
|
|
|
obj.poller_flags = newflags
|
|
|
|
try:
|
|
|
|
if obj.poller_registered:
|
|
|
|
poll_poller.pollster.modify(fd, flags)
|
|
|
|
else:
|
|
|
|
poll_poller.pollster.register(fd, flags)
|
|
|
|
obj.poller_registered = True
|
|
|
|
except IOError:
|
|
|
|
pass
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
2017-03-10 23:56:38 +01:00
|
|
|
r = poll_poller.pollster.poll(timeout)
|
2017-03-10 23:11:57 +01:00
|
|
|
except KeyboardInterrupt:
|
|
|
|
r = []
|
2017-07-21 09:06:02 +02:00
|
|
|
except socket.error as err:
|
|
|
|
if err.args[0] in (EBADF, WSAENOTSOCK, EINTR):
|
|
|
|
return
|
2018-03-21 14:56:27 +01:00
|
|
|
for fd, flags in helper_random.randomsample(r, len(r)):
|
2017-03-10 23:11:57 +01:00
|
|
|
obj = map.get(fd)
|
|
|
|
if obj is None:
|
|
|
|
continue
|
|
|
|
readwrite(obj, flags)
|
2018-01-22 22:37:29 +01:00
|
|
|
else:
|
|
|
|
current_thread().stop.wait(timeout)
|
2017-03-10 23:11:57 +01:00
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
# Aliases for backward compatibility
|
|
|
|
poll = select_poller
|
|
|
|
poll2 = poll3 = poll_poller
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def epoll_poller(timeout=0.0, map=None):
|
|
|
|
"""A poller which uses epoll(), supported on Linux 2.5.44 and newer."""
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
if map is None:
|
|
|
|
map = socket_map
|
2017-03-10 23:56:38 +01:00
|
|
|
try:
|
|
|
|
epoll_poller.pollster
|
|
|
|
except AttributeError:
|
|
|
|
epoll_poller.pollster = select.epoll()
|
2017-03-10 23:11:57 +01:00
|
|
|
if map:
|
|
|
|
for fd, obj in map.items():
|
2017-04-16 18:27:15 +02:00
|
|
|
flags = newflags = 0
|
2017-03-10 23:11:57 +01:00
|
|
|
if obj.readable():
|
|
|
|
flags |= select.POLLIN | select.POLLPRI
|
2017-04-16 18:27:15 +02:00
|
|
|
newflags |= OP_READ
|
|
|
|
else:
|
|
|
|
newflags &= ~ OP_READ
|
|
|
|
# accepting sockets should not be writable
|
|
|
|
if obj.writable() and not obj.accepting:
|
2017-03-10 23:11:57 +01:00
|
|
|
flags |= select.POLLOUT
|
2017-04-16 18:27:15 +02:00
|
|
|
newflags |= OP_WRITE
|
|
|
|
else:
|
|
|
|
newflags &= ~ OP_WRITE
|
2017-07-06 19:45:36 +02:00
|
|
|
if newflags != obj.poller_flags:
|
|
|
|
obj.poller_flags = newflags
|
2017-03-10 23:11:57 +01:00
|
|
|
# Only check for exceptions if object was either readable
|
|
|
|
# or writable.
|
|
|
|
flags |= select.POLLERR | select.POLLHUP | select.POLLNVAL
|
2017-07-06 19:45:36 +02:00
|
|
|
try:
|
|
|
|
if obj.poller_registered:
|
|
|
|
epoll_poller.pollster.modify(fd, flags)
|
|
|
|
else:
|
|
|
|
epoll_poller.pollster.register(fd, flags)
|
|
|
|
obj.poller_registered = True
|
|
|
|
except IOError:
|
|
|
|
pass
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
2017-03-10 23:56:38 +01:00
|
|
|
r = epoll_poller.pollster.poll(timeout)
|
2017-07-21 07:49:34 +02:00
|
|
|
except IOError as e:
|
|
|
|
if e.errno != EINTR:
|
|
|
|
raise
|
|
|
|
r = []
|
2018-10-10 12:23:21 +02:00
|
|
|
except select.error as err:
|
2017-03-10 23:11:57 +01:00
|
|
|
if err.args[0] != EINTR:
|
|
|
|
raise
|
|
|
|
r = []
|
2018-03-21 14:56:27 +01:00
|
|
|
for fd, flags in helper_random.randomsample(r, len(r)):
|
2017-03-10 23:11:57 +01:00
|
|
|
obj = map.get(fd)
|
|
|
|
if obj is None:
|
|
|
|
continue
|
2018-10-10 12:23:21 +02:00
|
|
|
readwrite(obj, flags)
|
2018-01-22 22:37:29 +01:00
|
|
|
else:
|
|
|
|
current_thread().stop.wait(timeout)
|
2017-03-10 23:11:57 +01:00
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def kqueue_poller(timeout=0.0, map=None):
|
|
|
|
"""A poller which uses kqueue(), BSD specific."""
|
2020-01-06 12:44:47 +01:00
|
|
|
# pylint: disable=no-member,too-many-statements
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
if map is None:
|
|
|
|
map = socket_map
|
2018-01-31 22:25:23 +01:00
|
|
|
try:
|
|
|
|
kqueue_poller.pollster
|
|
|
|
except AttributeError:
|
|
|
|
kqueue_poller.pollster = select.kqueue()
|
2017-03-10 23:11:57 +01:00
|
|
|
if map:
|
2018-01-31 22:25:23 +01:00
|
|
|
updates = []
|
2017-03-10 23:11:57 +01:00
|
|
|
selectables = 0
|
|
|
|
for fd, obj in map.items():
|
2017-08-22 13:49:27 +02:00
|
|
|
kq_filter = 0
|
2017-03-10 23:11:57 +01:00
|
|
|
if obj.readable():
|
2018-01-31 22:25:23 +01:00
|
|
|
kq_filter |= 1
|
|
|
|
selectables += 1
|
|
|
|
if obj.writable() and not obj.accepting:
|
|
|
|
kq_filter |= 2
|
|
|
|
selectables += 1
|
|
|
|
if kq_filter != obj.poller_filter:
|
|
|
|
# unlike other pollers, READ and WRITE aren't OR able but have
|
|
|
|
# to be set and checked separately
|
|
|
|
if kq_filter & 1 != obj.poller_filter & 1:
|
|
|
|
poller_flags = select.KQ_EV_ADD
|
|
|
|
if kq_filter & 1:
|
|
|
|
poller_flags |= select.KQ_EV_ENABLE
|
|
|
|
else:
|
|
|
|
poller_flags |= select.KQ_EV_DISABLE
|
2020-01-06 12:44:47 +01:00
|
|
|
updates.append(
|
|
|
|
select.kevent(
|
|
|
|
fd, filter=select.KQ_FILTER_READ,
|
|
|
|
flags=poller_flags))
|
2018-01-31 22:25:23 +01:00
|
|
|
if kq_filter & 2 != obj.poller_filter & 2:
|
|
|
|
poller_flags = select.KQ_EV_ADD
|
|
|
|
if kq_filter & 2:
|
|
|
|
poller_flags |= select.KQ_EV_ENABLE
|
|
|
|
else:
|
|
|
|
poller_flags |= select.KQ_EV_DISABLE
|
2020-01-06 12:44:47 +01:00
|
|
|
updates.append(
|
|
|
|
select.kevent(
|
|
|
|
fd, filter=select.KQ_FILTER_WRITE,
|
|
|
|
flags=poller_flags))
|
2018-01-31 22:25:23 +01:00
|
|
|
obj.poller_filter = kq_filter
|
|
|
|
|
|
|
|
if not selectables:
|
|
|
|
# unlike other pollers, kqueue poll does not wait if there are no
|
|
|
|
# filters setup
|
|
|
|
current_thread().stop.wait(timeout)
|
|
|
|
return
|
2017-03-10 23:11:57 +01:00
|
|
|
|
2018-01-31 22:25:23 +01:00
|
|
|
events = kqueue_poller.pollster.control(updates, selectables, timeout)
|
|
|
|
if len(events) > 1:
|
2018-03-21 14:56:27 +01:00
|
|
|
events = helper_random.randomsample(events, len(events))
|
2018-01-31 22:25:23 +01:00
|
|
|
|
|
|
|
for event in events:
|
2017-03-10 23:11:57 +01:00
|
|
|
fd = event.ident
|
2018-10-10 12:23:21 +02:00
|
|
|
obj = map.get(fd)
|
2017-03-10 23:11:57 +01:00
|
|
|
if obj is None:
|
|
|
|
continue
|
2018-01-31 22:25:23 +01:00
|
|
|
if event.flags & select.KQ_EV_ERROR:
|
|
|
|
_exception(obj)
|
|
|
|
continue
|
|
|
|
if event.flags & select.KQ_EV_EOF and event.data and event.fflags:
|
|
|
|
obj.handle_close()
|
|
|
|
continue
|
2017-03-10 23:11:57 +01:00
|
|
|
if event.filter == select.KQ_FILTER_READ:
|
|
|
|
read(obj)
|
|
|
|
if event.filter == select.KQ_FILTER_WRITE:
|
|
|
|
write(obj)
|
2018-01-22 22:37:29 +01:00
|
|
|
else:
|
|
|
|
current_thread().stop.wait(timeout)
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None):
|
|
|
|
"""Poll in a loop, until count or timeout is reached"""
|
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
if map is None:
|
|
|
|
map = socket_map
|
2018-01-23 15:59:58 +01:00
|
|
|
if count is None:
|
2018-10-10 12:23:21 +02:00
|
|
|
count = True
|
|
|
|
# code which grants backward compatibility with "use_poll"
|
2017-03-10 23:11:57 +01:00
|
|
|
# argument which should no longer be used in favor of
|
|
|
|
# "poller"
|
2017-03-10 23:56:38 +01:00
|
|
|
|
2017-07-06 19:45:36 +02:00
|
|
|
if poller is None:
|
2017-08-22 13:49:27 +02:00
|
|
|
if use_poll:
|
|
|
|
poller = poll_poller
|
|
|
|
elif hasattr(select, 'epoll'):
|
2017-07-06 19:45:36 +02:00
|
|
|
poller = epoll_poller
|
|
|
|
elif hasattr(select, 'kqueue'):
|
|
|
|
poller = kqueue_poller
|
|
|
|
elif hasattr(select, 'poll'):
|
|
|
|
poller = poll_poller
|
|
|
|
elif hasattr(select, 'select'):
|
|
|
|
poller = select_poller
|
2017-03-20 18:32:26 +01:00
|
|
|
|
2018-01-23 15:59:58 +01:00
|
|
|
if timeout == 0:
|
|
|
|
deadline = 0
|
2017-03-10 23:11:57 +01:00
|
|
|
else:
|
2018-01-23 15:59:58 +01:00
|
|
|
deadline = time.time() + timeout
|
|
|
|
while count:
|
|
|
|
# fill buckets first
|
|
|
|
update_sent()
|
|
|
|
update_received()
|
|
|
|
subtimeout = deadline - time.time()
|
|
|
|
if subtimeout <= 0:
|
|
|
|
break
|
|
|
|
# then poll
|
|
|
|
poller(subtimeout, map)
|
2018-10-10 12:23:21 +02:00
|
|
|
if isinstance(count, int):
|
2017-03-10 23:11:57 +01:00
|
|
|
count = count - 1
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2020-01-06 12:44:47 +01:00
|
|
|
class dispatcher(object):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Dispatcher for socket objects"""
|
2020-01-06 12:44:47 +01:00
|
|
|
# pylint: disable=too-many-public-methods,too-many-instance-attributes
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
debug = False
|
|
|
|
connected = False
|
|
|
|
accepting = False
|
|
|
|
connecting = False
|
|
|
|
closing = False
|
|
|
|
addr = None
|
|
|
|
ignore_log_types = frozenset(['warning'])
|
2017-04-16 18:27:15 +02:00
|
|
|
poller_registered = False
|
2017-07-06 19:45:36 +02:00
|
|
|
poller_flags = 0
|
2017-05-29 00:24:07 +02:00
|
|
|
# don't do network IO with a smaller bucket than this
|
|
|
|
minTx = 1500
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
def __init__(self, sock=None, map=None):
|
|
|
|
if map is None:
|
|
|
|
self._map = socket_map
|
|
|
|
else:
|
|
|
|
self._map = map
|
|
|
|
|
|
|
|
self._fileno = None
|
|
|
|
|
|
|
|
if sock:
|
|
|
|
# Set to nonblocking just to make sure for cases where we
|
|
|
|
# get a socket from a blocking source.
|
|
|
|
sock.setblocking(0)
|
|
|
|
self.set_socket(sock, map)
|
|
|
|
self.connected = True
|
|
|
|
# The constructor no longer requires that the socket
|
|
|
|
# passed be connected.
|
|
|
|
try:
|
|
|
|
self.addr = sock.getpeername()
|
|
|
|
except socket.error as err:
|
|
|
|
if err.args[0] in (ENOTCONN, EINVAL):
|
|
|
|
# To handle the case where we got an unconnected
|
|
|
|
# socket.
|
|
|
|
self.connected = False
|
|
|
|
else:
|
|
|
|
# The socket is broken in some unknown way, alert
|
|
|
|
# the user and remove it from the map (to prevent
|
|
|
|
# polling of broken sockets).
|
|
|
|
self.del_channel(map)
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
self.socket = None
|
|
|
|
|
|
|
|
def __repr__(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
status = [self.__class__.__module__ + "." + self.__class__.__name__]
|
2017-03-10 23:11:57 +01:00
|
|
|
if self.accepting and self.addr:
|
|
|
|
status.append('listening')
|
|
|
|
elif self.connected:
|
|
|
|
status.append('connected')
|
|
|
|
if self.addr is not None:
|
|
|
|
try:
|
|
|
|
status.append('%s:%d' % self.addr)
|
|
|
|
except TypeError:
|
|
|
|
status.append(repr(self.addr))
|
|
|
|
return '<%s at %#x>' % (' '.join(status), id(self))
|
|
|
|
|
|
|
|
__str__ = __repr__
|
|
|
|
|
|
|
|
def add_channel(self, map=None):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Add a channel"""
|
2020-01-06 12:44:47 +01:00
|
|
|
# pylint: disable=attribute-defined-outside-init
|
2017-03-10 23:11:57 +01:00
|
|
|
if map is None:
|
|
|
|
map = self._map
|
|
|
|
map[self._fileno] = self
|
2017-07-06 19:45:36 +02:00
|
|
|
self.poller_flags = 0
|
2018-01-31 22:25:23 +01:00
|
|
|
self.poller_filter = 0
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
def del_channel(self, map=None):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Delete a channel"""
|
2017-03-10 23:11:57 +01:00
|
|
|
fd = self._fileno
|
|
|
|
if map is None:
|
|
|
|
map = self._map
|
|
|
|
if fd in map:
|
|
|
|
del map[fd]
|
2018-01-31 22:25:23 +01:00
|
|
|
if self._fileno:
|
|
|
|
try:
|
2020-01-06 12:44:47 +01:00
|
|
|
kqueue_poller.pollster.control([select.kevent(
|
|
|
|
fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE)], 0)
|
|
|
|
except(AttributeError, KeyError, TypeError, IOError, OSError):
|
2018-01-31 22:25:23 +01:00
|
|
|
pass
|
|
|
|
try:
|
2020-01-06 12:44:47 +01:00
|
|
|
kqueue_poller.pollster.control([select.kevent(
|
|
|
|
fd, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE)], 0)
|
|
|
|
except(AttributeError, KeyError, TypeError, IOError, OSError):
|
2018-01-31 22:25:23 +01:00
|
|
|
pass
|
|
|
|
try:
|
|
|
|
epoll_poller.pollster.unregister(fd)
|
|
|
|
except (AttributeError, KeyError, TypeError, IOError):
|
|
|
|
# no epoll used, or not registered
|
|
|
|
pass
|
|
|
|
try:
|
|
|
|
poll_poller.pollster.unregister(fd)
|
|
|
|
except (AttributeError, KeyError, TypeError, IOError):
|
|
|
|
# no poll used, or not registered
|
|
|
|
pass
|
2017-03-10 23:11:57 +01:00
|
|
|
self._fileno = None
|
2018-01-31 22:25:23 +01:00
|
|
|
self.poller_flags = 0
|
|
|
|
self.poller_filter = 0
|
|
|
|
self.poller_registered = False
|
2017-03-10 23:11:57 +01:00
|
|
|
|
2020-01-06 12:44:47 +01:00
|
|
|
def create_socket(
|
|
|
|
self, family=socket.AF_INET, socket_type=socket.SOCK_STREAM):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Create a socket"""
|
2020-01-06 12:44:47 +01:00
|
|
|
# pylint: disable=attribute-defined-outside-init
|
2017-08-22 13:49:27 +02:00
|
|
|
self.family_and_type = family, socket_type
|
|
|
|
sock = socket.socket(family, socket_type)
|
2017-03-10 23:11:57 +01:00
|
|
|
sock.setblocking(0)
|
|
|
|
self.set_socket(sock)
|
|
|
|
|
|
|
|
def set_socket(self, sock, map=None):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Set socket"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.socket = sock
|
|
|
|
self._fileno = sock.fileno()
|
|
|
|
self.add_channel(map)
|
|
|
|
|
|
|
|
def set_reuse_addr(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""try to re-use a server port if possible"""
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
|
|
|
self.socket.setsockopt(
|
2020-01-06 12:44:47 +01:00
|
|
|
socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(
|
|
|
|
socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1
|
2018-10-10 12:23:21 +02:00
|
|
|
)
|
2017-03-10 23:11:57 +01:00
|
|
|
except socket.error:
|
|
|
|
pass
|
|
|
|
|
|
|
|
# ==================================================
|
|
|
|
# predicates for select()
|
|
|
|
# these are used as filters for the lists of sockets
|
|
|
|
# to pass to select().
|
|
|
|
# ==================================================
|
|
|
|
|
|
|
|
def readable(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Predicate to indicate download throttle status"""
|
2017-05-29 00:24:07 +02:00
|
|
|
if maxDownloadRate > 0:
|
|
|
|
return downloadBucket > dispatcher.minTx
|
2017-03-10 23:11:57 +01:00
|
|
|
return True
|
|
|
|
|
|
|
|
def writable(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Predicate to indicate upload throttle status"""
|
2017-05-29 00:24:07 +02:00
|
|
|
if maxUploadRate > 0:
|
|
|
|
return uploadBucket > dispatcher.minTx
|
2017-03-10 23:11:57 +01:00
|
|
|
return True
|
|
|
|
|
|
|
|
# ==================================================
|
|
|
|
# socket object methods.
|
|
|
|
# ==================================================
|
|
|
|
|
|
|
|
def listen(self, num):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Listen on a port"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.accepting = True
|
|
|
|
if os.name == 'nt' and num > 5:
|
|
|
|
num = 5
|
|
|
|
return self.socket.listen(num)
|
|
|
|
|
|
|
|
def bind(self, addr):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Bind to an address"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.addr = addr
|
|
|
|
return self.socket.bind(addr)
|
|
|
|
|
|
|
|
def connect(self, address):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Connect to an address"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.connected = False
|
|
|
|
self.connecting = True
|
|
|
|
err = self.socket.connect_ex(address)
|
2017-08-06 18:18:21 +02:00
|
|
|
if err in (EINPROGRESS, EALREADY, EWOULDBLOCK, WSAEWOULDBLOCK) \
|
2018-10-10 12:23:21 +02:00
|
|
|
or err == EINVAL and os.name in ('nt', 'ce'):
|
2017-03-10 23:11:57 +01:00
|
|
|
self.addr = address
|
|
|
|
return
|
|
|
|
if err in (0, EISCONN):
|
|
|
|
self.addr = address
|
|
|
|
self.handle_connect_event()
|
|
|
|
else:
|
|
|
|
raise socket.error(err, errorcode[err])
|
|
|
|
|
|
|
|
def accept(self):
|
2020-01-06 12:44:47 +01:00
|
|
|
"""Accept incoming connections.
|
|
|
|
Returns either an address pair or None."""
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
|
|
|
conn, addr = self.socket.accept()
|
|
|
|
except TypeError:
|
|
|
|
return None
|
|
|
|
except socket.error as why:
|
2020-01-06 12:44:47 +01:00
|
|
|
if why.args[0] in (
|
|
|
|
EWOULDBLOCK, WSAEWOULDBLOCK, ECONNABORTED,
|
|
|
|
EAGAIN, ENOTCONN):
|
2017-03-10 23:11:57 +01:00
|
|
|
return None
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
return conn, addr
|
|
|
|
|
|
|
|
def send(self, data):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Send data"""
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
|
|
|
result = self.socket.send(data)
|
|
|
|
return result
|
2017-05-24 16:51:49 +02:00
|
|
|
except socket.error as why:
|
2017-05-29 12:56:59 +02:00
|
|
|
if why.args[0] in (EAGAIN, EWOULDBLOCK, WSAEWOULDBLOCK):
|
|
|
|
return 0
|
2017-05-24 21:15:36 +02:00
|
|
|
elif why.args[0] in _DISCONNECTED:
|
2017-03-10 23:11:57 +01:00
|
|
|
self.handle_close()
|
|
|
|
return 0
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
|
|
|
def recv(self, buffer_size):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Receive data"""
|
2017-03-10 23:11:57 +01:00
|
|
|
try:
|
|
|
|
data = self.socket.recv(buffer_size)
|
|
|
|
if not data:
|
|
|
|
# a closed connection is indicated by signaling
|
|
|
|
# a read condition, and having recv() return 0.
|
|
|
|
self.handle_close()
|
|
|
|
return b''
|
2018-10-10 12:23:21 +02:00
|
|
|
return data
|
2017-03-10 23:11:57 +01:00
|
|
|
except socket.error as why:
|
|
|
|
# winsock sometimes raises ENOTCONN
|
2017-05-29 12:56:59 +02:00
|
|
|
if why.args[0] in (EAGAIN, EWOULDBLOCK, WSAEWOULDBLOCK):
|
|
|
|
return b''
|
2017-05-24 21:15:36 +02:00
|
|
|
if why.args[0] in _DISCONNECTED:
|
2017-03-10 23:11:57 +01:00
|
|
|
self.handle_close()
|
|
|
|
return b''
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
|
|
|
def close(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Close connection"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.connected = False
|
|
|
|
self.accepting = False
|
|
|
|
self.connecting = False
|
|
|
|
self.del_channel()
|
|
|
|
try:
|
|
|
|
self.socket.close()
|
|
|
|
except socket.error as why:
|
|
|
|
if why.args[0] not in (ENOTCONN, EBADF):
|
|
|
|
raise
|
|
|
|
|
|
|
|
# cheap inheritance, used to pass all other attribute
|
|
|
|
# references to the underlying socket object.
|
|
|
|
def __getattr__(self, attr):
|
|
|
|
try:
|
|
|
|
retattr = getattr(self.socket, attr)
|
|
|
|
except AttributeError:
|
2020-01-06 12:44:47 +01:00
|
|
|
raise AttributeError(
|
|
|
|
"%s instance has no attribute '%s'"
|
|
|
|
% (self.__class__.__name__, attr))
|
2017-03-10 23:11:57 +01:00
|
|
|
else:
|
2020-01-06 12:44:47 +01:00
|
|
|
msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s"\
|
|
|
|
" instead" % {'me': self.__class__.__name__, 'attr': attr}
|
2017-03-10 23:11:57 +01:00
|
|
|
warnings.warn(msg, DeprecationWarning, stacklevel=2)
|
|
|
|
return retattr
|
|
|
|
|
|
|
|
# log and log_info may be overridden to provide more sophisticated
|
|
|
|
# logging and warning methods. In general, log is for 'hit' logging
|
|
|
|
# and 'log_info' is for informational, warning and error logging.
|
|
|
|
|
|
|
|
def log(self, message):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Log a message to stderr"""
|
2017-03-10 23:11:57 +01:00
|
|
|
sys.stderr.write('log: %s\n' % str(message))
|
|
|
|
|
2017-08-22 13:49:27 +02:00
|
|
|
def log_info(self, message, log_type='info'):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Conditionally print a message"""
|
2017-08-22 13:49:27 +02:00
|
|
|
if log_type not in self.ignore_log_types:
|
2021-02-15 15:23:26 +01:00
|
|
|
print('%s: %s' % (log_type, message))
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
def handle_read_event(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Handle a read event"""
|
2017-03-10 23:11:57 +01:00
|
|
|
if self.accepting:
|
|
|
|
# accepting sockets are never connected, they "spawn" new
|
|
|
|
# sockets that are connected
|
|
|
|
self.handle_accept()
|
|
|
|
elif not self.connected:
|
|
|
|
if self.connecting:
|
|
|
|
self.handle_connect_event()
|
|
|
|
self.handle_read()
|
|
|
|
else:
|
|
|
|
self.handle_read()
|
|
|
|
|
|
|
|
def handle_connect_event(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Handle a connection event"""
|
2017-03-10 23:11:57 +01:00
|
|
|
err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
|
|
|
|
if err != 0:
|
|
|
|
raise socket.error(err, _strerror(err))
|
|
|
|
self.handle_connect()
|
|
|
|
self.connected = True
|
|
|
|
self.connecting = False
|
|
|
|
|
|
|
|
def handle_write_event(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Handle a write event"""
|
2017-03-10 23:11:57 +01:00
|
|
|
if self.accepting:
|
|
|
|
# Accepting sockets shouldn't get a write event.
|
|
|
|
# We will pretend it didn't happen.
|
|
|
|
return
|
|
|
|
|
|
|
|
if not self.connected:
|
|
|
|
if self.connecting:
|
|
|
|
self.handle_connect_event()
|
|
|
|
self.handle_write()
|
|
|
|
|
|
|
|
def handle_expt_event(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Handle expected exceptions"""
|
2017-03-10 23:11:57 +01:00
|
|
|
# handle_expt_event() is called if there might be an error on the
|
|
|
|
# socket, or if there is OOB data
|
|
|
|
# check for the error condition first
|
|
|
|
err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
|
|
|
|
if err != 0:
|
|
|
|
# we can get here when select.select() says that there is an
|
|
|
|
# exceptional condition on the socket
|
|
|
|
# since there is an error, we'll go ahead and close the socket
|
|
|
|
# like we would in a subclassed handle_read() that received no
|
|
|
|
# data
|
|
|
|
self.handle_close()
|
2017-08-06 20:39:14 +02:00
|
|
|
elif sys.platform.startswith("win"):
|
|
|
|
# async connect failed
|
|
|
|
self.handle_close()
|
2017-03-10 23:11:57 +01:00
|
|
|
else:
|
|
|
|
self.handle_expt()
|
|
|
|
|
|
|
|
def handle_error(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Handle unexpected exceptions"""
|
|
|
|
_, t, v, tbinfo = compact_traceback()
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
# sometimes a user repr method will crash.
|
|
|
|
try:
|
|
|
|
self_repr = repr(self)
|
2018-10-10 12:23:21 +02:00
|
|
|
except BaseException:
|
2017-03-10 23:11:57 +01:00
|
|
|
self_repr = '<__repr__(self) failed for object at %0x>' % id(self)
|
|
|
|
|
|
|
|
self.log_info(
|
|
|
|
'uncaptured python exception, closing channel %s (%s:%s %s)' % (
|
2020-01-06 12:44:47 +01:00
|
|
|
self_repr, t, v, tbinfo),
|
|
|
|
'error')
|
2017-03-10 23:11:57 +01:00
|
|
|
self.handle_close()
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
def handle_accept(self):
|
|
|
|
"""Handle an accept event"""
|
|
|
|
pair = self.accept()
|
|
|
|
if pair is not None:
|
|
|
|
self.handle_accepted(*pair)
|
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def handle_expt(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Log that the subclass does not implement handle_expt"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.log_info('unhandled incoming priority event', 'warning')
|
|
|
|
|
|
|
|
def handle_read(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Log that the subclass does not implement handle_read"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.log_info('unhandled read event', 'warning')
|
|
|
|
|
|
|
|
def handle_write(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Log that the subclass does not implement handle_write"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.log_info('unhandled write event', 'warning')
|
|
|
|
|
|
|
|
def handle_connect(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Log that the subclass does not implement handle_connect"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.log_info('unhandled connect event', 'warning')
|
|
|
|
|
|
|
|
def handle_accepted(self, sock, addr):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Log that the subclass does not implement handle_accepted"""
|
2017-03-10 23:11:57 +01:00
|
|
|
sock.close()
|
2017-08-22 13:49:27 +02:00
|
|
|
self.log_info('unhandled accepted event on %s' % (addr), 'warning')
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
def handle_close(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Log that the subclass does not implement handle_close"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.log_info('unhandled close event', 'warning')
|
|
|
|
self.close()
|
|
|
|
|
|
|
|
|
|
|
|
class dispatcher_with_send(dispatcher):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""
|
|
|
|
adds simple buffered output capability, useful for simple clients.
|
|
|
|
[for more sophisticated usage use asynchat.async_chat]
|
|
|
|
"""
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
def __init__(self, sock=None, map=None):
|
|
|
|
dispatcher.__init__(self, sock, map)
|
|
|
|
self.out_buffer = b''
|
|
|
|
|
|
|
|
def initiate_send(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Initiate a send"""
|
2017-03-10 23:11:57 +01:00
|
|
|
num_sent = 0
|
|
|
|
num_sent = dispatcher.send(self, self.out_buffer[:512])
|
|
|
|
self.out_buffer = self.out_buffer[num_sent:]
|
|
|
|
|
|
|
|
def handle_write(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Handle a write event"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.initiate_send()
|
|
|
|
|
|
|
|
def writable(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Predicate to indicate if the object is writable"""
|
|
|
|
return not self.connected or len(self.out_buffer)
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
def send(self, data):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Send data"""
|
2017-03-10 23:11:57 +01:00
|
|
|
if self.debug:
|
|
|
|
self.log_info('sending %s' % repr(data))
|
|
|
|
self.out_buffer = self.out_buffer + data
|
|
|
|
self.initiate_send()
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
# used for debugging.
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
def compact_traceback():
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Return a compact traceback"""
|
2017-03-10 23:11:57 +01:00
|
|
|
t, v, tb = sys.exc_info()
|
|
|
|
tbinfo = []
|
2020-01-06 12:44:47 +01:00
|
|
|
# Must have a traceback
|
|
|
|
if not tb:
|
2017-03-10 23:11:57 +01:00
|
|
|
raise AssertionError("traceback does not exist")
|
|
|
|
while tb:
|
|
|
|
tbinfo.append((
|
|
|
|
tb.tb_frame.f_code.co_filename,
|
|
|
|
tb.tb_frame.f_code.co_name,
|
|
|
|
str(tb.tb_lineno)
|
2018-10-10 12:23:21 +02:00
|
|
|
))
|
2017-03-10 23:11:57 +01:00
|
|
|
tb = tb.tb_next
|
|
|
|
|
|
|
|
# just to be safe
|
|
|
|
del tb
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
filename, function, line = tbinfo[-1]
|
2017-03-10 23:11:57 +01:00
|
|
|
info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo])
|
2018-10-10 12:23:21 +02:00
|
|
|
return (filename, function, line), t, v, info
|
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
def close_all(map=None, ignore_all=False):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Close all connections"""
|
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
if map is None:
|
|
|
|
map = socket_map
|
|
|
|
for x in list(map.values()):
|
|
|
|
try:
|
|
|
|
x.close()
|
2017-08-22 13:49:27 +02:00
|
|
|
except OSError as e:
|
|
|
|
if e.args[0] == EBADF:
|
2017-03-10 23:11:57 +01:00
|
|
|
pass
|
|
|
|
elif not ignore_all:
|
|
|
|
raise
|
|
|
|
except _reraised_exceptions:
|
|
|
|
raise
|
2018-10-10 12:23:21 +02:00
|
|
|
except BaseException:
|
2017-03-10 23:11:57 +01:00
|
|
|
if not ignore_all:
|
|
|
|
raise
|
|
|
|
map.clear()
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
# Asynchronous File I/O:
|
|
|
|
#
|
|
|
|
# After a little research (reading man pages on various unixen, and
|
|
|
|
# digging through the linux kernel), I've determined that select()
|
|
|
|
# isn't meant for doing asynchronous file i/o.
|
|
|
|
# Heartening, though - reading linux/mm/filemap.c shows that linux
|
|
|
|
# supports asynchronous read-ahead. So _MOST_ of the time, the data
|
|
|
|
# will be sitting in memory for us already when we go to read it.
|
|
|
|
#
|
|
|
|
# What other OS's (besides NT) support async file i/o? [VMS?]
|
|
|
|
#
|
|
|
|
# Regardless, this is useful for pipes, and stdin/stdout...
|
|
|
|
|
2018-10-10 12:23:21 +02:00
|
|
|
|
2017-03-10 23:11:57 +01:00
|
|
|
if os.name == 'posix':
|
|
|
|
import fcntl
|
|
|
|
|
2020-01-06 12:44:47 +01:00
|
|
|
class file_wrapper: # pylint: disable=old-style-class
|
2018-10-10 12:23:21 +02:00
|
|
|
"""
|
2020-01-06 12:44:47 +01:00
|
|
|
Here we override just enough to make a file look
|
|
|
|
like a socket for the purposes of asyncore.
|
2018-10-10 12:23:21 +02:00
|
|
|
|
|
|
|
The passed fd is automatically os.dup()'d
|
|
|
|
"""
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
def __init__(self, fd):
|
|
|
|
self.fd = os.dup(fd)
|
|
|
|
|
|
|
|
def recv(self, *args):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Fake recv()"""
|
2017-03-10 23:11:57 +01:00
|
|
|
return os.read(self.fd, *args)
|
|
|
|
|
|
|
|
def send(self, *args):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Fake send()"""
|
2017-03-10 23:11:57 +01:00
|
|
|
return os.write(self.fd, *args)
|
|
|
|
|
|
|
|
def getsockopt(self, level, optname, buflen=None):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Fake getsockopt()"""
|
2020-01-06 12:44:47 +01:00
|
|
|
if (level == socket.SOL_SOCKET and optname == socket.SO_ERROR and
|
2018-10-10 12:23:21 +02:00
|
|
|
not buflen):
|
2017-03-10 23:11:57 +01:00
|
|
|
return 0
|
2020-01-06 12:44:47 +01:00
|
|
|
raise NotImplementedError(
|
|
|
|
"Only asyncore specific behaviour implemented.")
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
read = recv
|
|
|
|
write = send
|
|
|
|
|
|
|
|
def close(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Fake close()"""
|
2017-03-10 23:11:57 +01:00
|
|
|
os.close(self.fd)
|
|
|
|
|
|
|
|
def fileno(self):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Fake fileno()"""
|
2017-03-10 23:11:57 +01:00
|
|
|
return self.fd
|
|
|
|
|
|
|
|
class file_dispatcher(dispatcher):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""A dispatcher for file_wrapper objects"""
|
2017-03-10 23:11:57 +01:00
|
|
|
|
|
|
|
def __init__(self, fd, map=None):
|
|
|
|
dispatcher.__init__(self, None, map)
|
|
|
|
self.connected = True
|
|
|
|
try:
|
|
|
|
fd = fd.fileno()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
self.set_file(fd)
|
|
|
|
# set it to non-blocking mode
|
|
|
|
flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
|
|
|
|
flags = flags | os.O_NONBLOCK
|
|
|
|
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
|
|
|
|
|
|
|
|
def set_file(self, fd):
|
2018-10-10 12:23:21 +02:00
|
|
|
"""Set file"""
|
2017-03-10 23:11:57 +01:00
|
|
|
self.socket = file_wrapper(fd)
|
|
|
|
self._fileno = self.socket.fileno()
|
|
|
|
self.add_channel()
|