blob: 5578ddab59777c7a0370ffe27d20a58196d79cdc [file] [log] [blame]
Fred Drake526a1822000-09-11 04:00:46 +00001# -*- Mode: Python -*-
Tim Peters146965a2001-01-14 18:09:23 +00002# Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp
Fred Drake526a1822000-09-11 04:00:46 +00003# Author: Sam Rushing <rushing@nightmare.com>
Guido van Rossum0039d7b1999-01-12 20:19:27 +00004
5# ======================================================================
6# Copyright 1996 by Sam Rushing
Tim Peters146965a2001-01-14 18:09:23 +00007#
Guido van Rossum0039d7b1999-01-12 20:19:27 +00008# All Rights Reserved
Tim Peters146965a2001-01-14 18:09:23 +00009#
Guido van Rossum0039d7b1999-01-12 20:19:27 +000010# Permission to use, copy, modify, and distribute this software and
11# its documentation for any purpose and without fee is hereby
12# granted, provided that the above copyright notice appear in all
13# copies and that both that copyright notice and this permission
14# notice appear in supporting documentation, and that the name of Sam
15# Rushing not be used in advertising or publicity pertaining to
16# distribution of the software without specific, written prior
17# permission.
Tim Peters146965a2001-01-14 18:09:23 +000018#
Guido van Rossum0039d7b1999-01-12 20:19:27 +000019# SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
20# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
21# NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
22# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
23# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
24# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
25# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26# ======================================================================
27
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000028"""Basic infrastructure for asynchronous socket service clients and servers.
29
30There are only two ways to have a program on a single processor do "more
Tim Peters146965a2001-01-14 18:09:23 +000031than one thing at a time". Multi-threaded programming is the simplest and
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000032most popular way to do it, but there is another very different technique,
33that lets you have nearly all the advantages of multi-threading, without
34actually using multiple threads. it's really only practical if your program
35is largely I/O bound. If your program is CPU bound, then pre-emptive
36scheduled threads are probably what you really need. Network servers are
Tim Peters146965a2001-01-14 18:09:23 +000037rarely CPU-bound, however.
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000038
Tim Peters146965a2001-01-14 18:09:23 +000039If your operating system supports the select() system call in its I/O
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000040library (and nearly all do), then you can use it to juggle multiple
41communication channels at once; doing other work while your I/O is taking
42place in the "background." Although this strategy can seem strange and
43complex, especially at first, it is in many ways easier to understand and
44control than multi-threaded programming. The module documented here solves
45many of the difficult problems for you, making the task of building
Tim Peters146965a2001-01-14 18:09:23 +000046sophisticated high-performance network servers and clients a snap.
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000047"""
48
Guido van Rossum0039d7b1999-01-12 20:19:27 +000049import select
50import socket
Guido van Rossum0039d7b1999-01-12 20:19:27 +000051import sys
Thomas Hellerd8ce87a2002-09-24 17:30:31 +000052import time
Giampaolo Rodolà8d2dc852010-05-06 18:06:30 +000053import warnings
54
Guido van Rossum0039d7b1999-01-12 20:19:27 +000055import os
Giampaolo Rodolà76fc8c72010-08-23 21:53:41 +000056from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, EINVAL, \
Antoine Pitrou24d659d2011-10-23 23:49:42 +020057 ENOTCONN, ESHUTDOWN, EISCONN, EBADF, ECONNABORTED, EPIPE, EAGAIN, \
Giampaolo Rodolàde3dc0f2011-03-03 14:10:58 +000058 errorcode
Guido van Rossum0039d7b1999-01-12 20:19:27 +000059
Raymond Hettingerdf1b6992014-11-09 15:56:33 -080060_DISCONNECTED = frozenset({ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED, EPIPE,
61 EBADF})
Giampaolo Rodolà985b68e2010-09-15 21:43:47 +000062
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000063try:
Fred Drake526a1822000-09-11 04:00:46 +000064 socket_map
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000065except NameError:
Fred Drake526a1822000-09-11 04:00:46 +000066 socket_map = {}
Guido van Rossum0039d7b1999-01-12 20:19:27 +000067
Josiah Carlsond74900e2008-07-07 04:15:08 +000068def _strerror(err):
Giampaolo Rodolà8d2dc852010-05-06 18:06:30 +000069 try:
Giampaolo Rodolà82e02b52010-05-18 20:11:58 +000070 return os.strerror(err)
71 except (ValueError, OverflowError, NameError):
Giampaolo Rodolà8d2dc852010-05-06 18:06:30 +000072 if err in errorcode:
73 return errorcode[err]
74 return "Unknown error %s" %err
Josiah Carlsond74900e2008-07-07 04:15:08 +000075
Neal Norwitz4ce69a52005-09-01 00:45:28 +000076class ExitNow(Exception):
Fred Drake526a1822000-09-11 04:00:46 +000077 pass
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000078
R. David Murray78532ba2009-04-12 15:35:44 +000079_reraised_exceptions = (ExitNow, KeyboardInterrupt, SystemExit)
80
Jeremy Hyltond7500362002-09-08 00:14:54 +000081def read(obj):
82 try:
83 obj.handle_read_event()
R. David Murray78532ba2009-04-12 15:35:44 +000084 except _reraised_exceptions:
Jeremy Hyltond7500362002-09-08 00:14:54 +000085 raise
86 except:
87 obj.handle_error()
88
89def write(obj):
90 try:
91 obj.handle_write_event()
R. David Murray78532ba2009-04-12 15:35:44 +000092 except _reraised_exceptions:
Jeremy Hyltond7500362002-09-08 00:14:54 +000093 raise
94 except:
95 obj.handle_error()
96
Josiah Carlsond74900e2008-07-07 04:15:08 +000097def _exception(obj):
Andrew M. Kuchling0fff6c82004-07-10 17:36:11 +000098 try:
99 obj.handle_expt_event()
R. David Murray78532ba2009-04-12 15:35:44 +0000100 except _reraised_exceptions:
Andrew M. Kuchling0fff6c82004-07-10 17:36:11 +0000101 raise
102 except:
103 obj.handle_error()
104
Jeremy Hyltond7500362002-09-08 00:14:54 +0000105def readwrite(obj, flags):
106 try:
R. David Murray78532ba2009-04-12 15:35:44 +0000107 if flags & select.POLLIN:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000108 obj.handle_read_event()
109 if flags & select.POLLOUT:
110 obj.handle_write_event()
R. David Murray78532ba2009-04-12 15:35:44 +0000111 if flags & select.POLLPRI:
112 obj.handle_expt_event()
Josiah Carlson0abc64d2009-06-03 19:48:02 +0000113 if flags & (select.POLLHUP | select.POLLERR | select.POLLNVAL):
114 obj.handle_close()
Andrew Svetlov0832af62012-12-18 23:10:48 +0200115 except OSError as e:
Giampaolo Rodolà1bc75c62011-03-03 13:57:47 +0000116 if e.args[0] not in _DISCONNECTED:
Josiah Carlson0abc64d2009-06-03 19:48:02 +0000117 obj.handle_error()
118 else:
119 obj.handle_close()
R. David Murray78532ba2009-04-12 15:35:44 +0000120 except _reraised_exceptions:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000121 raise
122 except:
123 obj.handle_error()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000124
Guido van Rossumd560ace2002-09-12 04:57:29 +0000125def poll(timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000126 if map is None:
127 map = socket_map
128 if map:
129 r = []; w = []; e = []
Josiah Carlsond74900e2008-07-07 04:15:08 +0000130 for fd, obj in list(map.items()):
Andrew M. Kuchlinge47c3812004-09-01 14:04:51 +0000131 is_r = obj.readable()
132 is_w = obj.writable()
133 if is_r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000134 r.append(fd)
Charles-François Natalif64f9e92011-07-14 20:00:49 +0200135 # accepting sockets should not be writable
136 if is_w and not obj.accepting:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000137 w.append(fd)
Andrew M. Kuchlinge47c3812004-09-01 14:04:51 +0000138 if is_r or is_w:
139 e.append(fd)
Thomas Hellerd8ce87a2002-09-24 17:30:31 +0000140 if [] == r == w == e:
141 time.sleep(timeout)
Josiah Carlsond74900e2008-07-07 04:15:08 +0000142 return
143
Victor Stinnerf70e1ca2015-03-30 21:16:11 +0200144 r, w, e = select.select(r, w, e, timeout)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000145
Fred Drake526a1822000-09-11 04:00:46 +0000146 for fd in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000147 obj = map.get(fd)
148 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000149 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000150 read(obj)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000151
Fred Drake526a1822000-09-11 04:00:46 +0000152 for fd in w:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000153 obj = map.get(fd)
154 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000155 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000156 write(obj)
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000157
Andrew M. Kuchling0fff6c82004-07-10 17:36:11 +0000158 for fd in e:
159 obj = map.get(fd)
160 if obj is None:
161 continue
162 _exception(obj)
163
Guido van Rossumd560ace2002-09-12 04:57:29 +0000164def poll2(timeout=0.0, map=None):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000165 # Use the poll() support added to the select module in Python 2.0
166 if map is None:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000167 map = socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000168 if timeout is not None:
169 # timeout is in milliseconds
170 timeout = int(timeout*1000)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000171 pollster = select.poll()
172 if map:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000173 for fd, obj in list(map.items()):
Andrew M. Kuchlinge47c3812004-09-01 14:04:51 +0000174 flags = 0
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000175 if obj.readable():
Andrew M. Kuchling6fe93cd2004-07-07 12:23:53 +0000176 flags |= select.POLLIN | select.POLLPRI
Charles-François Natalif64f9e92011-07-14 20:00:49 +0200177 # accepting sockets should not be writable
178 if obj.writable() and not obj.accepting:
Andrew M. Kuchling6fe93cd2004-07-07 12:23:53 +0000179 flags |= select.POLLOUT
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000180 if flags:
181 pollster.register(fd, flags)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000182 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000183 r = pollster.poll(timeout)
Antoine Pitrou24d659d2011-10-23 23:49:42 +0200184 except InterruptedError:
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000185 r = []
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000186 for fd, flags in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000187 obj = map.get(fd)
188 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000189 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000190 readwrite(obj, flags)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000191
Andrew M. Kuchling6c2871e2003-10-22 14:38:27 +0000192poll3 = poll2 # Alias for backward compatibility
193
Michael W. Hudsond5cf1432004-06-30 09:02:33 +0000194def loop(timeout=30.0, use_poll=False, map=None, count=None):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000195 if map is None:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000196 map = socket_map
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000197
Andrew M. Kuchling6c2871e2003-10-22 14:38:27 +0000198 if use_poll and hasattr(select, 'poll'):
199 poll_fun = poll2
Fred Drake526a1822000-09-11 04:00:46 +0000200 else:
201 poll_fun = poll
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000202
Michael W. Hudsond5cf1432004-06-30 09:02:33 +0000203 if count is None:
204 while map:
205 poll_fun(timeout, map)
206
207 else:
208 while map and count > 0:
209 poll_fun(timeout, map)
210 count = count - 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000211
212class dispatcher:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000213
Giampaolo Rodolà900d5472011-02-11 14:01:46 +0000214 debug = False
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000215 connected = False
216 accepting = False
Giampaolo Rodola'350c94b2012-03-22 16:17:43 +0100217 connecting = False
Giampaolo Rodolà900d5472011-02-11 14:01:46 +0000218 closing = False
Fred Drake526a1822000-09-11 04:00:46 +0000219 addr = None
Raymond Hettingerdf1b6992014-11-09 15:56:33 -0800220 ignore_log_types = frozenset({'warning'})
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000221
Guido van Rossumd560ace2002-09-12 04:57:29 +0000222 def __init__(self, sock=None, map=None):
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000223 if map is None:
224 self._map = socket_map
225 else:
226 self._map = map
227
Josiah Carlsond74900e2008-07-07 04:15:08 +0000228 self._fileno = None
229
Fred Drake526a1822000-09-11 04:00:46 +0000230 if sock:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000231 # Set to nonblocking just to make sure for cases where we
232 # get a socket from a blocking source.
233 sock.setblocking(0)
Guido van Rossumd560ace2002-09-12 04:57:29 +0000234 self.set_socket(sock, map)
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000235 self.connected = True
Josiah Carlsond74900e2008-07-07 04:15:08 +0000236 # The constructor no longer requires that the socket
237 # passed be connected.
Jeremy Hylton2a05bc72001-12-14 16:15:11 +0000238 try:
239 self.addr = sock.getpeername()
Andrew Svetlov0832af62012-12-18 23:10:48 +0200240 except OSError as err:
Giampaolo Rodola'350c94b2012-03-22 16:17:43 +0100241 if err.args[0] in (ENOTCONN, EINVAL):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000242 # To handle the case where we got an unconnected
243 # socket.
244 self.connected = False
245 else:
246 # The socket is broken in some unknown way, alert
247 # the user and remove it from the map (to prevent
248 # polling of broken sockets).
249 self.del_channel(map)
250 raise
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000251 else:
252 self.socket = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000253
Guido van Rossumd560ace2002-09-12 04:57:29 +0000254 def __repr__(self):
Serhiy Storchaka521e5862014-07-22 15:00:37 +0300255 status = [self.__class__.__module__+"."+self.__class__.__qualname__]
Martin v. Löwis29103c72001-10-18 17:33:19 +0000256 if self.accepting and self.addr:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000257 status.append('listening')
Martin v. Löwis29103c72001-10-18 17:33:19 +0000258 elif self.connected:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000259 status.append('connected')
Martin v. Löwis29103c72001-10-18 17:33:19 +0000260 if self.addr is not None:
261 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000262 status.append('%s:%d' % self.addr)
Martin v. Löwis29103c72001-10-18 17:33:19 +0000263 except TypeError:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000264 status.append(repr(self.addr))
265 return '<%s at %#x>' % (' '.join(status), id(self))
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000266
Giampaolo Rodolà8d2dc852010-05-06 18:06:30 +0000267 __str__ = __repr__
268
Guido van Rossumd560ace2002-09-12 04:57:29 +0000269 def add_channel(self, map=None):
270 #self.log_info('adding channel %s' % self)
Fred Drake526a1822000-09-11 04:00:46 +0000271 if map is None:
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000272 map = self._map
Guido van Rossum12e96682002-09-13 14:09:26 +0000273 map[self._fileno] = self
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000274
Guido van Rossumd560ace2002-09-12 04:57:29 +0000275 def del_channel(self, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000276 fd = self._fileno
277 if map is None:
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000278 map = self._map
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000279 if fd in map:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000280 #self.log_info('closing channel %d:%s' % (fd, self))
Guido van Rossum12e96682002-09-13 14:09:26 +0000281 del map[fd]
Raymond Hettinger3dc34842004-02-08 11:32:50 +0000282 self._fileno = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000283
Giampaolo Rodolà103a6d62011-02-25 22:21:22 +0000284 def create_socket(self, family=socket.AF_INET, type=socket.SOCK_STREAM):
Fred Drake526a1822000-09-11 04:00:46 +0000285 self.family_and_type = family, type
Josiah Carlsond74900e2008-07-07 04:15:08 +0000286 sock = socket.socket(family, type)
287 sock.setblocking(0)
288 self.set_socket(sock)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000289
Guido van Rossumd560ace2002-09-12 04:57:29 +0000290 def set_socket(self, sock, map=None):
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000291 self.socket = sock
292## self.__dict__['socket'] = sock
Fred Drake526a1822000-09-11 04:00:46 +0000293 self._fileno = sock.fileno()
Guido van Rossumd560ace2002-09-12 04:57:29 +0000294 self.add_channel(map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000295
Guido van Rossumd560ace2002-09-12 04:57:29 +0000296 def set_reuse_addr(self):
Fred Drake526a1822000-09-11 04:00:46 +0000297 # try to re-use a server port if possible
298 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000299 self.socket.setsockopt(
Andrew M. Kuchling9d499f22004-08-13 20:06:57 +0000300 socket.SOL_SOCKET, socket.SO_REUSEADDR,
Guido van Rossumd560ace2002-09-12 04:57:29 +0000301 self.socket.getsockopt(socket.SOL_SOCKET,
Andrew M. Kuchling9d499f22004-08-13 20:06:57 +0000302 socket.SO_REUSEADDR) | 1
Fred Drake526a1822000-09-11 04:00:46 +0000303 )
Andrew Svetlov0832af62012-12-18 23:10:48 +0200304 except OSError:
Fred Drake526a1822000-09-11 04:00:46 +0000305 pass
Tim Peters182b5ac2004-07-18 06:16:08 +0000306
Fred Drake526a1822000-09-11 04:00:46 +0000307 # ==================================================
308 # predicates for select()
309 # these are used as filters for the lists of sockets
310 # to pass to select().
311 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000312
Guido van Rossumd560ace2002-09-12 04:57:29 +0000313 def readable(self):
Tim Petersbc0e9102002-04-04 22:55:58 +0000314 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000315
Andrew M. Kuchling419af882004-03-21 19:52:01 +0000316 def writable(self):
317 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000318
Fred Drake526a1822000-09-11 04:00:46 +0000319 # ==================================================
320 # socket object methods.
321 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000322
Guido van Rossumd560ace2002-09-12 04:57:29 +0000323 def listen(self, num):
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000324 self.accepting = True
Fred Drake526a1822000-09-11 04:00:46 +0000325 if os.name == 'nt' and num > 5:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000326 num = 5
Guido van Rossumd560ace2002-09-12 04:57:29 +0000327 return self.socket.listen(num)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000328
Guido van Rossumd560ace2002-09-12 04:57:29 +0000329 def bind(self, addr):
Fred Drake526a1822000-09-11 04:00:46 +0000330 self.addr = addr
Guido van Rossumd560ace2002-09-12 04:57:29 +0000331 return self.socket.bind(addr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000332
Guido van Rossumd560ace2002-09-12 04:57:29 +0000333 def connect(self, address):
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000334 self.connected = False
Giampaolo Rodola'350c94b2012-03-22 16:17:43 +0100335 self.connecting = True
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000336 err = self.socket.connect_ex(address)
Giampaolo Rodolà76fc8c72010-08-23 21:53:41 +0000337 if err in (EINPROGRESS, EALREADY, EWOULDBLOCK) \
338 or err == EINVAL and os.name in ('nt', 'ce'):
Giampaolo Rodola'2a886412012-03-20 16:44:24 +0100339 self.addr = address
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000340 return
341 if err in (0, EISCONN):
342 self.addr = address
Josiah Carlsond74900e2008-07-07 04:15:08 +0000343 self.handle_connect_event()
Jeremy Hyltonf24339f2001-10-30 14:16:17 +0000344 else:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200345 raise OSError(err, errorcode[err])
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000346
Guido van Rossumd560ace2002-09-12 04:57:29 +0000347 def accept(self):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000348 # XXX can return either an address pair or None
Fred Drake526a1822000-09-11 04:00:46 +0000349 try:
350 conn, addr = self.socket.accept()
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000351 except TypeError:
352 return None
Andrew Svetlov0832af62012-12-18 23:10:48 +0200353 except OSError as why:
Giampaolo Rodolà1bc75c62011-03-03 13:57:47 +0000354 if why.args[0] in (EWOULDBLOCK, ECONNABORTED, EAGAIN):
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000355 return None
Fred Drake526a1822000-09-11 04:00:46 +0000356 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000357 raise
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000358 else:
359 return conn, addr
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000360
Guido van Rossumd560ace2002-09-12 04:57:29 +0000361 def send(self, data):
Fred Drake526a1822000-09-11 04:00:46 +0000362 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000363 result = self.socket.send(data)
Fred Drake526a1822000-09-11 04:00:46 +0000364 return result
Andrew Svetlov0832af62012-12-18 23:10:48 +0200365 except OSError as why:
Georg Brandlf1123692008-07-20 07:31:30 +0000366 if why.args[0] == EWOULDBLOCK:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000367 return 0
Giampaolo Rodolà86909b52010-09-15 21:59:04 +0000368 elif why.args[0] in _DISCONNECTED:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000369 self.handle_close()
Fred Drake526a1822000-09-11 04:00:46 +0000370 return 0
371 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000372 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000373
Guido van Rossumd560ace2002-09-12 04:57:29 +0000374 def recv(self, buffer_size):
Fred Drake526a1822000-09-11 04:00:46 +0000375 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000376 data = self.socket.recv(buffer_size)
Fred Drake526a1822000-09-11 04:00:46 +0000377 if not data:
378 # a closed connection is indicated by signaling
379 # a read condition, and having recv() return 0.
380 self.handle_close()
Guido van Rossumdf4a7432007-07-18 20:57:44 +0000381 return b''
Fred Drake526a1822000-09-11 04:00:46 +0000382 else:
383 return data
Andrew Svetlov0832af62012-12-18 23:10:48 +0200384 except OSError as why:
Andrew Svetlov737fb892012-12-18 21:14:22 +0200385 # winsock sometimes raises ENOTCONN
Giampaolo Rodolà86909b52010-09-15 21:59:04 +0000386 if why.args[0] in _DISCONNECTED:
Fred Drake526a1822000-09-11 04:00:46 +0000387 self.handle_close()
Guido van Rossumdf4a7432007-07-18 20:57:44 +0000388 return b''
Fred Drake526a1822000-09-11 04:00:46 +0000389 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000390 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000391
Guido van Rossumd560ace2002-09-12 04:57:29 +0000392 def close(self):
Giampaolo Rodolà900d5472011-02-11 14:01:46 +0000393 self.connected = False
394 self.accepting = False
Giampaolo Rodola'350c94b2012-03-22 16:17:43 +0100395 self.connecting = False
Giampaolo Rodolà900d5472011-02-11 14:01:46 +0000396 self.del_channel()
Giampaolo Rodola'a4c377c2013-04-09 17:21:25 +0200397 if self.socket is not None:
398 try:
399 self.socket.close()
400 except OSError as why:
401 if why.args[0] not in (ENOTCONN, EBADF):
402 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000403
Andrew M. Kuchlingc07fb2f2003-02-14 01:13:01 +0000404 # log and log_info may be overridden to provide more sophisticated
Fred Drake526a1822000-09-11 04:00:46 +0000405 # logging and warning methods. In general, log is for 'hit' logging
Tim Peters146965a2001-01-14 18:09:23 +0000406 # and 'log_info' is for informational, warning and error logging.
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000407
Guido van Rossumd560ace2002-09-12 04:57:29 +0000408 def log(self, message):
409 sys.stderr.write('log: %s\n' % str(message))
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000410
Guido van Rossumd560ace2002-09-12 04:57:29 +0000411 def log_info(self, message, type='info'):
R. David Murray78532ba2009-04-12 15:35:44 +0000412 if type not in self.ignore_log_types:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000413 print('%s: %s' % (type, message))
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000414
Guido van Rossumd560ace2002-09-12 04:57:29 +0000415 def handle_read_event(self):
Fred Drake526a1822000-09-11 04:00:46 +0000416 if self.accepting:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000417 # accepting sockets are never connected, they "spawn" new
418 # sockets that are connected
Fred Drake526a1822000-09-11 04:00:46 +0000419 self.handle_accept()
420 elif not self.connected:
Giampaolo Rodola'350c94b2012-03-22 16:17:43 +0100421 if self.connecting:
422 self.handle_connect_event()
Fred Drake526a1822000-09-11 04:00:46 +0000423 self.handle_read()
424 else:
425 self.handle_read()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000426
Josiah Carlsond74900e2008-07-07 04:15:08 +0000427 def handle_connect_event(self):
Giampaolo Rodolà934abdd2010-08-04 09:02:27 +0000428 err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
429 if err != 0:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200430 raise OSError(err, _strerror(err))
Josiah Carlsond74900e2008-07-07 04:15:08 +0000431 self.handle_connect()
Giampaolo Rodolà934abdd2010-08-04 09:02:27 +0000432 self.connected = True
Giampaolo Rodola'350c94b2012-03-22 16:17:43 +0100433 self.connecting = False
Josiah Carlsond74900e2008-07-07 04:15:08 +0000434
Guido van Rossumd560ace2002-09-12 04:57:29 +0000435 def handle_write_event(self):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000436 if self.accepting:
437 # Accepting sockets shouldn't get a write event.
438 # We will pretend it didn't happen.
439 return
440
Fred Drake526a1822000-09-11 04:00:46 +0000441 if not self.connected:
Giampaolo Rodola'350c94b2012-03-22 16:17:43 +0100442 if self.connecting:
443 self.handle_connect_event()
Fred Drake526a1822000-09-11 04:00:46 +0000444 self.handle_write()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000445
Guido van Rossumd560ace2002-09-12 04:57:29 +0000446 def handle_expt_event(self):
R. David Murray78532ba2009-04-12 15:35:44 +0000447 # handle_expt_event() is called if there might be an error on the
448 # socket, or if there is OOB data
449 # check for the error condition first
450 err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
451 if err != 0:
452 # we can get here when select.select() says that there is an
453 # exceptional condition on the socket
454 # since there is an error, we'll go ahead and close the socket
455 # like we would in a subclassed handle_read() that received no
456 # data
457 self.handle_close()
Josiah Carlsond74900e2008-07-07 04:15:08 +0000458 else:
459 self.handle_expt()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000460
Guido van Rossumd560ace2002-09-12 04:57:29 +0000461 def handle_error(self):
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000462 nil, t, v, tbinfo = compact_traceback()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000463
Fred Drake526a1822000-09-11 04:00:46 +0000464 # sometimes a user repr method will crash.
465 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000466 self_repr = repr(self)
Fred Drake526a1822000-09-11 04:00:46 +0000467 except:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000468 self_repr = '<__repr__(self) failed for object at %0x>' % id(self)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000469
Guido van Rossumd560ace2002-09-12 04:57:29 +0000470 self.log_info(
Fred Drake526a1822000-09-11 04:00:46 +0000471 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
472 self_repr,
473 t,
474 v,
475 tbinfo
476 ),
477 'error'
478 )
Josiah Carlson9f2f8332008-07-07 05:04:12 +0000479 self.handle_close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000480
Guido van Rossumd560ace2002-09-12 04:57:29 +0000481 def handle_expt(self):
R. David Murray78532ba2009-04-12 15:35:44 +0000482 self.log_info('unhandled incoming priority event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000483
Guido van Rossumd560ace2002-09-12 04:57:29 +0000484 def handle_read(self):
485 self.log_info('unhandled read event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000486
Guido van Rossumd560ace2002-09-12 04:57:29 +0000487 def handle_write(self):
488 self.log_info('unhandled write event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000489
Guido van Rossumd560ace2002-09-12 04:57:29 +0000490 def handle_connect(self):
491 self.log_info('unhandled connect event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000492
Guido van Rossumd560ace2002-09-12 04:57:29 +0000493 def handle_accept(self):
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000494 pair = self.accept()
495 if pair is not None:
496 self.handle_accepted(*pair)
497
498 def handle_accepted(self, sock, addr):
499 sock.close()
500 self.log_info('unhandled accepted event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000501
Guido van Rossumd560ace2002-09-12 04:57:29 +0000502 def handle_close(self):
503 self.log_info('unhandled close event', 'warning')
Fred Drake526a1822000-09-11 04:00:46 +0000504 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000505
506# ---------------------------------------------------------------------------
507# adds simple buffered output capability, useful for simple clients.
508# [for more sophisticated usage use asynchat.async_chat]
509# ---------------------------------------------------------------------------
510
Guido van Rossumd560ace2002-09-12 04:57:29 +0000511class dispatcher_with_send(dispatcher):
512
Andrew M. Kuchling67867ea2004-03-21 20:03:18 +0000513 def __init__(self, sock=None, map=None):
514 dispatcher.__init__(self, sock, map)
Guido van Rossumdf4a7432007-07-18 20:57:44 +0000515 self.out_buffer = b''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000516
Guido van Rossumd560ace2002-09-12 04:57:29 +0000517 def initiate_send(self):
Fred Drake526a1822000-09-11 04:00:46 +0000518 num_sent = 0
Charles-François Natalife22dca2013-01-01 16:31:54 +0100519 num_sent = dispatcher.send(self, self.out_buffer[:65536])
Fred Drake526a1822000-09-11 04:00:46 +0000520 self.out_buffer = self.out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000521
Guido van Rossumd560ace2002-09-12 04:57:29 +0000522 def handle_write(self):
Fred Drake526a1822000-09-11 04:00:46 +0000523 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000524
Guido van Rossumd560ace2002-09-12 04:57:29 +0000525 def writable(self):
Fred Drake526a1822000-09-11 04:00:46 +0000526 return (not self.connected) or len(self.out_buffer)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000527
Guido van Rossumd560ace2002-09-12 04:57:29 +0000528 def send(self, data):
Giampaolo Rodolà900d5472011-02-11 14:01:46 +0000529 if self.debug:
530 self.log_info('sending %s' % repr(data))
Fred Drake526a1822000-09-11 04:00:46 +0000531 self.out_buffer = self.out_buffer + data
532 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000533
534# ---------------------------------------------------------------------------
535# used for debugging.
536# ---------------------------------------------------------------------------
537
Guido van Rossumd560ace2002-09-12 04:57:29 +0000538def compact_traceback():
Guido van Rossum12e96682002-09-13 14:09:26 +0000539 t, v, tb = sys.exc_info()
Fred Drake526a1822000-09-11 04:00:46 +0000540 tbinfo = []
Josiah Carlsond74900e2008-07-07 04:15:08 +0000541 if not tb: # Must have a traceback
542 raise AssertionError("traceback does not exist")
Guido van Rossum12e96682002-09-13 14:09:26 +0000543 while tb:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000544 tbinfo.append((
Fred Drake526a1822000-09-11 04:00:46 +0000545 tb.tb_frame.f_code.co_filename,
Tim Peters146965a2001-01-14 18:09:23 +0000546 tb.tb_frame.f_code.co_name,
Fred Drake526a1822000-09-11 04:00:46 +0000547 str(tb.tb_lineno)
548 ))
549 tb = tb.tb_next
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000550
Fred Drake526a1822000-09-11 04:00:46 +0000551 # just to be safe
552 del tb
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000553
Fred Drake526a1822000-09-11 04:00:46 +0000554 file, function, line = tbinfo[-1]
Guido van Rossum12e96682002-09-13 14:09:26 +0000555 info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo])
Fred Drake526a1822000-09-11 04:00:46 +0000556 return (file, function, line), t, v, info
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000557
Josiah Carlsond74900e2008-07-07 04:15:08 +0000558def close_all(map=None, ignore_all=False):
Fred Drake526a1822000-09-11 04:00:46 +0000559 if map is None:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000560 map = socket_map
Josiah Carlsond74900e2008-07-07 04:15:08 +0000561 for x in list(map.values()):
562 try:
563 x.close()
564 except OSError as x:
Georg Brandlf1123692008-07-20 07:31:30 +0000565 if x.args[0] == EBADF:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000566 pass
567 elif not ignore_all:
568 raise
R. David Murray78532ba2009-04-12 15:35:44 +0000569 except _reraised_exceptions:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000570 raise
571 except:
572 if not ignore_all:
573 raise
Fred Drake526a1822000-09-11 04:00:46 +0000574 map.clear()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000575
576# Asynchronous File I/O:
577#
578# After a little research (reading man pages on various unixen, and
579# digging through the linux kernel), I've determined that select()
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000580# isn't meant for doing asynchronous file i/o.
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000581# Heartening, though - reading linux/mm/filemap.c shows that linux
582# supports asynchronous read-ahead. So _MOST_ of the time, the data
583# will be sitting in memory for us already when we go to read it.
584#
585# What other OS's (besides NT) support async file i/o? [VMS?]
586#
587# Regardless, this is useful for pipes, and stdin/stdout...
588
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000589if os.name == 'posix':
Fred Drake526a1822000-09-11 04:00:46 +0000590 class file_wrapper:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000591 # Here we override just enough to make a file
Fred Drake526a1822000-09-11 04:00:46 +0000592 # look like a socket for the purposes of asyncore.
Josiah Carlsond74900e2008-07-07 04:15:08 +0000593 # The passed fd is automatically os.dup()'d
Guido van Rossumd560ace2002-09-12 04:57:29 +0000594
595 def __init__(self, fd):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000596 self.fd = os.dup(fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000597
Victor Stinner4d4c69d2014-06-27 23:52:03 +0200598 def __del__(self):
599 if self.fd >= 0:
600 warnings.warn("unclosed file %r" % self, ResourceWarning)
601 self.close()
602
Guido van Rossumd560ace2002-09-12 04:57:29 +0000603 def recv(self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000604 return os.read(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000605
Guido van Rossumd560ace2002-09-12 04:57:29 +0000606 def send(self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000607 return os.write(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000608
Georg Brandlcbb0ae42010-07-28 08:19:35 +0000609 def getsockopt(self, level, optname, buflen=None):
610 if (level == socket.SOL_SOCKET and
611 optname == socket.SO_ERROR and
612 not buflen):
613 return 0
614 raise NotImplementedError("Only asyncore specific behaviour "
615 "implemented.")
616
Fred Drake526a1822000-09-11 04:00:46 +0000617 read = recv
618 write = send
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000619
Guido van Rossumd560ace2002-09-12 04:57:29 +0000620 def close(self):
Victor Stinner4d4c69d2014-06-27 23:52:03 +0200621 if self.fd < 0:
622 return
Andrew M. Kuchlingdfa74b92004-07-10 15:51:19 +0000623 os.close(self.fd)
Victor Stinner4d4c69d2014-06-27 23:52:03 +0200624 self.fd = -1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000625
Guido van Rossumd560ace2002-09-12 04:57:29 +0000626 def fileno(self):
Fred Drake526a1822000-09-11 04:00:46 +0000627 return self.fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000628
Guido van Rossumd560ace2002-09-12 04:57:29 +0000629 class file_dispatcher(dispatcher):
630
Andrew M. Kuchling67867ea2004-03-21 20:03:18 +0000631 def __init__(self, fd, map=None):
632 dispatcher.__init__(self, None, map)
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000633 self.connected = True
Josiah Carlsond74900e2008-07-07 04:15:08 +0000634 try:
635 fd = fd.fileno()
636 except AttributeError:
637 pass
Andrew M. Kuchlingdfa74b92004-07-10 15:51:19 +0000638 self.set_file(fd)
Fred Drake526a1822000-09-11 04:00:46 +0000639 # set it to non-blocking mode
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200640 os.set_blocking(fd, False)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000641
Guido van Rossumd560ace2002-09-12 04:57:29 +0000642 def set_file(self, fd):
Guido van Rossumd560ace2002-09-12 04:57:29 +0000643 self.socket = file_wrapper(fd)
Josiah Carlsonaae55cb2008-11-19 18:22:41 +0000644 self._fileno = self.socket.fileno()
Fred Drake526a1822000-09-11 04:00:46 +0000645 self.add_channel()