blob: f055d63ba49a3a3d933e82eb93bcf442f8953da3 [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
72 # we use a list here rather than cStringIO for a few reasons...
73 # del lst[:] is faster than sio.truncate(0)
74 # lst = [] is faster than sio.truncate(0)
75 # cStringIO will be gaining unicode support in py3k, which
76 # will negatively affect the performance of bytes compared to
77 # a ''.join() equivalent
78 self.incoming = []
79
80 # we toss the use of the "simple producer" and replace it with
81 # a pure deque, which the original fifo was a wrapping of
82 self.producer_fifo = deque()
Josiah Carlson9f2f8332008-07-07 05:04:12 +000083 asyncore.dispatcher.__init__ (self, sock, map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +000084
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000085 def collect_incoming_data(self, data):
Collin Winterce36ad82007-08-30 01:19:48 +000086 raise NotImplementedError("must be implemented in subclass")
Tim Peters863ac442002-04-16 01:38:40 +000087
Josiah Carlsond74900e2008-07-07 04:15:08 +000088 def _collect_incoming_data(self, data):
89 self.incoming.append(data)
90
91 def _get_data(self):
92 d = b''.join(self.incoming)
93 del self.incoming[:]
94 return d
95
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000096 def found_terminator(self):
Collin Winterce36ad82007-08-30 01:19:48 +000097 raise NotImplementedError("must be implemented in subclass")
Tim Peters863ac442002-04-16 01:38:40 +000098
Tim Peters146965a2001-01-14 18:09:23 +000099 def set_terminator (self, term):
100 "Set the input delimiter. Can be a fixed string of any length, an integer, or None"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000101 if isinstance(term, str) and self.use_encoding:
102 term = bytes(term, self.encoding)
Tim Peters146965a2001-01-14 18:09:23 +0000103 self.terminator = term
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000104
Tim Peters146965a2001-01-14 18:09:23 +0000105 def get_terminator (self):
106 return self.terminator
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000107
Tim Peters146965a2001-01-14 18:09:23 +0000108 # grab some more data from the socket,
109 # throw it to the collector method,
110 # check for the terminator,
111 # if found, transition to the next state.
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000112
Tim Peters146965a2001-01-14 18:09:23 +0000113 def handle_read (self):
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000114
Tim Peters146965a2001-01-14 18:09:23 +0000115 try:
116 data = self.recv (self.ac_in_buffer_size)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200117 except OSError as why:
Tim Peters146965a2001-01-14 18:09:23 +0000118 self.handle_error()
119 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000120
Josiah Carlsond74900e2008-07-07 04:15:08 +0000121 if isinstance(data, str) and self.use_encoding:
122 data = bytes(str, self.encoding)
123 self.ac_in_buffer = self.ac_in_buffer + data
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000124
Tim Peters146965a2001-01-14 18:09:23 +0000125 # Continue to search for self.terminator in self.ac_in_buffer,
126 # while calling self.collect_incoming_data. The while loop
127 # is necessary because we might read several data+terminator
Josiah Carlsond74900e2008-07-07 04:15:08 +0000128 # combos with a single recv(4096).
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000129
Tim Peters146965a2001-01-14 18:09:23 +0000130 while self.ac_in_buffer:
131 lb = len(self.ac_in_buffer)
132 terminator = self.get_terminator()
Andrew M. Kuchlingca69f022005-06-09 14:59:45 +0000133 if not terminator:
Tim Peters146965a2001-01-14 18:09:23 +0000134 # no terminator, collect it all
135 self.collect_incoming_data (self.ac_in_buffer)
Guido van Rossum806c2462007-08-06 23:33:07 +0000136 self.ac_in_buffer = b''
Josiah Carlsond74900e2008-07-07 04:15:08 +0000137 elif isinstance(terminator, int):
Tim Peters146965a2001-01-14 18:09:23 +0000138 # numeric terminator
139 n = terminator
140 if lb < n:
141 self.collect_incoming_data (self.ac_in_buffer)
Guido van Rossum076da092007-07-12 07:58:54 +0000142 self.ac_in_buffer = b''
Tim Peters146965a2001-01-14 18:09:23 +0000143 self.terminator = self.terminator - lb
144 else:
145 self.collect_incoming_data (self.ac_in_buffer[:n])
146 self.ac_in_buffer = self.ac_in_buffer[n:]
147 self.terminator = 0
148 self.found_terminator()
149 else:
150 # 3 cases:
151 # 1) end of buffer matches terminator exactly:
152 # collect data, transition
153 # 2) end of buffer matches some prefix:
154 # collect data to the prefix
155 # 3) end of buffer does not match any prefix:
156 # collect data
157 terminator_len = len(terminator)
Tim Petersb5d13922001-04-05 22:38:32 +0000158 index = self.ac_in_buffer.find(terminator)
Tim Peters146965a2001-01-14 18:09:23 +0000159 if index != -1:
160 # we found the terminator
161 if index > 0:
162 # don't bother reporting the empty string (source of subtle bugs)
163 self.collect_incoming_data (self.ac_in_buffer[:index])
164 self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
165 # This does the Right Thing if the terminator is changed here.
166 self.found_terminator()
167 else:
168 # check for a prefix of the terminator
169 index = find_prefix_at_end (self.ac_in_buffer, terminator)
170 if index:
171 if index != lb:
172 # we found a prefix, collect up to the prefix
173 self.collect_incoming_data (self.ac_in_buffer[:-index])
174 self.ac_in_buffer = self.ac_in_buffer[-index:]
175 break
176 else:
177 # no prefix, collect it all
178 self.collect_incoming_data (self.ac_in_buffer)
Guido van Rossum076da092007-07-12 07:58:54 +0000179 self.ac_in_buffer = b''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000180
Tim Peters146965a2001-01-14 18:09:23 +0000181 def handle_write (self):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000182 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000183
Tim Peters146965a2001-01-14 18:09:23 +0000184 def handle_close (self):
185 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000186
Tim Peters146965a2001-01-14 18:09:23 +0000187 def push (self, data):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000188 sabs = self.ac_out_buffer_size
189 if len(data) > sabs:
190 for i in range(0, len(data), sabs):
191 self.producer_fifo.append(data[i:i+sabs])
192 else:
193 self.producer_fifo.append(data)
Tim Peters146965a2001-01-14 18:09:23 +0000194 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000195
Tim Peters146965a2001-01-14 18:09:23 +0000196 def push_with_producer (self, producer):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000197 self.producer_fifo.append(producer)
Tim Peters146965a2001-01-14 18:09:23 +0000198 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000199
Tim Peters146965a2001-01-14 18:09:23 +0000200 def readable (self):
201 "predicate for inclusion in the readable for select()"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000202 # cannot use the old predicate, it violates the claim of the
203 # set_terminator method.
204
205 # return (len(self.ac_in_buffer) <= self.ac_in_buffer_size)
206 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000207
Tim Peters146965a2001-01-14 18:09:23 +0000208 def writable (self):
209 "predicate for inclusion in the writable for select()"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000210 return self.producer_fifo or (not self.connected)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000211
Tim Peters146965a2001-01-14 18:09:23 +0000212 def close_when_done (self):
213 "automatically close this channel once the outgoing queue is empty"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000214 self.producer_fifo.append(None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000215
Josiah Carlsond74900e2008-07-07 04:15:08 +0000216 def initiate_send(self):
217 while self.producer_fifo and self.connected:
218 first = self.producer_fifo[0]
219 # handle empty string/buffer or None entry
220 if not first:
221 del self.producer_fifo[0]
222 if first is None:
223 ## print("first is None")
224 self.handle_close()
Tim Peters146965a2001-01-14 18:09:23 +0000225 return
Josiah Carlsond74900e2008-07-07 04:15:08 +0000226 ## print("first is not None")
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000227
Josiah Carlsond74900e2008-07-07 04:15:08 +0000228 # handle classic producer behavior
229 obs = self.ac_out_buffer_size
Tim Peters146965a2001-01-14 18:09:23 +0000230 try:
Giampaolo Rodola'd9f38bc2012-08-04 14:38:16 +0200231 data = first[:obs]
Josiah Carlsond74900e2008-07-07 04:15:08 +0000232 except TypeError:
233 data = first.more()
234 if data:
235 self.producer_fifo.appendleft(data)
236 else:
237 del self.producer_fifo[0]
238 continue
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000239
Josiah Carlsond74900e2008-07-07 04:15:08 +0000240 if isinstance(data, str) and self.use_encoding:
241 data = bytes(data, self.encoding)
242
243 # send the data
244 try:
245 num_sent = self.send(data)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200246 except OSError:
Tim Peters146965a2001-01-14 18:09:23 +0000247 self.handle_error()
248 return
249
Josiah Carlsond74900e2008-07-07 04:15:08 +0000250 if num_sent:
251 if num_sent < len(data) or obs < len(first):
252 self.producer_fifo[0] = first[num_sent:]
253 else:
254 del self.producer_fifo[0]
255 # we tried to send some actual data
256 return
257
Tim Peters146965a2001-01-14 18:09:23 +0000258 def discard_buffers (self):
259 # Emergencies only!
Guido van Rossum076da092007-07-12 07:58:54 +0000260 self.ac_in_buffer = b''
Josiah Carlsond74900e2008-07-07 04:15:08 +0000261 del self.incoming[:]
262 self.producer_fifo.clear()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000263
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000264class simple_producer:
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000265
Tim Peters146965a2001-01-14 18:09:23 +0000266 def __init__ (self, data, buffer_size=512):
267 self.data = data
268 self.buffer_size = buffer_size
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000269
Tim Peters146965a2001-01-14 18:09:23 +0000270 def more (self):
271 if len (self.data) > self.buffer_size:
272 result = self.data[:self.buffer_size]
273 self.data = self.data[self.buffer_size:]
274 return result
275 else:
276 result = self.data
Guido van Rossum076da092007-07-12 07:58:54 +0000277 self.data = b''
Tim Peters146965a2001-01-14 18:09:23 +0000278 return result
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000279
280class fifo:
Tim Peters146965a2001-01-14 18:09:23 +0000281 def __init__ (self, list=None):
282 if not list:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000283 self.list = deque()
Tim Peters146965a2001-01-14 18:09:23 +0000284 else:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000285 self.list = deque(list)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000286
Tim Peters146965a2001-01-14 18:09:23 +0000287 def __len__ (self):
288 return len(self.list)
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000289
Tim Peters146965a2001-01-14 18:09:23 +0000290 def is_empty (self):
Armin Rigob562bc62004-09-27 17:49:00 +0000291 return not self.list
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000292
Tim Peters146965a2001-01-14 18:09:23 +0000293 def first (self):
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000294 return self.list[0]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000295
Tim Peters146965a2001-01-14 18:09:23 +0000296 def push (self, data):
Raymond Hettingerac093c62004-02-07 03:19:10 +0000297 self.list.append(data)
Tim Peters146965a2001-01-14 18:09:23 +0000298
299 def pop (self):
300 if self.list:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000301 return (1, self.list.popleft())
Tim Peters146965a2001-01-14 18:09:23 +0000302 else:
303 return (0, None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000304
305# Given 'haystack', see if any prefix of 'needle' is at its end. This
306# assumes an exact match has already been checked. Return the number of
307# characters matched.
308# for example:
309# f_p_a_e ("qwerty\r", "\r\n") => 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000310# f_p_a_e ("qwertydkjf", "\r\n") => 0
Andrew M. Kuchlingc63a3962002-03-20 02:22:58 +0000311# f_p_a_e ("qwerty\r\n", "\r\n") => <undefined>
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000312
313# this could maybe be made faster with a computed regex?
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000314# [answer: no; circa Python-2.0, Jan 2001]
Andrew M. Kuchlingc63a3962002-03-20 02:22:58 +0000315# new python: 28961/s
316# old python: 18307/s
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000317# re: 12820/s
318# regex: 14035/s
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000319
320def find_prefix_at_end (haystack, needle):
Tim Peters863ac442002-04-16 01:38:40 +0000321 l = len(needle) - 1
322 while l and not haystack.endswith(needle[:l]):
323 l -= 1
324 return l