Debian Codegraph @

geventwebsocket/websocket.py

raw symbols SCIP
1 import struct
2
3 from socket import error
4
5 from ._compat import string_types, range_type, text_type
6 from .exceptions import ProtocolError
7 from .exceptions import WebSocketError
8 from .exceptions import FrameTooLargeException
9 from .utf8validator import Utf8Validator
10
11
12 MSG_SOCKET_DEAD = "Socket is dead"
13 MSG_ALREADY_CLOSED = "Connection is already closed"
14 MSG_CLOSED = "Connection closed"
15
16
17 class WebSocket(object):
18 """
19 Base class for supporting websocket operations.
20
21 :ivar environ: The http environment referenced by this connection.
22 :ivar closed: Whether this connection is closed/closing.
23 :ivar stream: The underlying file like object that will be read from /
24 written to by this WebSocket object.
25 """
26
27 __slots__ = ('utf8validator', 'utf8validate_last', 'environ', 'closed',
28 'stream', 'raw_write', 'raw_read', 'handler')
29
30 OPCODE_CONTINUATION = 0x00
31 OPCODE_TEXT = 0x01
32 OPCODE_BINARY = 0x02
33 OPCODE_CLOSE = 0x08
34 OPCODE_PING = 0x09
35 OPCODE_PONG = 0x0a
36
37 def __init__(self, environ, stream, handler):
38 self.environ = environ
39 self.closed = False
40
41 self.stream = stream
42
43 self.raw_write = stream.write
44 self.raw_read = stream.read
45
46 self.utf8validator = Utf8Validator()
47 self.handler = handler
48
49 def __del__(self):
50 try:
51 self.close()
52 except:
53 # close() may fail if __init__ didn't complete
54 pass
55
56 def _decode_bytes(self, bytestring):
57 """
58 Internal method used to convert the utf-8 encoded bytestring into
59 unicode.
60
61 If the conversion fails, the socket will be closed.
62 """
63
64 if not bytestring:
65 return ''
66
67 try:
68 return bytestring.decode('utf-8')
69 except UnicodeDecodeError:
70 self.close(1007)
71
72 raise
73
74 def _encode_bytes(self, text):
75 """
76 :returns: The utf-8 byte string equivalent of `text`.
77 """
78
79 if not isinstance(text, str):
80 text = text_type(text or '')
81
82 return text.encode("utf-8")
83
84 def _is_valid_close_code(self, code):
85 """
86 :returns: Whether the returned close code is a valid hybi return code.
87 """
88 if code < 1000:
89 return False
90
91 if 1004 <= code <= 1006:
92 return False
93
94 if 1012 <= code <= 1016:
95 return False
96
97 if code == 1100:
98 # not sure about this one but the autobahn fuzzer requires it.
99 return False
100
101 if 2000 <= code <= 2999:
102 return False
103
104 return True
105
106 @property
107 def current_app(self):
108 if hasattr(self.handler.server.application, 'current_app'):
109 return self.handler.server.application.current_app
110 else:
111 # For backwards compatibility reasons
112 class MockApp():
113 def on_close(self, *args):
114 pass
115
116 return MockApp()
117
118 @property
119 def origin(self):
120 if not self.environ:
121 return
122
123 return self.environ.get('HTTP_ORIGIN')
124
125 @property
126 def protocol(self):
127 if not self.environ:
128 return
129
130 return self.environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL')
131
132 @property
133 def version(self):
134 if not self.environ:
135 return
136
137 return self.environ.get('HTTP_SEC_WEBSOCKET_VERSION')
138
139 @property
140 def path(self):
141 if not self.environ:
142 return
143
144 return self.environ.get('PATH_INFO')
145
146 @property
147 def logger(self):
148 return self.handler.logger
149
150 def handle_close(self, header, payload):
151 """
152 Called when a close frame has been decoded from the stream.
153
154 :param header: The decoded `Header`.
155 :param payload: The bytestring payload associated with the close frame.
156 """
157 if not payload:
158 self.close(1000, None)
159
160 return
161
162 if len(payload) < 2:
163 raise ProtocolError('Invalid close frame: {0} {1}'.format(
164 header, payload))
165
166 code = struct.unpack('!H', payload[:2])[0]
167 payload = payload[2:]
168
169 if payload:
170 validator = Utf8Validator()
171 val = validator.validate(payload)
172
173 if not val[0]:
174 raise UnicodeError
175
176 if not self._is_valid_close_code(code):
177 raise ProtocolError('Invalid close code {0}'.format(code))
178
179 self.close(code, payload)
180
181 def handle_ping(self, header, payload):
182 self.send_frame(payload, self.OPCODE_PONG)
183
184 def handle_pong(self, header, payload):
185 pass
186
187 def read_frame(self):
188 """
189 Block until a full frame has been read from the socket.
190
191 This is an internal method as calling this will not cleanup correctly
192 if an exception is called. Use `receive` instead.
193
194 :return: The header and payload as a tuple.
195 """
196
197 header = Header.decode_header(self.stream)
198
199 if header.flags:
200 raise ProtocolError
201
202 if not header.length:
203 return header, b''
204
205 try:
206 payload = self.raw_read(header.length)
207 except error:
208 payload = b''
209 except Exception:
210 # TODO log out this exception
211 payload = b''
212
213 if len(payload) != header.length:
214 raise WebSocketError('Unexpected EOF reading frame payload')
215
216 if header.mask:
217 payload = header.unmask_payload(payload)
218
219 return header, payload
220
221 def validate_utf8(self, payload):
222 # Make sure the frames are decodable independently
223 self.utf8validate_last = self.utf8validator.validate(payload)
224
225 if not self.utf8validate_last[0]:
226 raise UnicodeError("Encountered invalid UTF-8 while processing "
227 "text message at payload octet index "
228 "{0:d}".format(self.utf8validate_last[3]))
229
230 def read_message(self):
231 """
232 Return the next text or binary message from the socket.
233
234 This is an internal method as calling this will not cleanup correctly
235 if an exception is called. Use `receive` instead.
236 """
237 opcode = None
238 message = bytearray()
239
240 while True:
241 header, payload = self.read_frame()
242 f_opcode = header.opcode
243
244 if f_opcode in (self.OPCODE_TEXT, self.OPCODE_BINARY):
245 # a new frame
246 if opcode:
247 raise ProtocolError("The opcode in non-fin frame is "
248 "expected to be zero, got "
249 "{0!r}".format(f_opcode))
250
251 # Start reading a new message, reset the validator
252 self.utf8validator.reset()
253 self.utf8validate_last = (True, True, 0, 0)
254
255 opcode = f_opcode
256
257 elif f_opcode == self.OPCODE_CONTINUATION:
258 if not opcode:
259 raise ProtocolError("Unexpected frame with opcode=0")
260
261 elif f_opcode == self.OPCODE_PING:
262 self.handle_ping(header, payload)
263 continue
264
265 elif f_opcode == self.OPCODE_PONG:
266 self.handle_pong(header, payload)
267 continue
268
269 elif f_opcode == self.OPCODE_CLOSE:
270 self.handle_close(header, payload)
271 return
272
273 else:
274 raise ProtocolError("Unexpected opcode={0!r}".format(f_opcode))
275
276 if opcode == self.OPCODE_TEXT:
277 self.validate_utf8(payload)
278
279 message += payload
280
281 if header.fin:
282 break
283
284 if opcode == self.OPCODE_TEXT:
285 self.validate_utf8(message)
286 return self._decode_bytes(message)
287 else:
288 return message
289
290 def receive(self):
291 """
292 Read and return a message from the stream. If `None` is returned, then
293 the socket is considered closed/errored.
294 """
295
296 if self.closed:
297 self.current_app.on_close(MSG_ALREADY_CLOSED)
298 raise WebSocketError(MSG_ALREADY_CLOSED)
299
300 try:
301 return self.read_message()
302 except UnicodeError:
303 self.close(1007)
304 except ProtocolError:
305 self.close(1002)
306 except error:
307 self.close()
308 self.current_app.on_close(MSG_CLOSED)
309
310 return None
311
312 def send_frame(self, message, opcode):
313 """
314 Send a frame over the websocket with message as its payload
315 """
316 if self.closed:
317 self.current_app.on_close(MSG_ALREADY_CLOSED)
318 raise WebSocketError(MSG_ALREADY_CLOSED)
319
320 if opcode in (self.OPCODE_TEXT, self.OPCODE_PING):
321 message = self._encode_bytes(message)
322 elif opcode == self.OPCODE_BINARY:
323 message = bytes(message)
324
325 header = Header.encode_header(True, opcode, b'', len(message), 0)
326
327 try:
328 self.raw_write(header + message)
329 except error:
330 raise WebSocketError(MSG_SOCKET_DEAD)
331 except:
332 raise
333
334 def send(self, message, binary=None):
335 """
336 Send a frame over the websocket with message as its payload
337 """
338 if binary is None:
339 binary = not isinstance(message, string_types)
340
341 opcode = self.OPCODE_BINARY if binary else self.OPCODE_TEXT
342
343 try:
344 self.send_frame(message, opcode)
345 except WebSocketError:
346 self.current_app.on_close(MSG_SOCKET_DEAD)
347 raise WebSocketError(MSG_SOCKET_DEAD)
348
349 def close(self, code=1000, message=b''):
350 """
351 Close the websocket and connection, sending the specified code and
352 message. The underlying socket object is _not_ closed, that is the
353 responsibility of the initiator.
354 """
355
356 if self.closed:
357 self.current_app.on_close(MSG_ALREADY_CLOSED)
358
359 try:
360 message = self._encode_bytes(message)
361
362 self.send_frame(message, opcode=self.OPCODE_CLOSE)
363 except WebSocketError:
364 # Failed to write the closing frame but it's ok because we're
365 # closing the socket anyway.
366 self.logger.debug("Failed to write closing frame -> closing socket")
367 finally:
368 self.logger.debug("Closed WebSocket")
369 self.closed = True
370
371 self.stream = None
372 self.raw_write = None
373 self.raw_read = None
374
375 self.environ = None
376
377 #self.current_app.on_close(MSG_ALREADY_CLOSED)
378
379
380 class Stream(object):
381 """
382 Wraps the handler's socket/rfile attributes and makes it in to a file like
383 object that can be read from/written to by the lower level websocket api.
384 """
385
386 __slots__ = ('handler', 'read', 'write')
387
388 def __init__(self, handler):
389 self.handler = handler
390 self.read = handler.rfile.read
391 self.write = handler.socket.sendall
392
393
394 class Header(object):
395 __slots__ = ('fin', 'mask', 'opcode', 'flags', 'length')
396
397 FIN_MASK = 0x80
398 OPCODE_MASK = 0x0f
399 MASK_MASK = 0x80
400 LENGTH_MASK = 0x7f
401
402 RSV0_MASK = 0x40
403 RSV1_MASK = 0x20
404 RSV2_MASK = 0x10
405
406 # bitwise mask that will determine the reserved bits for a frame header
407 HEADER_FLAG_MASK = RSV0_MASK | RSV1_MASK | RSV2_MASK
408
409 def __init__(self, fin=0, opcode=0, flags=0, length=0):
410 self.mask = ''
411 self.fin = fin
412 self.opcode = opcode
413 self.flags = flags
414 self.length = length
415
416 def mask_payload(self, payload):
417 payload = bytearray(payload)
418 mask = bytearray(self.mask)
419
420 for i in range_type(self.length):
421 payload[i] ^= mask[i % 4]
422
423 return payload
424
425 # it's the same operation
426 unmask_payload = mask_payload
427
428 def __repr__(self):
429 opcodes = {
430 0: 'continuation(0)',
431 1: 'text(1)',
432 2: 'binary(2)',
433 8: 'close(8)',
434 9: 'ping(9)',
435 10: 'pong(10)'
436 }
437 flags = {
438 0x40: 'RSV1 MASK',
439 0x20: 'RSV2 MASK',
440 0x10: 'RSV3 MASK'
441 }
442
443 return ("<Header fin={0} opcode={1} length={2} flags={3} mask={4} at "
444 "0x{5:x}>").format(
445 self.fin,
446 opcodes.get(self.opcode, 'reserved({})'.format(self.opcode)),
447 self.length,
448 flags.get(self.flags, 'reserved({})'.format(self.flags)),
449 self.mask, id(self)
450 )
451
452 @classmethod
453 def decode_header(cls, stream):
454 """
455 Decode a WebSocket header.
456
457 :param stream: A file like object that can be 'read' from.
458 :returns: A `Header` instance.
459 """
460 read = stream.read
461 data = read(2)
462
463 if len(data) != 2:
464 raise WebSocketError("Unexpected EOF while decoding header")
465
466 first_byte, second_byte = struct.unpack('!BB', data)
467
468 header = cls(
469 fin=first_byte & cls.FIN_MASK == cls.FIN_MASK,
470 opcode=first_byte & cls.OPCODE_MASK,
471 flags=first_byte & cls.HEADER_FLAG_MASK,
472 length=second_byte & cls.LENGTH_MASK)
473
474 has_mask = second_byte & cls.MASK_MASK == cls.MASK_MASK
475
476 if header.opcode > 0x07:
477 if not header.fin:
478 raise ProtocolError(
479 "Received fragmented control frame: {0!r}".format(data))
480
481 # Control frames MUST have a payload length of 125 bytes or less
482 if header.length > 125:
483 raise FrameTooLargeException(
484 "Control frame cannot be larger than 125 bytes: "
485 "{0!r}".format(data))
486
487 if header.length == 126:
488 # 16 bit length
489 data = read(2)
490
491 if len(data) != 2:
492 raise WebSocketError('Unexpected EOF while decoding header')
493
494 header.length = struct.unpack('!H', data)[0]
495 elif header.length == 127:
496 # 64 bit length
497 data = read(8)
498
499 if len(data) != 8:
500 raise WebSocketError('Unexpected EOF while decoding header')
501
502 header.length = struct.unpack('!Q', data)[0]
503
504 if has_mask:
505 mask = read(4)
506
507 if len(mask) != 4:
508 raise WebSocketError('Unexpected EOF while decoding header')
509
510 header.mask = mask
511
512 return header
513
514 @classmethod
515 def encode_header(cls, fin, opcode, mask, length, flags):
516 """
517 Encodes a WebSocket header.
518
519 :param fin: Whether this is the final frame for this opcode.
520 :param opcode: The opcode of the payload, see `OPCODE_*`
521 :param mask: Whether the payload is masked.
522 :param length: The length of the frame.
523 :param flags: The RSV* flags.
524 :return: A bytestring encoded header.
525 """
526 first_byte = opcode
527 second_byte = 0
528 extra = b""
529 result = bytearray()
530
531 if fin:
532 first_byte |= cls.FIN_MASK
533
534 if flags & cls.RSV0_MASK:
535 first_byte |= cls.RSV0_MASK
536
537 if flags & cls.RSV1_MASK:
538 first_byte |= cls.RSV1_MASK
539
540 if flags & cls.RSV2_MASK:
541 first_byte |= cls.RSV2_MASK
542
543 # now deal with length complexities
544 if length < 126:
545 second_byte += length
546 elif length <= 0xffff:
547 second_byte += 126
548 extra = struct.pack('!H', length)
549 elif length <= 0xffffffffffffffff:
550 second_byte += 127
551 extra = struct.pack('!Q', length)
552 else:
553 raise FrameTooLargeException
554
555 if mask:
556 second_byte |= cls.MASK_MASK
557
558 result.append(first_byte)
559 result.append(second_byte)
560 result.extend(extra)
561
562 if mask:
563 result.extend(mask)
564
565 return result