logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

asyncore.py (20233B)


  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. warnings.warn(
  54. 'The asyncore module is deprecated. '
  55. 'The recommended replacement is asyncio',
  56. DeprecationWarning,
  57. stacklevel=2)
  58. _DISCONNECTED = frozenset({ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED, EPIPE,
  59. EBADF})
  60. try:
  61. socket_map
  62. except NameError:
  63. socket_map = {}
  64. def _strerror(err):
  65. try:
  66. return os.strerror(err)
  67. except (ValueError, OverflowError, NameError):
  68. if err in errorcode:
  69. return errorcode[err]
  70. return "Unknown error %s" %err
  71. class ExitNow(Exception):
  72. pass
  73. _reraised_exceptions = (ExitNow, KeyboardInterrupt, SystemExit)
  74. def read(obj):
  75. try:
  76. obj.handle_read_event()
  77. except _reraised_exceptions:
  78. raise
  79. except:
  80. obj.handle_error()
  81. def write(obj):
  82. try:
  83. obj.handle_write_event()
  84. except _reraised_exceptions:
  85. raise
  86. except:
  87. obj.handle_error()
  88. def _exception(obj):
  89. try:
  90. obj.handle_expt_event()
  91. except _reraised_exceptions:
  92. raise
  93. except:
  94. obj.handle_error()
  95. def readwrite(obj, flags):
  96. try:
  97. if flags & select.POLLIN:
  98. obj.handle_read_event()
  99. if flags & select.POLLOUT:
  100. obj.handle_write_event()
  101. if flags & select.POLLPRI:
  102. obj.handle_expt_event()
  103. if flags & (select.POLLHUP | select.POLLERR | select.POLLNVAL):
  104. obj.handle_close()
  105. except OSError as e:
  106. if e.errno not in _DISCONNECTED:
  107. obj.handle_error()
  108. else:
  109. obj.handle_close()
  110. except _reraised_exceptions:
  111. raise
  112. except:
  113. obj.handle_error()
  114. def poll(timeout=0.0, map=None):
  115. if map is None:
  116. map = socket_map
  117. if map:
  118. r = []; w = []; e = []
  119. for fd, obj in list(map.items()):
  120. is_r = obj.readable()
  121. is_w = obj.writable()
  122. if is_r:
  123. r.append(fd)
  124. # accepting sockets should not be writable
  125. if is_w and not obj.accepting:
  126. w.append(fd)
  127. if is_r or is_w:
  128. e.append(fd)
  129. if [] == r == w == e:
  130. time.sleep(timeout)
  131. return
  132. r, w, e = select.select(r, w, e, timeout)
  133. for fd in r:
  134. obj = map.get(fd)
  135. if obj is None:
  136. continue
  137. read(obj)
  138. for fd in w:
  139. obj = map.get(fd)
  140. if obj is None:
  141. continue
  142. write(obj)
  143. for fd in e:
  144. obj = map.get(fd)
  145. if obj is None:
  146. continue
  147. _exception(obj)
  148. def poll2(timeout=0.0, map=None):
  149. # Use the poll() support added to the select module in Python 2.0
  150. if map is None:
  151. map = socket_map
  152. if timeout is not None:
  153. # timeout is in milliseconds
  154. timeout = int(timeout*1000)
  155. pollster = select.poll()
  156. if map:
  157. for fd, obj in list(map.items()):
  158. flags = 0
  159. if obj.readable():
  160. flags |= select.POLLIN | select.POLLPRI
  161. # accepting sockets should not be writable
  162. if obj.writable() and not obj.accepting:
  163. flags |= select.POLLOUT
  164. if flags:
  165. pollster.register(fd, flags)
  166. r = pollster.poll(timeout)
  167. for fd, flags in r:
  168. obj = map.get(fd)
  169. if obj is None:
  170. continue
  171. readwrite(obj, flags)
  172. poll3 = poll2 # Alias for backward compatibility
  173. def loop(timeout=30.0, use_poll=False, map=None, count=None):
  174. if map is None:
  175. map = socket_map
  176. if use_poll and hasattr(select, 'poll'):
  177. poll_fun = poll2
  178. else:
  179. poll_fun = poll
  180. if count is None:
  181. while map:
  182. poll_fun(timeout, map)
  183. else:
  184. while map and count > 0:
  185. poll_fun(timeout, map)
  186. count = count - 1
  187. class dispatcher:
  188. debug = False
  189. connected = False
  190. accepting = False
  191. connecting = False
  192. closing = False
  193. addr = None
  194. ignore_log_types = frozenset({'warning'})
  195. def __init__(self, sock=None, map=None):
  196. if map is None:
  197. self._map = socket_map
  198. else:
  199. self._map = map
  200. self._fileno = None
  201. if sock:
  202. # Set to nonblocking just to make sure for cases where we
  203. # get a socket from a blocking source.
  204. sock.setblocking(False)
  205. self.set_socket(sock, map)
  206. self.connected = True
  207. # The constructor no longer requires that the socket
  208. # passed be connected.
  209. try:
  210. self.addr = sock.getpeername()
  211. except OSError as err:
  212. if err.errno in (ENOTCONN, EINVAL):
  213. # To handle the case where we got an unconnected
  214. # socket.
  215. self.connected = False
  216. else:
  217. # The socket is broken in some unknown way, alert
  218. # the user and remove it from the map (to prevent
  219. # polling of broken sockets).
  220. self.del_channel(map)
  221. raise
  222. else:
  223. self.socket = None
  224. def __repr__(self):
  225. status = [self.__class__.__module__+"."+self.__class__.__qualname__]
  226. if self.accepting and self.addr:
  227. status.append('listening')
  228. elif self.connected:
  229. status.append('connected')
  230. if self.addr is not None:
  231. try:
  232. status.append('%s:%d' % self.addr)
  233. except TypeError:
  234. status.append(repr(self.addr))
  235. return '<%s at %#x>' % (' '.join(status), id(self))
  236. def add_channel(self, map=None):
  237. #self.log_info('adding channel %s' % self)
  238. if map is None:
  239. map = self._map
  240. map[self._fileno] = self
  241. def del_channel(self, map=None):
  242. fd = self._fileno
  243. if map is None:
  244. map = self._map
  245. if fd in map:
  246. #self.log_info('closing channel %d:%s' % (fd, self))
  247. del map[fd]
  248. self._fileno = None
  249. def create_socket(self, family=socket.AF_INET, type=socket.SOCK_STREAM):
  250. self.family_and_type = family, type
  251. sock = socket.socket(family, type)
  252. sock.setblocking(False)
  253. self.set_socket(sock)
  254. def set_socket(self, sock, map=None):
  255. self.socket = sock
  256. self._fileno = sock.fileno()
  257. self.add_channel(map)
  258. def set_reuse_addr(self):
  259. # try to re-use a server port if possible
  260. try:
  261. self.socket.setsockopt(
  262. socket.SOL_SOCKET, socket.SO_REUSEADDR,
  263. self.socket.getsockopt(socket.SOL_SOCKET,
  264. socket.SO_REUSEADDR) | 1
  265. )
  266. except OSError:
  267. pass
  268. # ==================================================
  269. # predicates for select()
  270. # these are used as filters for the lists of sockets
  271. # to pass to select().
  272. # ==================================================
  273. def readable(self):
  274. return True
  275. def writable(self):
  276. return True
  277. # ==================================================
  278. # socket object methods.
  279. # ==================================================
  280. def listen(self, num):
  281. self.accepting = True
  282. if os.name == 'nt' and num > 5:
  283. num = 5
  284. return self.socket.listen(num)
  285. def bind(self, addr):
  286. self.addr = addr
  287. return self.socket.bind(addr)
  288. def connect(self, address):
  289. self.connected = False
  290. self.connecting = True
  291. err = self.socket.connect_ex(address)
  292. if err in (EINPROGRESS, EALREADY, EWOULDBLOCK) \
  293. or err == EINVAL and os.name == 'nt':
  294. self.addr = address
  295. return
  296. if err in (0, EISCONN):
  297. self.addr = address
  298. self.handle_connect_event()
  299. else:
  300. raise OSError(err, errorcode[err])
  301. def accept(self):
  302. # XXX can return either an address pair or None
  303. try:
  304. conn, addr = self.socket.accept()
  305. except TypeError:
  306. return None
  307. except OSError as why:
  308. if why.errno in (EWOULDBLOCK, ECONNABORTED, EAGAIN):
  309. return None
  310. else:
  311. raise
  312. else:
  313. return conn, addr
  314. def send(self, data):
  315. try:
  316. result = self.socket.send(data)
  317. return result
  318. except OSError as why:
  319. if why.errno == EWOULDBLOCK:
  320. return 0
  321. elif why.errno in _DISCONNECTED:
  322. self.handle_close()
  323. return 0
  324. else:
  325. raise
  326. def recv(self, buffer_size):
  327. try:
  328. data = self.socket.recv(buffer_size)
  329. if not data:
  330. # a closed connection is indicated by signaling
  331. # a read condition, and having recv() return 0.
  332. self.handle_close()
  333. return b''
  334. else:
  335. return data
  336. except OSError as why:
  337. # winsock sometimes raises ENOTCONN
  338. if why.errno in _DISCONNECTED:
  339. self.handle_close()
  340. return b''
  341. else:
  342. raise
  343. def close(self):
  344. self.connected = False
  345. self.accepting = False
  346. self.connecting = False
  347. self.del_channel()
  348. if self.socket is not None:
  349. try:
  350. self.socket.close()
  351. except OSError as why:
  352. if why.errno not in (ENOTCONN, EBADF):
  353. raise
  354. # log and log_info may be overridden to provide more sophisticated
  355. # logging and warning methods. In general, log is for 'hit' logging
  356. # and 'log_info' is for informational, warning and error logging.
  357. def log(self, message):
  358. sys.stderr.write('log: %s\n' % str(message))
  359. def log_info(self, message, type='info'):
  360. if type not in self.ignore_log_types:
  361. print('%s: %s' % (type, message))
  362. def handle_read_event(self):
  363. if self.accepting:
  364. # accepting sockets are never connected, they "spawn" new
  365. # sockets that are connected
  366. self.handle_accept()
  367. elif not self.connected:
  368. if self.connecting:
  369. self.handle_connect_event()
  370. self.handle_read()
  371. else:
  372. self.handle_read()
  373. def handle_connect_event(self):
  374. err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  375. if err != 0:
  376. raise OSError(err, _strerror(err))
  377. self.handle_connect()
  378. self.connected = True
  379. self.connecting = False
  380. def handle_write_event(self):
  381. if self.accepting:
  382. # Accepting sockets shouldn't get a write event.
  383. # We will pretend it didn't happen.
  384. return
  385. if not self.connected:
  386. if self.connecting:
  387. self.handle_connect_event()
  388. self.handle_write()
  389. def handle_expt_event(self):
  390. # handle_expt_event() is called if there might be an error on the
  391. # socket, or if there is OOB data
  392. # check for the error condition first
  393. err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  394. if err != 0:
  395. # we can get here when select.select() says that there is an
  396. # exceptional condition on the socket
  397. # since there is an error, we'll go ahead and close the socket
  398. # like we would in a subclassed handle_read() that received no
  399. # data
  400. self.handle_close()
  401. else:
  402. self.handle_expt()
  403. def handle_error(self):
  404. nil, t, v, tbinfo = compact_traceback()
  405. # sometimes a user repr method will crash.
  406. try:
  407. self_repr = repr(self)
  408. except:
  409. self_repr = '<__repr__(self) failed for object at %0x>' % id(self)
  410. self.log_info(
  411. 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
  412. self_repr,
  413. t,
  414. v,
  415. tbinfo
  416. ),
  417. 'error'
  418. )
  419. self.handle_close()
  420. def handle_expt(self):
  421. self.log_info('unhandled incoming priority event', 'warning')
  422. def handle_read(self):
  423. self.log_info('unhandled read event', 'warning')
  424. def handle_write(self):
  425. self.log_info('unhandled write event', 'warning')
  426. def handle_connect(self):
  427. self.log_info('unhandled connect event', 'warning')
  428. def handle_accept(self):
  429. pair = self.accept()
  430. if pair is not None:
  431. self.handle_accepted(*pair)
  432. def handle_accepted(self, sock, addr):
  433. sock.close()
  434. self.log_info('unhandled accepted event', 'warning')
  435. def handle_close(self):
  436. self.log_info('unhandled close event', 'warning')
  437. self.close()
  438. # ---------------------------------------------------------------------------
  439. # adds simple buffered output capability, useful for simple clients.
  440. # [for more sophisticated usage use asynchat.async_chat]
  441. # ---------------------------------------------------------------------------
  442. class dispatcher_with_send(dispatcher):
  443. def __init__(self, sock=None, map=None):
  444. dispatcher.__init__(self, sock, map)
  445. self.out_buffer = b''
  446. def initiate_send(self):
  447. num_sent = 0
  448. num_sent = dispatcher.send(self, self.out_buffer[:65536])
  449. self.out_buffer = self.out_buffer[num_sent:]
  450. def handle_write(self):
  451. self.initiate_send()
  452. def writable(self):
  453. return (not self.connected) or len(self.out_buffer)
  454. def send(self, data):
  455. if self.debug:
  456. self.log_info('sending %s' % repr(data))
  457. self.out_buffer = self.out_buffer + data
  458. self.initiate_send()
  459. # ---------------------------------------------------------------------------
  460. # used for debugging.
  461. # ---------------------------------------------------------------------------
  462. def compact_traceback():
  463. t, v, tb = sys.exc_info()
  464. tbinfo = []
  465. if not tb: # Must have a traceback
  466. raise AssertionError("traceback does not exist")
  467. while tb:
  468. tbinfo.append((
  469. tb.tb_frame.f_code.co_filename,
  470. tb.tb_frame.f_code.co_name,
  471. str(tb.tb_lineno)
  472. ))
  473. tb = tb.tb_next
  474. # just to be safe
  475. del tb
  476. file, function, line = tbinfo[-1]
  477. info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo])
  478. return (file, function, line), t, v, info
  479. def close_all(map=None, ignore_all=False):
  480. if map is None:
  481. map = socket_map
  482. for x in list(map.values()):
  483. try:
  484. x.close()
  485. except OSError as x:
  486. if x.errno == EBADF:
  487. pass
  488. elif not ignore_all:
  489. raise
  490. except _reraised_exceptions:
  491. raise
  492. except:
  493. if not ignore_all:
  494. raise
  495. map.clear()
  496. # Asynchronous File I/O:
  497. #
  498. # After a little research (reading man pages on various unixen, and
  499. # digging through the linux kernel), I've determined that select()
  500. # isn't meant for doing asynchronous file i/o.
  501. # Heartening, though - reading linux/mm/filemap.c shows that linux
  502. # supports asynchronous read-ahead. So _MOST_ of the time, the data
  503. # will be sitting in memory for us already when we go to read it.
  504. #
  505. # What other OS's (besides NT) support async file i/o? [VMS?]
  506. #
  507. # Regardless, this is useful for pipes, and stdin/stdout...
  508. if os.name == 'posix':
  509. class file_wrapper:
  510. # Here we override just enough to make a file
  511. # look like a socket for the purposes of asyncore.
  512. # The passed fd is automatically os.dup()'d
  513. def __init__(self, fd):
  514. self.fd = os.dup(fd)
  515. def __del__(self):
  516. if self.fd >= 0:
  517. warnings.warn("unclosed file %r" % self, ResourceWarning,
  518. source=self)
  519. self.close()
  520. def recv(self, *args):
  521. return os.read(self.fd, *args)
  522. def send(self, *args):
  523. return os.write(self.fd, *args)
  524. def getsockopt(self, level, optname, buflen=None):
  525. if (level == socket.SOL_SOCKET and
  526. optname == socket.SO_ERROR and
  527. not buflen):
  528. return 0
  529. raise NotImplementedError("Only asyncore specific behaviour "
  530. "implemented.")
  531. read = recv
  532. write = send
  533. def close(self):
  534. if self.fd < 0:
  535. return
  536. fd = self.fd
  537. self.fd = -1
  538. os.close(fd)
  539. def fileno(self):
  540. return self.fd
  541. class file_dispatcher(dispatcher):
  542. def __init__(self, fd, map=None):
  543. dispatcher.__init__(self, None, map)
  544. self.connected = True
  545. try:
  546. fd = fd.fileno()
  547. except AttributeError:
  548. pass
  549. self.set_file(fd)
  550. # set it to non-blocking mode
  551. os.set_blocking(fd, False)
  552. def set_file(self, fd):
  553. self.socket = file_wrapper(fd)
  554. self._fileno = self.socket.fileno()
  555. self.add_channel()