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