blob: fc6cabe7f25f2b6ddbc01829d673af16988c0a1e [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 asyncore
Raymond Hettingerac093c62004-02-07 03:19:10 +000049from collections import deque
Guido van Rossum0039d7b1999-01-12 20:19:27 +000050
Josiah Carlsond74900e2008-07-07 04:15:08 +000051
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020052class 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
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020058 ac_in_buffer_size = 65536
59 ac_out_buffer_size = 65536
Guido van Rossum0039d7b1999-01-12 20:19:27 +000060
Josiah Carlsond74900e2008-07-07 04:15:08 +000061 # we don't want to enable the use of encoding by default, because that is a
62 # sign of an application bug that we don't want to pass silently
63
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020064 use_encoding = 0
65 encoding = 'latin-1'
Josiah Carlsond74900e2008-07-07 04:15:08 +000066
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020067 def __init__(self, sock=None, map=None):
Josiah Carlsond74900e2008-07-07 04:15:08 +000068 # for string terminator matching
Guido van Rossum076da092007-07-12 07:58:54 +000069 self.ac_in_buffer = b''
Josiah Carlsond74900e2008-07-07 04:15:08 +000070
Serhiy Storchaka50254c52013-08-29 11:35:43 +030071 # we use a list here rather than io.BytesIO for a few reasons...
72 # del lst[:] is faster than bio.truncate(0)
73 # lst = [] is faster than bio.truncate(0)
Josiah Carlsond74900e2008-07-07 04:15:08 +000074 self.incoming = []
75
76 # we toss the use of the "simple producer" and replace it with
77 # a pure deque, which the original fifo was a wrapping of
78 self.producer_fifo = deque()
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020079 asyncore.dispatcher.__init__(self, sock, map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +000080
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000081 def collect_incoming_data(self, data):
Collin Winterce36ad82007-08-30 01:19:48 +000082 raise NotImplementedError("must be implemented in subclass")
Tim Peters863ac442002-04-16 01:38:40 +000083
Josiah Carlsond74900e2008-07-07 04:15:08 +000084 def _collect_incoming_data(self, data):
85 self.incoming.append(data)
86
87 def _get_data(self):
88 d = b''.join(self.incoming)
89 del self.incoming[:]
90 return d
91
Andrew M. Kuchling7dd5f3c2002-03-08 18:27:11 +000092 def found_terminator(self):
Collin Winterce36ad82007-08-30 01:19:48 +000093 raise NotImplementedError("must be implemented in subclass")
Tim Peters863ac442002-04-16 01:38:40 +000094
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020095 def set_terminator(self, term):
96 """Set the input delimiter.
97
98 Can be a fixed string of any length, an integer, or None.
99 """
Josiah Carlsond74900e2008-07-07 04:15:08 +0000100 if isinstance(term, str) and self.use_encoding:
101 term = bytes(term, self.encoding)
Victor Stinner630a4f62014-07-08 00:26:36 +0200102 elif isinstance(term, int) and term < 0:
103 raise ValueError('the number of received bytes must be positive')
Tim Peters146965a2001-01-14 18:09:23 +0000104 self.terminator = term
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000105
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200106 def get_terminator(self):
Tim Peters146965a2001-01-14 18:09:23 +0000107 return self.terminator
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000108
Tim Peters146965a2001-01-14 18:09:23 +0000109 # grab some more data from the socket,
110 # throw it to the collector method,
111 # check for the terminator,
112 # if found, transition to the next state.
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000113
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200114 def handle_read(self):
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000115
Tim Peters146965a2001-01-14 18:09:23 +0000116 try:
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200117 data = self.recv(self.ac_in_buffer_size)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200118 except OSError as why:
Tim Peters146965a2001-01-14 18:09:23 +0000119 self.handle_error()
120 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000121
Josiah Carlsond74900e2008-07-07 04:15:08 +0000122 if isinstance(data, str) and self.use_encoding:
123 data = bytes(str, self.encoding)
124 self.ac_in_buffer = self.ac_in_buffer + data
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000125
Tim Peters146965a2001-01-14 18:09:23 +0000126 # Continue to search for self.terminator in self.ac_in_buffer,
127 # while calling self.collect_incoming_data. The while loop
128 # is necessary because we might read several data+terminator
Josiah Carlsond74900e2008-07-07 04:15:08 +0000129 # combos with a single recv(4096).
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000130
Tim Peters146965a2001-01-14 18:09:23 +0000131 while self.ac_in_buffer:
132 lb = len(self.ac_in_buffer)
133 terminator = self.get_terminator()
Andrew M. Kuchlingca69f022005-06-09 14:59:45 +0000134 if not terminator:
Tim Peters146965a2001-01-14 18:09:23 +0000135 # no terminator, collect it all
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200136 self.collect_incoming_data(self.ac_in_buffer)
Guido van Rossum806c2462007-08-06 23:33:07 +0000137 self.ac_in_buffer = b''
Josiah Carlsond74900e2008-07-07 04:15:08 +0000138 elif isinstance(terminator, int):
Tim Peters146965a2001-01-14 18:09:23 +0000139 # numeric terminator
140 n = terminator
141 if lb < n:
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200142 self.collect_incoming_data(self.ac_in_buffer)
Guido van Rossum076da092007-07-12 07:58:54 +0000143 self.ac_in_buffer = b''
Tim Peters146965a2001-01-14 18:09:23 +0000144 self.terminator = self.terminator - lb
145 else:
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200146 self.collect_incoming_data(self.ac_in_buffer[:n])
Tim Peters146965a2001-01-14 18:09:23 +0000147 self.ac_in_buffer = self.ac_in_buffer[n:]
148 self.terminator = 0
149 self.found_terminator()
150 else:
151 # 3 cases:
152 # 1) end of buffer matches terminator exactly:
153 # collect data, transition
154 # 2) end of buffer matches some prefix:
155 # collect data to the prefix
156 # 3) end of buffer does not match any prefix:
157 # collect data
158 terminator_len = len(terminator)
Tim Petersb5d13922001-04-05 22:38:32 +0000159 index = self.ac_in_buffer.find(terminator)
Tim Peters146965a2001-01-14 18:09:23 +0000160 if index != -1:
161 # we found the terminator
162 if index > 0:
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200163 # don't bother reporting the empty string
164 # (source of subtle bugs)
165 self.collect_incoming_data(self.ac_in_buffer[:index])
Tim Peters146965a2001-01-14 18:09:23 +0000166 self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200167 # This does the Right Thing if the terminator
168 # is changed here.
Tim Peters146965a2001-01-14 18:09:23 +0000169 self.found_terminator()
170 else:
171 # check for a prefix of the terminator
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200172 index = find_prefix_at_end(self.ac_in_buffer, terminator)
Tim Peters146965a2001-01-14 18:09:23 +0000173 if index:
174 if index != lb:
175 # we found a prefix, collect up to the prefix
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200176 self.collect_incoming_data(self.ac_in_buffer[:-index])
Tim Peters146965a2001-01-14 18:09:23 +0000177 self.ac_in_buffer = self.ac_in_buffer[-index:]
178 break
179 else:
180 # no prefix, collect it all
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200181 self.collect_incoming_data(self.ac_in_buffer)
Guido van Rossum076da092007-07-12 07:58:54 +0000182 self.ac_in_buffer = b''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000183
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200184 def handle_write(self):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000185 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000186
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200187 def handle_close(self):
Tim Peters146965a2001-01-14 18:09:23 +0000188 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000189
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200190 def push(self, data):
Victor Stinnerd9e810a2014-07-08 00:00:30 +0200191 if not isinstance(data, (bytes, bytearray, memoryview)):
192 raise TypeError('data argument must be byte-ish (%r)',
193 type(data))
Josiah Carlsond74900e2008-07-07 04:15:08 +0000194 sabs = self.ac_out_buffer_size
195 if len(data) > sabs:
196 for i in range(0, len(data), sabs):
197 self.producer_fifo.append(data[i:i+sabs])
198 else:
199 self.producer_fifo.append(data)
Tim Peters146965a2001-01-14 18:09:23 +0000200 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000201
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200202 def push_with_producer(self, producer):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000203 self.producer_fifo.append(producer)
Tim Peters146965a2001-01-14 18:09:23 +0000204 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000205
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200206 def readable(self):
Tim Peters146965a2001-01-14 18:09:23 +0000207 "predicate for inclusion in the readable for select()"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000208 # cannot use the old predicate, it violates the claim of the
209 # set_terminator method.
210
211 # return (len(self.ac_in_buffer) <= self.ac_in_buffer_size)
212 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000213
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200214 def writable(self):
Tim Peters146965a2001-01-14 18:09:23 +0000215 "predicate for inclusion in the writable for select()"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000216 return self.producer_fifo or (not self.connected)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000217
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200218 def close_when_done(self):
Tim Peters146965a2001-01-14 18:09:23 +0000219 "automatically close this channel once the outgoing queue is empty"
Josiah Carlsond74900e2008-07-07 04:15:08 +0000220 self.producer_fifo.append(None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000221
Josiah Carlsond74900e2008-07-07 04:15:08 +0000222 def initiate_send(self):
223 while self.producer_fifo and self.connected:
224 first = self.producer_fifo[0]
225 # handle empty string/buffer or None entry
226 if not first:
227 del self.producer_fifo[0]
228 if first is None:
Josiah Carlsond74900e2008-07-07 04:15:08 +0000229 self.handle_close()
Tim Peters146965a2001-01-14 18:09:23 +0000230 return
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000231
Josiah Carlsond74900e2008-07-07 04:15:08 +0000232 # handle classic producer behavior
233 obs = self.ac_out_buffer_size
Tim Peters146965a2001-01-14 18:09:23 +0000234 try:
Giampaolo Rodola'd9f38bc2012-08-04 14:38:16 +0200235 data = first[:obs]
Josiah Carlsond74900e2008-07-07 04:15:08 +0000236 except TypeError:
237 data = first.more()
238 if data:
239 self.producer_fifo.appendleft(data)
240 else:
241 del self.producer_fifo[0]
242 continue
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000243
Josiah Carlsond74900e2008-07-07 04:15:08 +0000244 if isinstance(data, str) and self.use_encoding:
245 data = bytes(data, self.encoding)
246
247 # send the data
248 try:
249 num_sent = self.send(data)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200250 except OSError:
Tim Peters146965a2001-01-14 18:09:23 +0000251 self.handle_error()
252 return
253
Josiah Carlsond74900e2008-07-07 04:15:08 +0000254 if num_sent:
255 if num_sent < len(data) or obs < len(first):
256 self.producer_fifo[0] = first[num_sent:]
257 else:
258 del self.producer_fifo[0]
259 # we tried to send some actual data
260 return
261
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200262 def discard_buffers(self):
Tim Peters146965a2001-01-14 18:09:23 +0000263 # Emergencies only!
Guido van Rossum076da092007-07-12 07:58:54 +0000264 self.ac_in_buffer = b''
Josiah Carlsond74900e2008-07-07 04:15:08 +0000265 del self.incoming[:]
266 self.producer_fifo.clear()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000267
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200268
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000269class simple_producer:
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000270
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200271 def __init__(self, data, buffer_size=512):
Tim Peters146965a2001-01-14 18:09:23 +0000272 self.data = data
273 self.buffer_size = buffer_size
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000274
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200275 def more(self):
276 if len(self.data) > self.buffer_size:
Tim Peters146965a2001-01-14 18:09:23 +0000277 result = self.data[:self.buffer_size]
278 self.data = self.data[self.buffer_size:]
279 return result
280 else:
281 result = self.data
Guido van Rossum076da092007-07-12 07:58:54 +0000282 self.data = b''
Tim Peters146965a2001-01-14 18:09:23 +0000283 return result
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000284
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200285
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000286class fifo:
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200287 def __init__(self, list=None):
Giampaolo Rodola'bd048762014-06-21 13:58:30 +0200288 import warnings
289 warnings.warn('fifo class will be removed in Python 3.6',
290 DeprecationWarning, stacklevel=2)
Tim Peters146965a2001-01-14 18:09:23 +0000291 if not list:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000292 self.list = deque()
Tim Peters146965a2001-01-14 18:09:23 +0000293 else:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000294 self.list = deque(list)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000295
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200296 def __len__(self):
Tim Peters146965a2001-01-14 18:09:23 +0000297 return len(self.list)
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000298
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200299 def is_empty(self):
Armin Rigob562bc62004-09-27 17:49:00 +0000300 return not self.list
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000301
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200302 def first(self):
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000303 return self.list[0]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000304
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200305 def push(self, data):
Raymond Hettingerac093c62004-02-07 03:19:10 +0000306 self.list.append(data)
Tim Peters146965a2001-01-14 18:09:23 +0000307
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200308 def pop(self):
Tim Peters146965a2001-01-14 18:09:23 +0000309 if self.list:
Raymond Hettingerac093c62004-02-07 03:19:10 +0000310 return (1, self.list.popleft())
Tim Peters146965a2001-01-14 18:09:23 +0000311 else:
312 return (0, None)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000313
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200314
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000315# Given 'haystack', see if any prefix of 'needle' is at its end. This
316# assumes an exact match has already been checked. Return the number of
317# characters matched.
318# for example:
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200319# f_p_a_e("qwerty\r", "\r\n") => 1
320# f_p_a_e("qwertydkjf", "\r\n") => 0
321# f_p_a_e("qwerty\r\n", "\r\n") => <undefined>
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000322
323# this could maybe be made faster with a computed regex?
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000324# [answer: no; circa Python-2.0, Jan 2001]
Andrew M. Kuchlingc63a3962002-03-20 02:22:58 +0000325# new python: 28961/s
326# old python: 18307/s
Andrew M. Kuchlingd305f512001-01-24 21:10:55 +0000327# re: 12820/s
328# regex: 14035/s
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000329
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200330def find_prefix_at_end(haystack, needle):
Tim Peters863ac442002-04-16 01:38:40 +0000331 l = len(needle) - 1
332 while l and not haystack.endswith(needle[:l]):
333 l -= 1
334 return l