frame.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. raise Exception('the payload length is too damn high!')
  77. if mask:
  78. return header + self.masking_key + self.mask_payload()
  79. return header + self.payload
  80. def mask_payload(self):
  81. return mask(self.masking_key, self.payload)
  82. def fragment(self, fragment_size, mask=False):
  83. """
  84. Fragment the frame into a chain of fragment frames:
  85. - An initial frame with non-zero opcode
  86. - Zero or more frames with opcode = 0 and final = False
  87. - A final frame with opcode = 0 and final = True
  88. The first and last frame may be the same frame, having a non-zero
  89. opcode and final = True. Thus, this function returns a list containing
  90. at least a single frame.
  91. `fragment_size` indicates the maximum payload size of each fragment.
  92. The payload of the original frame is split into one or more parts, and
  93. each part is converted to a Frame instance.
  94. `mask` is a boolean (default False) indicating whether the payloads
  95. should be masked. If True, each frame is assigned a randomly generated
  96. masking key.
  97. """
  98. frames = []
  99. for start in range(0, len(self.payload), fragment_size):
  100. payload = self.payload[start:start + fragment_size]
  101. key = urandom(4) if mask else ''
  102. frames.append(Frame(OPCODE_CONTINUATION, payload, key, False))
  103. frames[0].opcode = self.opcode
  104. frames[-1].final = True
  105. return frames
  106. def __str__(self):
  107. s = '<%s opcode=0x%X len=%d' \
  108. % (self.__class__.__name__, self.opcode, len(self.payload))
  109. if self.masking_key:
  110. s += ' masking_key=%4s' % self.masking_key
  111. return s + '>'
  112. class ControlFrame(Frame):
  113. """
  114. A Control frame is a frame with an opcode OPCODE_CLOSE, OPCODE_PING or
  115. OPCODE_PONG. These frames must be handled as defined by RFC 6455, and
  116. """
  117. def fragment(self, fragment_size, mask=False):
  118. """
  119. Control frames must not be fragmented.
  120. """
  121. raise TypeError('control frames must not be fragmented')
  122. def pack(self):
  123. """
  124. Same as Frame.pack(), but asserts that the payload size does not exceed
  125. 125 bytes.
  126. """
  127. if len(self.payload) > 125:
  128. raise ValueError('control frames must not be larger than 125' \
  129. 'bytes')
  130. return Frame.pack(self)
  131. def unpack_close(self):
  132. """
  133. Unpack a close message into a status code and a reason. If no payload
  134. is given, the code is None and the reason is an empty string.
  135. """
  136. if self.payload:
  137. code = struct.unpack('!H', self.payload[:2])
  138. reason = self.payload[2:]
  139. else:
  140. code = None
  141. reason = ''
  142. return code, reason
  143. def receive_frame(sock):
  144. """
  145. Receive a single frame on socket `sock`. The frame schme is explained in
  146. the docs of Frame.pack().
  147. """
  148. b1, b2 = struct.unpack('!BB', recvn(sock, 2))
  149. final = bool(b1 & 0x80)
  150. rsv1 = bool(b1 & 0x40)
  151. rsv2 = bool(b1 & 0x20)
  152. rsv3 = bool(b1 & 0x10)
  153. opcode = b1 & 0x0F
  154. mask = bool(b2 & 0x80)
  155. payload_len = b2 & 0x7F
  156. if payload_len == 126:
  157. payload_len = struct.unpack('!H', recvn(sock, 2))
  158. elif payload_len == 127:
  159. payload_len = struct.unpack('!Q', recvn(sock, 8))
  160. if mask:
  161. masking_key = recvn(sock, 4)
  162. payload = mask(masking_key, recvn(sock, payload_len))
  163. else:
  164. masking_key = ''
  165. payload = recvn(sock, payload_len)
  166. # Control frames have most significant bit 1
  167. cls = ControlFrame if opcode & 0x8 else Frame
  168. return cls(opcode, payload, masking_key=masking_key, final=final,
  169. rsv1=rsv1, rsv2=rsv2, rsv3=rsv3)
  170. def recvn(sock, n):
  171. """
  172. Keep receiving data from `sock` until exactly `n` bytes have been read.
  173. """
  174. data = ''
  175. while len(data) < n:
  176. received = sock.recv(n - len(data))
  177. if not len(received):
  178. raise SocketClosed()
  179. data += received
  180. return data
  181. def mask(key, original):
  182. """
  183. Mask an octet string using the given masking key.
  184. The following masking algorithm is used, as defined in RFC 6455:
  185. for each octet:
  186. j = i MOD 4
  187. transformed-octet-i = original-octet-i XOR masking-key-octet-j
  188. """
  189. if len(key) != 4:
  190. raise ValueError('invalid masking key "%s"' % key)
  191. key = map(ord, key)
  192. masked = bytearray(original)
  193. for i in xrange(len(masked)):
  194. masked[i] ^= key[i % 4]
  195. return masked