Fix errors in migration to V3
[src/app-framework-binder.git] / src / websock.c
1 /*
2  * Copyright (C) 2016, 2017, 2018 "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 #if !defined(WEBSOCKET_DEFAULT_MAXLENGTH)
33 #  define WEBSOCKET_DEFAULT_MAXLENGTH 1048500  /* 76 less than 1M, probably enougth for headers */
34 #endif
35
36 #define FRAME_GET_FIN(BYTE)         (((BYTE) >> 7) & 0x01)
37 #define FRAME_GET_RSV1(BYTE)        (((BYTE) >> 6) & 0x01)
38 #define FRAME_GET_RSV2(BYTE)        (((BYTE) >> 5) & 0x01)
39 #define FRAME_GET_RSV3(BYTE)        (((BYTE) >> 4) & 0x01)
40 #define FRAME_GET_OPCODE(BYTE)      ( (BYTE)       & 0x0F)
41 #define FRAME_GET_MASK(BYTE)        (((BYTE) >> 7) & 0x01)
42 #define FRAME_GET_PAYLOAD_LEN(BYTE) ( (BYTE)       & 0x7F)
43
44 #define FRAME_SET_FIN(BYTE)         (((BYTE) & 0x01) << 7)
45 #define FRAME_SET_RSV1(BYTE)        (((BYTE) & 0x01) << 6)
46 #define FRAME_SET_RSV2(BYTE)        (((BYTE) & 0x01) << 5)
47 #define FRAME_SET_RSV3(BYTE)        (((BYTE) & 0x01) << 4)
48 #define FRAME_SET_OPCODE(BYTE)      ((BYTE) & 0x0F)
49 #define FRAME_SET_MASK(BYTE)        (((BYTE) & 0x01) << 7)
50 #define FRAME_SET_LENGTH(X64, IDX)  (unsigned char)((sizeof(X64)) <= (IDX) ? 0 : (((X64) >> ((IDX)*8)) & 0xFF))
51
52 #define OPCODE_CONTINUATION 0x0
53 #define OPCODE_TEXT         0x1
54 #define OPCODE_BINARY       0x2
55 #define OPCODE_CLOSE        0x8
56 #define OPCODE_PING         0x9
57 #define OPCODE_PONG         0xA
58
59 #define STATE_INIT    0
60 #define STATE_START   1
61 #define STATE_LENGTH  2
62 #define STATE_DATA    3
63
64 static size_t default_maxlength = WEBSOCKET_DEFAULT_MAXLENGTH;
65
66 struct websock {
67         int state;
68         uint64_t maxlength;
69         int lenhead, szhead;
70         uint64_t length;
71         uint32_t mask;
72         unsigned char header[14];       /* 2 + 8 + 4 */
73         const struct websock_itf *itf;
74         void *closure;
75 };
76
77 static ssize_t ws_writev(struct websock *ws, const struct iovec *iov, int iovcnt)
78 {
79         return ws->itf->writev(ws->closure, iov, iovcnt);
80 }
81
82 static ssize_t ws_readv(struct websock *ws, const struct iovec *iov, int iovcnt)
83 {
84         return ws->itf->readv(ws->closure, iov, iovcnt);
85 }
86
87 static ssize_t ws_read(struct websock *ws, void *buffer, size_t buffer_size)
88 {
89         struct iovec iov;
90         iov.iov_base = buffer;
91         iov.iov_len = buffer_size;
92         return ws_readv(ws, &iov, 1);
93 }
94
95 static int websock_send_internal_v(struct websock *ws, unsigned char first, const struct iovec *iovec, int count)
96 {
97         struct iovec iov[32];
98         int i, j;
99         size_t pos, size, len;
100         ssize_t rc;
101         unsigned char header[32];
102
103         /* checks count */
104         if (count < 0 || (count + 1) > (int)(sizeof iov / sizeof * iov)) {
105                 errno = EINVAL;
106                 return -1;
107         }
108
109         /* computes the size */
110         size = 0;
111         i = 1;
112         for (j = 0 ; j < count ; j++) {
113                 iov[i].iov_base = iovec[j].iov_base;
114                 len = iovec[j].iov_len;
115                 if (len != 0) {
116                         iov[i].iov_len = len;
117                         size += len;
118                         i++;
119                 }
120         }
121
122         /* makes the header */
123         pos = 0;
124         header[pos++] = first;
125         size = (uint64_t) size;
126         if (size < 126) {
127                 header[pos++] = FRAME_SET_MASK(0) | FRAME_SET_LENGTH(size, 0);
128         } else {
129                 if (size < 65536) {
130                         header[pos++] = FRAME_SET_MASK(0) | 126;
131                 } else {
132                         header[pos++] = FRAME_SET_MASK(0) | 127;
133                         header[pos++] = FRAME_SET_LENGTH(size, 7);
134                         header[pos++] = FRAME_SET_LENGTH(size, 6);
135                         header[pos++] = FRAME_SET_LENGTH(size, 5);
136                         header[pos++] = FRAME_SET_LENGTH(size, 4);
137                         header[pos++] = FRAME_SET_LENGTH(size, 3);
138                         header[pos++] = FRAME_SET_LENGTH(size, 2);
139                 }
140                 header[pos++] = FRAME_SET_LENGTH(size, 1);
141                 header[pos++] = FRAME_SET_LENGTH(size, 0);
142         }
143
144         /* allocates the vec */
145         iov[0].iov_base = header;
146         iov[0].iov_len = pos;
147         rc = ws_writev(ws, iov, i);
148
149         return rc < 0 ? -1 : 0;
150 }
151
152 static int websock_send_internal(struct websock *ws, unsigned char first, const void *buffer, size_t size)
153 {
154         struct iovec iov;
155
156         iov.iov_base = (void *)buffer;
157         iov.iov_len = size;
158         return websock_send_internal_v(ws, first, &iov, 1);
159 }
160
161 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)
162 {
163         unsigned char first = (unsigned char)(FRAME_SET_FIN(last)
164                                 | FRAME_SET_RSV1(rsv1)
165                                 | FRAME_SET_RSV1(rsv2)
166                                 | FRAME_SET_RSV1(rsv3)
167                                 | FRAME_SET_OPCODE(opcode));
168         return websock_send_internal_v(ws, first, iovec, count);
169 }
170
171 static inline int websock_send(struct websock *ws, int last, int rsv1, int rsv2, int rsv3, int opcode, const void *buffer, size_t size)
172 {
173         unsigned char first = (unsigned char)(FRAME_SET_FIN(last)
174                                 | FRAME_SET_RSV1(rsv1)
175                                 | FRAME_SET_RSV1(rsv2)
176                                 | FRAME_SET_RSV1(rsv3)
177                                 | FRAME_SET_OPCODE(opcode));
178         return websock_send_internal(ws, first, buffer, size);
179 }
180
181 int websock_close_empty(struct websock *ws)
182 {
183         return websock_close(ws, WEBSOCKET_CODE_NOT_SET, NULL, 0);
184 }
185
186 int websock_close(struct websock *ws, uint16_t code, const void *data, size_t length)
187 {
188         unsigned char buffer[2];
189         struct iovec iov[2];
190
191         if (code == WEBSOCKET_CODE_NOT_SET && length == 0)
192                 return websock_send(ws, 1, 0, 0, 0, OPCODE_CLOSE, NULL, 0);
193
194         /* checks the length */
195         if (length > 123) {
196                 errno = EINVAL;
197                 return -1;
198         }
199
200         /* prepare the buffer */
201         buffer[0] = (unsigned char)((code >> 8) & 0xFF);
202         buffer[1] = (unsigned char)(code & 0xFF);
203
204         /* Send server-side closing handshake */
205         iov[0].iov_base = (void *)buffer;
206         iov[0].iov_len = 2;
207         iov[1].iov_base = (void *)data;
208         iov[1].iov_len = length;
209         return websock_send_v(ws, 1, 0, 0, 0, OPCODE_CLOSE, iov, 2);
210 }
211
212 int websock_ping(struct websock *ws, const void *data, size_t length)
213 {
214         /* checks the length */
215         if (length > 125) {
216                 errno = EINVAL;
217                 return -1;
218         }
219
220         return websock_send(ws, 1, 0, 0, 0, OPCODE_PING, data, length);
221 }
222
223 int websock_pong(struct websock *ws, const void *data, size_t length)
224 {
225         /* checks the length */
226         if (length > 125) {
227                 errno = EINVAL;
228                 return -1;
229         }
230
231         return websock_send(ws, 1, 0, 0, 0, OPCODE_PONG, data, length);
232 }
233
234 int websock_text(struct websock *ws, int last, const void *text, size_t length)
235 {
236         return websock_send(ws, last, 0, 0, 0, OPCODE_TEXT, text, length);
237 }
238
239 int websock_text_v(struct websock *ws, int last, const struct iovec *iovec, int count)
240 {
241         return websock_send_v(ws, last, 0, 0, 0, OPCODE_TEXT, iovec, count);
242 }
243
244 int websock_binary(struct websock *ws, int last, const void *data, size_t length)
245 {
246         return websock_send(ws, last, 0, 0, 0, OPCODE_BINARY, data, length);
247 }
248
249 int websock_binary_v(struct websock *ws, int last, const struct iovec *iovec, int count)
250 {
251         return websock_send_v(ws, last, 0, 0, 0, OPCODE_BINARY, iovec, count);
252 }
253
254 int websock_continue(struct websock *ws, int last, const void *data, size_t length)
255 {
256         return websock_send(ws, last, 0, 0, 0, OPCODE_CONTINUATION, data, length);
257 }
258
259 int websock_continue_v(struct websock *ws, int last, const struct iovec *iovec, int count)
260 {
261         return websock_send_v(ws, last, 0, 0, 0, OPCODE_CONTINUATION, iovec, count);
262 }
263
264 int websock_error(struct websock *ws, uint16_t code, const void *data, size_t size)
265 {
266         int rc = websock_close(ws, code, data, size);
267         if (ws->itf->on_error != NULL)
268                 ws->itf->on_error(ws->closure, code, data, size);
269         return rc;
270 }
271
272 static int read_header(struct websock *ws)
273 {
274         if (ws->lenhead < ws->szhead) {
275                 ssize_t rbc =
276                     ws_read(ws, &ws->header[ws->lenhead], (size_t)(ws->szhead - ws->lenhead));
277                 if (rbc < 0)
278                         return -1;
279                 ws->lenhead += (int)rbc;
280         }
281         return 0;
282 }
283
284 static int check_control_header(struct websock *ws)
285 {
286         /* sanity checks */
287         if (FRAME_GET_RSV1(ws->header[0]) != 0)
288                 return 0;
289         if (FRAME_GET_RSV2(ws->header[0]) != 0)
290                 return 0;
291         if (FRAME_GET_RSV3(ws->header[0]) != 0)
292                 return 0;
293         if (FRAME_GET_PAYLOAD_LEN(ws->header[1]) > 125)
294                 return 0;
295         if (FRAME_GET_OPCODE(ws->header[0]) == OPCODE_CLOSE)
296                 return FRAME_GET_PAYLOAD_LEN(ws->header[1]) != 1;
297         return 1;
298 }
299
300 int websock_dispatch(struct websock *ws, int loop)
301 {
302         uint16_t code;
303 loop:
304         switch (ws->state) {
305         case STATE_INIT:
306                 ws->lenhead = 0;
307                 ws->szhead = 2;
308                 ws->state = STATE_START;
309                 /*@fallthrough@*/
310
311         case STATE_START:
312                 /* read the header */
313                 if (read_header(ws))
314                         return -1;
315                 else if (ws->lenhead < ws->szhead)
316                         return 0;
317                 /* fast track */
318                 switch (FRAME_GET_OPCODE(ws->header[0])) {
319                 case OPCODE_CONTINUATION:
320                 case OPCODE_TEXT:
321                 case OPCODE_BINARY:
322                         break;
323                 case OPCODE_CLOSE:
324                         if (!check_control_header(ws))
325                                 goto protocol_error;
326                         if (FRAME_GET_PAYLOAD_LEN(ws->header[1]))
327                                 ws->szhead += 2;
328                         break;
329                 case OPCODE_PING:
330                 case OPCODE_PONG:
331                         if (!check_control_header(ws))
332                                 goto protocol_error;
333                 default:
334                         break;
335                 }
336                 /* update heading size */
337                 switch (FRAME_GET_PAYLOAD_LEN(ws->header[1])) {
338                 case 127:
339                         ws->szhead += 6;
340                         /*@fallthrough@*/
341                 case 126:
342                         ws->szhead += 2;
343                         /*@fallthrough@*/
344                 default:
345                         ws->szhead += 4 * FRAME_GET_MASK(ws->header[1]);
346                 }
347                 ws->state = STATE_LENGTH;
348                 /*@fallthrough@*/
349
350         case STATE_LENGTH:
351                 /* continue to read the header */
352                 if (read_header(ws))
353                         return -1;
354                 else if (ws->lenhead < ws->szhead)
355                         return 0;
356
357                 /* compute length */
358                 switch (FRAME_GET_PAYLOAD_LEN(ws->header[1])) {
359                 case 127:
360                         ws->length = (((uint64_t) ws->header[2]) << 56)
361                             | (((uint64_t) ws->header[3]) << 48)
362                             | (((uint64_t) ws->header[4]) << 40)
363                             | (((uint64_t) ws->header[5]) << 32)
364                             | (((uint64_t) ws->header[6]) << 24)
365                             | (((uint64_t) ws->header[7]) << 16)
366                             | (((uint64_t) ws->header[8]) << 8)
367                             | (uint64_t) ws->header[9];
368                         break;
369                 case 126:
370                         ws->length = (((uint64_t) ws->header[2]) << 8)
371                             | (uint64_t) ws->header[3];
372                         break;
373                 default:
374                         ws->length = FRAME_GET_PAYLOAD_LEN(ws->header[1]);
375                         break;
376                 }
377                 if (FRAME_GET_OPCODE(ws->header[0]) == OPCODE_CLOSE && ws->length != 0)
378                         ws->length -= 2;
379                 if (ws->length > ws->maxlength)
380                         goto too_long_error;
381
382                 /* compute mask */
383                 if (FRAME_GET_MASK(ws->header[1])) {
384                         ((unsigned char *)&ws->mask)[0] = ws->header[ws->szhead - 4];
385                         ((unsigned char *)&ws->mask)[1] = ws->header[ws->szhead - 3];
386                         ((unsigned char *)&ws->mask)[2] = ws->header[ws->szhead - 2];
387                         ((unsigned char *)&ws->mask)[3] = ws->header[ws->szhead - 1];
388                 } else
389                         ws->mask = 0;
390
391                 /* all heading fields are known, process */
392                 ws->state = STATE_DATA;
393                 if (ws->itf->on_extension != NULL) {
394                         if (ws->itf->on_extension(ws->closure,
395                                         FRAME_GET_FIN(ws->header[0]),
396                                         FRAME_GET_RSV1(ws->header[0]),
397                                         FRAME_GET_RSV2(ws->header[0]),
398                                         FRAME_GET_RSV3(ws->header[0]),
399                                         FRAME_GET_OPCODE(ws->header[0]),
400                                         (size_t) ws->length)) {
401                                 return 0;
402                         }
403                 }
404
405                 /* not an extension case */
406                 if (FRAME_GET_RSV1(ws->header[0]) != 0)
407                         goto protocol_error;
408                 if (FRAME_GET_RSV2(ws->header[0]) != 0)
409                         goto protocol_error;
410                 if (FRAME_GET_RSV3(ws->header[0]) != 0)
411                         goto protocol_error;
412
413                 /* handle */
414                 switch (FRAME_GET_OPCODE(ws->header[0])) {
415                 case OPCODE_CONTINUATION:
416                         ws->itf->on_continue(ws->closure,
417                                              FRAME_GET_FIN(ws->header[0]),
418                                              (size_t) ws->length);
419                         if (!loop)
420                                 return 0;
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                         if (!loop)
427                                 return 0;
428                         break;
429                 case OPCODE_BINARY:
430                         ws->itf->on_binary(ws->closure,
431                                            FRAME_GET_FIN(ws->header[0]),
432                                            (size_t) ws->length);
433                         if (!loop)
434                                 return 0;
435                         break;
436                 case OPCODE_CLOSE:
437                         if (ws->length == 0)
438                                 code = WEBSOCKET_CODE_NOT_SET;
439                         else {
440                                 code = (uint16_t)(ws->header[ws->szhead - 2] & 0xff);
441                                 code = (uint16_t)(code << 8);
442                                 code = (uint16_t)(code | (uint16_t)(ws->header[ws->szhead - 1] & 0xff));
443                         }
444                         ws->itf->on_close(ws->closure, code, (size_t) ws->length);
445                         return 0;
446                 case OPCODE_PING:
447                         if (ws->itf->on_ping)
448                                 ws->itf->on_ping(ws->closure, ws->length);
449                         else {
450                                 websock_drop(ws);
451                                 websock_pong(ws, NULL, 0);
452                         }
453                         ws->state = STATE_INIT;
454                         if (!loop)
455                                 return 0;
456                         break;
457                 case OPCODE_PONG:
458                         if (ws->itf->on_pong)
459                                 ws->itf->on_pong(ws->closure, ws->length);
460                         else
461                                 websock_drop(ws);
462                         ws->state = STATE_INIT;
463                         if (!loop)
464                                 return 0;
465                         break;
466                 default:
467                         goto protocol_error;
468                 }
469                 break;
470
471         case STATE_DATA:
472                 if (ws->length)
473                         return 0;
474                 ws->state = STATE_INIT;
475                 break;
476         }
477         goto loop;
478
479  too_long_error:
480         websock_error(ws, WEBSOCKET_CODE_MESSAGE_TOO_LARGE, NULL, 0);
481         return 0;
482
483  protocol_error:
484         websock_error(ws, WEBSOCKET_CODE_PROTOCOL_ERROR, NULL, 0);
485         return 0;
486 }
487
488 static void unmask(struct websock * ws, void *buffer, size_t size)
489 {
490         uint32_t mask, *b32;
491         uint8_t m, *b8;
492
493         mask = ws->mask;
494         b8 = buffer;
495         while (size && ((sizeof(uint32_t) - 1) & (uintptr_t) b8)) {
496                 m = ((uint8_t *) & mask)[0];
497                 ((uint8_t *) & mask)[0] = ((uint8_t *) & mask)[1];
498                 ((uint8_t *) & mask)[1] = ((uint8_t *) & mask)[2];
499                 ((uint8_t *) & mask)[2] = ((uint8_t *) & mask)[3];
500                 ((uint8_t *) & mask)[3] = m;
501                 *b8++ ^= m;
502                 size--;
503         }
504         b32 = (uint32_t *) b8;
505         while (size >= sizeof(uint32_t)) {
506                 *b32++ ^= mask;
507                 size -= sizeof(uint32_t);
508         }
509         b8 = (uint8_t *) b32;
510         while (size) {
511                 m = ((uint8_t *) & mask)[0];
512                 ((uint8_t *) & mask)[0] = ((uint8_t *) & mask)[1];
513                 ((uint8_t *) & mask)[1] = ((uint8_t *) & mask)[2];
514                 ((uint8_t *) & mask)[2] = ((uint8_t *) & mask)[3];
515                 ((uint8_t *) & mask)[3] = m;
516                 *b8++ ^= m;
517                 size--;
518         }
519         ws->mask = mask;
520 }
521
522 ssize_t websock_read(struct websock * ws, void *buffer, size_t size)
523 {
524         ssize_t rc;
525
526         if (ws->state != STATE_DATA)
527                 return 0;
528
529         if (size > ws->length)
530                 size = (size_t) ws->length;
531
532         rc = ws_read(ws, buffer, size);
533         if (rc > 0) {
534                 size = (size_t) rc;
535                 ws->length -= size;
536
537                 if (ws->mask != 0)
538                         unmask(ws, buffer, size);
539         }
540         return rc;
541 }
542
543 int websock_drop(struct websock *ws)
544 {
545         char buffer[8000];
546
547         while (ws->length)
548                 if (websock_read(ws, buffer, sizeof buffer) < 0)
549                         return -1;
550         return 0;
551 }
552
553 struct websock *websock_create_v13(const struct websock_itf *itf, void *closure)
554 {
555         struct websock *result = calloc(1, sizeof *result);
556         if (result) {
557                 result->itf = itf;
558                 result->closure = closure;
559                 result->maxlength = default_maxlength;
560         }
561         return result;
562 }
563
564 void websock_destroy(struct websock *ws)
565 {
566         free(ws);
567 }
568
569 void websock_set_default_max_length(size_t maxlen)
570 {
571         default_maxlength = maxlen;
572 }
573
574 void websock_set_max_length(struct websock *ws, size_t maxlen)
575 {
576         ws->maxlength = (uint64_t)maxlen;
577 }
578
579 const char *websocket_explain_error(uint16_t code)
580 {
581         static const char *msgs[] = {
582                 "OK",                /* 1000 */
583                 "GOING_AWAY",        /* 1001 */
584                 "PROTOCOL_ERROR",    /* 1002 */
585                 "CANT_ACCEPT",       /* 1003 */
586                 "RESERVED",          /* 1004 */
587                 "NOT_SET",           /* 1005 */
588                 "ABNORMAL",          /* 1006 */
589                 "INVALID_UTF8",      /* 1007 */
590                 "POLICY_VIOLATION",  /* 1008 */
591                 "MESSAGE_TOO_LARGE", /* 1009 */
592                 "EXPECT_EXTENSION",  /* 1010 */
593                 "INTERNAL_ERROR",    /* 1011 */
594         };
595         if (code < 1000 || (code - 1000) >= (sizeof msgs / sizeof *msgs))
596                 return "?";
597         return msgs[code - 1000];
598 }