xref: /unit/test/unit/applications/websockets.py (revision 1130:020fa3fb48f8)
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=1):
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,
70                            read_timeout=read_timeout,
71                            buff_size=bytes,
72                        )
73                    break
74                except:
75                    break
76
77            return data
78
79        frame = {}
80
81        head1, = struct.unpack('!B', recv_bytes(sock, 1))
82        head2, = struct.unpack('!B', recv_bytes(sock, 1))
83
84        frame['fin'] = bool(head1 & 0b10000000)
85        frame['rsv1'] = bool(head1 & 0b01000000)
86        frame['rsv2'] = bool(head1 & 0b00100000)
87        frame['rsv3'] = bool(head1 & 0b00010000)
88        frame['opcode'] = head1 & 0b00001111
89        frame['mask'] = head2 & 0b10000000
90
91        length = head2 & 0b01111111
92        if length == 126:
93            data = recv_bytes(sock, 2)
94            length, = struct.unpack('!H', data)
95        elif length == 127:
96            data = recv_bytes(sock, 8)
97            length, = struct.unpack('!Q', data)
98
99        if frame['mask']:
100            mask_bits = recv_bytes(sock, 4)
101
102        data = recv_bytes(sock, length)
103        if frame['mask']:
104            data = self.apply_mask(data, mask_bits)
105
106        if frame['opcode'] == self.OP_CLOSE:
107            if length >= 2:
108                code, = struct.unpack('!H', data[:2])
109                reason = data[2:].decode('utf-8')
110                if not (code in self.CLOSE_CODES or 3000 <= code < 5000):
111                    self.fail('Invalid status code')
112                frame['code'] = code
113                frame['reason'] = reason
114            elif length == 0:
115                frame['code'] = 1005
116                frame['reason'] = ''
117            else:
118                self.fail('Close frame too short')
119
120        frame['data'] = data
121
122        if frame['mask']:
123            self.fail('Received frame with mask')
124
125        return frame
126
127    def frame_to_send(
128        self,
129        opcode,
130        data,
131        fin=True,
132        length=None,
133        rsv1=False,
134        rsv2=False,
135        rsv3=False,
136        mask=True,
137    ):
138        frame = b''
139
140        if isinstance(data, str):
141            data = data.encode('utf-8')
142
143        head1 = (
144            (0b10000000 if fin else 0)
145            | (0b01000000 if rsv1 else 0)
146            | (0b00100000 if rsv2 else 0)
147            | (0b00010000 if rsv3 else 0)
148            | opcode
149        )
150
151        head2 = 0b10000000 if mask else 0
152
153        data_length = len(data) if length is None else length
154        if data_length < 126:
155            frame += struct.pack('!BB', head1, head2 | data_length)
156        elif data_length < 65536:
157            frame += struct.pack('!BBH', head1, head2 | 126, data_length)
158        else:
159            frame += struct.pack('!BBQ', head1, head2 | 127, data_length)
160
161        if mask:
162            mask_bits = struct.pack('!I', random.getrandbits(32))
163            frame += mask_bits
164
165        if mask:
166            frame += self.apply_mask(data, mask_bits)
167        else:
168            frame += data
169
170        return frame
171
172    def frame_write(self, sock, *args, **kwargs):
173        chopsize = kwargs.pop('chopsize') if 'chopsize' in kwargs else None
174
175        frame = self.frame_to_send(*args, **kwargs)
176
177        if chopsize is None:
178            sock.sendall(frame)
179
180        else:
181            pos = 0
182            frame_len = len(frame)
183            while (pos < frame_len):
184                end = min(pos + chopsize, frame_len)
185                sock.sendall(frame[pos:end])
186                pos = end
187
188    def message(self, sock, type, message, fragmention_size=None, **kwargs):
189        message_len = len(message)
190
191        if fragmention_size is None:
192            fragmention_size = message_len
193
194        if message_len <= fragmention_size:
195            self.frame_write(sock, type, message, **kwargs)
196            return
197
198        pos = 0
199        op_code = type
200        while(pos < message_len):
201            end = min(pos + fragmention_size, message_len)
202            fin = (end == message_len)
203            self.frame_write(sock, op_code, message[pos:end], fin=fin, **kwargs)
204            op_code = self.OP_CONT
205            pos = end
206
207    def message_read(self, sock, read_timeout=1):
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