blob: 0378fa70697af220c7692a14b6f3847c309f63c3 [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"""
Guido van Rossum0039d7b1999-01-12 20:19:27 +000048import socket
49import asyncore
Raymond Hettingerac093c62004-02-07 03:19:10 +000050from collections import deque
Guido van Rossum0039d7b1999-01-12 20:19:27 +000051
Josiah Carlsond74900e2008-07-07 04:15:08 +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
Charles-François Natalife22dca2013-01-01 16:31:54 +010059 ac_in_buffer_size = 65536
60 ac_out_buffer_size = 65536
Guido van Rossum0039d7b1999-01-12 20:19:27 +000061
Josiah Carlsond74900e2008-07-07 04:15:08 +000062 # we don't want to enable the use of encoding by default, because that is a
63 # sign of an application bug that we don't want to pass silently
64
65 use_encoding = 0
Marc-André Lemburg8f36af72011-02-25 15:42:01 +000066 encoding = 'latin-1'
Josiah Carlsond74900e2008-07-07 04:15:08 +000067
Josiah Carlson9f2f8332008-07-07 05:04:12 +000068 def __init__ (self, sock=None, map=None):
Josiah Carlsond74900e2008-07-07 04:15:08 +000069 # for string terminator matching
Guido van Rossum076da092007-07-12 07:58:54 +000070 self.ac_in_buffer = b''
Josiah Carlsond74900e2008-07-07 04:15:08 +000071
Serhiy Storchaka50254c52013-08-29 11:35:43 +030072 # we use a list here rather than io.BytesIO for a few reasons...
73 # del lst[:] is faster than bio.truncate(0)
74 # lst = [] is faster than bio.truncate(0)
Josiah Carlsond74900e2008-07-07 04:15:08 +000075 self.incoming = []
76
77 # we toss the use of the "simple producer" and replace it with
78 # a pure deque, which the original fifo was a wrapping of
79 self.producer_fifo = deque()
Josiah Carlson9f2f8332008-07-07 05:04:12 +000080 asyncore.dispatcher.__init__ (self, sock, map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +000081
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000082 def collect_incoming_data(self, data):
Collin Winterce36ad82007-08-30 01:19:48 +000083 raise NotImplementedError("must be implemented in subclass")
Tim Peters863ac442002-04-16 01:38:40 +000084
Josiah Carlsond74900e2008-07-07 04:15:08 +000085 def _collect_incoming_data(self, data):
86 self.incoming.append(data)
87
88 def _get_data(self):
89 d = b''.join(self.incoming)
90 del self.incoming[:]
91 return d
92
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000093 def found_terminator(self):
Collin Winterce36ad82007-08-30 01:19:48 +000094 raise NotImplementedError("must be implemented in subclass")
Tim Peters863ac442002-04-16 01:38:40 +000095
Tim Peters146965a2001-01-14 18:09:23 +000096 def set_terminator (self, term):
97 "Set the input delimiter. Can be a fixed string of any length, an integer, or None"
Josiah Carlsond74900e2008-07-07 04:15:08 +000098 if isinstance(term, str) and self.use_encoding:
99 term = bytes(term, self.encoding)
Tim Peters146965a2001-01-14 18:09:23 +0000100 self.terminator = term
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000101
Tim Peters146965a2001-01-14 18:09:23 +0000102 def get_terminator (self):
103 return self.terminator
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000104
Tim Peters146965a2001-01-14 18:09:23 +0000105 # grab some more data from the socket,
106 # throw it to the collector method,
107 # check for the terminator,
108 # if found, transition to the next state.
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000109
Tim Peters146965a2001-01-14 18:09:23 +0000110 def handle_read (self):
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000111
Tim Peters146965a2001-01-14 18:09:23 +0000112 try:
113 data = self.recv (self.ac_in_buffer_size)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200114 except OSError as why:
Tim Peters146965a2001-01-14 18:09:23 +0000115 self.handle_error()
116 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000117
Josiah Carlsond74900e2008-07-07 04:15:08 +0000118 if isinstance(data, str) and self.use_encoding:
119 data = bytes(str, self.encoding)
120 self.ac_in_buffer = self.ac_in_buffer + data
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000121
Tim Peters146965a2001-01-14 18:09:23 +0000122 # Continue to search for self.terminator in self.ac_in_buffer,
123 # while calling self.collect_incoming_data. The while loop
124 # is necessary because we might read several data+terminator
Josiah Carlsond74900e2008-07-07 04:15:08 +0000125 # combos with a single recv(4096).
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000126
Tim Peters146965a2001-01-14 18:09:23 +0000127 while self.ac_in_buffer:
128 lb = len(self.ac_in_buffer)
129 terminator = self.get_terminator()
Andrew M. Kuchlingca69f022005-06-09 14:59:45 +0000130 if not terminator:
Tim Peters146965a2001-01-14 18:09:23 +0000131 # no terminator, collect it all
132 self.collect_incoming_data (self.ac_in_buffer)
Guido van Rossum806c2462007-08-06 23:33:07 +0000133 self.ac_in_buffer = b''
Josiah Carlsond74900e2008-07-07 04:15:08 +0000134 elif isinstance(terminator, int):
Tim Peters146965a2001-01-14 18:09:23 +0000135 # numeric terminator
136 n = terminator
137 if lb < n:
138 self.collect_incoming_data (self.ac_in_buffer)
Guido van Rossum076da092007-07-12 07:58:54 +0000139 self.ac_in_buffer = b''
Tim Peters146965a2001-01-14 18:09:23 +0000140 self.terminator = self.terminator - lb
141 else:
142 self.collect_incoming_data (self.ac_in_buffer[:n])
143 self.ac_in_buffer = self.ac_in_buffer[n:]
144 self.terminator = 0
145 self.found_terminator()
146 else:
147 # 3 cases:
148 # 1) end of buffer matches terminator exactly:
149 # collect data, transition
150 # 2) end of buffer matches some prefix:
151 # collect data to the prefix
152 # 3) end of buffer does not match any prefix:
153 # collect data
154 terminator_len = len(terminator)
Tim Petersb5d13922001-04-05 22:38:32 +0000155 index = self.ac_in_buffer.find(terminator)
Tim Peters146965a2001-01-14 18:09:23 +0000156 if index != -1:
157 # we found the terminator
158 if index > 0:
159 # don't bother reporting the empty string (source of subtle bugs)
160 self.collect_incoming_data (self.ac_in_buffer[:index])
161 self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
162 # This does the Right Thing if the terminator is changed here.
163 self.found_terminator()
164 else:
165 # check for a prefix of the terminator
166 index = find_prefix_at_end (self.ac_in_buffer, terminator)
167 if index:
168 if index != lb:
169 # we found a prefix, collect up to the prefix
170 self.collect_incoming_data (self.ac_in_buffer[:-index])
171 self.ac_in_buffer = self.ac_in_buffer[-index:]
172 break
173 else:
174 # no prefix, collect it all
175 self.collect_incoming_data (self.ac_in_buffer)
Guido van Rossum076da092007-07-12 07:58:54 +0000176 self.ac_in_buffer = b''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000177
Tim Peters146965a2001-01-14 18:09:23 +0000178 def handle_write (self):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000179 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000180
Tim Peters146965a2001-01-14 18:09:23 +0000181 def handle_close (self):
182 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000183
Tim Peters146965a2001-01-14 18:09:23 +0000184 def push (self, data):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000185 sabs = self.ac_out_buffer_size
186 if len(data) > sabs:
187 for i in range(0, len(data), sabs):
188 self.producer_fifo.append(data[i:i+sabs])
189 else:
190 self.producer_fifo.append(data)
Tim Peters146965a2001-01-14 18:09:23 +0000191 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000192
Tim Peters146965a2001-01-14 18:09:23 +0000193 def push_with_producer (self, producer):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000194 self.producer_fifo.append(producer)
Tim Peters146965a2001-01-14 18:09:23 +0000195 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000196
Tim Peters146965a2001-01-14 18:09:23 +0000197 def readable (self):
198 "predicate for inclusion in the readable for select()"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000199 # cannot use the old predicate, it violates the claim of the
200 # set_terminator method.
201
202 # return (len(self.ac_in_buffer) <= self.ac_in_buffer_size)
203 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000204
Tim Peters146965a2001-01-14 18:09:23 +0000205 def writable (self):
206 "predicate for inclusion in the writable for select()"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000207 return self.producer_fifo or (not self.connected)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000208
Tim Peters146965a2001-01-14 18:09:23 +0000209 def close_when_done (self):
210 "automatically close this channel once the outgoing queue is empty"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000211 self.producer_fifo.append(None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000212
Josiah Carlsond74900e2008-07-07 04:15:08 +0000213 def initiate_send(self):
214 while self.producer_fifo and self.connected:
215 first = self.producer_fifo[0]
216 # handle empty string/buffer or None entry
217 if not first:
218 del self.producer_fifo[0]
219 if first is None:
220 ## print("first is None")
221 self.handle_close()
Tim Peters146965a2001-01-14 18:09:23 +0000222 return
Josiah Carlsond74900e2008-07-07 04:15:08 +0000223 ## print("first is not None")
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000224
Josiah Carlsond74900e2008-07-07 04:15:08 +0000225 # handle classic producer behavior
226 obs = self.ac_out_buffer_size
Tim Peters146965a2001-01-14 18:09:23 +0000227 try:
Giampaolo Rodola'd9f38bc2012-08-04 14:38:16 +0200228 data = first[:obs]
Josiah Carlsond74900e2008-07-07 04:15:08 +0000229 except TypeError:
230 data = first.more()
231 if data:
232 self.producer_fifo.appendleft(data)
233 else:
234 del self.producer_fifo[0]
235 continue
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000236
Josiah Carlsond74900e2008-07-07 04:15:08 +0000237 if isinstance(data, str) and self.use_encoding:
238 data = bytes(data, self.encoding)
239
240 # send the data
241 try:
242 num_sent = self.send(data)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200243 except OSError:
Tim Peters146965a2001-01-14 18:09:23 +0000244 self.handle_error()
245 return
246
Josiah Carlsond74900e2008-07-07 04:15:08 +0000247 if num_sent:
248 if num_sent < len(data) or obs < len(first):
249 self.producer_fifo[0] = first[num_sent:]
250 else:
251 del self.producer_fifo[0]
252 # we tried to send some actual data
253 return
254
Tim Peters146965a2001-01-14 18:09:23 +0000255 def discard_buffers (self):
256 # Emergencies only!
Guido van Rossum076da092007-07-12 07:58:54 +0000257 self.ac_in_buffer = b''
Josiah Carlsond74900e2008-07-07 04:15:08 +0000258 del self.incoming[:]
259 self.producer_fifo.clear()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000260
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000261class simple_producer:
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000262
Tim Peters146965a2001-01-14 18:09:23 +0000263 def __init__ (self, data, buffer_size=512):
264 self.data = data
265 self.buffer_size = buffer_size
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000266
Tim Peters146965a2001-01-14 18:09:23 +0000267 def more (self):
268 if len (self.data) > self.buffer_size:
269 result = self.data[:self.buffer_size]
270 self.data = self.data[self.buffer_size:]
271 return result
272 else:
273 result = self.data
Guido van Rossum076da092007-07-12 07:58:54 +0000274 self.data = b''
Tim Peters146965a2001-01-14 18:09:23 +0000275 return result
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000276
277class fifo:
Tim Peters146965a2001-01-14 18:09:23 +0000278 def __init__ (self, list=None):
279 if not list:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000280 self.list = deque()
Tim Peters146965a2001-01-14 18:09:23 +0000281 else:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000282 self.list = deque(list)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000283
Tim Peters146965a2001-01-14 18:09:23 +0000284 def __len__ (self):
285 return len(self.list)
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000286
Tim Peters146965a2001-01-14 18:09:23 +0000287 def is_empty (self):
Armin Rigob562bc62004-09-27 17:49:00 +0000288 return not self.list
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000289
Tim Peters146965a2001-01-14 18:09:23 +0000290 def first (self):
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000291 return self.list[0]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000292
Tim Peters146965a2001-01-14 18:09:23 +0000293 def push (self, data):
Raymond Hettingerac093c62004-02-07 03:19:10 +0000294 self.list.append(data)
Tim Peters146965a2001-01-14 18:09:23 +0000295
296 def pop (self):
297 if self.list:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000298 return (1, self.list.popleft())
Tim Peters146965a2001-01-14 18:09:23 +0000299 else:
300 return (0, None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000301
302# Given 'haystack', see if any prefix of 'needle' is at its end. This
303# assumes an exact match has already been checked. Return the number of
304# characters matched.
305# for example:
306# f_p_a_e ("qwerty\r", "\r\n") => 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000307# f_p_a_e ("qwertydkjf", "\r\n") => 0
Andrew M. Kuchlingc63a3962002-03-20 02:22:58 +0000308# f_p_a_e ("qwerty\r\n", "\r\n") => <undefined>
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000309
310# this could maybe be made faster with a computed regex?
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000311# [answer: no; circa Python-2.0, Jan 2001]
Andrew M. Kuchlingc63a3962002-03-20 02:22:58 +0000312# new python: 28961/s
313# old python: 18307/s
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000314# re: 12820/s
315# regex: 14035/s
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000316
317def find_prefix_at_end (haystack, needle):
Tim Peters863ac442002-04-16 01:38:40 +0000318 l = len(needle) - 1
319 while l and not haystack.endswith(needle[:l]):
320 l -= 1
321 return l