blob: fba55e0d89515725ef37d750392a987302b63c46 [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
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +000056from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \
Josiah Carlsond74900e2008-07-07 04:15:08 +000057 ENOTCONN, ESHUTDOWN, EINTR, EISCONN, EBADF, ECONNABORTED, errorcode
Guido van Rossum0039d7b1999-01-12 20:19:27 +000058
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000059try:
Fred Drake526a1822000-09-11 04:00:46 +000060 socket_map
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000061except NameError:
Fred Drake526a1822000-09-11 04:00:46 +000062 socket_map = {}
Guido van Rossum0039d7b1999-01-12 20:19:27 +000063
Josiah Carlsond74900e2008-07-07 04:15:08 +000064def _strerror(err):
Giampaolo Rodolà8d2dc852010-05-06 18:06:30 +000065 try:
Giampaolo Rodolà82e02b52010-05-18 20:11:58 +000066 return os.strerror(err)
67 except (ValueError, OverflowError, NameError):
Giampaolo Rodolà8d2dc852010-05-06 18:06:30 +000068 if err in errorcode:
69 return errorcode[err]
70 return "Unknown error %s" %err
Josiah Carlsond74900e2008-07-07 04:15:08 +000071
Neal Norwitz4ce69a52005-09-01 00:45:28 +000072class ExitNow(Exception):
Fred Drake526a1822000-09-11 04:00:46 +000073 pass
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000074
R. David Murray78532ba2009-04-12 15:35:44 +000075_reraised_exceptions = (ExitNow, KeyboardInterrupt, SystemExit)
76
Jeremy Hyltond7500362002-09-08 00:14:54 +000077def read(obj):
78 try:
79 obj.handle_read_event()
R. David Murray78532ba2009-04-12 15:35:44 +000080 except _reraised_exceptions:
Jeremy Hyltond7500362002-09-08 00:14:54 +000081 raise
82 except:
83 obj.handle_error()
84
85def write(obj):
86 try:
87 obj.handle_write_event()
R. David Murray78532ba2009-04-12 15:35:44 +000088 except _reraised_exceptions:
Jeremy Hyltond7500362002-09-08 00:14:54 +000089 raise
90 except:
91 obj.handle_error()
92
Josiah Carlsond74900e2008-07-07 04:15:08 +000093def _exception(obj):
Andrew M. Kuchling0fff6c82004-07-10 17:36:11 +000094 try:
95 obj.handle_expt_event()
R. David Murray78532ba2009-04-12 15:35:44 +000096 except _reraised_exceptions:
Andrew M. Kuchling0fff6c82004-07-10 17:36:11 +000097 raise
98 except:
99 obj.handle_error()
100
Jeremy Hyltond7500362002-09-08 00:14:54 +0000101def readwrite(obj, flags):
102 try:
R. David Murray78532ba2009-04-12 15:35:44 +0000103 if flags & select.POLLIN:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000104 obj.handle_read_event()
105 if flags & select.POLLOUT:
106 obj.handle_write_event()
R. David Murray78532ba2009-04-12 15:35:44 +0000107 if flags & select.POLLPRI:
108 obj.handle_expt_event()
Josiah Carlson0abc64d2009-06-03 19:48:02 +0000109 if flags & (select.POLLHUP | select.POLLERR | select.POLLNVAL):
110 obj.handle_close()
111 except socket.error as e:
112 if e.args[0] not in (EBADF, ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED):
113 obj.handle_error()
114 else:
115 obj.handle_close()
R. David Murray78532ba2009-04-12 15:35:44 +0000116 except _reraised_exceptions:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000117 raise
118 except:
119 obj.handle_error()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000120
Guido van Rossumd560ace2002-09-12 04:57:29 +0000121def poll(timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000122 if map is None:
123 map = socket_map
124 if map:
125 r = []; w = []; e = []
Josiah Carlsond74900e2008-07-07 04:15:08 +0000126 for fd, obj in list(map.items()):
Andrew M. Kuchlinge47c3812004-09-01 14:04:51 +0000127 is_r = obj.readable()
128 is_w = obj.writable()
129 if is_r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000130 r.append(fd)
Andrew M. Kuchlinge47c3812004-09-01 14:04:51 +0000131 if is_w:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000132 w.append(fd)
Andrew M. Kuchlinge47c3812004-09-01 14:04:51 +0000133 if is_r or is_w:
134 e.append(fd)
Thomas Hellerd8ce87a2002-09-24 17:30:31 +0000135 if [] == r == w == e:
136 time.sleep(timeout)
Josiah Carlsond74900e2008-07-07 04:15:08 +0000137 return
138
139 try:
140 r, w, e = select.select(r, w, e, timeout)
141 except select.error as err:
Georg Brandlf1123692008-07-20 07:31:30 +0000142 if err.args[0] != EINTR:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000143 raise
144 else:
145 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000146
Fred Drake526a1822000-09-11 04:00:46 +0000147 for fd in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000148 obj = map.get(fd)
149 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000150 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000151 read(obj)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000152
Fred Drake526a1822000-09-11 04:00:46 +0000153 for fd in w:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000154 obj = map.get(fd)
155 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000156 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000157 write(obj)
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000158
Andrew M. Kuchling0fff6c82004-07-10 17:36:11 +0000159 for fd in e:
160 obj = map.get(fd)
161 if obj is None:
162 continue
163 _exception(obj)
164
Guido van Rossumd560ace2002-09-12 04:57:29 +0000165def poll2(timeout=0.0, map=None):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000166 # Use the poll() support added to the select module in Python 2.0
167 if map is None:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000168 map = socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000169 if timeout is not None:
170 # timeout is in milliseconds
171 timeout = int(timeout*1000)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000172 pollster = select.poll()
173 if map:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000174 for fd, obj in list(map.items()):
Andrew M. Kuchlinge47c3812004-09-01 14:04:51 +0000175 flags = 0
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000176 if obj.readable():
Andrew M. Kuchling6fe93cd2004-07-07 12:23:53 +0000177 flags |= select.POLLIN | select.POLLPRI
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000178 if obj.writable():
Andrew M. Kuchling6fe93cd2004-07-07 12:23:53 +0000179 flags |= select.POLLOUT
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000180 if flags:
Andrew M. Kuchlinge47c3812004-09-01 14:04:51 +0000181 # Only check for exceptions if object was either readable
182 # or writable.
183 flags |= select.POLLERR | select.POLLHUP | select.POLLNVAL
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000184 pollster.register(fd, flags)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000185 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000186 r = pollster.poll(timeout)
Guido van Rossumb940e112007-01-10 16:19:56 +0000187 except select.error as err:
Georg Brandlf1123692008-07-20 07:31:30 +0000188 if err.args[0] != EINTR:
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000189 raise
190 r = []
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000191 for fd, flags in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000192 obj = map.get(fd)
193 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000194 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000195 readwrite(obj, flags)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000196
Andrew M. Kuchling6c2871e2003-10-22 14:38:27 +0000197poll3 = poll2 # Alias for backward compatibility
198
Michael W. Hudsond5cf1432004-06-30 09:02:33 +0000199def loop(timeout=30.0, use_poll=False, map=None, count=None):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000200 if map is None:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000201 map = socket_map
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000202
Andrew M. Kuchling6c2871e2003-10-22 14:38:27 +0000203 if use_poll and hasattr(select, 'poll'):
204 poll_fun = poll2
Fred Drake526a1822000-09-11 04:00:46 +0000205 else:
206 poll_fun = poll
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000207
Michael W. Hudsond5cf1432004-06-30 09:02:33 +0000208 if count is None:
209 while map:
210 poll_fun(timeout, map)
211
212 else:
213 while map and count > 0:
214 poll_fun(timeout, map)
215 count = count - 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000216
217class dispatcher:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000218
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000219 debug = False
220 connected = False
221 accepting = False
222 closing = False
Fred Drake526a1822000-09-11 04:00:46 +0000223 addr = None
R. David Murray78532ba2009-04-12 15:35:44 +0000224 ignore_log_types = frozenset(['warning'])
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000225
Guido van Rossumd560ace2002-09-12 04:57:29 +0000226 def __init__(self, sock=None, map=None):
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000227 if map is None:
228 self._map = socket_map
229 else:
230 self._map = map
231
Josiah Carlsond74900e2008-07-07 04:15:08 +0000232 self._fileno = None
233
Fred Drake526a1822000-09-11 04:00:46 +0000234 if sock:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000235 # Set to nonblocking just to make sure for cases where we
236 # get a socket from a blocking source.
237 sock.setblocking(0)
Guido van Rossumd560ace2002-09-12 04:57:29 +0000238 self.set_socket(sock, map)
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000239 self.connected = True
Josiah Carlsond74900e2008-07-07 04:15:08 +0000240 # The constructor no longer requires that the socket
241 # passed be connected.
Jeremy Hylton2a05bc72001-12-14 16:15:11 +0000242 try:
243 self.addr = sock.getpeername()
Josiah Carlsond74900e2008-07-07 04:15:08 +0000244 except socket.error as err:
Georg Brandlf1123692008-07-20 07:31:30 +0000245 if err.args[0] == ENOTCONN:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000246 # To handle the case where we got an unconnected
247 # socket.
248 self.connected = False
249 else:
250 # The socket is broken in some unknown way, alert
251 # the user and remove it from the map (to prevent
252 # polling of broken sockets).
253 self.del_channel(map)
254 raise
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000255 else:
256 self.socket = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000257
Guido van Rossumd560ace2002-09-12 04:57:29 +0000258 def __repr__(self):
Martin v. Löwis29103c72001-10-18 17:33:19 +0000259 status = [self.__class__.__module__+"."+self.__class__.__name__]
260 if self.accepting and self.addr:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000261 status.append('listening')
Martin v. Löwis29103c72001-10-18 17:33:19 +0000262 elif self.connected:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000263 status.append('connected')
Martin v. Löwis29103c72001-10-18 17:33:19 +0000264 if self.addr is not None:
265 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000266 status.append('%s:%d' % self.addr)
Martin v. Löwis29103c72001-10-18 17:33:19 +0000267 except TypeError:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000268 status.append(repr(self.addr))
269 return '<%s at %#x>' % (' '.join(status), id(self))
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000270
Giampaolo Rodolà8d2dc852010-05-06 18:06:30 +0000271 __str__ = __repr__
272
Guido van Rossumd560ace2002-09-12 04:57:29 +0000273 def add_channel(self, map=None):
274 #self.log_info('adding channel %s' % self)
Fred Drake526a1822000-09-11 04:00:46 +0000275 if map is None:
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000276 map = self._map
Guido van Rossum12e96682002-09-13 14:09:26 +0000277 map[self._fileno] = self
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000278
Guido van Rossumd560ace2002-09-12 04:57:29 +0000279 def del_channel(self, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000280 fd = self._fileno
281 if map is None:
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000282 map = self._map
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000283 if fd in map:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000284 #self.log_info('closing channel %d:%s' % (fd, self))
Guido van Rossum12e96682002-09-13 14:09:26 +0000285 del map[fd]
Raymond Hettinger3dc34842004-02-08 11:32:50 +0000286 self._fileno = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000287
Guido van Rossumd560ace2002-09-12 04:57:29 +0000288 def create_socket(self, family, type):
Fred Drake526a1822000-09-11 04:00:46 +0000289 self.family_and_type = family, type
Josiah Carlsond74900e2008-07-07 04:15:08 +0000290 sock = socket.socket(family, type)
291 sock.setblocking(0)
292 self.set_socket(sock)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000293
Guido van Rossumd560ace2002-09-12 04:57:29 +0000294 def set_socket(self, sock, map=None):
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000295 self.socket = sock
296## self.__dict__['socket'] = sock
Fred Drake526a1822000-09-11 04:00:46 +0000297 self._fileno = sock.fileno()
Guido van Rossumd560ace2002-09-12 04:57:29 +0000298 self.add_channel(map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000299
Guido van Rossumd560ace2002-09-12 04:57:29 +0000300 def set_reuse_addr(self):
Fred Drake526a1822000-09-11 04:00:46 +0000301 # try to re-use a server port if possible
302 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000303 self.socket.setsockopt(
Andrew M. Kuchling9d499f22004-08-13 20:06:57 +0000304 socket.SOL_SOCKET, socket.SO_REUSEADDR,
Guido van Rossumd560ace2002-09-12 04:57:29 +0000305 self.socket.getsockopt(socket.SOL_SOCKET,
Andrew M. Kuchling9d499f22004-08-13 20:06:57 +0000306 socket.SO_REUSEADDR) | 1
Fred Drake526a1822000-09-11 04:00:46 +0000307 )
Fred Drake9f9b5932001-05-11 18:28:54 +0000308 except socket.error:
Fred Drake526a1822000-09-11 04:00:46 +0000309 pass
Tim Peters182b5ac2004-07-18 06:16:08 +0000310
Fred Drake526a1822000-09-11 04:00:46 +0000311 # ==================================================
312 # predicates for select()
313 # these are used as filters for the lists of sockets
314 # to pass to select().
315 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000316
Guido van Rossumd560ace2002-09-12 04:57:29 +0000317 def readable(self):
Tim Petersbc0e9102002-04-04 22:55:58 +0000318 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000319
Andrew M. Kuchling419af882004-03-21 19:52:01 +0000320 def writable(self):
321 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000322
Fred Drake526a1822000-09-11 04:00:46 +0000323 # ==================================================
324 # socket object methods.
325 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000326
Guido van Rossumd560ace2002-09-12 04:57:29 +0000327 def listen(self, num):
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000328 self.accepting = True
Fred Drake526a1822000-09-11 04:00:46 +0000329 if os.name == 'nt' and num > 5:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000330 num = 5
Guido van Rossumd560ace2002-09-12 04:57:29 +0000331 return self.socket.listen(num)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000332
Guido van Rossumd560ace2002-09-12 04:57:29 +0000333 def bind(self, addr):
Fred Drake526a1822000-09-11 04:00:46 +0000334 self.addr = addr
Guido van Rossumd560ace2002-09-12 04:57:29 +0000335 return self.socket.bind(addr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000336
Guido van Rossumd560ace2002-09-12 04:57:29 +0000337 def connect(self, address):
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000338 self.connected = False
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000339 err = self.socket.connect_ex(address)
Guido van Rossum9a40c1c2002-12-26 18:22:54 +0000340 # XXX Should interpret Winsock return values
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000341 if err in (EINPROGRESS, EALREADY, EWOULDBLOCK):
342 return
343 if err in (0, EISCONN):
344 self.addr = address
Josiah Carlsond74900e2008-07-07 04:15:08 +0000345 self.handle_connect_event()
Jeremy Hyltonf24339f2001-10-30 14:16:17 +0000346 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000347 raise socket.error(err, errorcode[err])
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000348
Guido van Rossumd560ace2002-09-12 04:57:29 +0000349 def accept(self):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000350 # XXX can return either an address pair or None
Fred Drake526a1822000-09-11 04:00:46 +0000351 try:
352 conn, addr = self.socket.accept()
353 return conn, addr
Guido van Rossumb940e112007-01-10 16:19:56 +0000354 except socket.error as why:
Georg Brandlf1123692008-07-20 07:31:30 +0000355 if why.args[0] == EWOULDBLOCK:
Fred Drake526a1822000-09-11 04:00:46 +0000356 pass
357 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000358 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000359
Guido van Rossumd560ace2002-09-12 04:57:29 +0000360 def send(self, data):
Fred Drake526a1822000-09-11 04:00:46 +0000361 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000362 result = self.socket.send(data)
Fred Drake526a1822000-09-11 04:00:46 +0000363 return result
Guido van Rossumb940e112007-01-10 16:19:56 +0000364 except socket.error as why:
Georg Brandlf1123692008-07-20 07:31:30 +0000365 if why.args[0] == EWOULDBLOCK:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000366 return 0
Georg Brandlf1123692008-07-20 07:31:30 +0000367 elif why.args[0] in (ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000368 self.handle_close()
Fred Drake526a1822000-09-11 04:00:46 +0000369 return 0
370 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000371 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000372
Guido van Rossumd560ace2002-09-12 04:57:29 +0000373 def recv(self, buffer_size):
Fred Drake526a1822000-09-11 04:00:46 +0000374 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000375 data = self.socket.recv(buffer_size)
Fred Drake526a1822000-09-11 04:00:46 +0000376 if not data:
377 # a closed connection is indicated by signaling
378 # a read condition, and having recv() return 0.
379 self.handle_close()
Guido van Rossumdf4a7432007-07-18 20:57:44 +0000380 return b''
Fred Drake526a1822000-09-11 04:00:46 +0000381 else:
382 return data
Guido van Rossumb940e112007-01-10 16:19:56 +0000383 except socket.error as why:
Fred Drake526a1822000-09-11 04:00:46 +0000384 # winsock sometimes throws ENOTCONN
Georg Brandlf1123692008-07-20 07:31:30 +0000385 if why.args[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN, ECONNABORTED]:
Fred Drake526a1822000-09-11 04:00:46 +0000386 self.handle_close()
Guido van Rossumdf4a7432007-07-18 20:57:44 +0000387 return b''
Fred Drake526a1822000-09-11 04:00:46 +0000388 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000389 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000390
Guido van Rossumd560ace2002-09-12 04:57:29 +0000391 def close(self):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000392 self.connected = False
393 self.accepting = False
Fred Drake526a1822000-09-11 04:00:46 +0000394 self.del_channel()
Josiah Carlsond74900e2008-07-07 04:15:08 +0000395 try:
396 self.socket.close()
397 except socket.error as why:
Georg Brandlf1123692008-07-20 07:31:30 +0000398 if why.args[0] not in (ENOTCONN, EBADF):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000399 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000400
Fred Drake526a1822000-09-11 04:00:46 +0000401 # cheap inheritance, used to pass all other attribute
402 # references to the underlying socket object.
Guido van Rossumd560ace2002-09-12 04:57:29 +0000403 def __getattr__(self, attr):
Giampaolo Rodolà8d2dc852010-05-06 18:06:30 +0000404 try:
405 retattr = getattr(self.socket, attr)
406 except AttributeError:
407 raise AttributeError("%s instance has no attribute '%s'"
408 %(self.__class__.__name__, attr))
409 else:
Giampaolo Rodolàd61e3972010-05-06 20:02:37 +0000410 msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s " \
411 "instead" % {'me' : self.__class__.__name__, 'attr' : attr}
412 warnings.warn(msg, DeprecationWarning, stacklevel=2)
Giampaolo Rodolà8d2dc852010-05-06 18:06:30 +0000413 return retattr
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000414
Andrew M. Kuchlingc07fb2f2003-02-14 01:13:01 +0000415 # log and log_info may be overridden to provide more sophisticated
Fred Drake526a1822000-09-11 04:00:46 +0000416 # logging and warning methods. In general, log is for 'hit' logging
Tim Peters146965a2001-01-14 18:09:23 +0000417 # and 'log_info' is for informational, warning and error logging.
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000418
Guido van Rossumd560ace2002-09-12 04:57:29 +0000419 def log(self, message):
420 sys.stderr.write('log: %s\n' % str(message))
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000421
Guido van Rossumd560ace2002-09-12 04:57:29 +0000422 def log_info(self, message, type='info'):
R. David Murray78532ba2009-04-12 15:35:44 +0000423 if type not in self.ignore_log_types:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000424 print('%s: %s' % (type, message))
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000425
Guido van Rossumd560ace2002-09-12 04:57:29 +0000426 def handle_read_event(self):
Fred Drake526a1822000-09-11 04:00:46 +0000427 if self.accepting:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000428 # accepting sockets are never connected, they "spawn" new
429 # sockets that are connected
Fred Drake526a1822000-09-11 04:00:46 +0000430 self.handle_accept()
431 elif not self.connected:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000432 self.handle_connect_event()
Fred Drake526a1822000-09-11 04:00:46 +0000433 self.handle_read()
434 else:
435 self.handle_read()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000436
Josiah Carlsond74900e2008-07-07 04:15:08 +0000437 def handle_connect_event(self):
438 self.connected = True
439 self.handle_connect()
440
Guido van Rossumd560ace2002-09-12 04:57:29 +0000441 def handle_write_event(self):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000442 if self.accepting:
443 # Accepting sockets shouldn't get a write event.
444 # We will pretend it didn't happen.
445 return
446
Fred Drake526a1822000-09-11 04:00:46 +0000447 if not self.connected:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000448 #check for errors
449 err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
450 if err != 0:
451 raise socket.error(err, _strerror(err))
452
453 self.handle_connect_event()
Fred Drake526a1822000-09-11 04:00:46 +0000454 self.handle_write()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000455
Guido van Rossumd560ace2002-09-12 04:57:29 +0000456 def handle_expt_event(self):
R. David Murray78532ba2009-04-12 15:35:44 +0000457 # handle_expt_event() is called if there might be an error on the
458 # socket, or if there is OOB data
459 # check for the error condition first
460 err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
461 if err != 0:
462 # we can get here when select.select() says that there is an
463 # exceptional condition on the socket
464 # since there is an error, we'll go ahead and close the socket
465 # like we would in a subclassed handle_read() that received no
466 # data
467 self.handle_close()
Josiah Carlsond74900e2008-07-07 04:15:08 +0000468 else:
469 self.handle_expt()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000470
Guido van Rossumd560ace2002-09-12 04:57:29 +0000471 def handle_error(self):
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000472 nil, t, v, tbinfo = compact_traceback()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000473
Fred Drake526a1822000-09-11 04:00:46 +0000474 # sometimes a user repr method will crash.
475 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000476 self_repr = repr(self)
Fred Drake526a1822000-09-11 04:00:46 +0000477 except:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000478 self_repr = '<__repr__(self) failed for object at %0x>' % id(self)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000479
Guido van Rossumd560ace2002-09-12 04:57:29 +0000480 self.log_info(
Fred Drake526a1822000-09-11 04:00:46 +0000481 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
482 self_repr,
483 t,
484 v,
485 tbinfo
486 ),
487 'error'
488 )
Josiah Carlson9f2f8332008-07-07 05:04:12 +0000489 self.handle_close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000490
Guido van Rossumd560ace2002-09-12 04:57:29 +0000491 def handle_expt(self):
R. David Murray78532ba2009-04-12 15:35:44 +0000492 self.log_info('unhandled incoming priority event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000493
Guido van Rossumd560ace2002-09-12 04:57:29 +0000494 def handle_read(self):
495 self.log_info('unhandled read event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000496
Guido van Rossumd560ace2002-09-12 04:57:29 +0000497 def handle_write(self):
498 self.log_info('unhandled write event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000499
Guido van Rossumd560ace2002-09-12 04:57:29 +0000500 def handle_connect(self):
501 self.log_info('unhandled connect event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000502
Guido van Rossumd560ace2002-09-12 04:57:29 +0000503 def handle_accept(self):
504 self.log_info('unhandled accept event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000505
Guido van Rossumd560ace2002-09-12 04:57:29 +0000506 def handle_close(self):
507 self.log_info('unhandled close event', 'warning')
Fred Drake526a1822000-09-11 04:00:46 +0000508 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000509
510# ---------------------------------------------------------------------------
511# adds simple buffered output capability, useful for simple clients.
512# [for more sophisticated usage use asynchat.async_chat]
513# ---------------------------------------------------------------------------
514
Guido van Rossumd560ace2002-09-12 04:57:29 +0000515class dispatcher_with_send(dispatcher):
516
Andrew M. Kuchling67867ea2004-03-21 20:03:18 +0000517 def __init__(self, sock=None, map=None):
518 dispatcher.__init__(self, sock, map)
Guido van Rossumdf4a7432007-07-18 20:57:44 +0000519 self.out_buffer = b''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000520
Guido van Rossumd560ace2002-09-12 04:57:29 +0000521 def initiate_send(self):
Fred Drake526a1822000-09-11 04:00:46 +0000522 num_sent = 0
Guido van Rossumd560ace2002-09-12 04:57:29 +0000523 num_sent = dispatcher.send(self, self.out_buffer[:512])
Fred Drake526a1822000-09-11 04:00:46 +0000524 self.out_buffer = self.out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000525
Guido van Rossumd560ace2002-09-12 04:57:29 +0000526 def handle_write(self):
Fred Drake526a1822000-09-11 04:00:46 +0000527 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000528
Guido van Rossumd560ace2002-09-12 04:57:29 +0000529 def writable(self):
Fred Drake526a1822000-09-11 04:00:46 +0000530 return (not self.connected) or len(self.out_buffer)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000531
Guido van Rossumd560ace2002-09-12 04:57:29 +0000532 def send(self, data):
Fred Drake526a1822000-09-11 04:00:46 +0000533 if self.debug:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000534 self.log_info('sending %s' % repr(data))
Fred Drake526a1822000-09-11 04:00:46 +0000535 self.out_buffer = self.out_buffer + data
536 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000537
538# ---------------------------------------------------------------------------
539# used for debugging.
540# ---------------------------------------------------------------------------
541
Guido van Rossumd560ace2002-09-12 04:57:29 +0000542def compact_traceback():
Guido van Rossum12e96682002-09-13 14:09:26 +0000543 t, v, tb = sys.exc_info()
Fred Drake526a1822000-09-11 04:00:46 +0000544 tbinfo = []
Josiah Carlsond74900e2008-07-07 04:15:08 +0000545 if not tb: # Must have a traceback
546 raise AssertionError("traceback does not exist")
Guido van Rossum12e96682002-09-13 14:09:26 +0000547 while tb:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000548 tbinfo.append((
Fred Drake526a1822000-09-11 04:00:46 +0000549 tb.tb_frame.f_code.co_filename,
Tim Peters146965a2001-01-14 18:09:23 +0000550 tb.tb_frame.f_code.co_name,
Fred Drake526a1822000-09-11 04:00:46 +0000551 str(tb.tb_lineno)
552 ))
553 tb = tb.tb_next
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000554
Fred Drake526a1822000-09-11 04:00:46 +0000555 # just to be safe
556 del tb
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000557
Fred Drake526a1822000-09-11 04:00:46 +0000558 file, function, line = tbinfo[-1]
Guido van Rossum12e96682002-09-13 14:09:26 +0000559 info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo])
Fred Drake526a1822000-09-11 04:00:46 +0000560 return (file, function, line), t, v, info
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000561
Josiah Carlsond74900e2008-07-07 04:15:08 +0000562def close_all(map=None, ignore_all=False):
Fred Drake526a1822000-09-11 04:00:46 +0000563 if map is None:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000564 map = socket_map
Josiah Carlsond74900e2008-07-07 04:15:08 +0000565 for x in list(map.values()):
566 try:
567 x.close()
568 except OSError as x:
Georg Brandlf1123692008-07-20 07:31:30 +0000569 if x.args[0] == EBADF:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000570 pass
571 elif not ignore_all:
572 raise
R. David Murray78532ba2009-04-12 15:35:44 +0000573 except _reraised_exceptions:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000574 raise
575 except:
576 if not ignore_all:
577 raise
Fred Drake526a1822000-09-11 04:00:46 +0000578 map.clear()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000579
580# Asynchronous File I/O:
581#
582# After a little research (reading man pages on various unixen, and
583# digging through the linux kernel), I've determined that select()
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000584# isn't meant for doing asynchronous file i/o.
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000585# Heartening, though - reading linux/mm/filemap.c shows that linux
586# supports asynchronous read-ahead. So _MOST_ of the time, the data
587# will be sitting in memory for us already when we go to read it.
588#
589# What other OS's (besides NT) support async file i/o? [VMS?]
590#
591# Regardless, this is useful for pipes, and stdin/stdout...
592
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000593if os.name == 'posix':
Fred Drake526a1822000-09-11 04:00:46 +0000594 import fcntl
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000595
Fred Drake526a1822000-09-11 04:00:46 +0000596 class file_wrapper:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000597 # Here we override just enough to make a file
Fred Drake526a1822000-09-11 04:00:46 +0000598 # look like a socket for the purposes of asyncore.
Josiah Carlsond74900e2008-07-07 04:15:08 +0000599 # The passed fd is automatically os.dup()'d
Guido van Rossumd560ace2002-09-12 04:57:29 +0000600
601 def __init__(self, fd):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000602 self.fd = os.dup(fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000603
Guido van Rossumd560ace2002-09-12 04:57:29 +0000604 def recv(self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000605 return os.read(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000606
Guido van Rossumd560ace2002-09-12 04:57:29 +0000607 def send(self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000608 return os.write(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000609
Georg Brandlcbb0ae42010-07-28 08:19:35 +0000610 def getsockopt(self, level, optname, buflen=None):
611 if (level == socket.SOL_SOCKET and
612 optname == socket.SO_ERROR and
613 not buflen):
614 return 0
615 raise NotImplementedError("Only asyncore specific behaviour "
616 "implemented.")
617
Fred Drake526a1822000-09-11 04:00:46 +0000618 read = recv
619 write = send
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000620
Guido van Rossumd560ace2002-09-12 04:57:29 +0000621 def close(self):
Andrew M. Kuchlingdfa74b92004-07-10 15:51:19 +0000622 os.close(self.fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000623
Guido van Rossumd560ace2002-09-12 04:57:29 +0000624 def fileno(self):
Fred Drake526a1822000-09-11 04:00:46 +0000625 return self.fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000626
Guido van Rossumd560ace2002-09-12 04:57:29 +0000627 class file_dispatcher(dispatcher):
628
Andrew M. Kuchling67867ea2004-03-21 20:03:18 +0000629 def __init__(self, fd, map=None):
630 dispatcher.__init__(self, None, map)
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000631 self.connected = True
Josiah Carlsond74900e2008-07-07 04:15:08 +0000632 try:
633 fd = fd.fileno()
634 except AttributeError:
635 pass
Andrew M. Kuchlingdfa74b92004-07-10 15:51:19 +0000636 self.set_file(fd)
Fred Drake526a1822000-09-11 04:00:46 +0000637 # set it to non-blocking mode
Guido van Rossumd560ace2002-09-12 04:57:29 +0000638 flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
Fred Drakea94414a2001-05-10 15:33:31 +0000639 flags = flags | os.O_NONBLOCK
Guido van Rossumd560ace2002-09-12 04:57:29 +0000640 fcntl.fcntl(fd, fcntl.F_SETFL, flags)
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()