asyncore.py 20 KB

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