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