blob: f63a83eebadd4c32e824b9cc4ae6a02314ea82b3 [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
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000049import exceptions
Guido van Rossum0039d7b1999-01-12 20:19:27 +000050import select
51import socket
Guido van Rossum0039d7b1999-01-12 20:19:27 +000052import sys
Thomas Hellerd8ce87a2002-09-24 17:30:31 +000053import time
Guido van Rossum0039d7b1999-01-12 20:19:27 +000054
55import os
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +000056from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \
Andrew M. Kuchling174bdbc2004-03-21 19:58:28 +000057 ENOTCONN, ESHUTDOWN, EINTR, EISCONN, 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
Jeremy Hyltond7500362002-09-08 00:14:54 +000064class ExitNow(exceptions.Exception):
Fred Drake526a1822000-09-11 04:00:46 +000065 pass
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000066
Jeremy Hyltond7500362002-09-08 00:14:54 +000067def read(obj):
68 try:
69 obj.handle_read_event()
70 except ExitNow:
71 raise
72 except:
73 obj.handle_error()
74
75def write(obj):
76 try:
77 obj.handle_write_event()
78 except ExitNow:
79 raise
80 except:
81 obj.handle_error()
82
Andrew M. Kuchling0fff6c82004-07-10 17:36:11 +000083def _exception (obj):
84 try:
85 obj.handle_expt_event()
86 except ExitNow:
87 raise
88 except:
89 obj.handle_error()
90
Jeremy Hyltond7500362002-09-08 00:14:54 +000091def readwrite(obj, flags):
92 try:
Andrew M. Kuchling93037772004-03-21 19:26:00 +000093 if flags & (select.POLLIN | select.POLLPRI):
Jeremy Hyltond7500362002-09-08 00:14:54 +000094 obj.handle_read_event()
95 if flags & select.POLLOUT:
96 obj.handle_write_event()
Andrew M. Kuchling93037772004-03-21 19:26:00 +000097 if flags & (select.POLLERR | select.POLLHUP | select.POLLNVAL):
98 obj.handle_expt_event()
Jeremy Hyltond7500362002-09-08 00:14:54 +000099 except ExitNow:
100 raise
101 except:
102 obj.handle_error()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000103
Guido van Rossumd560ace2002-09-12 04:57:29 +0000104def poll(timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000105 if map is None:
106 map = socket_map
107 if map:
108 r = []; w = []; e = []
Guido van Rossumd560ace2002-09-12 04:57:29 +0000109 for fd, obj in map.items():
Andrew M. Kuchling0fff6c82004-07-10 17:36:11 +0000110 e.append(fd)
Fred Drake526a1822000-09-11 04:00:46 +0000111 if obj.readable():
Jeremy Hyltond7500362002-09-08 00:14:54 +0000112 r.append(fd)
Fred Drake526a1822000-09-11 04:00:46 +0000113 if obj.writable():
Jeremy Hyltond7500362002-09-08 00:14:54 +0000114 w.append(fd)
Thomas Hellerd8ce87a2002-09-24 17:30:31 +0000115 if [] == r == w == e:
116 time.sleep(timeout)
117 else:
118 try:
119 r, w, e = select.select(r, w, e, timeout)
120 except select.error, err:
Thomas Heller6d817ad2002-09-26 13:19:48 +0000121 if err[0] != EINTR:
Thomas Hellerd8ce87a2002-09-24 17:30:31 +0000122 raise
Guido van Rossume94d8fa2002-11-05 18:41:20 +0000123 else:
124 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000125
Fred Drake526a1822000-09-11 04:00:46 +0000126 for fd in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000127 obj = map.get(fd)
128 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000129 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000130 read(obj)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000131
Fred Drake526a1822000-09-11 04:00:46 +0000132 for fd in w:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000133 obj = map.get(fd)
134 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000135 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000136 write(obj)
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000137
Andrew M. Kuchling0fff6c82004-07-10 17:36:11 +0000138 for fd in e:
139 obj = map.get(fd)
140 if obj is None:
141 continue
142 _exception(obj)
143
Guido van Rossumd560ace2002-09-12 04:57:29 +0000144def poll2(timeout=0.0, map=None):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000145 # Use the poll() support added to the select module in Python 2.0
146 if map is None:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000147 map = socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000148 if timeout is not None:
149 # timeout is in milliseconds
150 timeout = int(timeout*1000)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000151 pollster = select.poll()
152 if map:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000153 for fd, obj in map.items():
Andrew M. Kuchling0ebbbe32004-03-21 19:50:09 +0000154 flags = select.POLLERR | select.POLLHUP | select.POLLNVAL
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000155 if obj.readable():
Andrew M. Kuchling6fe93cd2004-07-07 12:23:53 +0000156 flags |= select.POLLIN | select.POLLPRI
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000157 if obj.writable():
Andrew M. Kuchling6fe93cd2004-07-07 12:23:53 +0000158 flags |= select.POLLOUT
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000159 if flags:
160 pollster.register(fd, flags)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000161 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000162 r = pollster.poll(timeout)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000163 except select.error, err:
164 if err[0] != EINTR:
165 raise
166 r = []
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000167 for fd, flags in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000168 obj = map.get(fd)
169 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000170 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000171 readwrite(obj, flags)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000172
Andrew M. Kuchling6c2871e2003-10-22 14:38:27 +0000173poll3 = poll2 # Alias for backward compatibility
174
Michael W. Hudsond5cf1432004-06-30 09:02:33 +0000175def loop(timeout=30.0, use_poll=False, map=None, count=None):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000176 if map is None:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000177 map = socket_map
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000178
Andrew M. Kuchling6c2871e2003-10-22 14:38:27 +0000179 if use_poll and hasattr(select, 'poll'):
180 poll_fun = poll2
Fred Drake526a1822000-09-11 04:00:46 +0000181 else:
182 poll_fun = poll
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000183
Michael W. Hudsond5cf1432004-06-30 09:02:33 +0000184 if count is None:
185 while map:
186 poll_fun(timeout, map)
187
188 else:
189 while map and count > 0:
190 poll_fun(timeout, map)
191 count = count - 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000192
193class dispatcher:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000194
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000195 debug = False
196 connected = False
197 accepting = False
198 closing = False
Fred Drake526a1822000-09-11 04:00:46 +0000199 addr = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000200
Guido van Rossumd560ace2002-09-12 04:57:29 +0000201 def __init__(self, sock=None, map=None):
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000202 if map is None:
203 self._map = socket_map
204 else:
205 self._map = map
206
Fred Drake526a1822000-09-11 04:00:46 +0000207 if sock:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000208 self.set_socket(sock, map)
Fred Drake526a1822000-09-11 04:00:46 +0000209 # I think it should inherit this anyway
Guido van Rossumd560ace2002-09-12 04:57:29 +0000210 self.socket.setblocking(0)
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000211 self.connected = True
Jeremy Hylton2a05bc72001-12-14 16:15:11 +0000212 # XXX Does the constructor require that the socket passed
213 # be connected?
214 try:
215 self.addr = sock.getpeername()
216 except socket.error:
217 # The addr isn't crucial
218 pass
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000219 else:
220 self.socket = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000221
Guido van Rossumd560ace2002-09-12 04:57:29 +0000222 def __repr__(self):
Martin v. Löwis29103c72001-10-18 17:33:19 +0000223 status = [self.__class__.__module__+"."+self.__class__.__name__]
224 if self.accepting and self.addr:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000225 status.append('listening')
Martin v. Löwis29103c72001-10-18 17:33:19 +0000226 elif self.connected:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000227 status.append('connected')
Martin v. Löwis29103c72001-10-18 17:33:19 +0000228 if self.addr is not None:
229 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000230 status.append('%s:%d' % self.addr)
Martin v. Löwis29103c72001-10-18 17:33:19 +0000231 except TypeError:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000232 status.append(repr(self.addr))
233 return '<%s at %#x>' % (' '.join(status), id(self))
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000234
Guido van Rossumd560ace2002-09-12 04:57:29 +0000235 def add_channel(self, map=None):
236 #self.log_info('adding channel %s' % self)
Fred Drake526a1822000-09-11 04:00:46 +0000237 if map is None:
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000238 map = self._map
Guido van Rossum12e96682002-09-13 14:09:26 +0000239 map[self._fileno] = self
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000240
Guido van Rossumd560ace2002-09-12 04:57:29 +0000241 def del_channel(self, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000242 fd = self._fileno
243 if map is None:
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000244 map = self._map
Guido van Rossumd560ace2002-09-12 04:57:29 +0000245 if map.has_key(fd):
246 #self.log_info('closing channel %d:%s' % (fd, self))
Guido van Rossum12e96682002-09-13 14:09:26 +0000247 del map[fd]
Raymond Hettinger3dc34842004-02-08 11:32:50 +0000248 self._fileno = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000249
Guido van Rossumd560ace2002-09-12 04:57:29 +0000250 def create_socket(self, family, type):
Fred Drake526a1822000-09-11 04:00:46 +0000251 self.family_and_type = family, type
Guido van Rossumd560ace2002-09-12 04:57:29 +0000252 self.socket = socket.socket(family, type)
Fred Drake526a1822000-09-11 04:00:46 +0000253 self.socket.setblocking(0)
254 self._fileno = self.socket.fileno()
255 self.add_channel()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000256
Guido van Rossumd560ace2002-09-12 04:57:29 +0000257 def set_socket(self, sock, map=None):
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000258 self.socket = sock
259## self.__dict__['socket'] = sock
Fred Drake526a1822000-09-11 04:00:46 +0000260 self._fileno = sock.fileno()
Guido van Rossumd560ace2002-09-12 04:57:29 +0000261 self.add_channel(map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000262
Guido van Rossumd560ace2002-09-12 04:57:29 +0000263 def set_reuse_addr(self):
Fred Drake526a1822000-09-11 04:00:46 +0000264 # try to re-use a server port if possible
265 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000266 self.socket.setsockopt(
Fred Drake526a1822000-09-11 04:00:46 +0000267 socket.SOL_SOCKET, socket.SO_REUSEADDR,
Guido van Rossumd560ace2002-09-12 04:57:29 +0000268 self.socket.getsockopt(socket.SOL_SOCKET,
269 socket.SO_REUSEADDR) | 1
Fred Drake526a1822000-09-11 04:00:46 +0000270 )
Fred Drake9f9b5932001-05-11 18:28:54 +0000271 except socket.error:
Fred Drake526a1822000-09-11 04:00:46 +0000272 pass
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000273
Fred Drake526a1822000-09-11 04:00:46 +0000274 # ==================================================
275 # predicates for select()
276 # these are used as filters for the lists of sockets
277 # to pass to select().
278 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000279
Guido van Rossumd560ace2002-09-12 04:57:29 +0000280 def readable(self):
Tim Petersbc0e9102002-04-04 22:55:58 +0000281 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000282
Andrew M. Kuchling419af882004-03-21 19:52:01 +0000283 def writable(self):
284 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000285
Fred Drake526a1822000-09-11 04:00:46 +0000286 # ==================================================
287 # socket object methods.
288 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000289
Guido van Rossumd560ace2002-09-12 04:57:29 +0000290 def listen(self, num):
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000291 self.accepting = True
Fred Drake526a1822000-09-11 04:00:46 +0000292 if os.name == 'nt' and num > 5:
293 num = 1
Guido van Rossumd560ace2002-09-12 04:57:29 +0000294 return self.socket.listen(num)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000295
Guido van Rossumd560ace2002-09-12 04:57:29 +0000296 def bind(self, addr):
Fred Drake526a1822000-09-11 04:00:46 +0000297 self.addr = addr
Guido van Rossumd560ace2002-09-12 04:57:29 +0000298 return self.socket.bind(addr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000299
Guido van Rossumd560ace2002-09-12 04:57:29 +0000300 def connect(self, address):
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000301 self.connected = False
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000302 err = self.socket.connect_ex(address)
Guido van Rossum9a40c1c2002-12-26 18:22:54 +0000303 # XXX Should interpret Winsock return values
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000304 if err in (EINPROGRESS, EALREADY, EWOULDBLOCK):
305 return
306 if err in (0, EISCONN):
307 self.addr = address
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000308 self.connected = True
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000309 self.handle_connect()
Jeremy Hyltonf24339f2001-10-30 14:16:17 +0000310 else:
Andrew M. Kuchling174bdbc2004-03-21 19:58:28 +0000311 raise socket.error, (err, errorcode[err])
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000312
Guido van Rossumd560ace2002-09-12 04:57:29 +0000313 def accept(self):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000314 # XXX can return either an address pair or None
Fred Drake526a1822000-09-11 04:00:46 +0000315 try:
316 conn, addr = self.socket.accept()
317 return conn, addr
318 except socket.error, why:
319 if why[0] == EWOULDBLOCK:
320 pass
321 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000322 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000323
Guido van Rossumd560ace2002-09-12 04:57:29 +0000324 def send(self, data):
Fred Drake526a1822000-09-11 04:00:46 +0000325 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000326 result = self.socket.send(data)
Fred Drake526a1822000-09-11 04:00:46 +0000327 return result
328 except socket.error, why:
329 if why[0] == EWOULDBLOCK:
330 return 0
331 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000332 raise
Fred Drake526a1822000-09-11 04:00:46 +0000333 return 0
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000334
Guido van Rossumd560ace2002-09-12 04:57:29 +0000335 def recv(self, buffer_size):
Fred Drake526a1822000-09-11 04:00:46 +0000336 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000337 data = self.socket.recv(buffer_size)
Fred Drake526a1822000-09-11 04:00:46 +0000338 if not data:
339 # a closed connection is indicated by signaling
340 # a read condition, and having recv() return 0.
341 self.handle_close()
342 return ''
343 else:
344 return data
345 except socket.error, why:
346 # winsock sometimes throws ENOTCONN
347 if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
348 self.handle_close()
349 return ''
350 else:
Tim Peters4e0e1b62004-07-07 20:54:48 +0000351 raise
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000352
Guido van Rossumd560ace2002-09-12 04:57:29 +0000353 def close(self):
Fred Drake526a1822000-09-11 04:00:46 +0000354 self.del_channel()
355 self.socket.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000356
Fred Drake526a1822000-09-11 04:00:46 +0000357 # cheap inheritance, used to pass all other attribute
358 # references to the underlying socket object.
Guido van Rossumd560ace2002-09-12 04:57:29 +0000359 def __getattr__(self, attr):
360 return getattr(self.socket, attr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000361
Andrew M. Kuchlingc07fb2f2003-02-14 01:13:01 +0000362 # log and log_info may be overridden to provide more sophisticated
Fred Drake526a1822000-09-11 04:00:46 +0000363 # logging and warning methods. In general, log is for 'hit' logging
Tim Peters146965a2001-01-14 18:09:23 +0000364 # and 'log_info' is for informational, warning and error logging.
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000365
Guido van Rossumd560ace2002-09-12 04:57:29 +0000366 def log(self, message):
367 sys.stderr.write('log: %s\n' % str(message))
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000368
Guido van Rossumd560ace2002-09-12 04:57:29 +0000369 def log_info(self, message, type='info'):
Fred Drake526a1822000-09-11 04:00:46 +0000370 if __debug__ or type != 'info':
371 print '%s: %s' % (type, message)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000372
Guido van Rossumd560ace2002-09-12 04:57:29 +0000373 def handle_read_event(self):
Fred Drake526a1822000-09-11 04:00:46 +0000374 if self.accepting:
375 # for an accepting socket, getting a read implies
376 # that we are connected
377 if not self.connected:
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000378 self.connected = True
Fred Drake526a1822000-09-11 04:00:46 +0000379 self.handle_accept()
380 elif not self.connected:
381 self.handle_connect()
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000382 self.connected = True
Fred Drake526a1822000-09-11 04:00:46 +0000383 self.handle_read()
384 else:
385 self.handle_read()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000386
Guido van Rossumd560ace2002-09-12 04:57:29 +0000387 def handle_write_event(self):
Fred Drake526a1822000-09-11 04:00:46 +0000388 # getting a write implies that we are connected
389 if not self.connected:
390 self.handle_connect()
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000391 self.connected = True
Fred Drake526a1822000-09-11 04:00:46 +0000392 self.handle_write()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000393
Guido van Rossumd560ace2002-09-12 04:57:29 +0000394 def handle_expt_event(self):
Fred Drake526a1822000-09-11 04:00:46 +0000395 self.handle_expt()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000396
Guido van Rossumd560ace2002-09-12 04:57:29 +0000397 def handle_error(self):
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000398 nil, t, v, tbinfo = compact_traceback()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000399
Fred Drake526a1822000-09-11 04:00:46 +0000400 # sometimes a user repr method will crash.
401 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000402 self_repr = repr(self)
Fred Drake526a1822000-09-11 04:00:46 +0000403 except:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000404 self_repr = '<__repr__(self) failed for object at %0x>' % id(self)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000405
Guido van Rossumd560ace2002-09-12 04:57:29 +0000406 self.log_info(
Fred Drake526a1822000-09-11 04:00:46 +0000407 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
408 self_repr,
409 t,
410 v,
411 tbinfo
412 ),
413 'error'
414 )
415 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000416
Guido van Rossumd560ace2002-09-12 04:57:29 +0000417 def handle_expt(self):
418 self.log_info('unhandled exception', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000419
Guido van Rossumd560ace2002-09-12 04:57:29 +0000420 def handle_read(self):
421 self.log_info('unhandled read event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000422
Guido van Rossumd560ace2002-09-12 04:57:29 +0000423 def handle_write(self):
424 self.log_info('unhandled write event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000425
Guido van Rossumd560ace2002-09-12 04:57:29 +0000426 def handle_connect(self):
427 self.log_info('unhandled connect event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000428
Guido van Rossumd560ace2002-09-12 04:57:29 +0000429 def handle_accept(self):
430 self.log_info('unhandled accept event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000431
Guido van Rossumd560ace2002-09-12 04:57:29 +0000432 def handle_close(self):
433 self.log_info('unhandled close event', 'warning')
Fred Drake526a1822000-09-11 04:00:46 +0000434 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000435
436# ---------------------------------------------------------------------------
437# adds simple buffered output capability, useful for simple clients.
438# [for more sophisticated usage use asynchat.async_chat]
439# ---------------------------------------------------------------------------
440
Guido van Rossumd560ace2002-09-12 04:57:29 +0000441class dispatcher_with_send(dispatcher):
442
Andrew M. Kuchling67867ea2004-03-21 20:03:18 +0000443 def __init__(self, sock=None, map=None):
444 dispatcher.__init__(self, sock, map)
Fred Drake526a1822000-09-11 04:00:46 +0000445 self.out_buffer = ''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000446
Guido van Rossumd560ace2002-09-12 04:57:29 +0000447 def initiate_send(self):
Fred Drake526a1822000-09-11 04:00:46 +0000448 num_sent = 0
Guido van Rossumd560ace2002-09-12 04:57:29 +0000449 num_sent = dispatcher.send(self, self.out_buffer[:512])
Fred Drake526a1822000-09-11 04:00:46 +0000450 self.out_buffer = self.out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000451
Guido van Rossumd560ace2002-09-12 04:57:29 +0000452 def handle_write(self):
Fred Drake526a1822000-09-11 04:00:46 +0000453 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000454
Guido van Rossumd560ace2002-09-12 04:57:29 +0000455 def writable(self):
Fred Drake526a1822000-09-11 04:00:46 +0000456 return (not self.connected) or len(self.out_buffer)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000457
Guido van Rossumd560ace2002-09-12 04:57:29 +0000458 def send(self, data):
Fred Drake526a1822000-09-11 04:00:46 +0000459 if self.debug:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000460 self.log_info('sending %s' % repr(data))
Fred Drake526a1822000-09-11 04:00:46 +0000461 self.out_buffer = self.out_buffer + data
462 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000463
464# ---------------------------------------------------------------------------
465# used for debugging.
466# ---------------------------------------------------------------------------
467
Guido van Rossumd560ace2002-09-12 04:57:29 +0000468def compact_traceback():
Guido van Rossum12e96682002-09-13 14:09:26 +0000469 t, v, tb = sys.exc_info()
Fred Drake526a1822000-09-11 04:00:46 +0000470 tbinfo = []
Guido van Rossum12e96682002-09-13 14:09:26 +0000471 assert tb # Must have a traceback
472 while tb:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000473 tbinfo.append((
Fred Drake526a1822000-09-11 04:00:46 +0000474 tb.tb_frame.f_code.co_filename,
Tim Peters146965a2001-01-14 18:09:23 +0000475 tb.tb_frame.f_code.co_name,
Fred Drake526a1822000-09-11 04:00:46 +0000476 str(tb.tb_lineno)
477 ))
478 tb = tb.tb_next
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000479
Fred Drake526a1822000-09-11 04:00:46 +0000480 # just to be safe
481 del tb
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000482
Fred Drake526a1822000-09-11 04:00:46 +0000483 file, function, line = tbinfo[-1]
Guido van Rossum12e96682002-09-13 14:09:26 +0000484 info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo])
Fred Drake526a1822000-09-11 04:00:46 +0000485 return (file, function, line), t, v, info
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000486
Guido van Rossumd560ace2002-09-12 04:57:29 +0000487def close_all(map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000488 if map is None:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000489 map = socket_map
Fred Drake526a1822000-09-11 04:00:46 +0000490 for x in map.values():
491 x.socket.close()
492 map.clear()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000493
494# Asynchronous File I/O:
495#
496# After a little research (reading man pages on various unixen, and
497# digging through the linux kernel), I've determined that select()
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000498# isn't meant for doing asynchronous file i/o.
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000499# Heartening, though - reading linux/mm/filemap.c shows that linux
500# supports asynchronous read-ahead. So _MOST_ of the time, the data
501# will be sitting in memory for us already when we go to read it.
502#
503# What other OS's (besides NT) support async file i/o? [VMS?]
504#
505# Regardless, this is useful for pipes, and stdin/stdout...
506
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000507if os.name == 'posix':
Fred Drake526a1822000-09-11 04:00:46 +0000508 import fcntl
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000509
Fred Drake526a1822000-09-11 04:00:46 +0000510 class file_wrapper:
511 # here we override just enough to make a file
512 # look like a socket for the purposes of asyncore.
Guido van Rossumd560ace2002-09-12 04:57:29 +0000513
514 def __init__(self, fd):
Fred Drake526a1822000-09-11 04:00:46 +0000515 self.fd = fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000516
Guido van Rossumd560ace2002-09-12 04:57:29 +0000517 def recv(self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000518 return os.read(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000519
Guido van Rossumd560ace2002-09-12 04:57:29 +0000520 def send(self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000521 return os.write(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000522
Fred Drake526a1822000-09-11 04:00:46 +0000523 read = recv
524 write = send
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000525
Guido van Rossumd560ace2002-09-12 04:57:29 +0000526 def close(self):
Andrew M. Kuchlingdfa74b92004-07-10 15:51:19 +0000527 os.close(self.fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000528
Guido van Rossumd560ace2002-09-12 04:57:29 +0000529 def fileno(self):
Fred Drake526a1822000-09-11 04:00:46 +0000530 return self.fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000531
Guido van Rossumd560ace2002-09-12 04:57:29 +0000532 class file_dispatcher(dispatcher):
533
Andrew M. Kuchling67867ea2004-03-21 20:03:18 +0000534 def __init__(self, fd, map=None):
535 dispatcher.__init__(self, None, map)
Andrew M. Kuchling68522b12004-03-21 19:46:16 +0000536 self.connected = True
Andrew M. Kuchlingdfa74b92004-07-10 15:51:19 +0000537 self.set_file(fd)
Fred Drake526a1822000-09-11 04:00:46 +0000538 # set it to non-blocking mode
Guido van Rossumd560ace2002-09-12 04:57:29 +0000539 flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
Fred Drakea94414a2001-05-10 15:33:31 +0000540 flags = flags | os.O_NONBLOCK
Guido van Rossumd560ace2002-09-12 04:57:29 +0000541 fcntl.fcntl(fd, fcntl.F_SETFL, flags)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000542
Guido van Rossumd560ace2002-09-12 04:57:29 +0000543 def set_file(self, fd):
Fred Drake526a1822000-09-11 04:00:46 +0000544 self._fileno = fd
Guido van Rossumd560ace2002-09-12 04:57:29 +0000545 self.socket = file_wrapper(fd)
Fred Drake526a1822000-09-11 04:00:46 +0000546 self.add_channel()