fix double free error
[src/app-framework-binder.git] / src / websock.c
1 /*
2  * Copyright (C) 2016 "IoT.bzh"
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * This work is a far adaptation of apache-websocket:
19  *   origin:  https://github.com/disconnect/apache-websocket
20  *   commit:  cfaef071223f11ba016bff7e1e4b7c9e5df45b50
21  *   Copyright 2010-2012 self.disconnect (APACHE-2)
22  */
23
24 #include <stdlib.h>
25 #include <stdint.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <sys/uio.h>
29
30 #include "websock.h"
31
32 #define BLOCK_DATA_SIZE              4096
33
34 #define FRAME_GET_FIN(BYTE)         (((BYTE) >> 7) & 0x01)
35 #define FRAME_GET_RSV1(BYTE)        (((BYTE) >> 6) & 0x01)
36 #define FRAME_GET_RSV2(BYTE)        (((BYTE) >> 5) & 0x01)
37 #define FRAME_GET_RSV3(BYTE)        (((BYTE) >> 4) & 0x01)
38 #define FRAME_GET_OPCODE(BYTE)      ( (BYTE)       & 0x0F)
39 #define FRAME_GET_MASK(BYTE)        (((BYTE) >> 7) & 0x01)
40 #define FRAME_GET_PAYLOAD_LEN(BYTE) ( (BYTE)       & 0x7F)
41
42 #define FRAME_SET_FIN(BYTE)         (((BYTE) & 0x01) << 7)
43 #define FRAME_SET_RSV1(BYTE)        (((BYTE) & 0x01) << 6)
44 #define FRAME_SET_RSV2(BYTE)        (((BYTE) & 0x01) << 5)
45 #define FRAME_SET_RSV3(BYTE)        (((BYTE) & 0x01) << 4)
46 #define FRAME_SET_OPCODE(BYTE)      ((BYTE) & 0x0F)
47 #define FRAME_SET_MASK(BYTE)        (((BYTE) & 0x01) << 7)
48 #define FRAME_SET_LENGTH(X64, IDX)  (unsigned char)(((X64) >> ((IDX)*8)) & 0xFF)
49
50 #define OPCODE_CONTINUATION 0x0
51 #define OPCODE_TEXT         0x1
52 #define OPCODE_BINARY       0x2
53 #define OPCODE_CLOSE        0x8
54 #define OPCODE_PING         0x9
55 #define OPCODE_PONG         0xA
56
57 #define STATE_INIT    0
58 #define STATE_START   1
59 #define STATE_LENGTH  2
60 #define STATE_DATA    3
61
62 struct websock {
63         int state;
64         uint64_t maxlength;
65         int lenhead, szhead;
66         uint64_t length;
67         uint32_t mask;
68         unsigned char header[14];       /* 2 + 8 + 4 */
69         const struct websock_itf *itf;
70         void *closure;
71 };
72
73 static ssize_t ws_writev(struct websock *ws, const struct iovec *iov, int iovcnt)
74 {
75         return ws->itf->writev(ws->closure, iov, iovcnt);
76 }
77
78 static ssize_t ws_readv(struct websock *ws, const struct iovec *iov, int iovcnt)
79 {
80         return ws->itf->readv(ws->closure, iov, iovcnt);
81 }
82
83 #if 0
84 static ssize_t ws_write(struct websock *ws, const void *buffer, size_t buffer_size)
85 {
86         struct iovec iov;
87         iov.iov_base = (void *)buffer;  /* const cast */
88         iov.iov_len = buffer_size;
89         return ws_writev(ws, &iov, 1);
90 }
91 #endif
92
93 static ssize_t ws_read(struct websock *ws, void *buffer, size_t buffer_size)
94 {
95         struct iovec iov;
96         iov.iov_base = buffer;
97         iov.iov_len = buffer_size;
98         return ws_readv(ws, &iov, 1);
99 }
100
101 static int websock_send_internal_v(struct websock *ws, unsigned char first, const struct iovec *iovec, int count)
102 {
103         struct iovec iov[32];
104         int i, j;
105         size_t pos, size, len;
106         ssize_t rc;
107         unsigned char header[32];
108
109         /* checks count */
110         if (count < 0 || (count + 1) > (int)(sizeof iov / sizeof * iov)) {
111                 errno = EINVAL;
112                 return -1;
113         }
114
115         /* computes the size */
116         size = 0;
117         i = 1;
118         for (j = 0 ; j < count ; j++) {
119                 iov[i].iov_base = iovec[j].iov_base;
120                 len = iovec[j].iov_len;
121                 if (len != 0) {
122                         iov[i].iov_len = len;
123                         size += len;
124                         i++;
125                 }
126         }
127
128         /* makes the header */
129         pos = 0;
130         header[pos++] = first;
131         size = (uint64_t) size;
132         if (size < 126) {
133                 header[pos++] = FRAME_SET_MASK(0) | FRAME_SET_LENGTH(size, 0);
134         } else {
135                 if (size < 65536) {
136                         header[pos++] = FRAME_SET_MASK(0) | 126;
137                 } else {
138                         header[pos++] = FRAME_SET_MASK(0) | 127;
139                         header[pos++] = FRAME_SET_LENGTH(size, 7);
140                         header[pos++] = FRAME_SET_LENGTH(size, 6);
141                         header[pos++] = FRAME_SET_LENGTH(size, 5);
142                         header[pos++] = FRAME_SET_LENGTH(size, 4);
143                         header[pos++] = FRAME_SET_LENGTH(size, 3);
144                         header[pos++] = FRAME_SET_LENGTH(size, 2);
145                 }
146                 header[pos++] = FRAME_SET_LENGTH(size, 1);
147                 header[pos++] = FRAME_SET_LENGTH(size, 0);
148         }
149
150         /* allocates the vec */
151         iov[0].iov_base = header;
152         iov[0].iov_len = pos;
153         rc = ws_writev(ws, iov, i);
154
155         return rc < 0 ? -1 : 0;
156 }
157
158 static int websock_send_internal(struct websock *ws, unsigned char first, const void *buffer, size_t size)
159 {
160         struct iovec iov;
161
162         iov.iov_base = (void *)buffer;
163         iov.iov_len = size;
164         return websock_send_internal_v(ws, first, &iov, 1);
165 }
166
167 static inline int websock_send_v(struct websock *ws, int last, int rsv1, int rsv2, int rsv3, int opcode, const struct iovec *iovec, int count)
168 {
169         unsigned char first = (unsigned char)(FRAME_SET_FIN(last)
170                                 | FRAME_SET_RSV1(rsv1)
171                                 | FRAME_SET_RSV1(rsv2)
172                                 | FRAME_SET_RSV1(rsv3)
173                                 | FRAME_SET_OPCODE(opcode));
174         return websock_send_internal_v(ws, first, iovec, count);
175 }
176
177 static inline int websock_send(struct websock *ws, int last, int rsv1, int rsv2, int rsv3, int opcode, const void *buffer, size_t size)
178 {
179         unsigned char first = (unsigned char)(FRAME_SET_FIN(last)
180                                 | FRAME_SET_RSV1(rsv1)
181                                 | FRAME_SET_RSV1(rsv2)
182                                 | FRAME_SET_RSV1(rsv3)
183                                 | FRAME_SET_OPCODE(opcode));
184         return websock_send_internal(ws, first, buffer, size);
185 }
186
187 int websock_close_empty(struct websock *ws)
188 {
189         return websock_close(ws, WEBSOCKET_CODE_NOT_SET, NULL, 0);
190 }
191
192 int websock_close(struct websock *ws, uint16_t code, const void *data, size_t length)
193 {
194         unsigned char buffer[2];
195         struct iovec iov[2];
196
197         if (code == WEBSOCKET_CODE_NOT_SET && length == 0)
198                 return websock_send(ws, 1, 0, 0, 0, OPCODE_CLOSE, NULL, 0);
199
200         /* checks the length */
201         if (length > 123) {
202                 errno = EINVAL;
203                 return -1;
204         }
205
206         /* prepare the buffer */
207         buffer[0] = (unsigned char)((code >> 8) & 0xFF);
208         buffer[1] = (unsigned char)(code & 0xFF);
209
210         /* Send server-side closing handshake */
211         iov[0].iov_base = (void *)buffer;
212         iov[0].iov_len = 2;
213         iov[1].iov_base = (void *)data;
214         iov[1].iov_len = length;
215         return websock_send_v(ws, 1, 0, 0, 0, OPCODE_CLOSE, iov, 2);
216 }
217
218 int websock_ping(struct websock *ws, const void *data, size_t length)
219 {
220         /* checks the length */
221         if (length > 125) {
222                 errno = EINVAL;
223                 return -1;
224         }
225
226         return websock_send(ws, 1, 0, 0, 0, OPCODE_PING, data, length);
227 }
228
229 int websock_pong(struct websock *ws, const void *data, size_t length)
230 {
231         /* checks the length */
232         if (length > 125) {
233                 errno = EINVAL;
234                 return -1;
235         }
236
237         return websock_send(ws, 1, 0, 0, 0, OPCODE_PONG, data, length);
238 }
239
240 int websock_text(struct websock *ws, int last, const void *text, size_t length)
241 {
242         return websock_send(ws, last, 0, 0, 0, OPCODE_TEXT, text, length);
243 }
244
245 int websock_text_v(struct websock *ws, int last, const struct iovec *iovec, int count)
246 {
247         return websock_send_v(ws, last, 0, 0, 0, OPCODE_TEXT, iovec, count);
248 }
249
250 int websock_binary(struct websock *ws, int last, const void *data, size_t length)
251 {
252         return websock_send(ws, last, 0, 0, 0, OPCODE_BINARY, data, length);
253 }
254
255 int websock_binary_v(struct websock *ws, int last, const struct iovec *iovec, int count)
256 {
257         return websock_send_v(ws, last, 0, 0, 0, OPCODE_BINARY, iovec, count);
258 }
259
260 int websock_continue(struct websock *ws, int last, const void *data, size_t length)
261 {
262         return websock_send(ws, last, 0, 0, 0, OPCODE_CONTINUATION, data, length);
263 }
264
265 int websock_continue_v(struct websock *ws, int last, const struct iovec *iovec, int count)
266 {
267         return websock_send_v(ws, last, 0, 0, 0, OPCODE_CONTINUATION, iovec, count);
268 }
269
270 int websock_error(struct websock *ws, uint16_t code, const void *data, size_t size)
271 {
272         int rc = websock_close(ws, code, data, size);
273         if (ws->itf->on_error != NULL)
274                 ws->itf->on_error(ws->closure, code, data, size);
275         return rc;
276 }
277
278 static int read_header(struct websock *ws)
279 {
280         if (ws->lenhead < ws->szhead) {
281                 ssize_t rbc =
282                     ws_read(ws, &ws->header[ws->lenhead], (size_t)(ws->szhead - ws->lenhead));
283                 if (rbc < 0)
284                         return -1;
285                 ws->lenhead += (int)rbc;
286         }
287         return 0;
288 }
289
290 static int check_control_header(struct websock *ws)
291 {
292         /* sanity checks */
293         if (FRAME_GET_RSV1(ws->header[0]) != 0)
294                 return 0;
295         if (FRAME_GET_RSV2(ws->header[0]) != 0)
296                 return 0;
297         if (FRAME_GET_RSV3(ws->header[0]) != 0)
298                 return 0;
299         if (FRAME_GET_PAYLOAD_LEN(ws->header[1]) > 125)
300                 return 0;
301         if (FRAME_GET_OPCODE(ws->header[0]) == OPCODE_CLOSE)
302                 return FRAME_GET_PAYLOAD_LEN(ws->header[1]) != 1;
303         return 1;
304 }
305
306 int websock_dispatch(struct websock *ws)
307 {
308         uint16_t code;
309 loop:
310         switch (ws->state) {
311         case STATE_INIT:
312                 ws->lenhead = 0;
313                 ws->szhead = 2;
314                 ws->state = STATE_START;
315
316         case STATE_START:
317                 /* read the header */
318                 if (read_header(ws))
319                         return -1;
320                 else if (ws->lenhead < ws->szhead)
321                         return 0;
322                 /* fast track */
323                 switch (FRAME_GET_OPCODE(ws->header[0])) {
324                 case OPCODE_CONTINUATION:
325                 case OPCODE_TEXT:
326                 case OPCODE_BINARY:
327                         break;
328                 case OPCODE_CLOSE:
329                         if (!check_control_header(ws))
330                                 goto protocol_error;
331                         if (FRAME_GET_PAYLOAD_LEN(ws->header[1]))
332                                 ws->szhead += 2;
333                         break;
334                 case OPCODE_PING:
335                 case OPCODE_PONG:
336                         if (!check_control_header(ws))
337                                 goto protocol_error;
338                 default:
339                         break;
340                 }
341                 /* update heading size */
342                 switch (FRAME_GET_PAYLOAD_LEN(ws->header[1])) {
343                 case 127:
344                         ws->szhead += 6;
345                 case 126:
346                         ws->szhead += 2;
347                 default:
348                         ws->szhead += 4 * FRAME_GET_MASK(ws->header[1]);
349                 }
350                 ws->state = STATE_LENGTH;
351
352         case STATE_LENGTH:
353                 /* continue to read the header */
354                 if (read_header(ws))
355                         return -1;
356                 else if (ws->lenhead < ws->szhead)
357                         return 0;
358
359                 /* compute length */
360                 switch (FRAME_GET_PAYLOAD_LEN(ws->header[1])) {
361                 case 127:
362                         ws->length = (((uint64_t) ws->header[2]) << 56)
363                             | (((uint64_t) ws->header[3]) << 48)
364                             | (((uint64_t) ws->header[4]) << 40)
365                             | (((uint64_t) ws->header[5]) << 32)
366                             | (((uint64_t) ws->header[6]) << 24)
367                             | (((uint64_t) ws->header[7]) << 16)
368                             | (((uint64_t) ws->header[8]) << 8)
369                             | (uint64_t) ws->header[9];
370                         break;
371                 case 126:
372                         ws->length = (((uint64_t) ws->header[2]) << 8)
373                             | (uint64_t) ws->header[3];
374                         break;
375                 default:
376                         ws->length = FRAME_GET_PAYLOAD_LEN(ws->header[1]);
377                         break;
378                 }
379                 if (FRAME_GET_OPCODE(ws->header[0]) == OPCODE_CLOSE && ws->length != 0)
380                         ws->length -= 2;
381                 if (ws->length > ws->maxlength)
382                         goto too_long_error;
383
384                 /* compute mask */
385                 if (FRAME_GET_MASK(ws->header[1])) {
386                         ((unsigned char *)&ws->mask)[0] = ws->header[ws->szhead - 4];
387                         ((unsigned char *)&ws->mask)[1] = ws->header[ws->szhead - 3];
388                         ((unsigned char *)&ws->mask)[2] = ws->header[ws->szhead - 2];
389                         ((unsigned char *)&ws->mask)[3] = ws->header[ws->szhead - 1];
390                 } else
391                         ws->mask = 0;
392
393                 /* all heading fields are known, process */
394                 ws->state = STATE_DATA;
395                 if (ws->itf->on_extension != NULL) {
396                         if (ws->itf->on_extension(ws->closure,
397                                         FRAME_GET_FIN(ws->header[0]),
398                                         FRAME_GET_RSV1(ws->header[0]),
399                                         FRAME_GET_RSV2(ws->header[0]),
400                                         FRAME_GET_RSV3(ws->header[0]),
401                                         FRAME_GET_OPCODE(ws->header[0]),
402                                         (size_t) ws->length)) {
403                                 return 0;
404                         }
405                 }
406
407                 /* not an extension case */
408                 if (FRAME_GET_RSV1(ws->header[0]) != 0)
409                         goto protocol_error;
410                 if (FRAME_GET_RSV2(ws->header[0]) != 0)
411                         goto protocol_error;
412                 if (FRAME_GET_RSV3(ws->header[0]) != 0)
413                         goto protocol_error;
414
415                 /* handle */
416                 switch (FRAME_GET_OPCODE(ws->header[0])) {
417                 case OPCODE_CONTINUATION:
418                         ws->itf->on_continue(ws->closure,
419                                              FRAME_GET_FIN(ws->header[0]),
420                                              (size_t) ws->length);
421                         break;
422                 case OPCODE_TEXT:
423                         ws->itf->on_text(ws->closure,
424                                          FRAME_GET_FIN(ws->header[0]),
425                                          (size_t) ws->length);
426                         break;
427                 case OPCODE_BINARY:
428                         ws->itf->on_binary(ws->closure,
429                                            FRAME_GET_FIN(ws->header[0]),
430                                            (size_t) ws->length);
431                         break;
432                 case OPCODE_CLOSE:
433                         if (ws->length == 0)
434                                 code = WEBSOCKET_CODE_NOT_SET;
435                         else {
436                                 code = (uint16_t)(ws->header[ws->szhead - 2] & 0xff);
437                                 code = (uint16_t)(code << 8);
438                                 code = (uint16_t)(code | (uint16_t)(ws->header[ws->szhead - 1] & 0xff));
439                         }
440                         ws->itf->on_close(ws->closure, code, (size_t) ws->length);
441                         return 0;
442                 case OPCODE_PING:
443                         if (ws->itf->on_ping)
444                                 ws->itf->on_ping(ws->closure, ws->length);
445                         else {
446                                 websock_drop(ws);
447                                 websock_pong(ws, NULL, 0);
448                         }
449                         ws->state = STATE_INIT;
450                         break;
451                 case OPCODE_PONG:
452                         if (ws->itf->on_pong)
453                                 ws->itf->on_pong(ws->closure, ws->length);
454                         else
455                                 websock_drop(ws);
456                         ws->state = STATE_INIT;
457                         break;
458                 default:
459                         goto protocol_error;
460                 }
461                 break;
462
463         case STATE_DATA:
464                 if (ws->length)
465                         return 0;
466                 ws->state = STATE_INIT;
467                 break;
468         }
469         goto loop;
470
471  too_long_error:
472         websock_error(ws, WEBSOCKET_CODE_MESSAGE_TOO_LARGE, NULL, 0);
473         return 0;
474
475  protocol_error:
476         websock_error(ws, WEBSOCKET_CODE_PROTOCOL_ERROR, NULL, 0);
477         return 0;
478 }
479
480 static void unmask(struct websock * ws, void *buffer, size_t size)
481 {
482         uint32_t mask, *b32;
483         uint8_t m, *b8;
484
485         mask = ws->mask;
486         b8 = buffer;
487         while (size && ((sizeof(uint32_t) - 1) & (uintptr_t) b8)) {
488                 m = ((uint8_t *) & mask)[0];
489                 ((uint8_t *) & mask)[0] = ((uint8_t *) & mask)[1];
490                 ((uint8_t *) & mask)[1] = ((uint8_t *) & mask)[2];
491                 ((uint8_t *) & mask)[2] = ((uint8_t *) & mask)[3];
492                 ((uint8_t *) & mask)[3] = m;
493                 *b8++ ^= m;
494                 size--;
495         }
496         b32 = (uint32_t *) b8;
497         while (size >= sizeof(uint32_t)) {
498                 *b32++ ^= mask;
499                 size -= sizeof(uint32_t);
500         }
501         b8 = (uint8_t *) b32;
502         while (size) {
503                 m = ((uint8_t *) & mask)[0];
504                 ((uint8_t *) & mask)[0] = ((uint8_t *) & mask)[1];
505                 ((uint8_t *) & mask)[1] = ((uint8_t *) & mask)[2];
506                 ((uint8_t *) & mask)[2] = ((uint8_t *) & mask)[3];
507                 ((uint8_t *) & mask)[3] = m;
508                 *b8++ ^= m;
509                 size--;
510         }
511         ws->mask = mask;
512 }
513
514 ssize_t websock_read(struct websock * ws, void *buffer, size_t size)
515 {
516         ssize_t rc;
517
518         if (ws->state != STATE_DATA)
519                 return 0;
520
521         if (size > ws->length)
522                 size = (size_t) ws->length;
523
524         rc = ws_read(ws, buffer, size);
525         if (rc > 0) {
526                 size = (size_t) rc;
527                 ws->length -= size;
528
529                 if (ws->mask != 0)
530                         unmask(ws, buffer, size);
531         }
532         return rc;
533 }
534
535 int websock_drop(struct websock *ws)
536 {
537         char buffer[8000];
538
539         while (ws->length)
540                 if (ws_read(ws, buffer, sizeof buffer) < 0)
541                         return -1;
542         return 0;
543 }
544
545 struct websock *websock_create_v13(const struct websock_itf *itf, void *closure)
546 {
547         struct websock *result = calloc(1, sizeof *result);
548         if (result) {
549                 result->itf = itf;
550                 result->closure = closure;
551                 result->maxlength = 65000;
552         }
553         return result;
554 }
555
556 void websock_destroy(struct websock *ws)
557 {
558         free(ws);
559 }