websocket.py 6.4 KB

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