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