asynchat.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. import errno
  45. import socket
  46. from collections import deque
  47. from sys import py3kwarning
  48. from warnings import filterwarnings, catch_warnings
  49. _BLOCKING_IO_ERRORS = (errno.EAGAIN, errno.EALREADY, errno.EINPROGRESS,
  50. errno.EWOULDBLOCK)
  51. class async_chat (asyncore.dispatcher):
  52. """This is an abstract class. You must derive from this class, and add
  53. the two methods collect_incoming_data() and found_terminator()"""
  54. # these are overridable defaults
  55. ac_in_buffer_size = 4096
  56. ac_out_buffer_size = 4096
  57. def __init__ (self, sock=None, map=None):
  58. # for string terminator matching
  59. self.ac_in_buffer = ''
  60. # we use a list here rather than cStringIO for a few reasons...
  61. # del lst[:] is faster than sio.truncate(0)
  62. # lst = [] is faster than sio.truncate(0)
  63. # cStringIO will be gaining unicode support in py3k, which
  64. # will negatively affect the performance of bytes compared to
  65. # a ''.join() equivalent
  66. self.incoming = []
  67. # we toss the use of the "simple producer" and replace it with
  68. # a pure deque, which the original fifo was a wrapping of
  69. self.producer_fifo = deque()
  70. asyncore.dispatcher.__init__ (self, sock, map)
  71. def collect_incoming_data(self, data):
  72. raise NotImplementedError("must be implemented in subclass")
  73. def _collect_incoming_data(self, data):
  74. self.incoming.append(data)
  75. def _get_data(self):
  76. d = ''.join(self.incoming)
  77. del self.incoming[:]
  78. return d
  79. def found_terminator(self):
  80. raise NotImplementedError("must be implemented in subclass")
  81. def set_terminator (self, term):
  82. "Set the input delimiter. Can be a fixed string of any length, an integer, or None"
  83. self.terminator = term
  84. def get_terminator (self):
  85. return self.terminator
  86. # grab some more data from the socket,
  87. # throw it to the collector method,
  88. # check for the terminator,
  89. # if found, transition to the next state.
  90. def handle_read (self):
  91. try:
  92. data = self.recv (self.ac_in_buffer_size)
  93. except socket.error, why:
  94. if why.args[0] in _BLOCKING_IO_ERRORS:
  95. return
  96. self.handle_error()
  97. return
  98. self.ac_in_buffer = self.ac_in_buffer + data
  99. # Continue to search for self.terminator in self.ac_in_buffer,
  100. # while calling self.collect_incoming_data. The while loop
  101. # is necessary because we might read several data+terminator
  102. # combos with a single recv(4096).
  103. while self.ac_in_buffer:
  104. lb = len(self.ac_in_buffer)
  105. terminator = self.get_terminator()
  106. if not terminator:
  107. # no terminator, collect it all
  108. self.collect_incoming_data (self.ac_in_buffer)
  109. self.ac_in_buffer = ''
  110. elif isinstance(terminator, int) or isinstance(terminator, long):
  111. # numeric terminator
  112. n = terminator
  113. if lb < n:
  114. self.collect_incoming_data (self.ac_in_buffer)
  115. self.ac_in_buffer = ''
  116. self.terminator = self.terminator - lb
  117. else:
  118. self.collect_incoming_data (self.ac_in_buffer[:n])
  119. self.ac_in_buffer = self.ac_in_buffer[n:]
  120. self.terminator = 0
  121. self.found_terminator()
  122. else:
  123. # 3 cases:
  124. # 1) end of buffer matches terminator exactly:
  125. # collect data, transition
  126. # 2) end of buffer matches some prefix:
  127. # collect data to the prefix
  128. # 3) end of buffer does not match any prefix:
  129. # collect data
  130. terminator_len = len(terminator)
  131. index = self.ac_in_buffer.find(terminator)
  132. if index != -1:
  133. # we found the terminator
  134. if index > 0:
  135. # don't bother reporting the empty string (source of subtle bugs)
  136. self.collect_incoming_data (self.ac_in_buffer[:index])
  137. self.ac_in_buffer = self.ac_in_buffer[index+terminator_len:]
  138. # This does the Right Thing if the terminator is changed here.
  139. self.found_terminator()
  140. else:
  141. # check for a prefix of the terminator
  142. index = find_prefix_at_end (self.ac_in_buffer, terminator)
  143. if index:
  144. if index != lb:
  145. # we found a prefix, collect up to the prefix
  146. self.collect_incoming_data (self.ac_in_buffer[:-index])
  147. self.ac_in_buffer = self.ac_in_buffer[-index:]
  148. break
  149. else:
  150. # no prefix, collect it all
  151. self.collect_incoming_data (self.ac_in_buffer)
  152. self.ac_in_buffer = ''
  153. def handle_write (self):
  154. self.initiate_send()
  155. def handle_close (self):
  156. self.close()
  157. def push (self, data):
  158. sabs = self.ac_out_buffer_size
  159. if len(data) > sabs:
  160. for i in xrange(0, len(data), sabs):
  161. self.producer_fifo.append(data[i:i+sabs])
  162. else:
  163. self.producer_fifo.append(data)
  164. self.initiate_send()
  165. def push_with_producer (self, producer):
  166. self.producer_fifo.append(producer)
  167. self.initiate_send()
  168. def readable (self):
  169. "predicate for inclusion in the readable for select()"
  170. # cannot use the old predicate, it violates the claim of the
  171. # set_terminator method.
  172. # return (len(self.ac_in_buffer) <= self.ac_in_buffer_size)
  173. return 1
  174. def writable (self):
  175. "predicate for inclusion in the writable for select()"
  176. return self.producer_fifo or (not self.connected)
  177. def close_when_done (self):
  178. "automatically close this channel once the outgoing queue is empty"
  179. self.producer_fifo.append(None)
  180. def initiate_send(self):
  181. while self.producer_fifo and self.connected:
  182. first = self.producer_fifo[0]
  183. # handle empty string/buffer or None entry
  184. if not first:
  185. del self.producer_fifo[0]
  186. if first is None:
  187. self.handle_close()
  188. return
  189. # handle classic producer behavior
  190. obs = self.ac_out_buffer_size
  191. try:
  192. with catch_warnings():
  193. if py3kwarning:
  194. filterwarnings("ignore", ".*buffer", DeprecationWarning)
  195. data = buffer(first, 0, obs)
  196. except TypeError:
  197. data = first.more()
  198. if data:
  199. self.producer_fifo.appendleft(data)
  200. else:
  201. del self.producer_fifo[0]
  202. continue
  203. # send the data
  204. try:
  205. num_sent = self.send(data)
  206. except socket.error:
  207. self.handle_error()
  208. return
  209. if num_sent:
  210. if num_sent < len(data) or obs < len(first):
  211. self.producer_fifo[0] = first[num_sent:]
  212. else:
  213. del self.producer_fifo[0]
  214. # we tried to send some actual data
  215. return
  216. def discard_buffers (self):
  217. # Emergencies only!
  218. self.ac_in_buffer = ''
  219. del self.incoming[:]
  220. self.producer_fifo.clear()
  221. class simple_producer:
  222. def __init__ (self, data, buffer_size=512):
  223. self.data = data
  224. self.buffer_size = buffer_size
  225. def more (self):
  226. if len (self.data) > self.buffer_size:
  227. result = self.data[:self.buffer_size]
  228. self.data = self.data[self.buffer_size:]
  229. return result
  230. else:
  231. result = self.data
  232. self.data = ''
  233. return result
  234. class fifo:
  235. def __init__ (self, list=None):
  236. if not list:
  237. self.list = deque()
  238. else:
  239. self.list = deque(list)
  240. def __len__ (self):
  241. return len(self.list)
  242. def is_empty (self):
  243. return not self.list
  244. def first (self):
  245. return self.list[0]
  246. def push (self, data):
  247. self.list.append(data)
  248. def pop (self):
  249. if self.list:
  250. return (1, self.list.popleft())
  251. else:
  252. return (0, None)
  253. # Given 'haystack', see if any prefix of 'needle' is at its end. This
  254. # assumes an exact match has already been checked. Return the number of
  255. # characters matched.
  256. # for example:
  257. # f_p_a_e ("qwerty\r", "\r\n") => 1
  258. # f_p_a_e ("qwertydkjf", "\r\n") => 0
  259. # f_p_a_e ("qwerty\r\n", "\r\n") => <undefined>
  260. # this could maybe be made faster with a computed regex?
  261. # [answer: no; circa Python-2.0, Jan 2001]
  262. # new python: 28961/s
  263. # old python: 18307/s
  264. # re: 12820/s
  265. # regex: 14035/s
  266. def find_prefix_at_end (haystack, needle):
  267. l = len(needle) - 1
  268. while l and not haystack.endswith(needle[:l]):
  269. l -= 1
  270. return l