frame.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import struct
  2. from os import urandom
  3. from exceptions import SocketClosed
  4. OPCODE_CONTINUATION = 0x0
  5. OPCODE_TEXT = 0x1
  6. OPCODE_BINARY = 0x2
  7. OPCODE_CLOSE = 0x8
  8. OPCODE_PING = 0x9
  9. OPCODE_PONG = 0xA
  10. CLOSE_NORMAL = 1000
  11. CLOSE_GOING_AWAY = 1001
  12. CLOSE_PROTOCOL_ERROR = 1002
  13. CLOSE_NOACCEPT_DTYPE = 1003
  14. CLOSE_INVALID_DATA = 1007
  15. CLOSE_POLICY = 1008
  16. CLOSE_MESSAGE_TOOBIG = 1009
  17. CLOSE_MISSING_EXTENSIONS = 1010
  18. CLOSE_UNABLE = 1011
  19. class Frame(object):
  20. """
  21. A Frame instance represents a web socket data frame as defined in RFC 6455.
  22. To encoding a frame for sending it over a socket, use Frame.pack(). To
  23. receive and decode a frame from a socket, use receive_frame().
  24. """
  25. def __init__(self, opcode, payload, masking_key='', mask=False, final=True,
  26. rsv1=False, rsv2=False, rsv3=False):
  27. """
  28. Create a new frame.
  29. `opcode` is one of the constants as defined above.
  30. `payload` is a string of bytes containing the data sendt in the frame.
  31. `masking_key` is an optional custom key to use for masking, or `mask`
  32. can be used instead to let this constructor generate a random masking
  33. key.
  34. `final` is a boolean indicating whether this frame is the last in a
  35. chain of fragments.
  36. `rsv1`, `rsv2` and `rsv3` are booleans indicating bit values for RSV1,
  37. RVS2 and RSV3, which are only non-zero if defined so by extensions.
  38. """
  39. if mask:
  40. masking_key = urandom(4)
  41. if len(masking_key) not in (0, 4):
  42. raise ValueError('invalid masking key "%s"' % masking_key)
  43. self.final = final
  44. self.rsv1 = rsv1
  45. self.rsv2 = rsv2
  46. self.rsv3 = rsv3
  47. self.opcode = opcode
  48. self.masking_key = masking_key
  49. self.payload = payload
  50. def pack(self):
  51. """
  52. Pack the frame into a string according to the following scheme:
  53. +-+-+-+-+-------+-+-------------+-------------------------------+
  54. |F|R|R|R| opcode|M| Payload len | Extended payload length |
  55. |I|S|S|S| (4) |A| (7) | (16/64) |
  56. |N|V|V|V| |S| | (if payload len==126/127) |
  57. | |1|2|3| |K| | |
  58. +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
  59. | Extended payload length continued, if payload len == 127 |
  60. + - - - - - - - - - - - - - - - +-------------------------------+
  61. | |Masking-key, if MASK set to 1 |
  62. +-------------------------------+-------------------------------+
  63. | Masking-key (continued) | Payload Data |
  64. +-------------------------------- - - - - - - - - - - - - - - - +
  65. : Payload Data continued ... :
  66. + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
  67. | Payload Data continued ... |
  68. +---------------------------------------------------------------+
  69. """
  70. header = struct.pack('!B', (self.fin << 7) | (self.rsv1 << 6) |
  71. (self.rsv2 << 5) | (self.rsv3 << 4) | self.opcode)
  72. mask = bool(self.masking_key) << 7
  73. payload_len = len(self.payload)
  74. if payload_len <= 125:
  75. header += struct.pack('!B', mask | payload_len)
  76. elif payload_len < (1 << 16):
  77. header += struct.pack('!BH', mask | 126, payload_len)
  78. elif payload_len < (1 << 63):
  79. header += struct.pack('!BQ', mask | 127, payload_len)
  80. else:
  81. # FIXME: RFC 6455 defines an action for this...
  82. raise Exception('the payload length is too damn high!')
  83. if mask:
  84. return header + self.masking_key + self.mask_payload()
  85. return header + self.payload
  86. def mask_payload(self):
  87. return mask(self.masking_key, self.payload)
  88. def fragment(self, fragment_size, mask=False):
  89. """
  90. Fragment the frame into a chain of fragment frames:
  91. - An initial frame with non-zero opcode
  92. - Zero or more frames with opcode = 0 and final = False
  93. - A final frame with opcode = 0 and final = True
  94. The first and last frame may be the same frame, having a non-zero
  95. opcode and final = True. Thus, this function returns a list containing
  96. at least a single frame.
  97. `fragment_size` indicates the maximum payload size of each fragment.
  98. The payload of the original frame is split into one or more parts, and
  99. each part is converted to a Frame instance.
  100. `mask` is a boolean (default False) indicating whether the payloads
  101. should be masked. If True, each frame is assigned a randomly generated
  102. masking key.
  103. """
  104. frames = []
  105. for start in range(0, len(self.payload), fragment_size):
  106. payload = self.payload[start:start + fragment_size]
  107. frames.append(Frame(OPCODE_CONTINUATION, payload, mask=mask,
  108. final=False))
  109. frames[0].opcode = self.opcode
  110. frames[-1].final = True
  111. return frames
  112. def __str__(self):
  113. s = '<%s opcode=0x%X len=%d' \
  114. % (self.__class__.__name__, self.opcode, len(self.payload))
  115. if self.masking_key:
  116. s += ' masking_key=%4s' % self.masking_key
  117. return s + '>'
  118. class ControlFrame(Frame):
  119. """
  120. A Control frame is a frame with an opcode OPCODE_CLOSE, OPCODE_PING or
  121. OPCODE_PONG. These frames must be handled as defined by RFC 6455, and
  122. """
  123. def fragment(self, fragment_size, mask=False):
  124. """
  125. Control frames must not be fragmented.
  126. """
  127. raise TypeError('control frames must not be fragmented')
  128. def pack(self):
  129. """
  130. Same as Frame.pack(), but asserts that the payload size does not exceed
  131. 125 bytes.
  132. """
  133. if len(self.payload) > 125:
  134. raise ValueError('control frames must not be larger than 125' \
  135. 'bytes')
  136. return Frame.pack(self)
  137. def unpack_close(self):
  138. """
  139. Unpack a close message into a status code and a reason. If no payload
  140. is given, the code is None and the reason is an empty string.
  141. """
  142. if self.payload:
  143. code = struct.unpack('!H', self.payload[:2])
  144. reason = self.payload[2:]
  145. else:
  146. code = None
  147. reason = ''
  148. return code, reason
  149. def receive_frame(sock):
  150. """
  151. Receive a single frame on socket `sock`. The frame scheme is explained in
  152. the docs of Frame.pack().
  153. """
  154. b1, b2 = struct.unpack('!BB', recvn(sock, 2))
  155. final = bool(b1 & 0x80)
  156. rsv1 = bool(b1 & 0x40)
  157. rsv2 = bool(b1 & 0x20)
  158. rsv3 = bool(b1 & 0x10)
  159. opcode = b1 & 0x0F
  160. mask = bool(b2 & 0x80)
  161. payload_len = b2 & 0x7F
  162. if payload_len == 126:
  163. payload_len = struct.unpack('!H', recvn(sock, 2))
  164. elif payload_len == 127:
  165. payload_len = struct.unpack('!Q', recvn(sock, 8))
  166. if mask:
  167. masking_key = recvn(sock, 4)
  168. payload = mask(masking_key, recvn(sock, payload_len))
  169. else:
  170. masking_key = ''
  171. payload = recvn(sock, payload_len)
  172. # Control frames have most significant bit 1
  173. cls = ControlFrame if opcode & 0x8 else Frame
  174. return cls(opcode, payload, masking_key=masking_key, final=final,
  175. rsv1=rsv1, rsv2=rsv2, rsv3=rsv3)
  176. def recvn(sock, n):
  177. """
  178. Keep receiving data from `sock` until exactly `n` bytes have been read.
  179. """
  180. data = ''
  181. while len(data) < n:
  182. received = sock.recv(n - len(data))
  183. if not len(received):
  184. raise SocketClosed()
  185. data += received
  186. return data
  187. def mask(key, original):
  188. """
  189. Mask an octet string using the given masking key.
  190. The following masking algorithm is used, as defined in RFC 6455:
  191. for each octet:
  192. j = i MOD 4
  193. transformed-octet-i = original-octet-i XOR masking-key-octet-j
  194. """
  195. if len(key) != 4:
  196. raise ValueError('invalid masking key "%s"' % key)
  197. key = map(ord, key)
  198. masked = bytearray(original)
  199. for i in xrange(len(masked)):
  200. masked[i] ^= key[i % 4]
  201. return masked