websocket.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import re
  2. import struct
  3. from hashlib import sha1
  4. from threading import Thread
  5. from frame import ControlFrame, receive_fragments, receive_frame, \
  6. OPCODE_CLOSE, OPCODE_PING, OPCODE_PONG
  7. from message import create_message
  8. from exceptions import SocketClosed, PingError
  9. WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
  10. WS_VERSION = '13'
  11. class WebSocket(object):
  12. def __init__(self, sock, encoding=None):
  13. self.sock = sock
  14. self.encoding = encoding
  15. self.received_close_params = None
  16. self.close_frame_sent = False
  17. self.ping_sent = False
  18. self.ping_payload = None
  19. def send_message(self, message, fragment_size=None):
  20. if fragment_size is None:
  21. self.send_frame(message.frame())
  22. else:
  23. map(self.send_frame, message.fragment(fragment_size))
  24. def send_frame(self, frame):
  25. self.sock.sendall(frame.pack())
  26. def handle_control_frame(self, frame):
  27. if frame.opcode == OPCODE_CLOSE:
  28. self.received_close_params = frame.unpack_close()
  29. elif frame.opcode == OPCODE_PING:
  30. # Respond with a pong message with identical payload
  31. self.send_frame(ControlFrame(OPCODE_PONG, frame.payload))
  32. elif frame.opcode == OPCODE_PONG:
  33. # Assert that the PONG payload is identical to that of the PING
  34. if not self.ping_sent:
  35. raise PingError('received PONG while no PING was sent')
  36. self.ping_sent = False
  37. if frame.payload != self.ping_payload:
  38. raise PingError('received PONG with invalid payload')
  39. self.ping_payload = None
  40. self.onpong(frame.payload)
  41. def receive_message(self):
  42. frames = receive_fragments(self.sock, self.handle_control_frame)
  43. payload = ''.join([f.payload for f in frames])
  44. return create_message(frames[0].opcode, payload)
  45. def send_handshake(self):
  46. raw_headers = self.sock.recv(512)
  47. if self.encoding:
  48. raw_headers = raw_headers.decode(self.encoding, 'ignore')
  49. location = re.search(r'^GET (.*) HTTP/1.1\r\n', raw_headers).group(1)
  50. headers = dict(re.findall(r'(.*?): (.*?)\r\n', raw_headers))
  51. # Check if headers that MUST be present are actually present
  52. for name in ('Host', 'Upgrade', 'Connection', 'Sec-WebSocket-Key',
  53. 'Origin', 'Sec-WebSocket-Version'):
  54. assert name in headers
  55. # Check WebSocket version used by client
  56. assert headers['Sec-WebSocket-Version'] == WS_VERSION
  57. # Make sure the requested protocols are supported by this server
  58. if 'Sec-WebSocket-Protocol' in headers:
  59. parts = headers['Sec-WebSocket-Protocol'].split(',')
  60. protocols = map(str.strip, parts)
  61. for protocol in protocols:
  62. assert protocol in self.protocols
  63. else:
  64. protocols = []
  65. key = headers['Sec-WebSocket-Key']
  66. accept = sha1(key + WS_GUID).digest().encode('base64')
  67. shake = 'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'
  68. shake += 'Upgrade: WebSocket\r\n'
  69. shake += 'Connection: Upgrade\r\n'
  70. shake += 'WebSocket-Origin: %s\r\n' % headers['Origin']
  71. shake += 'WebSocket-Location: ws://%s%s\r\n' % (headers['Host'], location)
  72. shake += 'Sec-WebSocket-Accept: %s\r\n' % accept
  73. if self.protocols:
  74. shake += 'Sec-WebSocket-Protocol: %s\r\n' \
  75. % ', '.join(self.protocols)
  76. self.sock.send(shake + '\r\n')
  77. self.onopen()
  78. def receive_forever(self):
  79. try:
  80. while True:
  81. self.onmessage(self, self.receive_message())
  82. if self.received_close_params is not None:
  83. self.handle_close(*self.received_close_params)
  84. break
  85. except SocketClosed:
  86. self.onclose(None, '')
  87. def run_threaded(self, daemon=True):
  88. t = Thread(target=self.receive_forever)
  89. t.daemon = daemon
  90. t.start()
  91. def send_close(self, code, reason):
  92. payload = '' if code is None else struct.pack('!H', code)
  93. self.send_frame(ControlFrame(OPCODE_CLOSE, payload))
  94. self.close_frame_sent = True
  95. def send_ping(self, payload=''):
  96. """
  97. Send a ping control frame with an optional payload.
  98. """
  99. self.send_frame(ControlFrame(OPCODE_PING, payload))
  100. self.ping_payload = payload
  101. self.ping_sent = True
  102. self.onping()
  103. def handle_close(self, code=None, reason=''):
  104. """
  105. Handle a close message by sending a response close message if no close
  106. message was sent before, and closing the connection. The onclose()
  107. handler is called afterwards.
  108. """
  109. if not self.close_frame_sent:
  110. payload = '' if code is None else struct.pack('!H', code)
  111. self.send_frame(ControlFrame(OPCODE_CLOSE, payload))
  112. self.sock.close()
  113. self.onclose(code, reason)
  114. def close(self, code=None, reason=''):
  115. """
  116. Close the socket by sending a close message and waiting for a response
  117. close message. The onclose() handler is called after the close message
  118. has been sent, but before the response has been received.
  119. """
  120. self.send_close(code, reason)
  121. # FIXME: swap the two lines below?
  122. self.onclose(code, reason)
  123. frame = receive_frame(self.sock)
  124. self.sock.close()
  125. if frame.opcode != OPCODE_CLOSE:
  126. raise ValueError('Expected close frame, got %s instead' % frame)
  127. def onopen(self):
  128. """
  129. Called after the handshake has completed.
  130. """
  131. pass
  132. def onmessage(self, message):
  133. """
  134. Called when a message is received. `message' is a Message object, which
  135. can be constructed from a single frame or multiple fragmented frames.
  136. """
  137. raise NotImplemented
  138. def onping(self, payload):
  139. """
  140. Called after a ping control frame has been sent. This handler could be
  141. used to start a timeout handler for a pong message that is not received
  142. in time.
  143. """
  144. raise NotImplemented
  145. def onpong(self, payload):
  146. """
  147. Called when a pong control frame is received.
  148. """
  149. raise NotImplemented
  150. def onclose(self, code, reason):
  151. """
  152. Called when the socket is closed by either end point.
  153. """
  154. pass