frame.py 8.0 KB

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