asynchat.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. # -*- Mode: Python; tab-width: 4 -*-
  2. # Id: asynchat.py,v 2.26 2000/09/07 22:29:26 rushing Exp
  3. # Author: Sam Rushing <rushing@nightmare.com>
  4. # ======================================================================
  5. # Copyright 1996 by Sam Rushing
  6. #
  7. # All Rights Reserved
  8. #
  9. # Permission to use, copy, modify, and distribute this software and
  10. # its documentation for any purpose and without fee is hereby
  11. # granted, provided that the above copyright notice appear in all
  12. # copies and that both that copyright notice and this permission
  13. # notice appear in supporting documentation, and that the name of Sam
  14. # Rushing not be used in advertising or publicity pertaining to
  15. # distribution of the software without specific, written prior
  16. # permission.
  17. #
  18. # SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
  19. # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
  20. # NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
  21. # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  22. # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  23. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  24. # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  25. # ======================================================================
  26. r"""A class supporting chat-style (command/response) protocols.
  27. This class adds support for 'chat' style protocols - where one side
  28. sends a 'command', and the other sends a response (examples would be
  29. the common internet protocols - smtp, nntp, ftp, etc..).
  30. The handle_read() method looks at the input stream for the current
  31. 'terminator' (usually '\r\n' for single-line responses, '\r\n.\r\n'
  32. for multi-line output), calling self.found_terminator() on its
  33. receipt.
  34. for example:
  35. Say you build an async nntp client using this class. At the start
  36. of the connection, you'll have self.terminator set to '\r\n', in
  37. order to process the single-line greeting. Just before issuing a
  38. 'LIST' command you'll set it to '\r\n.\r\n'. The output of the LIST
  39. command will be accumulated (using your own 'collect_incoming_data'
  40. method) up to the terminator, and then control will be returned to
  41. you - by calling your self.found_terminator() method.
  42. """
  43. import asyncore
  44. from collections import deque
  45. class async_chat(asyncore.dispatcher):
  46. """This is an abstract class. You must derive from this class, and add
  47. the two methods collect_incoming_data() and found_terminator()"""
  48. # these are overridable defaults
  49. ac_in_buffer_size = 65536
  50. ac_out_buffer_size = 65536
  51. # we don't want to enable the use of encoding by default, because that is a
  52. # sign of an application bug that we don't want to pass silently
  53. use_encoding = 0
  54. encoding = 'latin-1'
  55. def __init__(self, sock=None, map=None):
  56. # for string terminator matching
  57. self.ac_in_buffer = b''
  58. # we use a list here rather than io.BytesIO for a few reasons...
  59. # del lst[:] is faster than bio.truncate(0)
  60. # lst = [] is faster than bio.truncate(0)
  61. self.incoming = []
  62. # we toss the use of the "simple producer" and replace it with
  63. # a pure deque, which the original fifo was a wrapping of
  64. self.producer_fifo = deque()
  65. asyncore.dispatcher.__init__(self, sock, map)
  66. def collect_incoming_data(self, data):
  67. raise NotImplementedError("must be implemented in subclass")
  68. def _collect_incoming_data(self, data):
  69. self.incoming.append(data)
  70. def _get_data(self):
  71. d = b''.join(self.incoming)
  72. del self.incoming[:]
  73. return d
  74. def found_terminator(self):
  75. raise NotImplementedError("must be implemented in subclass")
  76. def set_terminator(self, term):
  77. """Set the input delimiter.
  78. Can be a fixed string of any length, an integer, or None.
  79. """
  80. if isinstance(term, str) and self.use_encoding:
  81. term = bytes(term, self.encoding)
  82. elif isinstance(term, int) and term < 0:
  83. raise ValueError('the number of received bytes must be positive')
  84. self.terminator = term
  85. def get_terminator(self):
  86. return self.terminator
  87. # grab some more data from the socket,
  88. # throw it to the collector method,
  89. # check for the terminator,
  90. # if found, transition to the next state.
  91. def handle_read(self):
  92. try:
  93. data = self.recv(self.ac_in_buffer_size)
  94. except BlockingIOError:
  95. return
  96. except OSError:
  97. self.handle_error()
  98. return
  99. if isinstance(data, str) and self.use_encoding:
  100. data = bytes(str, self.encoding)
  101. self.ac_in_buffer = self.ac_in_buffer + data
  102. # Continue to search for self.terminator in self.ac_in_buffer,
  103. # while calling self.collect_incoming_data. The while loop
  104. # is necessary because we might read several data+terminator
  105. # combos with a single recv(4096).
  106. while self.ac_in_buffer:
  107. lb = len(self.ac_in_buffer)
  108. terminator = self.get_terminator()
  109. if not terminator:
  110. # no terminator, collect it all
  111. self.collect_incoming_data(self.ac_in_buffer)
  112. self.ac_in_buffer = b''
  113. elif isinstance(terminator, int):
  114. # numeric terminator
  115. n = terminator
  116. if lb < n:
  117. self.collect_incoming_data(self.ac_in_buffer)
  118. self.ac_in_buffer = b''
  119. self.terminator = self.terminator - lb
  120. else:
  121. self.collect_incoming_data(self.ac_in_buffer[:n])
  122. self.ac_in_buffer = self.ac_in_buffer[n:]
  123. self.terminator = 0
  124. self.found_terminator()
  125. else:
  126. # 3 cases:
  127. # 1) end of buffer matches terminator exactly:
  128. # collect data, transition
  129. # 2) end of buffer matches some prefix:
  130. # collect data to the prefix
  131. # 3) end of buffer does not match any prefix:
  132. # collect data
  133. terminator_len = len(terminator)
  134. index = self.ac_in_buffer.find(terminator)
  135. if index != -1:
  136. # we found the terminator
  137. if index > 0:
  138. # don't bother reporting the empty string
  139. # (source of subtle bugs)
  140. self.collect_incoming_data(self.ac_in_buffer[:index])
  141. self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
  142. # This does the Right Thing if the terminator
  143. # is changed here.
  144. self.found_terminator()
  145. else:
  146. # check for a prefix of the terminator
  147. index = find_prefix_at_end(self.ac_in_buffer, terminator)
  148. if index:
  149. if index != lb:
  150. # we found a prefix, collect up to the prefix
  151. self.collect_incoming_data(self.ac_in_buffer[:-index])
  152. self.ac_in_buffer = self.ac_in_buffer[-index:]
  153. break
  154. else:
  155. # no prefix, collect it all
  156. self.collect_incoming_data(self.ac_in_buffer)
  157. self.ac_in_buffer = b''
  158. def handle_write(self):
  159. self.initiate_send()
  160. def handle_close(self):
  161. self.close()
  162. def push(self, data):
  163. if not isinstance(data, (bytes, bytearray, memoryview)):
  164. raise TypeError('data argument must be byte-ish (%r)',
  165. type(data))
  166. sabs = self.ac_out_buffer_size
  167. if len(data) > sabs:
  168. for i in range(0, len(data), sabs):
  169. self.producer_fifo.append(data[i:i+sabs])
  170. else:
  171. self.producer_fifo.append(data)
  172. self.initiate_send()
  173. def push_with_producer(self, producer):
  174. self.producer_fifo.append(producer)
  175. self.initiate_send()
  176. def readable(self):
  177. "predicate for inclusion in the readable for select()"
  178. # cannot use the old predicate, it violates the claim of the
  179. # set_terminator method.
  180. # return (len(self.ac_in_buffer) <= self.ac_in_buffer_size)
  181. return 1
  182. def writable(self):
  183. "predicate for inclusion in the writable for select()"
  184. return self.producer_fifo or (not self.connected)
  185. def close_when_done(self):
  186. "automatically close this channel once the outgoing queue is empty"
  187. self.producer_fifo.append(None)
  188. def initiate_send(self):
  189. while self.producer_fifo and self.connected:
  190. first = self.producer_fifo[0]
  191. # handle empty string/buffer or None entry
  192. if not first:
  193. del self.producer_fifo[0]
  194. if first is None:
  195. self.handle_close()
  196. return
  197. # handle classic producer behavior
  198. obs = self.ac_out_buffer_size
  199. try:
  200. data = first[:obs]
  201. except TypeError:
  202. data = first.more()
  203. if data:
  204. self.producer_fifo.appendleft(data)
  205. else:
  206. del self.producer_fifo[0]
  207. continue
  208. if isinstance(data, str) and self.use_encoding:
  209. data = bytes(data, self.encoding)
  210. # send the data
  211. try:
  212. num_sent = self.send(data)
  213. except OSError:
  214. self.handle_error()
  215. return
  216. if num_sent:
  217. if num_sent < len(data) or obs < len(first):
  218. self.producer_fifo[0] = first[num_sent:]
  219. else:
  220. del self.producer_fifo[0]
  221. # we tried to send some actual data
  222. return
  223. def discard_buffers(self):
  224. # Emergencies only!
  225. self.ac_in_buffer = b''
  226. del self.incoming[:]
  227. self.producer_fifo.clear()
  228. class simple_producer:
  229. def __init__(self, data, buffer_size=512):
  230. self.data = data
  231. self.buffer_size = buffer_size
  232. def more(self):
  233. if len(self.data) > self.buffer_size:
  234. result = self.data[:self.buffer_size]
  235. self.data = self.data[self.buffer_size:]
  236. return result
  237. else:
  238. result = self.data
  239. self.data = b''
  240. return result
  241. # Given 'haystack', see if any prefix of 'needle' is at its end. This
  242. # assumes an exact match has already been checked. Return the number of
  243. # characters matched.
  244. # for example:
  245. # f_p_a_e("qwerty\r", "\r\n") => 1
  246. # f_p_a_e("qwertydkjf", "\r\n") => 0
  247. # f_p_a_e("qwerty\r\n", "\r\n") => <undefined>
  248. # this could maybe be made faster with a computed regex?
  249. # [answer: no; circa Python-2.0, Jan 2001]
  250. # new python: 28961/s
  251. # old python: 18307/s
  252. # re: 12820/s
  253. # regex: 14035/s
  254. def find_prefix_at_end(haystack, needle):
  255. l = len(needle) - 1
  256. while l and not haystack.endswith(needle[:l]):
  257. l -= 1
  258. return l