blob: e1c97949b00b0cbf7a897891c79ed32a7e121394 [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
Guido van Rossum0039d7b1999-01-12 20:19:27 +000051
Guido van Rossum0039d7b1999-01-12 20:19:27 +000052class async_chat (asyncore.dispatcher):
Tim Peters146965a2001-01-14 18:09:23 +000053 """This is an abstract class. You must derive from this class, and add
54 the two methods collect_incoming_data() and found_terminator()"""
Guido van Rossum0039d7b1999-01-12 20:19:27 +000055
Tim Peters146965a2001-01-14 18:09:23 +000056 # these are overridable defaults
Guido van Rossum0039d7b1999-01-12 20:19:27 +000057
Tim Peters146965a2001-01-14 18:09:23 +000058 ac_in_buffer_size = 4096
59 ac_out_buffer_size = 4096
Guido van Rossum0039d7b1999-01-12 20:19:27 +000060
Tim Peters146965a2001-01-14 18:09:23 +000061 def __init__ (self, conn=None):
62 self.ac_in_buffer = ''
63 self.ac_out_buffer = ''
64 self.producer_fifo = fifo()
65 asyncore.dispatcher.__init__ (self, conn)
Guido van Rossum0039d7b1999-01-12 20:19:27 +000066
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000067 def collect_incoming_data(self, data):
68 raise NotImplementedError, "must be implemented in subclass"
Tim Peters863ac442002-04-16 01:38:40 +000069
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000070 def found_terminator(self):
71 raise NotImplementedError, "must be implemented in subclass"
Tim Peters863ac442002-04-16 01:38:40 +000072
Tim Peters146965a2001-01-14 18:09:23 +000073 def set_terminator (self, term):
74 "Set the input delimiter. Can be a fixed string of any length, an integer, or None"
75 self.terminator = term
Guido van Rossum0039d7b1999-01-12 20:19:27 +000076
Tim Peters146965a2001-01-14 18:09:23 +000077 def get_terminator (self):
78 return self.terminator
Guido van Rossum0039d7b1999-01-12 20:19:27 +000079
Tim Peters146965a2001-01-14 18:09:23 +000080 # grab some more data from the socket,
81 # throw it to the collector method,
82 # check for the terminator,
83 # if found, transition to the next state.
Guido van Rossum0039d7b1999-01-12 20:19:27 +000084
Tim Peters146965a2001-01-14 18:09:23 +000085 def handle_read (self):
Guido van Rossum0039d7b1999-01-12 20:19:27 +000086
Tim Peters146965a2001-01-14 18:09:23 +000087 try:
88 data = self.recv (self.ac_in_buffer_size)
89 except socket.error, why:
90 self.handle_error()
91 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +000092
Tim Peters146965a2001-01-14 18:09:23 +000093 self.ac_in_buffer = self.ac_in_buffer + data
Guido van Rossum0039d7b1999-01-12 20:19:27 +000094
Tim Peters146965a2001-01-14 18:09:23 +000095 # Continue to search for self.terminator in self.ac_in_buffer,
96 # while calling self.collect_incoming_data. The while loop
97 # is necessary because we might read several data+terminator
98 # combos with a single recv(1024).
Guido van Rossum0039d7b1999-01-12 20:19:27 +000099
Tim Peters146965a2001-01-14 18:09:23 +0000100 while self.ac_in_buffer:
101 lb = len(self.ac_in_buffer)
102 terminator = self.get_terminator()
103 if terminator is None:
104 # no terminator, collect it all
105 self.collect_incoming_data (self.ac_in_buffer)
106 self.ac_in_buffer = ''
107 elif type(terminator) == type(0):
108 # numeric terminator
109 n = terminator
110 if lb < n:
111 self.collect_incoming_data (self.ac_in_buffer)
112 self.ac_in_buffer = ''
113 self.terminator = self.terminator - lb
114 else:
115 self.collect_incoming_data (self.ac_in_buffer[:n])
116 self.ac_in_buffer = self.ac_in_buffer[n:]
117 self.terminator = 0
118 self.found_terminator()
119 else:
120 # 3 cases:
121 # 1) end of buffer matches terminator exactly:
122 # collect data, transition
123 # 2) end of buffer matches some prefix:
124 # collect data to the prefix
125 # 3) end of buffer does not match any prefix:
126 # collect data
127 terminator_len = len(terminator)
Tim Petersb5d13922001-04-05 22:38:32 +0000128 index = self.ac_in_buffer.find(terminator)
Tim Peters146965a2001-01-14 18:09:23 +0000129 if index != -1:
130 # we found the terminator
131 if index > 0:
132 # don't bother reporting the empty string (source of subtle bugs)
133 self.collect_incoming_data (self.ac_in_buffer[:index])
134 self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
135 # This does the Right Thing if the terminator is changed here.
136 self.found_terminator()
137 else:
138 # check for a prefix of the terminator
139 index = find_prefix_at_end (self.ac_in_buffer, terminator)
140 if index:
141 if index != lb:
142 # we found a prefix, collect up to the prefix
143 self.collect_incoming_data (self.ac_in_buffer[:-index])
144 self.ac_in_buffer = self.ac_in_buffer[-index:]
145 break
146 else:
147 # no prefix, collect it all
148 self.collect_incoming_data (self.ac_in_buffer)
149 self.ac_in_buffer = ''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000150
Tim Peters146965a2001-01-14 18:09:23 +0000151 def handle_write (self):
152 self.initiate_send ()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000153
Tim Peters146965a2001-01-14 18:09:23 +0000154 def handle_close (self):
155 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000156
Tim Peters146965a2001-01-14 18:09:23 +0000157 def push (self, data):
158 self.producer_fifo.push (simple_producer (data))
159 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000160
Tim Peters146965a2001-01-14 18:09:23 +0000161 def push_with_producer (self, producer):
162 self.producer_fifo.push (producer)
163 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000164
Tim Peters146965a2001-01-14 18:09:23 +0000165 def readable (self):
166 "predicate for inclusion in the readable for select()"
167 return (len(self.ac_in_buffer) <= self.ac_in_buffer_size)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000168
Tim Peters146965a2001-01-14 18:09:23 +0000169 def writable (self):
170 "predicate for inclusion in the writable for select()"
171 # return len(self.ac_out_buffer) or len(self.producer_fifo) or (not self.connected)
172 # this is about twice as fast, though not as clear.
173 return not (
Tim Peters6fd71202001-04-08 07:23:44 +0000174 (self.ac_out_buffer == '') and
Tim Peters146965a2001-01-14 18:09:23 +0000175 self.producer_fifo.is_empty() and
176 self.connected
177 )
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000178
Tim Peters146965a2001-01-14 18:09:23 +0000179 def close_when_done (self):
180 "automatically close this channel once the outgoing queue is empty"
181 self.producer_fifo.push (None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000182
Tim Peters146965a2001-01-14 18:09:23 +0000183 # refill the outgoing buffer by calling the more() method
184 # of the first producer in the queue
185 def refill_buffer (self):
186 _string_type = type('')
187 while 1:
188 if len(self.producer_fifo):
189 p = self.producer_fifo.first()
190 # a 'None' in the producer fifo is a sentinel,
191 # telling us to close the channel.
192 if p is None:
193 if not self.ac_out_buffer:
194 self.producer_fifo.pop()
195 self.close()
196 return
197 elif type(p) is _string_type:
198 self.producer_fifo.pop()
199 self.ac_out_buffer = self.ac_out_buffer + p
200 return
201 data = p.more()
202 if data:
203 self.ac_out_buffer = self.ac_out_buffer + data
204 return
205 else:
206 self.producer_fifo.pop()
207 else:
208 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000209
Tim Peters146965a2001-01-14 18:09:23 +0000210 def initiate_send (self):
211 obs = self.ac_out_buffer_size
212 # try to refill the buffer
213 if (len (self.ac_out_buffer) < obs):
214 self.refill_buffer()
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000215
Tim Peters146965a2001-01-14 18:09:23 +0000216 if self.ac_out_buffer and self.connected:
217 # try to send the buffer
218 try:
219 num_sent = self.send (self.ac_out_buffer[:obs])
220 if num_sent:
221 self.ac_out_buffer = self.ac_out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000222
Tim Peters146965a2001-01-14 18:09:23 +0000223 except socket.error, why:
224 self.handle_error()
225 return
226
227 def discard_buffers (self):
228 # Emergencies only!
229 self.ac_in_buffer = ''
230 self.ac_out_buffer = ''
231 while self.producer_fifo:
232 self.producer_fifo.pop()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000233
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000234
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000235class simple_producer:
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000236
Tim Peters146965a2001-01-14 18:09:23 +0000237 def __init__ (self, data, buffer_size=512):
238 self.data = data
239 self.buffer_size = buffer_size
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000240
Tim Peters146965a2001-01-14 18:09:23 +0000241 def more (self):
242 if len (self.data) > self.buffer_size:
243 result = self.data[:self.buffer_size]
244 self.data = self.data[self.buffer_size:]
245 return result
246 else:
247 result = self.data
248 self.data = ''
249 return result
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000250
251class fifo:
Tim Peters146965a2001-01-14 18:09:23 +0000252 def __init__ (self, list=None):
253 if not list:
254 self.list = []
255 else:
256 self.list = list
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000257
Tim Peters146965a2001-01-14 18:09:23 +0000258 def __len__ (self):
259 return len(self.list)
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000260
Tim Peters146965a2001-01-14 18:09:23 +0000261 def is_empty (self):
262 return self.list == []
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000263
Tim Peters146965a2001-01-14 18:09:23 +0000264 def first (self):
265 return self.list[0]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000266
Tim Peters146965a2001-01-14 18:09:23 +0000267 def push (self, data):
268 self.list.append (data)
269
270 def pop (self):
271 if self.list:
272 result = self.list[0]
273 del self.list[0]
274 return (1, result)
275 else:
276 return (0, None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000277
278# Given 'haystack', see if any prefix of 'needle' is at its end. This
279# assumes an exact match has already been checked. Return the number of
280# characters matched.
281# for example:
282# f_p_a_e ("qwerty\r", "\r\n") => 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000283# f_p_a_e ("qwertydkjf", "\r\n") => 0
Andrew M. Kuchlingc63a3962002-03-20 02:22:58 +0000284# f_p_a_e ("qwerty\r\n", "\r\n") => <undefined>
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000285
286# this could maybe be made faster with a computed regex?
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000287# [answer: no; circa Python-2.0, Jan 2001]
Andrew M. Kuchlingc63a3962002-03-20 02:22:58 +0000288# new python: 28961/s
289# old python: 18307/s
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000290# re: 12820/s
291# regex: 14035/s
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000292
293def find_prefix_at_end (haystack, needle):
Tim Peters863ac442002-04-16 01:38:40 +0000294 l = len(needle) - 1
295 while l and not haystack.endswith(needle[:l]):
296 l -= 1
297 return l