/gdata/tlslite/integration/AsyncStateMachine.py

http://radioappz.googlecode.com/ · Python · 235 lines · 117 code · 14 blank · 104 comment · 11 complexity · 3e4fb2df88065718e67a82e2d4328640 MD5 · raw file

  1. """
  2. A state machine for using TLS Lite with asynchronous I/O.
  3. """
  4. class AsyncStateMachine:
  5. """
  6. This is an abstract class that's used to integrate TLS Lite with
  7. asyncore and Twisted.
  8. This class signals wantsReadsEvent() and wantsWriteEvent(). When
  9. the underlying socket has become readable or writeable, the event
  10. should be passed to this class by calling inReadEvent() or
  11. inWriteEvent(). This class will then try to read or write through
  12. the socket, and will update its state appropriately.
  13. This class will forward higher-level events to its subclass. For
  14. example, when a complete TLS record has been received,
  15. outReadEvent() will be called with the decrypted data.
  16. """
  17. def __init__(self):
  18. self._clear()
  19. def _clear(self):
  20. #These store the various asynchronous operations (i.e.
  21. #generators). Only one of them, at most, is ever active at a
  22. #time.
  23. self.handshaker = None
  24. self.closer = None
  25. self.reader = None
  26. self.writer = None
  27. #This stores the result from the last call to the
  28. #currently active operation. If 0 it indicates that the
  29. #operation wants to read, if 1 it indicates that the
  30. #operation wants to write. If None, there is no active
  31. #operation.
  32. self.result = None
  33. def _checkAssert(self, maxActive=1):
  34. #This checks that only one operation, at most, is
  35. #active, and that self.result is set appropriately.
  36. activeOps = 0
  37. if self.handshaker:
  38. activeOps += 1
  39. if self.closer:
  40. activeOps += 1
  41. if self.reader:
  42. activeOps += 1
  43. if self.writer:
  44. activeOps += 1
  45. if self.result == None:
  46. if activeOps != 0:
  47. raise AssertionError()
  48. elif self.result in (0,1):
  49. if activeOps != 1:
  50. raise AssertionError()
  51. else:
  52. raise AssertionError()
  53. if activeOps > maxActive:
  54. raise AssertionError()
  55. def wantsReadEvent(self):
  56. """If the state machine wants to read.
  57. If an operation is active, this returns whether or not the
  58. operation wants to read from the socket. If an operation is
  59. not active, this returns None.
  60. @rtype: bool or None
  61. @return: If the state machine wants to read.
  62. """
  63. if self.result != None:
  64. return self.result == 0
  65. return None
  66. def wantsWriteEvent(self):
  67. """If the state machine wants to write.
  68. If an operation is active, this returns whether or not the
  69. operation wants to write to the socket. If an operation is
  70. not active, this returns None.
  71. @rtype: bool or None
  72. @return: If the state machine wants to write.
  73. """
  74. if self.result != None:
  75. return self.result == 1
  76. return None
  77. def outConnectEvent(self):
  78. """Called when a handshake operation completes.
  79. May be overridden in subclass.
  80. """
  81. pass
  82. def outCloseEvent(self):
  83. """Called when a close operation completes.
  84. May be overridden in subclass.
  85. """
  86. pass
  87. def outReadEvent(self, readBuffer):
  88. """Called when a read operation completes.
  89. May be overridden in subclass."""
  90. pass
  91. def outWriteEvent(self):
  92. """Called when a write operation completes.
  93. May be overridden in subclass."""
  94. pass
  95. def inReadEvent(self):
  96. """Tell the state machine it can read from the socket."""
  97. try:
  98. self._checkAssert()
  99. if self.handshaker:
  100. self._doHandshakeOp()
  101. elif self.closer:
  102. self._doCloseOp()
  103. elif self.reader:
  104. self._doReadOp()
  105. elif self.writer:
  106. self._doWriteOp()
  107. else:
  108. self.reader = self.tlsConnection.readAsync(16384)
  109. self._doReadOp()
  110. except:
  111. self._clear()
  112. raise
  113. def inWriteEvent(self):
  114. """Tell the state machine it can write to the socket."""
  115. try:
  116. self._checkAssert()
  117. if self.handshaker:
  118. self._doHandshakeOp()
  119. elif self.closer:
  120. self._doCloseOp()
  121. elif self.reader:
  122. self._doReadOp()
  123. elif self.writer:
  124. self._doWriteOp()
  125. else:
  126. self.outWriteEvent()
  127. except:
  128. self._clear()
  129. raise
  130. def _doHandshakeOp(self):
  131. try:
  132. self.result = self.handshaker.next()
  133. except StopIteration:
  134. self.handshaker = None
  135. self.result = None
  136. self.outConnectEvent()
  137. def _doCloseOp(self):
  138. try:
  139. self.result = self.closer.next()
  140. except StopIteration:
  141. self.closer = None
  142. self.result = None
  143. self.outCloseEvent()
  144. def _doReadOp(self):
  145. self.result = self.reader.next()
  146. if not self.result in (0,1):
  147. readBuffer = self.result
  148. self.reader = None
  149. self.result = None
  150. self.outReadEvent(readBuffer)
  151. def _doWriteOp(self):
  152. try:
  153. self.result = self.writer.next()
  154. except StopIteration:
  155. self.writer = None
  156. self.result = None
  157. def setHandshakeOp(self, handshaker):
  158. """Start a handshake operation.
  159. @type handshaker: generator
  160. @param handshaker: A generator created by using one of the
  161. asynchronous handshake functions (i.e. handshakeServerAsync, or
  162. handshakeClientxxx(..., async=True).
  163. """
  164. try:
  165. self._checkAssert(0)
  166. self.handshaker = handshaker
  167. self._doHandshakeOp()
  168. except:
  169. self._clear()
  170. raise
  171. def setServerHandshakeOp(self, **args):
  172. """Start a handshake operation.
  173. The arguments passed to this function will be forwarded to
  174. L{tlslite.TLSConnection.TLSConnection.handshakeServerAsync}.
  175. """
  176. handshaker = self.tlsConnection.handshakeServerAsync(**args)
  177. self.setHandshakeOp(handshaker)
  178. def setCloseOp(self):
  179. """Start a close operation.
  180. """
  181. try:
  182. self._checkAssert(0)
  183. self.closer = self.tlsConnection.closeAsync()
  184. self._doCloseOp()
  185. except:
  186. self._clear()
  187. raise
  188. def setWriteOp(self, writeBuffer):
  189. """Start a write operation.
  190. @type writeBuffer: str
  191. @param writeBuffer: The string to transmit.
  192. """
  193. try:
  194. self._checkAssert(0)
  195. self.writer = self.tlsConnection.writeAsync(writeBuffer)
  196. self._doWriteOp()
  197. except:
  198. self._clear()
  199. raise