| 1 | n/a | # -*- Mode: Python -*- |
|---|
| 2 | n/a | # Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp |
|---|
| 3 | n/a | # Author: Sam Rushing <rushing@nightmare.com> |
|---|
| 4 | n/a | |
|---|
| 5 | n/a | # ====================================================================== |
|---|
| 6 | n/a | # Copyright 1996 by Sam Rushing |
|---|
| 7 | n/a | # |
|---|
| 8 | n/a | # All Rights Reserved |
|---|
| 9 | n/a | # |
|---|
| 10 | n/a | # Permission to use, copy, modify, and distribute this software and |
|---|
| 11 | n/a | # its documentation for any purpose and without fee is hereby |
|---|
| 12 | n/a | # granted, provided that the above copyright notice appear in all |
|---|
| 13 | n/a | # copies and that both that copyright notice and this permission |
|---|
| 14 | n/a | # notice appear in supporting documentation, and that the name of Sam |
|---|
| 15 | n/a | # Rushing not be used in advertising or publicity pertaining to |
|---|
| 16 | n/a | # distribution of the software without specific, written prior |
|---|
| 17 | n/a | # permission. |
|---|
| 18 | n/a | # |
|---|
| 19 | n/a | # SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, |
|---|
| 20 | n/a | # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN |
|---|
| 21 | n/a | # NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR |
|---|
| 22 | n/a | # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS |
|---|
| 23 | n/a | # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, |
|---|
| 24 | n/a | # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN |
|---|
| 25 | n/a | # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
|---|
| 26 | n/a | # ====================================================================== |
|---|
| 27 | n/a | |
|---|
| 28 | n/a | """Basic infrastructure for asynchronous socket service clients and servers. |
|---|
| 29 | n/a | |
|---|
| 30 | n/a | There are only two ways to have a program on a single processor do "more |
|---|
| 31 | n/a | than one thing at a time". Multi-threaded programming is the simplest and |
|---|
| 32 | n/a | most popular way to do it, but there is another very different technique, |
|---|
| 33 | n/a | that lets you have nearly all the advantages of multi-threading, without |
|---|
| 34 | n/a | actually using multiple threads. it's really only practical if your program |
|---|
| 35 | n/a | is largely I/O bound. If your program is CPU bound, then pre-emptive |
|---|
| 36 | n/a | scheduled threads are probably what you really need. Network servers are |
|---|
| 37 | n/a | rarely CPU-bound, however. |
|---|
| 38 | n/a | |
|---|
| 39 | n/a | If your operating system supports the select() system call in its I/O |
|---|
| 40 | n/a | library (and nearly all do), then you can use it to juggle multiple |
|---|
| 41 | n/a | communication channels at once; doing other work while your I/O is taking |
|---|
| 42 | n/a | place in the "background." Although this strategy can seem strange and |
|---|
| 43 | n/a | complex, especially at first, it is in many ways easier to understand and |
|---|
| 44 | n/a | control than multi-threaded programming. The module documented here solves |
|---|
| 45 | n/a | many of the difficult problems for you, making the task of building |
|---|
| 46 | n/a | sophisticated high-performance network servers and clients a snap. |
|---|
| 47 | n/a | """ |
|---|
| 48 | n/a | |
|---|
| 49 | n/a | import select |
|---|
| 50 | n/a | import socket |
|---|
| 51 | n/a | import sys |
|---|
| 52 | n/a | import time |
|---|
| 53 | n/a | import warnings |
|---|
| 54 | n/a | |
|---|
| 55 | n/a | import os |
|---|
| 56 | n/a | from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, EINVAL, \ |
|---|
| 57 | n/a | ENOTCONN, ESHUTDOWN, EISCONN, EBADF, ECONNABORTED, EPIPE, EAGAIN, \ |
|---|
| 58 | n/a | errorcode |
|---|
| 59 | n/a | |
|---|
| 60 | n/a | _DISCONNECTED = frozenset({ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED, EPIPE, |
|---|
| 61 | n/a | EBADF}) |
|---|
| 62 | n/a | |
|---|
| 63 | n/a | try: |
|---|
| 64 | n/a | socket_map |
|---|
| 65 | n/a | except NameError: |
|---|
| 66 | n/a | socket_map = {} |
|---|
| 67 | n/a | |
|---|
| 68 | n/a | def _strerror(err): |
|---|
| 69 | n/a | try: |
|---|
| 70 | n/a | return os.strerror(err) |
|---|
| 71 | n/a | except (ValueError, OverflowError, NameError): |
|---|
| 72 | n/a | if err in errorcode: |
|---|
| 73 | n/a | return errorcode[err] |
|---|
| 74 | n/a | return "Unknown error %s" %err |
|---|
| 75 | n/a | |
|---|
| 76 | n/a | class ExitNow(Exception): |
|---|
| 77 | n/a | pass |
|---|
| 78 | n/a | |
|---|
| 79 | n/a | _reraised_exceptions = (ExitNow, KeyboardInterrupt, SystemExit) |
|---|
| 80 | n/a | |
|---|
| 81 | n/a | def read(obj): |
|---|
| 82 | n/a | try: |
|---|
| 83 | n/a | obj.handle_read_event() |
|---|
| 84 | n/a | except _reraised_exceptions: |
|---|
| 85 | n/a | raise |
|---|
| 86 | n/a | except: |
|---|
| 87 | n/a | obj.handle_error() |
|---|
| 88 | n/a | |
|---|
| 89 | n/a | def write(obj): |
|---|
| 90 | n/a | try: |
|---|
| 91 | n/a | obj.handle_write_event() |
|---|
| 92 | n/a | except _reraised_exceptions: |
|---|
| 93 | n/a | raise |
|---|
| 94 | n/a | except: |
|---|
| 95 | n/a | obj.handle_error() |
|---|
| 96 | n/a | |
|---|
| 97 | n/a | def _exception(obj): |
|---|
| 98 | n/a | try: |
|---|
| 99 | n/a | obj.handle_expt_event() |
|---|
| 100 | n/a | except _reraised_exceptions: |
|---|
| 101 | n/a | raise |
|---|
| 102 | n/a | except: |
|---|
| 103 | n/a | obj.handle_error() |
|---|
| 104 | n/a | |
|---|
| 105 | n/a | def readwrite(obj, flags): |
|---|
| 106 | n/a | try: |
|---|
| 107 | n/a | if flags & select.POLLIN: |
|---|
| 108 | n/a | obj.handle_read_event() |
|---|
| 109 | n/a | if flags & select.POLLOUT: |
|---|
| 110 | n/a | obj.handle_write_event() |
|---|
| 111 | n/a | if flags & select.POLLPRI: |
|---|
| 112 | n/a | obj.handle_expt_event() |
|---|
| 113 | n/a | if flags & (select.POLLHUP | select.POLLERR | select.POLLNVAL): |
|---|
| 114 | n/a | obj.handle_close() |
|---|
| 115 | n/a | except OSError as e: |
|---|
| 116 | n/a | if e.args[0] not in _DISCONNECTED: |
|---|
| 117 | n/a | obj.handle_error() |
|---|
| 118 | n/a | else: |
|---|
| 119 | n/a | obj.handle_close() |
|---|
| 120 | n/a | except _reraised_exceptions: |
|---|
| 121 | n/a | raise |
|---|
| 122 | n/a | except: |
|---|
| 123 | n/a | obj.handle_error() |
|---|
| 124 | n/a | |
|---|
| 125 | n/a | def poll(timeout=0.0, map=None): |
|---|
| 126 | n/a | if map is None: |
|---|
| 127 | n/a | map = socket_map |
|---|
| 128 | n/a | if map: |
|---|
| 129 | n/a | r = []; w = []; e = [] |
|---|
| 130 | n/a | for fd, obj in list(map.items()): |
|---|
| 131 | n/a | is_r = obj.readable() |
|---|
| 132 | n/a | is_w = obj.writable() |
|---|
| 133 | n/a | if is_r: |
|---|
| 134 | n/a | r.append(fd) |
|---|
| 135 | n/a | # accepting sockets should not be writable |
|---|
| 136 | n/a | if is_w and not obj.accepting: |
|---|
| 137 | n/a | w.append(fd) |
|---|
| 138 | n/a | if is_r or is_w: |
|---|
| 139 | n/a | e.append(fd) |
|---|
| 140 | n/a | if [] == r == w == e: |
|---|
| 141 | n/a | time.sleep(timeout) |
|---|
| 142 | n/a | return |
|---|
| 143 | n/a | |
|---|
| 144 | n/a | r, w, e = select.select(r, w, e, timeout) |
|---|
| 145 | n/a | |
|---|
| 146 | n/a | for fd in r: |
|---|
| 147 | n/a | obj = map.get(fd) |
|---|
| 148 | n/a | if obj is None: |
|---|
| 149 | n/a | continue |
|---|
| 150 | n/a | read(obj) |
|---|
| 151 | n/a | |
|---|
| 152 | n/a | for fd in w: |
|---|
| 153 | n/a | obj = map.get(fd) |
|---|
| 154 | n/a | if obj is None: |
|---|
| 155 | n/a | continue |
|---|
| 156 | n/a | write(obj) |
|---|
| 157 | n/a | |
|---|
| 158 | n/a | for fd in e: |
|---|
| 159 | n/a | obj = map.get(fd) |
|---|
| 160 | n/a | if obj is None: |
|---|
| 161 | n/a | continue |
|---|
| 162 | n/a | _exception(obj) |
|---|
| 163 | n/a | |
|---|
| 164 | n/a | def poll2(timeout=0.0, map=None): |
|---|
| 165 | n/a | # Use the poll() support added to the select module in Python 2.0 |
|---|
| 166 | n/a | if map is None: |
|---|
| 167 | n/a | map = socket_map |
|---|
| 168 | n/a | if timeout is not None: |
|---|
| 169 | n/a | # timeout is in milliseconds |
|---|
| 170 | n/a | timeout = int(timeout*1000) |
|---|
| 171 | n/a | pollster = select.poll() |
|---|
| 172 | n/a | if map: |
|---|
| 173 | n/a | for fd, obj in list(map.items()): |
|---|
| 174 | n/a | flags = 0 |
|---|
| 175 | n/a | if obj.readable(): |
|---|
| 176 | n/a | flags |= select.POLLIN | select.POLLPRI |
|---|
| 177 | n/a | # accepting sockets should not be writable |
|---|
| 178 | n/a | if obj.writable() and not obj.accepting: |
|---|
| 179 | n/a | flags |= select.POLLOUT |
|---|
| 180 | n/a | if flags: |
|---|
| 181 | n/a | pollster.register(fd, flags) |
|---|
| 182 | n/a | |
|---|
| 183 | n/a | r = pollster.poll(timeout) |
|---|
| 184 | n/a | for fd, flags in r: |
|---|
| 185 | n/a | obj = map.get(fd) |
|---|
| 186 | n/a | if obj is None: |
|---|
| 187 | n/a | continue |
|---|
| 188 | n/a | readwrite(obj, flags) |
|---|
| 189 | n/a | |
|---|
| 190 | n/a | poll3 = poll2 # Alias for backward compatibility |
|---|
| 191 | n/a | |
|---|
| 192 | n/a | def loop(timeout=30.0, use_poll=False, map=None, count=None): |
|---|
| 193 | n/a | if map is None: |
|---|
| 194 | n/a | map = socket_map |
|---|
| 195 | n/a | |
|---|
| 196 | n/a | if use_poll and hasattr(select, 'poll'): |
|---|
| 197 | n/a | poll_fun = poll2 |
|---|
| 198 | n/a | else: |
|---|
| 199 | n/a | poll_fun = poll |
|---|
| 200 | n/a | |
|---|
| 201 | n/a | if count is None: |
|---|
| 202 | n/a | while map: |
|---|
| 203 | n/a | poll_fun(timeout, map) |
|---|
| 204 | n/a | |
|---|
| 205 | n/a | else: |
|---|
| 206 | n/a | while map and count > 0: |
|---|
| 207 | n/a | poll_fun(timeout, map) |
|---|
| 208 | n/a | count = count - 1 |
|---|
| 209 | n/a | |
|---|
| 210 | n/a | class dispatcher: |
|---|
| 211 | n/a | |
|---|
| 212 | n/a | debug = False |
|---|
| 213 | n/a | connected = False |
|---|
| 214 | n/a | accepting = False |
|---|
| 215 | n/a | connecting = False |
|---|
| 216 | n/a | closing = False |
|---|
| 217 | n/a | addr = None |
|---|
| 218 | n/a | ignore_log_types = frozenset({'warning'}) |
|---|
| 219 | n/a | |
|---|
| 220 | n/a | def __init__(self, sock=None, map=None): |
|---|
| 221 | n/a | if map is None: |
|---|
| 222 | n/a | self._map = socket_map |
|---|
| 223 | n/a | else: |
|---|
| 224 | n/a | self._map = map |
|---|
| 225 | n/a | |
|---|
| 226 | n/a | self._fileno = None |
|---|
| 227 | n/a | |
|---|
| 228 | n/a | if sock: |
|---|
| 229 | n/a | # Set to nonblocking just to make sure for cases where we |
|---|
| 230 | n/a | # get a socket from a blocking source. |
|---|
| 231 | n/a | sock.setblocking(0) |
|---|
| 232 | n/a | self.set_socket(sock, map) |
|---|
| 233 | n/a | self.connected = True |
|---|
| 234 | n/a | # The constructor no longer requires that the socket |
|---|
| 235 | n/a | # passed be connected. |
|---|
| 236 | n/a | try: |
|---|
| 237 | n/a | self.addr = sock.getpeername() |
|---|
| 238 | n/a | except OSError as err: |
|---|
| 239 | n/a | if err.args[0] in (ENOTCONN, EINVAL): |
|---|
| 240 | n/a | # To handle the case where we got an unconnected |
|---|
| 241 | n/a | # socket. |
|---|
| 242 | n/a | self.connected = False |
|---|
| 243 | n/a | else: |
|---|
| 244 | n/a | # The socket is broken in some unknown way, alert |
|---|
| 245 | n/a | # the user and remove it from the map (to prevent |
|---|
| 246 | n/a | # polling of broken sockets). |
|---|
| 247 | n/a | self.del_channel(map) |
|---|
| 248 | n/a | raise |
|---|
| 249 | n/a | else: |
|---|
| 250 | n/a | self.socket = None |
|---|
| 251 | n/a | |
|---|
| 252 | n/a | def __repr__(self): |
|---|
| 253 | n/a | status = [self.__class__.__module__+"."+self.__class__.__qualname__] |
|---|
| 254 | n/a | if self.accepting and self.addr: |
|---|
| 255 | n/a | status.append('listening') |
|---|
| 256 | n/a | elif self.connected: |
|---|
| 257 | n/a | status.append('connected') |
|---|
| 258 | n/a | if self.addr is not None: |
|---|
| 259 | n/a | try: |
|---|
| 260 | n/a | status.append('%s:%d' % self.addr) |
|---|
| 261 | n/a | except TypeError: |
|---|
| 262 | n/a | status.append(repr(self.addr)) |
|---|
| 263 | n/a | return '<%s at %#x>' % (' '.join(status), id(self)) |
|---|
| 264 | n/a | |
|---|
| 265 | n/a | __str__ = __repr__ |
|---|
| 266 | n/a | |
|---|
| 267 | n/a | def add_channel(self, map=None): |
|---|
| 268 | n/a | #self.log_info('adding channel %s' % self) |
|---|
| 269 | n/a | if map is None: |
|---|
| 270 | n/a | map = self._map |
|---|
| 271 | n/a | map[self._fileno] = self |
|---|
| 272 | n/a | |
|---|
| 273 | n/a | def del_channel(self, map=None): |
|---|
| 274 | n/a | fd = self._fileno |
|---|
| 275 | n/a | if map is None: |
|---|
| 276 | n/a | map = self._map |
|---|
| 277 | n/a | if fd in map: |
|---|
| 278 | n/a | #self.log_info('closing channel %d:%s' % (fd, self)) |
|---|
| 279 | n/a | del map[fd] |
|---|
| 280 | n/a | self._fileno = None |
|---|
| 281 | n/a | |
|---|
| 282 | n/a | def create_socket(self, family=socket.AF_INET, type=socket.SOCK_STREAM): |
|---|
| 283 | n/a | self.family_and_type = family, type |
|---|
| 284 | n/a | sock = socket.socket(family, type) |
|---|
| 285 | n/a | sock.setblocking(0) |
|---|
| 286 | n/a | self.set_socket(sock) |
|---|
| 287 | n/a | |
|---|
| 288 | n/a | def set_socket(self, sock, map=None): |
|---|
| 289 | n/a | self.socket = sock |
|---|
| 290 | n/a | ## self.__dict__['socket'] = sock |
|---|
| 291 | n/a | self._fileno = sock.fileno() |
|---|
| 292 | n/a | self.add_channel(map) |
|---|
| 293 | n/a | |
|---|
| 294 | n/a | def set_reuse_addr(self): |
|---|
| 295 | n/a | # try to re-use a server port if possible |
|---|
| 296 | n/a | try: |
|---|
| 297 | n/a | self.socket.setsockopt( |
|---|
| 298 | n/a | socket.SOL_SOCKET, socket.SO_REUSEADDR, |
|---|
| 299 | n/a | self.socket.getsockopt(socket.SOL_SOCKET, |
|---|
| 300 | n/a | socket.SO_REUSEADDR) | 1 |
|---|
| 301 | n/a | ) |
|---|
| 302 | n/a | except OSError: |
|---|
| 303 | n/a | pass |
|---|
| 304 | n/a | |
|---|
| 305 | n/a | # ================================================== |
|---|
| 306 | n/a | # predicates for select() |
|---|
| 307 | n/a | # these are used as filters for the lists of sockets |
|---|
| 308 | n/a | # to pass to select(). |
|---|
| 309 | n/a | # ================================================== |
|---|
| 310 | n/a | |
|---|
| 311 | n/a | def readable(self): |
|---|
| 312 | n/a | return True |
|---|
| 313 | n/a | |
|---|
| 314 | n/a | def writable(self): |
|---|
| 315 | n/a | return True |
|---|
| 316 | n/a | |
|---|
| 317 | n/a | # ================================================== |
|---|
| 318 | n/a | # socket object methods. |
|---|
| 319 | n/a | # ================================================== |
|---|
| 320 | n/a | |
|---|
| 321 | n/a | def listen(self, num): |
|---|
| 322 | n/a | self.accepting = True |
|---|
| 323 | n/a | if os.name == 'nt' and num > 5: |
|---|
| 324 | n/a | num = 5 |
|---|
| 325 | n/a | return self.socket.listen(num) |
|---|
| 326 | n/a | |
|---|
| 327 | n/a | def bind(self, addr): |
|---|
| 328 | n/a | self.addr = addr |
|---|
| 329 | n/a | return self.socket.bind(addr) |
|---|
| 330 | n/a | |
|---|
| 331 | n/a | def connect(self, address): |
|---|
| 332 | n/a | self.connected = False |
|---|
| 333 | n/a | self.connecting = True |
|---|
| 334 | n/a | err = self.socket.connect_ex(address) |
|---|
| 335 | n/a | if err in (EINPROGRESS, EALREADY, EWOULDBLOCK) \ |
|---|
| 336 | n/a | or err == EINVAL and os.name == 'nt': |
|---|
| 337 | n/a | self.addr = address |
|---|
| 338 | n/a | return |
|---|
| 339 | n/a | if err in (0, EISCONN): |
|---|
| 340 | n/a | self.addr = address |
|---|
| 341 | n/a | self.handle_connect_event() |
|---|
| 342 | n/a | else: |
|---|
| 343 | n/a | raise OSError(err, errorcode[err]) |
|---|
| 344 | n/a | |
|---|
| 345 | n/a | def accept(self): |
|---|
| 346 | n/a | # XXX can return either an address pair or None |
|---|
| 347 | n/a | try: |
|---|
| 348 | n/a | conn, addr = self.socket.accept() |
|---|
| 349 | n/a | except TypeError: |
|---|
| 350 | n/a | return None |
|---|
| 351 | n/a | except OSError as why: |
|---|
| 352 | n/a | if why.args[0] in (EWOULDBLOCK, ECONNABORTED, EAGAIN): |
|---|
| 353 | n/a | return None |
|---|
| 354 | n/a | else: |
|---|
| 355 | n/a | raise |
|---|
| 356 | n/a | else: |
|---|
| 357 | n/a | return conn, addr |
|---|
| 358 | n/a | |
|---|
| 359 | n/a | def send(self, data): |
|---|
| 360 | n/a | try: |
|---|
| 361 | n/a | result = self.socket.send(data) |
|---|
| 362 | n/a | return result |
|---|
| 363 | n/a | except OSError as why: |
|---|
| 364 | n/a | if why.args[0] == EWOULDBLOCK: |
|---|
| 365 | n/a | return 0 |
|---|
| 366 | n/a | elif why.args[0] in _DISCONNECTED: |
|---|
| 367 | n/a | self.handle_close() |
|---|
| 368 | n/a | return 0 |
|---|
| 369 | n/a | else: |
|---|
| 370 | n/a | raise |
|---|
| 371 | n/a | |
|---|
| 372 | n/a | def recv(self, buffer_size): |
|---|
| 373 | n/a | try: |
|---|
| 374 | n/a | data = self.socket.recv(buffer_size) |
|---|
| 375 | n/a | if not data: |
|---|
| 376 | n/a | # a closed connection is indicated by signaling |
|---|
| 377 | n/a | # a read condition, and having recv() return 0. |
|---|
| 378 | n/a | self.handle_close() |
|---|
| 379 | n/a | return b'' |
|---|
| 380 | n/a | else: |
|---|
| 381 | n/a | return data |
|---|
| 382 | n/a | except OSError as why: |
|---|
| 383 | n/a | # winsock sometimes raises ENOTCONN |
|---|
| 384 | n/a | if why.args[0] in _DISCONNECTED: |
|---|
| 385 | n/a | self.handle_close() |
|---|
| 386 | n/a | return b'' |
|---|
| 387 | n/a | else: |
|---|
| 388 | n/a | raise |
|---|
| 389 | n/a | |
|---|
| 390 | n/a | def close(self): |
|---|
| 391 | n/a | self.connected = False |
|---|
| 392 | n/a | self.accepting = False |
|---|
| 393 | n/a | self.connecting = False |
|---|
| 394 | n/a | self.del_channel() |
|---|
| 395 | n/a | if self.socket is not None: |
|---|
| 396 | n/a | try: |
|---|
| 397 | n/a | self.socket.close() |
|---|
| 398 | n/a | except OSError as why: |
|---|
| 399 | n/a | if why.args[0] not in (ENOTCONN, EBADF): |
|---|
| 400 | n/a | raise |
|---|
| 401 | n/a | |
|---|
| 402 | n/a | # log and log_info may be overridden to provide more sophisticated |
|---|
| 403 | n/a | # logging and warning methods. In general, log is for 'hit' logging |
|---|
| 404 | n/a | # and 'log_info' is for informational, warning and error logging. |
|---|
| 405 | n/a | |
|---|
| 406 | n/a | def log(self, message): |
|---|
| 407 | n/a | sys.stderr.write('log: %s\n' % str(message)) |
|---|
| 408 | n/a | |
|---|
| 409 | n/a | def log_info(self, message, type='info'): |
|---|
| 410 | n/a | if type not in self.ignore_log_types: |
|---|
| 411 | n/a | print('%s: %s' % (type, message)) |
|---|
| 412 | n/a | |
|---|
| 413 | n/a | def handle_read_event(self): |
|---|
| 414 | n/a | if self.accepting: |
|---|
| 415 | n/a | # accepting sockets are never connected, they "spawn" new |
|---|
| 416 | n/a | # sockets that are connected |
|---|
| 417 | n/a | self.handle_accept() |
|---|
| 418 | n/a | elif not self.connected: |
|---|
| 419 | n/a | if self.connecting: |
|---|
| 420 | n/a | self.handle_connect_event() |
|---|
| 421 | n/a | self.handle_read() |
|---|
| 422 | n/a | else: |
|---|
| 423 | n/a | self.handle_read() |
|---|
| 424 | n/a | |
|---|
| 425 | n/a | def handle_connect_event(self): |
|---|
| 426 | n/a | err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) |
|---|
| 427 | n/a | if err != 0: |
|---|
| 428 | n/a | raise OSError(err, _strerror(err)) |
|---|
| 429 | n/a | self.handle_connect() |
|---|
| 430 | n/a | self.connected = True |
|---|
| 431 | n/a | self.connecting = False |
|---|
| 432 | n/a | |
|---|
| 433 | n/a | def handle_write_event(self): |
|---|
| 434 | n/a | if self.accepting: |
|---|
| 435 | n/a | # Accepting sockets shouldn't get a write event. |
|---|
| 436 | n/a | # We will pretend it didn't happen. |
|---|
| 437 | n/a | return |
|---|
| 438 | n/a | |
|---|
| 439 | n/a | if not self.connected: |
|---|
| 440 | n/a | if self.connecting: |
|---|
| 441 | n/a | self.handle_connect_event() |
|---|
| 442 | n/a | self.handle_write() |
|---|
| 443 | n/a | |
|---|
| 444 | n/a | def handle_expt_event(self): |
|---|
| 445 | n/a | # handle_expt_event() is called if there might be an error on the |
|---|
| 446 | n/a | # socket, or if there is OOB data |
|---|
| 447 | n/a | # check for the error condition first |
|---|
| 448 | n/a | err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) |
|---|
| 449 | n/a | if err != 0: |
|---|
| 450 | n/a | # we can get here when select.select() says that there is an |
|---|
| 451 | n/a | # exceptional condition on the socket |
|---|
| 452 | n/a | # since there is an error, we'll go ahead and close the socket |
|---|
| 453 | n/a | # like we would in a subclassed handle_read() that received no |
|---|
| 454 | n/a | # data |
|---|
| 455 | n/a | self.handle_close() |
|---|
| 456 | n/a | else: |
|---|
| 457 | n/a | self.handle_expt() |
|---|
| 458 | n/a | |
|---|
| 459 | n/a | def handle_error(self): |
|---|
| 460 | n/a | nil, t, v, tbinfo = compact_traceback() |
|---|
| 461 | n/a | |
|---|
| 462 | n/a | # sometimes a user repr method will crash. |
|---|
| 463 | n/a | try: |
|---|
| 464 | n/a | self_repr = repr(self) |
|---|
| 465 | n/a | except: |
|---|
| 466 | n/a | self_repr = '<__repr__(self) failed for object at %0x>' % id(self) |
|---|
| 467 | n/a | |
|---|
| 468 | n/a | self.log_info( |
|---|
| 469 | n/a | 'uncaptured python exception, closing channel %s (%s:%s %s)' % ( |
|---|
| 470 | n/a | self_repr, |
|---|
| 471 | n/a | t, |
|---|
| 472 | n/a | v, |
|---|
| 473 | n/a | tbinfo |
|---|
| 474 | n/a | ), |
|---|
| 475 | n/a | 'error' |
|---|
| 476 | n/a | ) |
|---|
| 477 | n/a | self.handle_close() |
|---|
| 478 | n/a | |
|---|
| 479 | n/a | def handle_expt(self): |
|---|
| 480 | n/a | self.log_info('unhandled incoming priority event', 'warning') |
|---|
| 481 | n/a | |
|---|
| 482 | n/a | def handle_read(self): |
|---|
| 483 | n/a | self.log_info('unhandled read event', 'warning') |
|---|
| 484 | n/a | |
|---|
| 485 | n/a | def handle_write(self): |
|---|
| 486 | n/a | self.log_info('unhandled write event', 'warning') |
|---|
| 487 | n/a | |
|---|
| 488 | n/a | def handle_connect(self): |
|---|
| 489 | n/a | self.log_info('unhandled connect event', 'warning') |
|---|
| 490 | n/a | |
|---|
| 491 | n/a | def handle_accept(self): |
|---|
| 492 | n/a | pair = self.accept() |
|---|
| 493 | n/a | if pair is not None: |
|---|
| 494 | n/a | self.handle_accepted(*pair) |
|---|
| 495 | n/a | |
|---|
| 496 | n/a | def handle_accepted(self, sock, addr): |
|---|
| 497 | n/a | sock.close() |
|---|
| 498 | n/a | self.log_info('unhandled accepted event', 'warning') |
|---|
| 499 | n/a | |
|---|
| 500 | n/a | def handle_close(self): |
|---|
| 501 | n/a | self.log_info('unhandled close event', 'warning') |
|---|
| 502 | n/a | self.close() |
|---|
| 503 | n/a | |
|---|
| 504 | n/a | # --------------------------------------------------------------------------- |
|---|
| 505 | n/a | # adds simple buffered output capability, useful for simple clients. |
|---|
| 506 | n/a | # [for more sophisticated usage use asynchat.async_chat] |
|---|
| 507 | n/a | # --------------------------------------------------------------------------- |
|---|
| 508 | n/a | |
|---|
| 509 | n/a | class dispatcher_with_send(dispatcher): |
|---|
| 510 | n/a | |
|---|
| 511 | n/a | def __init__(self, sock=None, map=None): |
|---|
| 512 | n/a | dispatcher.__init__(self, sock, map) |
|---|
| 513 | n/a | self.out_buffer = b'' |
|---|
| 514 | n/a | |
|---|
| 515 | n/a | def initiate_send(self): |
|---|
| 516 | n/a | num_sent = 0 |
|---|
| 517 | n/a | num_sent = dispatcher.send(self, self.out_buffer[:65536]) |
|---|
| 518 | n/a | self.out_buffer = self.out_buffer[num_sent:] |
|---|
| 519 | n/a | |
|---|
| 520 | n/a | def handle_write(self): |
|---|
| 521 | n/a | self.initiate_send() |
|---|
| 522 | n/a | |
|---|
| 523 | n/a | def writable(self): |
|---|
| 524 | n/a | return (not self.connected) or len(self.out_buffer) |
|---|
| 525 | n/a | |
|---|
| 526 | n/a | def send(self, data): |
|---|
| 527 | n/a | if self.debug: |
|---|
| 528 | n/a | self.log_info('sending %s' % repr(data)) |
|---|
| 529 | n/a | self.out_buffer = self.out_buffer + data |
|---|
| 530 | n/a | self.initiate_send() |
|---|
| 531 | n/a | |
|---|
| 532 | n/a | # --------------------------------------------------------------------------- |
|---|
| 533 | n/a | # used for debugging. |
|---|
| 534 | n/a | # --------------------------------------------------------------------------- |
|---|
| 535 | n/a | |
|---|
| 536 | n/a | def compact_traceback(): |
|---|
| 537 | n/a | t, v, tb = sys.exc_info() |
|---|
| 538 | n/a | tbinfo = [] |
|---|
| 539 | n/a | if not tb: # Must have a traceback |
|---|
| 540 | n/a | raise AssertionError("traceback does not exist") |
|---|
| 541 | n/a | while tb: |
|---|
| 542 | n/a | tbinfo.append(( |
|---|
| 543 | n/a | tb.tb_frame.f_code.co_filename, |
|---|
| 544 | n/a | tb.tb_frame.f_code.co_name, |
|---|
| 545 | n/a | str(tb.tb_lineno) |
|---|
| 546 | n/a | )) |
|---|
| 547 | n/a | tb = tb.tb_next |
|---|
| 548 | n/a | |
|---|
| 549 | n/a | # just to be safe |
|---|
| 550 | n/a | del tb |
|---|
| 551 | n/a | |
|---|
| 552 | n/a | file, function, line = tbinfo[-1] |
|---|
| 553 | n/a | info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo]) |
|---|
| 554 | n/a | return (file, function, line), t, v, info |
|---|
| 555 | n/a | |
|---|
| 556 | n/a | def close_all(map=None, ignore_all=False): |
|---|
| 557 | n/a | if map is None: |
|---|
| 558 | n/a | map = socket_map |
|---|
| 559 | n/a | for x in list(map.values()): |
|---|
| 560 | n/a | try: |
|---|
| 561 | n/a | x.close() |
|---|
| 562 | n/a | except OSError as x: |
|---|
| 563 | n/a | if x.args[0] == EBADF: |
|---|
| 564 | n/a | pass |
|---|
| 565 | n/a | elif not ignore_all: |
|---|
| 566 | n/a | raise |
|---|
| 567 | n/a | except _reraised_exceptions: |
|---|
| 568 | n/a | raise |
|---|
| 569 | n/a | except: |
|---|
| 570 | n/a | if not ignore_all: |
|---|
| 571 | n/a | raise |
|---|
| 572 | n/a | map.clear() |
|---|
| 573 | n/a | |
|---|
| 574 | n/a | # Asynchronous File I/O: |
|---|
| 575 | n/a | # |
|---|
| 576 | n/a | # After a little research (reading man pages on various unixen, and |
|---|
| 577 | n/a | # digging through the linux kernel), I've determined that select() |
|---|
| 578 | n/a | # isn't meant for doing asynchronous file i/o. |
|---|
| 579 | n/a | # Heartening, though - reading linux/mm/filemap.c shows that linux |
|---|
| 580 | n/a | # supports asynchronous read-ahead. So _MOST_ of the time, the data |
|---|
| 581 | n/a | # will be sitting in memory for us already when we go to read it. |
|---|
| 582 | n/a | # |
|---|
| 583 | n/a | # What other OS's (besides NT) support async file i/o? [VMS?] |
|---|
| 584 | n/a | # |
|---|
| 585 | n/a | # Regardless, this is useful for pipes, and stdin/stdout... |
|---|
| 586 | n/a | |
|---|
| 587 | n/a | if os.name == 'posix': |
|---|
| 588 | n/a | class file_wrapper: |
|---|
| 589 | n/a | # Here we override just enough to make a file |
|---|
| 590 | n/a | # look like a socket for the purposes of asyncore. |
|---|
| 591 | n/a | # The passed fd is automatically os.dup()'d |
|---|
| 592 | n/a | |
|---|
| 593 | n/a | def __init__(self, fd): |
|---|
| 594 | n/a | self.fd = os.dup(fd) |
|---|
| 595 | n/a | |
|---|
| 596 | n/a | def __del__(self): |
|---|
| 597 | n/a | if self.fd >= 0: |
|---|
| 598 | n/a | warnings.warn("unclosed file %r" % self, ResourceWarning, |
|---|
| 599 | n/a | source=self) |
|---|
| 600 | n/a | self.close() |
|---|
| 601 | n/a | |
|---|
| 602 | n/a | def recv(self, *args): |
|---|
| 603 | n/a | return os.read(self.fd, *args) |
|---|
| 604 | n/a | |
|---|
| 605 | n/a | def send(self, *args): |
|---|
| 606 | n/a | return os.write(self.fd, *args) |
|---|
| 607 | n/a | |
|---|
| 608 | n/a | def getsockopt(self, level, optname, buflen=None): |
|---|
| 609 | n/a | if (level == socket.SOL_SOCKET and |
|---|
| 610 | n/a | optname == socket.SO_ERROR and |
|---|
| 611 | n/a | not buflen): |
|---|
| 612 | n/a | return 0 |
|---|
| 613 | n/a | raise NotImplementedError("Only asyncore specific behaviour " |
|---|
| 614 | n/a | "implemented.") |
|---|
| 615 | n/a | |
|---|
| 616 | n/a | read = recv |
|---|
| 617 | n/a | write = send |
|---|
| 618 | n/a | |
|---|
| 619 | n/a | def close(self): |
|---|
| 620 | n/a | if self.fd < 0: |
|---|
| 621 | n/a | return |
|---|
| 622 | n/a | os.close(self.fd) |
|---|
| 623 | n/a | self.fd = -1 |
|---|
| 624 | n/a | |
|---|
| 625 | n/a | def fileno(self): |
|---|
| 626 | n/a | return self.fd |
|---|
| 627 | n/a | |
|---|
| 628 | n/a | class file_dispatcher(dispatcher): |
|---|
| 629 | n/a | |
|---|
| 630 | n/a | def __init__(self, fd, map=None): |
|---|
| 631 | n/a | dispatcher.__init__(self, None, map) |
|---|
| 632 | n/a | self.connected = True |
|---|
| 633 | n/a | try: |
|---|
| 634 | n/a | fd = fd.fileno() |
|---|
| 635 | n/a | except AttributeError: |
|---|
| 636 | n/a | pass |
|---|
| 637 | n/a | self.set_file(fd) |
|---|
| 638 | n/a | # set it to non-blocking mode |
|---|
| 639 | n/a | os.set_blocking(fd, False) |
|---|
| 640 | n/a | |
|---|
| 641 | n/a | def set_file(self, fd): |
|---|
| 642 | n/a | self.socket = file_wrapper(fd) |
|---|
| 643 | n/a | self._fileno = self.socket.fileno() |
|---|
| 644 | n/a | self.add_channel() |
|---|