blob: 1d5fb7f030803596f33733de55b3fc031b7fbb63 [file] [log] [blame]
Guido van Rossum0039d7b1999-01-12 20:19:27 +00001# -*- Mode: Python; tab-width: 4 -*-
Tim Peters658cba62001-02-09 20:06:00 +00002# Id: asynchat.py,v 2.26 2000/09/07 22:29:26 rushing Exp
Tim Peters146965a2001-01-14 18:09:23 +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 Rossume4a1b6d2001-04-06 15:30:33 +000028r"""A class supporting chat-style (command/response) protocols.
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000029
30This class adds support for 'chat' style protocols - where one side
31sends a 'command', and the other sends a response (examples would be
32the common internet protocols - smtp, nntp, ftp, etc..).
33
34The handle_read() method looks at the input stream for the current
35'terminator' (usually '\r\n' for single-line responses, '\r\n.\r\n'
36for multi-line output), calling self.found_terminator() on its
37receipt.
38
39for example:
40Say you build an async nntp client using this class. At the start
41of the connection, you'll have self.terminator set to '\r\n', in
42order to process the single-line greeting. Just before issuing a
43'LIST' command you'll set it to '\r\n.\r\n'. The output of the LIST
44command will be accumulated (using your own 'collect_incoming_data'
45method) up to the terminator, and then control will be returned to
46you - by calling your self.found_terminator() method.
47"""
48
Guido van Rossum0039d7b1999-01-12 20:19:27 +000049import socket
50import asyncore
Raymond Hettingerac093c62004-02-07 03:19:10 +000051from collections import deque
Guido van Rossum0039d7b1999-01-12 20:19:27 +000052
Guido van Rossum0039d7b1999-01-12 20:19:27 +000053class async_chat (asyncore.dispatcher):
Tim Peters146965a2001-01-14 18:09:23 +000054 """This is an abstract class. You must derive from this class, and add
55 the two methods collect_incoming_data() and found_terminator()"""
Guido van Rossum0039d7b1999-01-12 20:19:27 +000056
Tim Peters146965a2001-01-14 18:09:23 +000057 # these are overridable defaults
Guido van Rossum0039d7b1999-01-12 20:19:27 +000058
Tim Peters146965a2001-01-14 18:09:23 +000059 ac_in_buffer_size = 4096
60 ac_out_buffer_size = 4096
Guido van Rossum0039d7b1999-01-12 20:19:27 +000061
Tim Peters146965a2001-01-14 18:09:23 +000062 def __init__ (self, conn=None):
Josiah Carlson1a72d882008-06-10 05:00:08 +000063 # for string terminator matching
Tim Peters146965a2001-01-14 18:09:23 +000064 self.ac_in_buffer = ''
Josiah Carlson1a72d882008-06-10 05:00:08 +000065
66 # we use a list here rather than cStringIO for a few reasons...
67 # del lst[:] is faster than sio.truncate(0)
68 # lst = [] is faster than sio.truncate(0)
69 # cStringIO will be gaining unicode support in py3k, which
70 # will negatively affect the performance of bytes compared to
71 # a ''.join() equivalent
72 self.incoming = []
73
74 # we toss the use of the "simple producer" and replace it with
75 # a pure deque, which the original fifo was a wrapping of
76 self.producer_fifo = deque()
Tim Peters146965a2001-01-14 18:09:23 +000077 asyncore.dispatcher.__init__ (self, conn)
Guido van Rossum0039d7b1999-01-12 20:19:27 +000078
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000079 def collect_incoming_data(self, data):
Josiah Carlson1a72d882008-06-10 05:00:08 +000080 raise NotImplementedError("must be implemented in subclass")
81
82 def _collect_incoming_data(self, data):
83 self.incoming.append(data)
84
85 def _get_data(self):
86 d = ''.join(self.incoming)
87 del self.incoming[:]
88 return d
Tim Peters863ac442002-04-16 01:38:40 +000089
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000090 def found_terminator(self):
Josiah Carlson1a72d882008-06-10 05:00:08 +000091 raise NotImplementedError("must be implemented in subclass")
Tim Peters863ac442002-04-16 01:38:40 +000092
Tim Peters146965a2001-01-14 18:09:23 +000093 def set_terminator (self, term):
94 "Set the input delimiter. Can be a fixed string of any length, an integer, or None"
95 self.terminator = term
Guido van Rossum0039d7b1999-01-12 20:19:27 +000096
Tim Peters146965a2001-01-14 18:09:23 +000097 def get_terminator (self):
98 return self.terminator
Guido van Rossum0039d7b1999-01-12 20:19:27 +000099
Tim Peters146965a2001-01-14 18:09:23 +0000100 # grab some more data from the socket,
101 # throw it to the collector method,
102 # check for the terminator,
103 # if found, transition to the next state.
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000104
Tim Peters146965a2001-01-14 18:09:23 +0000105 def handle_read (self):
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000106
Tim Peters146965a2001-01-14 18:09:23 +0000107 try:
108 data = self.recv (self.ac_in_buffer_size)
109 except socket.error, why:
110 self.handle_error()
111 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000112
Tim Peters146965a2001-01-14 18:09:23 +0000113 self.ac_in_buffer = self.ac_in_buffer + data
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000114
Tim Peters146965a2001-01-14 18:09:23 +0000115 # Continue to search for self.terminator in self.ac_in_buffer,
116 # while calling self.collect_incoming_data. The while loop
117 # is necessary because we might read several data+terminator
Josiah Carlson1a72d882008-06-10 05:00:08 +0000118 # combos with a single recv(4096).
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000119
Tim Peters146965a2001-01-14 18:09:23 +0000120 while self.ac_in_buffer:
121 lb = len(self.ac_in_buffer)
122 terminator = self.get_terminator()
Andrew M. Kuchlingca69f022005-06-09 14:59:45 +0000123 if not terminator:
Tim Peters146965a2001-01-14 18:09:23 +0000124 # no terminator, collect it all
125 self.collect_incoming_data (self.ac_in_buffer)
126 self.ac_in_buffer = ''
Andrew M. Kuchlingca69f022005-06-09 14:59:45 +0000127 elif isinstance(terminator, int) or isinstance(terminator, long):
Tim Peters146965a2001-01-14 18:09:23 +0000128 # numeric terminator
129 n = terminator
130 if lb < n:
131 self.collect_incoming_data (self.ac_in_buffer)
132 self.ac_in_buffer = ''
133 self.terminator = self.terminator - lb
134 else:
135 self.collect_incoming_data (self.ac_in_buffer[:n])
136 self.ac_in_buffer = self.ac_in_buffer[n:]
137 self.terminator = 0
138 self.found_terminator()
139 else:
140 # 3 cases:
141 # 1) end of buffer matches terminator exactly:
142 # collect data, transition
143 # 2) end of buffer matches some prefix:
144 # collect data to the prefix
145 # 3) end of buffer does not match any prefix:
146 # collect data
147 terminator_len = len(terminator)
Tim Petersb5d13922001-04-05 22:38:32 +0000148 index = self.ac_in_buffer.find(terminator)
Tim Peters146965a2001-01-14 18:09:23 +0000149 if index != -1:
150 # we found the terminator
151 if index > 0:
152 # don't bother reporting the empty string (source of subtle bugs)
153 self.collect_incoming_data (self.ac_in_buffer[:index])
154 self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
155 # This does the Right Thing if the terminator is changed here.
156 self.found_terminator()
157 else:
158 # check for a prefix of the terminator
159 index = find_prefix_at_end (self.ac_in_buffer, terminator)
160 if index:
161 if index != lb:
162 # we found a prefix, collect up to the prefix
163 self.collect_incoming_data (self.ac_in_buffer[:-index])
164 self.ac_in_buffer = self.ac_in_buffer[-index:]
165 break
166 else:
167 # no prefix, collect it all
168 self.collect_incoming_data (self.ac_in_buffer)
169 self.ac_in_buffer = ''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000170
Tim Peters146965a2001-01-14 18:09:23 +0000171 def handle_write (self):
Josiah Carlson1a72d882008-06-10 05:00:08 +0000172 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000173
Tim Peters146965a2001-01-14 18:09:23 +0000174 def handle_close (self):
175 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000176
Tim Peters146965a2001-01-14 18:09:23 +0000177 def push (self, data):
Josiah Carlson1a72d882008-06-10 05:00:08 +0000178 sabs = self.ac_out_buffer_size
179 if len(data) > sabs:
180 for i in xrange(0, len(data), sabs):
181 self.producer_fifo.append(data[i:i+sabs])
182 else:
183 self.producer_fifo.append(data)
Tim Peters146965a2001-01-14 18:09:23 +0000184 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000185
Tim Peters146965a2001-01-14 18:09:23 +0000186 def push_with_producer (self, producer):
Josiah Carlson1a72d882008-06-10 05:00:08 +0000187 self.producer_fifo.append(producer)
Tim Peters146965a2001-01-14 18:09:23 +0000188 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000189
Tim Peters146965a2001-01-14 18:09:23 +0000190 def readable (self):
191 "predicate for inclusion in the readable for select()"
Josiah Carlson1a72d882008-06-10 05:00:08 +0000192 # cannot use the old predicate, it violates the claim of the
193 # set_terminator method.
194
195 # return (len(self.ac_in_buffer) <= self.ac_in_buffer_size)
196 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000197
Tim Peters146965a2001-01-14 18:09:23 +0000198 def writable (self):
199 "predicate for inclusion in the writable for select()"
Josiah Carlson1a72d882008-06-10 05:00:08 +0000200 return self.producer_fifo or (not self.connected)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000201
Tim Peters146965a2001-01-14 18:09:23 +0000202 def close_when_done (self):
203 "automatically close this channel once the outgoing queue is empty"
Josiah Carlson1a72d882008-06-10 05:00:08 +0000204 self.producer_fifo.append(None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000205
Josiah Carlson1a72d882008-06-10 05:00:08 +0000206 def initiate_send(self):
207 while self.producer_fifo and self.connected:
208 first = self.producer_fifo[0]
209 # handle empty string/buffer or None entry
210 if not first:
211 del self.producer_fifo[0]
212 if first is None:
213 self.handle_close()
Tim Peters146965a2001-01-14 18:09:23 +0000214 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000215
Josiah Carlson1a72d882008-06-10 05:00:08 +0000216 # handle classic producer behavior
217 obs = self.ac_out_buffer_size
Tim Peters146965a2001-01-14 18:09:23 +0000218 try:
Josiah Carlson1a72d882008-06-10 05:00:08 +0000219 data = buffer(first, 0, obs)
220 except TypeError:
221 data = first.more()
222 if data:
223 self.producer_fifo.appendleft(data)
224 else:
225 del self.producer_fifo[0]
226 continue
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000227
Josiah Carlson1a72d882008-06-10 05:00:08 +0000228 # send the data
229 try:
230 num_sent = self.send(data)
231 except socket.error:
Tim Peters146965a2001-01-14 18:09:23 +0000232 self.handle_error()
233 return
234
Josiah Carlson1a72d882008-06-10 05:00:08 +0000235 if num_sent:
236 if num_sent < len(data) or obs < len(first):
237 self.producer_fifo[0] = first[num_sent:]
238 else:
239 del self.producer_fifo[0]
240 # we tried to send some actual data
241 return
242
Tim Peters146965a2001-01-14 18:09:23 +0000243 def discard_buffers (self):
244 # Emergencies only!
245 self.ac_in_buffer = ''
Josiah Carlson1a72d882008-06-10 05:00:08 +0000246 del self.incoming[:]
247 self.producer_fifo.clear()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000248
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000249class simple_producer:
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000250
Tim Peters146965a2001-01-14 18:09:23 +0000251 def __init__ (self, data, buffer_size=512):
252 self.data = data
253 self.buffer_size = buffer_size
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000254
Tim Peters146965a2001-01-14 18:09:23 +0000255 def more (self):
256 if len (self.data) > self.buffer_size:
257 result = self.data[:self.buffer_size]
258 self.data = self.data[self.buffer_size:]
259 return result
260 else:
261 result = self.data
262 self.data = ''
263 return result
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000264
265class fifo:
Tim Peters146965a2001-01-14 18:09:23 +0000266 def __init__ (self, list=None):
267 if not list:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000268 self.list = deque()
Tim Peters146965a2001-01-14 18:09:23 +0000269 else:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000270 self.list = deque(list)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000271
Tim Peters146965a2001-01-14 18:09:23 +0000272 def __len__ (self):
273 return len(self.list)
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000274
Tim Peters146965a2001-01-14 18:09:23 +0000275 def is_empty (self):
Armin Rigob562bc62004-09-27 17:49:00 +0000276 return not self.list
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000277
Tim Peters146965a2001-01-14 18:09:23 +0000278 def first (self):
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000279 return self.list[0]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000280
Tim Peters146965a2001-01-14 18:09:23 +0000281 def push (self, data):
Raymond Hettingerac093c62004-02-07 03:19:10 +0000282 self.list.append(data)
Tim Peters146965a2001-01-14 18:09:23 +0000283
284 def pop (self):
285 if self.list:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000286 return (1, self.list.popleft())
Tim Peters146965a2001-01-14 18:09:23 +0000287 else:
288 return (0, None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000289
290# Given 'haystack', see if any prefix of 'needle' is at its end. This
291# assumes an exact match has already been checked. Return the number of
292# characters matched.
293# for example:
294# f_p_a_e ("qwerty\r", "\r\n") => 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000295# f_p_a_e ("qwertydkjf", "\r\n") => 0
Andrew M. Kuchlingc63a3962002-03-20 02:22:58 +0000296# f_p_a_e ("qwerty\r\n", "\r\n") => <undefined>
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000297
298# this could maybe be made faster with a computed regex?
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000299# [answer: no; circa Python-2.0, Jan 2001]
Andrew M. Kuchlingc63a3962002-03-20 02:22:58 +0000300# new python: 28961/s
301# old python: 18307/s
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000302# re: 12820/s
303# regex: 14035/s
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000304
305def find_prefix_at_end (haystack, needle):
Tim Peters863ac442002-04-16 01:38:40 +0000306 l = len(needle) - 1
307 while l and not haystack.endswith(needle[:l]):
308 l -= 1
309 return l