xref: /unit/test/unit/applications/websockets.py (revision 1150:3dc2f4d0cd60)
1import random
2import base64
3import struct
4import select
5import hashlib
6import itertools
7from unit.applications.proto import TestApplicationProto
8
9GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
10
11
12class TestApplicationWebsocket(TestApplicationProto):
13
14    OP_CONT = 0x00
15    OP_TEXT = 0x01
16    OP_BINARY = 0x02
17    OP_CLOSE = 0x08
18    OP_PING = 0x09
19    OP_PONG = 0x0A
20    CLOSE_CODES = [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011]
21
22    def __init__(self, preinit=False):
23        self.preinit = preinit
24
25    def key(self):
26        raw_key = bytes(random.getrandbits(8) for _ in range(16))
27        return base64.b64encode(raw_key).decode()
28
29    def accept(self, key):
30        sha1 = hashlib.sha1((key + GUID).encode()).digest()
31        return base64.b64encode(sha1).decode()
32
33    def upgrade(self):
34        key = self.key()
35
36        if self.preinit:
37            self.get()
38
39        resp, sock = self.get(
40            headers={
41                'Host': 'localhost',
42                'Upgrade': 'websocket',
43                'Connection': 'Upgrade',
44                'Sec-WebSocket-Key': key,
45                'Sec-WebSocket-Protocol': 'chat',
46                'Sec-WebSocket-Version': 13,
47            },
48            read_timeout=1,
49            start=True,
50        )
51
52        return (resp, sock, key)
53
54    def apply_mask(self, data, mask):
55        return bytes(b ^ m for b, m in zip(data, itertools.cycle(mask)))
56
57    def serialize_close(self, code=1000, reason=''):
58        return struct.pack('!H', code) + reason.encode('utf-8')
59
60    def frame_read(self, sock, read_timeout=10):
61        def recv_bytes(sock, bytes):
62            data = b''
63            while select.select([sock], [], [], read_timeout)[0]:
64                try:
65                    if bytes < 65536:
66                        data = sock.recv(bytes)
67                    else:
68                        data = self.recvall(
69                            sock, read_timeout=read_timeout, buff_size=bytes
70                        )
71                    break
72                except:
73                    break
74
75            return data
76
77        frame = {}
78
79        head1, = struct.unpack('!B', recv_bytes(sock, 1))
80        head2, = struct.unpack('!B', recv_bytes(sock, 1))
81
82        frame['fin'] = bool(head1 & 0b10000000)
83        frame['rsv1'] = bool(head1 & 0b01000000)
84        frame['rsv2'] = bool(head1 & 0b00100000)
85        frame['rsv3'] = bool(head1 & 0b00010000)
86        frame['opcode'] = head1 & 0b00001111
87        frame['mask'] = head2 & 0b10000000
88
89        length = head2 & 0b01111111
90        if length == 126:
91            data = recv_bytes(sock, 2)
92            length, = struct.unpack('!H', data)
93        elif length == 127:
94            data = recv_bytes(sock, 8)
95            length, = struct.unpack('!Q', data)
96
97        if frame['mask']:
98            mask_bits = recv_bytes(sock, 4)
99
100        data = recv_bytes(sock, length)
101        if frame['mask']:
102            data = self.apply_mask(data, mask_bits)
103
104        if frame['opcode'] == self.OP_CLOSE:
105            if length >= 2:
106                code, = struct.unpack('!H', data[:2])
107                reason = data[2:].decode('utf-8')
108                if not (code in self.CLOSE_CODES or 3000 <= code < 5000):
109                    self.fail('Invalid status code')
110                frame['code'] = code
111                frame['reason'] = reason
112            elif length == 0:
113                frame['code'] = 1005
114                frame['reason'] = ''
115            else:
116                self.fail('Close frame too short')
117
118        frame['data'] = data
119
120        if frame['mask']:
121            self.fail('Received frame with mask')
122
123        return frame
124
125    def frame_to_send(
126        self,
127        opcode,
128        data,
129        fin=True,
130        length=None,
131        rsv1=False,
132        rsv2=False,
133        rsv3=False,
134        mask=True,
135    ):
136        frame = b''
137
138        if isinstance(data, str):
139            data = data.encode('utf-8')
140
141        head1 = (
142            (0b10000000 if fin else 0)
143            | (0b01000000 if rsv1 else 0)
144            | (0b00100000 if rsv2 else 0)
145            | (0b00010000 if rsv3 else 0)
146            | opcode
147        )
148
149        head2 = 0b10000000 if mask else 0
150
151        data_length = len(data) if length is None else length
152        if data_length < 126:
153            frame += struct.pack('!BB', head1, head2 | data_length)
154        elif data_length < 65536:
155            frame += struct.pack('!BBH', head1, head2 | 126, data_length)
156        else:
157            frame += struct.pack('!BBQ', head1, head2 | 127, data_length)
158
159        if mask:
160            mask_bits = struct.pack('!I', random.getrandbits(32))
161            frame += mask_bits
162
163        if mask:
164            frame += self.apply_mask(data, mask_bits)
165        else:
166            frame += data
167
168        return frame
169
170    def frame_write(self, sock, *args, **kwargs):
171        chopsize = kwargs.pop('chopsize') if 'chopsize' in kwargs else None
172
173        frame = self.frame_to_send(*args, **kwargs)
174
175        if chopsize is None:
176            sock.sendall(frame)
177
178        else:
179            pos = 0
180            frame_len = len(frame)
181            while pos < frame_len:
182                end = min(pos + chopsize, frame_len)
183                sock.sendall(frame[pos:end])
184                pos = end
185
186    def message(self, sock, type, message, fragmention_size=None, **kwargs):
187        message_len = len(message)
188
189        if fragmention_size is None:
190            fragmention_size = message_len
191
192        if message_len <= fragmention_size:
193            self.frame_write(sock, type, message, **kwargs)
194            return
195
196        pos = 0
197        op_code = type
198        while pos < message_len:
199            end = min(pos + fragmention_size, message_len)
200            fin = end == message_len
201            self.frame_write(
202                sock, op_code, message[pos:end], fin=fin, **kwargs
203            )
204            op_code = self.OP_CONT
205            pos = end
206
207    def message_read(self, sock, read_timeout=10):
208        frame = self.frame_read(sock, read_timeout=read_timeout)
209
210        while not frame['fin']:
211            temp = self.frame_read(sock, read_timeout=read_timeout)
212            frame['data'] += temp['data']
213            frame['fin'] = temp['fin']
214
215        return frame
216