blob: 7bd269b744610b3ee5d49406be72f23d1d10fc45 [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, \
Jeremy Hyltone16e54f2001-10-29 16:44:37 +000057 ENOTCONN, ESHUTDOWN, EINTR, EISCONN
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
83def readwrite(obj, flags):
84 try:
85 if flags & select.POLLIN:
86 obj.handle_read_event()
87 if flags & select.POLLOUT:
88 obj.handle_write_event()
89 except ExitNow:
90 raise
91 except:
92 obj.handle_error()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000093
Guido van Rossumd560ace2002-09-12 04:57:29 +000094def poll(timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +000095 if map is None:
96 map = socket_map
97 if map:
98 r = []; w = []; e = []
Guido van Rossumd560ace2002-09-12 04:57:29 +000099 for fd, obj in map.items():
Fred Drake526a1822000-09-11 04:00:46 +0000100 if obj.readable():
Jeremy Hyltond7500362002-09-08 00:14:54 +0000101 r.append(fd)
Fred Drake526a1822000-09-11 04:00:46 +0000102 if obj.writable():
Jeremy Hyltond7500362002-09-08 00:14:54 +0000103 w.append(fd)
Thomas Hellerd8ce87a2002-09-24 17:30:31 +0000104 if [] == r == w == e:
105 time.sleep(timeout)
106 else:
107 try:
108 r, w, e = select.select(r, w, e, timeout)
109 except select.error, err:
Thomas Heller6d817ad2002-09-26 13:19:48 +0000110 if err[0] != EINTR:
Thomas Hellerd8ce87a2002-09-24 17:30:31 +0000111 raise
Guido van Rossume94d8fa2002-11-05 18:41:20 +0000112 else:
113 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000114
Fred Drake526a1822000-09-11 04:00:46 +0000115 for fd in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000116 obj = map.get(fd)
117 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000118 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000119 read(obj)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000120
Fred Drake526a1822000-09-11 04:00:46 +0000121 for fd in w:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000122 obj = map.get(fd)
123 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000124 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000125 write(obj)
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000126
Guido van Rossumd560ace2002-09-12 04:57:29 +0000127def poll2(timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000128 import poll
129 if map is None:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000130 map = socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000131 if timeout is not None:
132 # timeout is in milliseconds
133 timeout = int(timeout*1000)
Fred Drake526a1822000-09-11 04:00:46 +0000134 if map:
135 l = []
Guido van Rossumd560ace2002-09-12 04:57:29 +0000136 for fd, obj in map.items():
Fred Drake526a1822000-09-11 04:00:46 +0000137 flags = 0
138 if obj.readable():
139 flags = poll.POLLIN
140 if obj.writable():
141 flags = flags | poll.POLLOUT
142 if flags:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000143 l.append((fd, flags))
144 r = poll.poll(l, timeout)
Fred Drake526a1822000-09-11 04:00:46 +0000145 for fd, flags in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000146 obj = map.get(fd)
147 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000148 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000149 readwrite(obj, flags)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000150
Guido van Rossumd560ace2002-09-12 04:57:29 +0000151def poll3(timeout=0.0, map=None):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000152 # Use the poll() support added to the select module in Python 2.0
153 if map is None:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000154 map = socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000155 if timeout is not None:
156 # timeout is in milliseconds
157 timeout = int(timeout*1000)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000158 pollster = select.poll()
159 if map:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000160 for fd, obj in map.items():
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000161 flags = 0
162 if obj.readable():
163 flags = select.POLLIN
164 if obj.writable():
165 flags = flags | select.POLLOUT
166 if flags:
167 pollster.register(fd, flags)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000168 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000169 r = pollster.poll(timeout)
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000170 except select.error, err:
171 if err[0] != EINTR:
172 raise
173 r = []
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000174 for fd, flags in r:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000175 obj = map.get(fd)
176 if obj is None:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000177 continue
Jeremy Hyltond7500362002-09-08 00:14:54 +0000178 readwrite(obj, flags)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000179
Guido van Rossumd560ace2002-09-12 04:57:29 +0000180def loop(timeout=30.0, use_poll=0, map=None):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000181 if map is None:
Jeremy Hyltond7500362002-09-08 00:14:54 +0000182 map = socket_map
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000183
Fred Drake526a1822000-09-11 04:00:46 +0000184 if use_poll:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000185 if hasattr(select, 'poll'):
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000186 poll_fun = poll3
187 else:
188 poll_fun = poll2
Fred Drake526a1822000-09-11 04:00:46 +0000189 else:
190 poll_fun = poll
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000191
Fred Drake526a1822000-09-11 04:00:46 +0000192 while map:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000193 poll_fun(timeout, map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000194
195class dispatcher:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000196
Fred Drake526a1822000-09-11 04:00:46 +0000197 debug = 0
198 connected = 0
199 accepting = 0
200 closing = 0
201 addr = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000202
Guido van Rossumd560ace2002-09-12 04:57:29 +0000203 def __init__(self, sock=None, map=None):
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000204 if map is None:
205 self._map = socket_map
206 else:
207 self._map = map
208
Fred Drake526a1822000-09-11 04:00:46 +0000209 if sock:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000210 self.set_socket(sock, map)
Fred Drake526a1822000-09-11 04:00:46 +0000211 # I think it should inherit this anyway
Guido van Rossumd560ace2002-09-12 04:57:29 +0000212 self.socket.setblocking(0)
Fred Drake526a1822000-09-11 04:00:46 +0000213 self.connected = 1
Jeremy Hylton2a05bc72001-12-14 16:15:11 +0000214 # XXX Does the constructor require that the socket passed
215 # be connected?
216 try:
217 self.addr = sock.getpeername()
218 except socket.error:
219 # The addr isn't crucial
220 pass
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000221 else:
222 self.socket = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000223
Guido van Rossumd560ace2002-09-12 04:57:29 +0000224 def __repr__(self):
Martin v. Löwis29103c72001-10-18 17:33:19 +0000225 status = [self.__class__.__module__+"."+self.__class__.__name__]
226 if self.accepting and self.addr:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000227 status.append('listening')
Martin v. Löwis29103c72001-10-18 17:33:19 +0000228 elif self.connected:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000229 status.append('connected')
Martin v. Löwis29103c72001-10-18 17:33:19 +0000230 if self.addr is not None:
231 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000232 status.append('%s:%d' % self.addr)
Martin v. Löwis29103c72001-10-18 17:33:19 +0000233 except TypeError:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000234 status.append(repr(self.addr))
235 return '<%s at %#x>' % (' '.join(status), id(self))
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000236
Guido van Rossumd560ace2002-09-12 04:57:29 +0000237 def add_channel(self, map=None):
238 #self.log_info('adding channel %s' % self)
Fred Drake526a1822000-09-11 04:00:46 +0000239 if map is None:
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000240 map = self._map
Guido van Rossum12e96682002-09-13 14:09:26 +0000241 map[self._fileno] = self
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000242
Guido van Rossumd560ace2002-09-12 04:57:29 +0000243 def del_channel(self, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000244 fd = self._fileno
245 if map is None:
Andrew M. Kuchlingf9ca4092003-10-22 13:48:27 +0000246 map = self._map
Guido van Rossumd560ace2002-09-12 04:57:29 +0000247 if map.has_key(fd):
248 #self.log_info('closing channel %d:%s' % (fd, self))
Guido van Rossum12e96682002-09-13 14:09:26 +0000249 del map[fd]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000250
Guido van Rossumd560ace2002-09-12 04:57:29 +0000251 def create_socket(self, family, type):
Fred Drake526a1822000-09-11 04:00:46 +0000252 self.family_and_type = family, type
Guido van Rossumd560ace2002-09-12 04:57:29 +0000253 self.socket = socket.socket(family, type)
Fred Drake526a1822000-09-11 04:00:46 +0000254 self.socket.setblocking(0)
255 self._fileno = self.socket.fileno()
256 self.add_channel()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000257
Guido van Rossumd560ace2002-09-12 04:57:29 +0000258 def set_socket(self, sock, map=None):
Jeremy Hyltonfbd57972001-10-29 16:32:19 +0000259 self.socket = sock
260## self.__dict__['socket'] = sock
Fred Drake526a1822000-09-11 04:00:46 +0000261 self._fileno = sock.fileno()
Guido van Rossumd560ace2002-09-12 04:57:29 +0000262 self.add_channel(map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000263
Guido van Rossumd560ace2002-09-12 04:57:29 +0000264 def set_reuse_addr(self):
Fred Drake526a1822000-09-11 04:00:46 +0000265 # try to re-use a server port if possible
266 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000267 self.socket.setsockopt(
Fred Drake526a1822000-09-11 04:00:46 +0000268 socket.SOL_SOCKET, socket.SO_REUSEADDR,
Guido van Rossumd560ace2002-09-12 04:57:29 +0000269 self.socket.getsockopt(socket.SOL_SOCKET,
270 socket.SO_REUSEADDR) | 1
Fred Drake526a1822000-09-11 04:00:46 +0000271 )
Fred Drake9f9b5932001-05-11 18:28:54 +0000272 except socket.error:
Fred Drake526a1822000-09-11 04:00:46 +0000273 pass
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000274
Fred Drake526a1822000-09-11 04:00:46 +0000275 # ==================================================
276 # predicates for select()
277 # these are used as filters for the lists of sockets
278 # to pass to select().
279 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000280
Guido van Rossumd560ace2002-09-12 04:57:29 +0000281 def readable(self):
Tim Petersbc0e9102002-04-04 22:55:58 +0000282 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000283
Fred Drake526a1822000-09-11 04:00:46 +0000284 if os.name == 'mac':
285 # The macintosh will select a listening socket for
286 # write if you let it. What might this mean?
Guido van Rossumd560ace2002-09-12 04:57:29 +0000287 def writable(self):
Fred Drake526a1822000-09-11 04:00:46 +0000288 return not self.accepting
289 else:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000290 def writable(self):
Tim Petersbc0e9102002-04-04 22:55:58 +0000291 return True
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000292
Fred Drake526a1822000-09-11 04:00:46 +0000293 # ==================================================
294 # socket object methods.
295 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000296
Guido van Rossumd560ace2002-09-12 04:57:29 +0000297 def listen(self, num):
Fred Drake526a1822000-09-11 04:00:46 +0000298 self.accepting = 1
299 if os.name == 'nt' and num > 5:
300 num = 1
Guido van Rossumd560ace2002-09-12 04:57:29 +0000301 return self.socket.listen(num)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000302
Guido van Rossumd560ace2002-09-12 04:57:29 +0000303 def bind(self, addr):
Fred Drake526a1822000-09-11 04:00:46 +0000304 self.addr = addr
Guido van Rossumd560ace2002-09-12 04:57:29 +0000305 return self.socket.bind(addr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000306
Guido van Rossumd560ace2002-09-12 04:57:29 +0000307 def connect(self, address):
Fred Drake526a1822000-09-11 04:00:46 +0000308 self.connected = 0
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000309 err = self.socket.connect_ex(address)
Guido van Rossum9a40c1c2002-12-26 18:22:54 +0000310 # XXX Should interpret Winsock return values
Jeremy Hyltone16e54f2001-10-29 16:44:37 +0000311 if err in (EINPROGRESS, EALREADY, EWOULDBLOCK):
312 return
313 if err in (0, EISCONN):
314 self.addr = address
315 self.connected = 1
316 self.handle_connect()
Jeremy Hyltonf24339f2001-10-30 14:16:17 +0000317 else:
318 raise socket.error, err
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000319
Guido van Rossumd560ace2002-09-12 04:57:29 +0000320 def accept(self):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000321 # XXX can return either an address pair or None
Fred Drake526a1822000-09-11 04:00:46 +0000322 try:
323 conn, addr = self.socket.accept()
324 return conn, addr
325 except socket.error, why:
326 if why[0] == EWOULDBLOCK:
327 pass
328 else:
329 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000330
Guido van Rossumd560ace2002-09-12 04:57:29 +0000331 def send(self, data):
Fred Drake526a1822000-09-11 04:00:46 +0000332 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000333 result = self.socket.send(data)
Fred Drake526a1822000-09-11 04:00:46 +0000334 return result
335 except socket.error, why:
336 if why[0] == EWOULDBLOCK:
337 return 0
338 else:
339 raise socket.error, why
340 return 0
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000341
Guido van Rossumd560ace2002-09-12 04:57:29 +0000342 def recv(self, buffer_size):
Fred Drake526a1822000-09-11 04:00:46 +0000343 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000344 data = self.socket.recv(buffer_size)
Fred Drake526a1822000-09-11 04:00:46 +0000345 if not data:
346 # a closed connection is indicated by signaling
347 # a read condition, and having recv() return 0.
348 self.handle_close()
349 return ''
350 else:
351 return data
352 except socket.error, why:
353 # winsock sometimes throws ENOTCONN
354 if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
355 self.handle_close()
356 return ''
357 else:
358 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000359
Guido van Rossumd560ace2002-09-12 04:57:29 +0000360 def close(self):
Fred Drake526a1822000-09-11 04:00:46 +0000361 self.del_channel()
362 self.socket.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000363
Fred Drake526a1822000-09-11 04:00:46 +0000364 # cheap inheritance, used to pass all other attribute
365 # references to the underlying socket object.
Guido van Rossumd560ace2002-09-12 04:57:29 +0000366 def __getattr__(self, attr):
367 return getattr(self.socket, attr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000368
Andrew M. Kuchlingc07fb2f2003-02-14 01:13:01 +0000369 # log and log_info may be overridden to provide more sophisticated
Fred Drake526a1822000-09-11 04:00:46 +0000370 # logging and warning methods. In general, log is for 'hit' logging
Tim Peters146965a2001-01-14 18:09:23 +0000371 # and 'log_info' is for informational, warning and error logging.
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000372
Guido van Rossumd560ace2002-09-12 04:57:29 +0000373 def log(self, message):
374 sys.stderr.write('log: %s\n' % str(message))
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000375
Guido van Rossumd560ace2002-09-12 04:57:29 +0000376 def log_info(self, message, type='info'):
Fred Drake526a1822000-09-11 04:00:46 +0000377 if __debug__ or type != 'info':
378 print '%s: %s' % (type, message)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000379
Guido van Rossumd560ace2002-09-12 04:57:29 +0000380 def handle_read_event(self):
Fred Drake526a1822000-09-11 04:00:46 +0000381 if self.accepting:
382 # for an accepting socket, getting a read implies
383 # that we are connected
384 if not self.connected:
385 self.connected = 1
386 self.handle_accept()
387 elif not self.connected:
388 self.handle_connect()
389 self.connected = 1
390 self.handle_read()
391 else:
392 self.handle_read()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000393
Guido van Rossumd560ace2002-09-12 04:57:29 +0000394 def handle_write_event(self):
Fred Drake526a1822000-09-11 04:00:46 +0000395 # getting a write implies that we are connected
396 if not self.connected:
397 self.handle_connect()
398 self.connected = 1
399 self.handle_write()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000400
Guido van Rossumd560ace2002-09-12 04:57:29 +0000401 def handle_expt_event(self):
Fred Drake526a1822000-09-11 04:00:46 +0000402 self.handle_expt()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000403
Guido van Rossumd560ace2002-09-12 04:57:29 +0000404 def handle_error(self):
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000405 nil, t, v, tbinfo = compact_traceback()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000406
Fred Drake526a1822000-09-11 04:00:46 +0000407 # sometimes a user repr method will crash.
408 try:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000409 self_repr = repr(self)
Fred Drake526a1822000-09-11 04:00:46 +0000410 except:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000411 self_repr = '<__repr__(self) failed for object at %0x>' % id(self)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000412
Guido van Rossumd560ace2002-09-12 04:57:29 +0000413 self.log_info(
Fred Drake526a1822000-09-11 04:00:46 +0000414 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
415 self_repr,
416 t,
417 v,
418 tbinfo
419 ),
420 'error'
421 )
422 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000423
Guido van Rossumd560ace2002-09-12 04:57:29 +0000424 def handle_expt(self):
425 self.log_info('unhandled exception', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000426
Guido van Rossumd560ace2002-09-12 04:57:29 +0000427 def handle_read(self):
428 self.log_info('unhandled read event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000429
Guido van Rossumd560ace2002-09-12 04:57:29 +0000430 def handle_write(self):
431 self.log_info('unhandled write event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000432
Guido van Rossumd560ace2002-09-12 04:57:29 +0000433 def handle_connect(self):
434 self.log_info('unhandled connect event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000435
Guido van Rossumd560ace2002-09-12 04:57:29 +0000436 def handle_accept(self):
437 self.log_info('unhandled accept event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000438
Guido van Rossumd560ace2002-09-12 04:57:29 +0000439 def handle_close(self):
440 self.log_info('unhandled close event', 'warning')
Fred Drake526a1822000-09-11 04:00:46 +0000441 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000442
443# ---------------------------------------------------------------------------
444# adds simple buffered output capability, useful for simple clients.
445# [for more sophisticated usage use asynchat.async_chat]
446# ---------------------------------------------------------------------------
447
Guido van Rossumd560ace2002-09-12 04:57:29 +0000448class dispatcher_with_send(dispatcher):
449
450 def __init__(self, sock=None):
451 dispatcher.__init__(self, sock)
Fred Drake526a1822000-09-11 04:00:46 +0000452 self.out_buffer = ''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000453
Guido van Rossumd560ace2002-09-12 04:57:29 +0000454 def initiate_send(self):
Fred Drake526a1822000-09-11 04:00:46 +0000455 num_sent = 0
Guido van Rossumd560ace2002-09-12 04:57:29 +0000456 num_sent = dispatcher.send(self, self.out_buffer[:512])
Fred Drake526a1822000-09-11 04:00:46 +0000457 self.out_buffer = self.out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000458
Guido van Rossumd560ace2002-09-12 04:57:29 +0000459 def handle_write(self):
Fred Drake526a1822000-09-11 04:00:46 +0000460 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000461
Guido van Rossumd560ace2002-09-12 04:57:29 +0000462 def writable(self):
Fred Drake526a1822000-09-11 04:00:46 +0000463 return (not self.connected) or len(self.out_buffer)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000464
Guido van Rossumd560ace2002-09-12 04:57:29 +0000465 def send(self, data):
Fred Drake526a1822000-09-11 04:00:46 +0000466 if self.debug:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000467 self.log_info('sending %s' % repr(data))
Fred Drake526a1822000-09-11 04:00:46 +0000468 self.out_buffer = self.out_buffer + data
469 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000470
471# ---------------------------------------------------------------------------
472# used for debugging.
473# ---------------------------------------------------------------------------
474
Guido van Rossumd560ace2002-09-12 04:57:29 +0000475def compact_traceback():
Guido van Rossum12e96682002-09-13 14:09:26 +0000476 t, v, tb = sys.exc_info()
Fred Drake526a1822000-09-11 04:00:46 +0000477 tbinfo = []
Guido van Rossum12e96682002-09-13 14:09:26 +0000478 assert tb # Must have a traceback
479 while tb:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000480 tbinfo.append((
Fred Drake526a1822000-09-11 04:00:46 +0000481 tb.tb_frame.f_code.co_filename,
Tim Peters146965a2001-01-14 18:09:23 +0000482 tb.tb_frame.f_code.co_name,
Fred Drake526a1822000-09-11 04:00:46 +0000483 str(tb.tb_lineno)
484 ))
485 tb = tb.tb_next
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000486
Fred Drake526a1822000-09-11 04:00:46 +0000487 # just to be safe
488 del tb
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000489
Fred Drake526a1822000-09-11 04:00:46 +0000490 file, function, line = tbinfo[-1]
Guido van Rossum12e96682002-09-13 14:09:26 +0000491 info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo])
Fred Drake526a1822000-09-11 04:00:46 +0000492 return (file, function, line), t, v, info
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000493
Guido van Rossumd560ace2002-09-12 04:57:29 +0000494def close_all(map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000495 if map is None:
Guido van Rossumd560ace2002-09-12 04:57:29 +0000496 map = socket_map
Fred Drake526a1822000-09-11 04:00:46 +0000497 for x in map.values():
498 x.socket.close()
499 map.clear()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000500
501# Asynchronous File I/O:
502#
503# After a little research (reading man pages on various unixen, and
504# digging through the linux kernel), I've determined that select()
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000505# isn't meant for doing asynchronous file i/o.
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000506# Heartening, though - reading linux/mm/filemap.c shows that linux
507# supports asynchronous read-ahead. So _MOST_ of the time, the data
508# will be sitting in memory for us already when we go to read it.
509#
510# What other OS's (besides NT) support async file i/o? [VMS?]
511#
512# Regardless, this is useful for pipes, and stdin/stdout...
513
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000514if os.name == 'posix':
Fred Drake526a1822000-09-11 04:00:46 +0000515 import fcntl
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000516
Fred Drake526a1822000-09-11 04:00:46 +0000517 class file_wrapper:
518 # here we override just enough to make a file
519 # look like a socket for the purposes of asyncore.
Guido van Rossumd560ace2002-09-12 04:57:29 +0000520
521 def __init__(self, fd):
Fred Drake526a1822000-09-11 04:00:46 +0000522 self.fd = fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000523
Guido van Rossumd560ace2002-09-12 04:57:29 +0000524 def recv(self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000525 return os.read(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000526
Guido van Rossumd560ace2002-09-12 04:57:29 +0000527 def send(self, *args):
Jeremy Hyltonf32e4592002-04-04 21:02:24 +0000528 return os.write(self.fd, *args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000529
Fred Drake526a1822000-09-11 04:00:46 +0000530 read = recv
531 write = send
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000532
Guido van Rossumd560ace2002-09-12 04:57:29 +0000533 def close(self):
534 return os.close(self.fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000535
Guido van Rossumd560ace2002-09-12 04:57:29 +0000536 def fileno(self):
Fred Drake526a1822000-09-11 04:00:46 +0000537 return self.fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000538
Guido van Rossumd560ace2002-09-12 04:57:29 +0000539 class file_dispatcher(dispatcher):
540
541 def __init__(self, fd):
542 dispatcher.__init__(self)
Fred Drake526a1822000-09-11 04:00:46 +0000543 self.connected = 1
544 # set it to non-blocking mode
Guido van Rossumd560ace2002-09-12 04:57:29 +0000545 flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
Fred Drakea94414a2001-05-10 15:33:31 +0000546 flags = flags | os.O_NONBLOCK
Guido van Rossumd560ace2002-09-12 04:57:29 +0000547 fcntl.fcntl(fd, fcntl.F_SETFL, flags)
548 self.set_file(fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000549
Guido van Rossumd560ace2002-09-12 04:57:29 +0000550 def set_file(self, fd):
Fred Drake526a1822000-09-11 04:00:46 +0000551 self._fileno = fd
Guido van Rossumd560ace2002-09-12 04:57:29 +0000552 self.socket = file_wrapper(fd)
Fred Drake526a1822000-09-11 04:00:46 +0000553 self.add_channel()