1 | /* |
2 | * This file is part of the MicroPython project, http://micropython.org/ |
3 | * |
4 | * The MIT License (MIT) |
5 | * |
6 | * Copyright (c) 2016 Paul Sokolovsky |
7 | * |
8 | * Permission is hereby granted, free of charge, to any person obtaining a copy |
9 | * of this software and associated documentation files (the "Software"), to deal |
10 | * in the Software without restriction, including without limitation the rights |
11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
12 | * copies of the Software, and to permit persons to whom the Software is |
13 | * furnished to do so, subject to the following conditions: |
14 | * |
15 | * The above copyright notice and this permission notice shall be included in |
16 | * all copies or substantial portions of the Software. |
17 | * |
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
24 | * THE SOFTWARE. |
25 | */ |
26 | |
27 | #include <stdio.h> |
28 | #include <stdint.h> |
29 | #include <string.h> |
30 | |
31 | #include "py/runtime.h" |
32 | #include "py/stream.h" |
33 | #include "extmod/moduwebsocket.h" |
34 | |
35 | #if MICROPY_PY_UWEBSOCKET |
36 | |
37 | enum { , FRAME_OPT, PAYLOAD, CONTROL }; |
38 | |
39 | enum { BLOCKING_WRITE = 0x80 }; |
40 | |
41 | typedef struct _mp_obj_websocket_t { |
42 | mp_obj_base_t base; |
43 | mp_obj_t sock; |
44 | uint32_t msg_sz; |
45 | byte mask[4]; |
46 | byte state; |
47 | byte to_recv; |
48 | byte mask_pos; |
49 | byte buf_pos; |
50 | byte buf[6]; |
51 | byte opts; |
52 | // Copy of last data frame flags |
53 | byte ws_flags; |
54 | // Copy of current frame flags |
55 | byte last_flags; |
56 | } mp_obj_websocket_t; |
57 | |
58 | STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode); |
59 | |
60 | STATIC mp_obj_t websocket_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { |
61 | mp_arg_check_num(n_args, n_kw, 1, 2, false); |
62 | mp_get_stream_raise(args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); |
63 | mp_obj_websocket_t *o = m_new_obj(mp_obj_websocket_t); |
64 | o->base.type = type; |
65 | o->sock = args[0]; |
66 | o->state = FRAME_HEADER; |
67 | o->to_recv = 2; |
68 | o->mask_pos = 0; |
69 | o->buf_pos = 0; |
70 | o->opts = FRAME_TXT; |
71 | if (n_args > 1 && args[1] == mp_const_true) { |
72 | o->opts |= BLOCKING_WRITE; |
73 | } |
74 | return MP_OBJ_FROM_PTR(o); |
75 | } |
76 | |
77 | STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { |
78 | mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); |
79 | const mp_stream_p_t *stream_p = mp_get_stream(self->sock); |
80 | while (1) { |
81 | if (self->to_recv != 0) { |
82 | mp_uint_t out_sz = stream_p->read(self->sock, self->buf + self->buf_pos, self->to_recv, errcode); |
83 | if (out_sz == 0 || out_sz == MP_STREAM_ERROR) { |
84 | return out_sz; |
85 | } |
86 | self->buf_pos += out_sz; |
87 | self->to_recv -= out_sz; |
88 | if (self->to_recv != 0) { |
89 | *errcode = MP_EAGAIN; |
90 | return MP_STREAM_ERROR; |
91 | } |
92 | } |
93 | |
94 | switch (self->state) { |
95 | case FRAME_HEADER: { |
96 | // TODO: Split frame handling below is untested so far, so conservatively disable it |
97 | assert(self->buf[0] & 0x80); |
98 | |
99 | // "Control frames MAY be injected in the middle of a fragmented message." |
100 | // So, they must be processed before data frames (and not alter |
101 | // self->ws_flags) |
102 | byte frame_type = self->buf[0]; |
103 | self->last_flags = frame_type; |
104 | frame_type &= FRAME_OPCODE_MASK; |
105 | |
106 | if ((self->buf[0] & FRAME_OPCODE_MASK) == FRAME_CONT) { |
107 | // Preserve previous frame type |
108 | self->ws_flags = (self->ws_flags & FRAME_OPCODE_MASK) | (self->buf[0] & ~FRAME_OPCODE_MASK); |
109 | } else { |
110 | self->ws_flags = self->buf[0]; |
111 | } |
112 | |
113 | // Reset mask in case someone will use "simplified" protocol |
114 | // without masks. |
115 | memset(self->mask, 0, sizeof(self->mask)); |
116 | |
117 | int to_recv = 0; |
118 | size_t sz = self->buf[1] & 0x7f; |
119 | if (sz == 126) { |
120 | // Msg size is next 2 bytes |
121 | to_recv += 2; |
122 | } else if (sz == 127) { |
123 | // Msg size is next 8 bytes |
124 | assert(0); |
125 | } |
126 | if (self->buf[1] & 0x80) { |
127 | // Next 4 bytes is mask |
128 | to_recv += 4; |
129 | } |
130 | |
131 | self->buf_pos = 0; |
132 | self->to_recv = to_recv; |
133 | self->msg_sz = sz; // May be overridden by FRAME_OPT |
134 | if (to_recv != 0) { |
135 | self->state = FRAME_OPT; |
136 | } else { |
137 | if (frame_type >= FRAME_CLOSE) { |
138 | self->state = CONTROL; |
139 | } else { |
140 | self->state = PAYLOAD; |
141 | } |
142 | } |
143 | continue; |
144 | } |
145 | |
146 | case FRAME_OPT: { |
147 | if ((self->buf_pos & 3) == 2) { |
148 | // First two bytes are message length |
149 | self->msg_sz = (self->buf[0] << 8) | self->buf[1]; |
150 | } |
151 | if (self->buf_pos >= 4) { |
152 | // Last 4 bytes is mask |
153 | memcpy(self->mask, self->buf + self->buf_pos - 4, 4); |
154 | } |
155 | self->buf_pos = 0; |
156 | if ((self->last_flags & FRAME_OPCODE_MASK) >= FRAME_CLOSE) { |
157 | self->state = CONTROL; |
158 | } else { |
159 | self->state = PAYLOAD; |
160 | } |
161 | continue; |
162 | } |
163 | |
164 | case PAYLOAD: |
165 | case CONTROL: { |
166 | mp_uint_t out_sz = 0; |
167 | if (self->msg_sz == 0) { |
168 | // In case message had zero payload |
169 | goto no_payload; |
170 | } |
171 | |
172 | size_t sz = MIN(size, self->msg_sz); |
173 | out_sz = stream_p->read(self->sock, buf, sz, errcode); |
174 | if (out_sz == 0 || out_sz == MP_STREAM_ERROR) { |
175 | return out_sz; |
176 | } |
177 | |
178 | sz = out_sz; |
179 | for (byte *p = buf; sz--; p++) { |
180 | *p ^= self->mask[self->mask_pos++ & 3]; |
181 | } |
182 | |
183 | self->msg_sz -= out_sz; |
184 | if (self->msg_sz == 0) { |
185 | byte last_state; |
186 | no_payload: |
187 | last_state = self->state; |
188 | self->state = FRAME_HEADER; |
189 | self->to_recv = 2; |
190 | self->mask_pos = 0; |
191 | self->buf_pos = 0; |
192 | |
193 | // Handle control frame |
194 | if (last_state == CONTROL) { |
195 | byte frame_type = self->last_flags & FRAME_OPCODE_MASK; |
196 | if (frame_type == FRAME_CLOSE) { |
197 | static const char close_resp[2] = {0x88, 0}; |
198 | int err; |
199 | websocket_write(self_in, close_resp, sizeof(close_resp), &err); |
200 | return 0; |
201 | } |
202 | |
203 | // DEBUG_printf("Finished receiving ctrl message %x, ignoring\n", self->last_flags); |
204 | continue; |
205 | } |
206 | } |
207 | |
208 | if (out_sz != 0) { |
209 | return out_sz; |
210 | } |
211 | // Empty (data) frame received is not EOF |
212 | continue; |
213 | } |
214 | |
215 | } |
216 | } |
217 | } |
218 | |
219 | STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { |
220 | mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); |
221 | assert(size < 0x10000); |
222 | byte [4] = {0x80 | (self->opts & FRAME_OPCODE_MASK)}; |
223 | int hdr_sz; |
224 | if (size < 126) { |
225 | header[1] = size; |
226 | hdr_sz = 2; |
227 | } else { |
228 | header[1] = 126; |
229 | header[2] = size >> 8; |
230 | header[3] = size & 0xff; |
231 | hdr_sz = 4; |
232 | } |
233 | |
234 | mp_obj_t dest[3]; |
235 | if (self->opts & BLOCKING_WRITE) { |
236 | mp_load_method(self->sock, MP_QSTR_setblocking, dest); |
237 | dest[2] = mp_const_true; |
238 | mp_call_method_n_kw(1, 0, dest); |
239 | } |
240 | |
241 | mp_uint_t out_sz = mp_stream_write_exactly(self->sock, header, hdr_sz, errcode); |
242 | if (*errcode == 0) { |
243 | out_sz = mp_stream_write_exactly(self->sock, buf, size, errcode); |
244 | } |
245 | |
246 | if (self->opts & BLOCKING_WRITE) { |
247 | dest[2] = mp_const_false; |
248 | mp_call_method_n_kw(1, 0, dest); |
249 | } |
250 | |
251 | if (*errcode != 0) { |
252 | return MP_STREAM_ERROR; |
253 | } |
254 | return out_sz; |
255 | } |
256 | |
257 | STATIC mp_uint_t websocket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { |
258 | mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); |
259 | switch (request) { |
260 | case MP_STREAM_CLOSE: |
261 | // TODO: Send close signaling to the other side, otherwise it's |
262 | // abrupt close (connection abort). |
263 | mp_stream_close(self->sock); |
264 | return 0; |
265 | case MP_STREAM_GET_DATA_OPTS: |
266 | return self->ws_flags & FRAME_OPCODE_MASK; |
267 | case MP_STREAM_SET_DATA_OPTS: { |
268 | int cur = self->opts & FRAME_OPCODE_MASK; |
269 | self->opts = (self->opts & ~FRAME_OPCODE_MASK) | (arg & FRAME_OPCODE_MASK); |
270 | return cur; |
271 | } |
272 | default: |
273 | *errcode = MP_EINVAL; |
274 | return MP_STREAM_ERROR; |
275 | } |
276 | } |
277 | |
278 | STATIC const mp_rom_map_elem_t websocket_locals_dict_table[] = { |
279 | { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, |
280 | { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, |
281 | { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, |
282 | { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, |
283 | { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&mp_stream_ioctl_obj) }, |
284 | { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, |
285 | }; |
286 | STATIC MP_DEFINE_CONST_DICT(websocket_locals_dict, websocket_locals_dict_table); |
287 | |
288 | STATIC const mp_stream_p_t websocket_stream_p = { |
289 | .read = websocket_read, |
290 | .write = websocket_write, |
291 | .ioctl = websocket_ioctl, |
292 | }; |
293 | |
294 | STATIC const mp_obj_type_t websocket_type = { |
295 | { &mp_type_type }, |
296 | .name = MP_QSTR_websocket, |
297 | .make_new = websocket_make_new, |
298 | .protocol = &websocket_stream_p, |
299 | .locals_dict = (void *)&websocket_locals_dict, |
300 | }; |
301 | |
302 | STATIC const mp_rom_map_elem_t uwebsocket_module_globals_table[] = { |
303 | { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uwebsocket) }, |
304 | { MP_ROM_QSTR(MP_QSTR_websocket), MP_ROM_PTR(&websocket_type) }, |
305 | }; |
306 | |
307 | STATIC MP_DEFINE_CONST_DICT(uwebsocket_module_globals, uwebsocket_module_globals_table); |
308 | |
309 | const mp_obj_module_t mp_module_uwebsocket = { |
310 | .base = { &mp_type_module }, |
311 | .globals = (mp_obj_dict_t *)&uwebsocket_module_globals, |
312 | }; |
313 | |
314 | #endif // MICROPY_PY_UWEBSOCKET |
315 | |