fix a warning on 32 bits
[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 #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)((sizeof(X64)) <= (IDX) ? 0 : (((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, int loop)
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                         if (!loop)
422                                 return 0;
423                         break;
424                 case OPCODE_TEXT:
425                         ws->itf->on_text(ws->closure,
426                                          FRAME_GET_FIN(ws->header[0]),
427                                          (size_t) ws->length);
428                         if (!loop)
429                                 return 0;
430                         break;
431                 case OPCODE_BINARY:
432                         ws->itf->on_binary(ws->closure,
433                                            FRAME_GET_FIN(ws->header[0]),
434                                            (size_t) ws->length);
435                         if (!loop)
436                                 return 0;
437                         break;
438                 case OPCODE_CLOSE:
439                         if (ws->length == 0)
440                                 code = WEBSOCKET_CODE_NOT_SET;
441                         else {
442                                 code = (uint16_t)(ws->header[ws->szhead - 2] & 0xff);
443                                 code = (uint16_t)(code << 8);
444                                 code = (uint16_t)(code | (uint16_t)(ws->header[ws->szhead - 1] & 0xff));
445                         }
446                         ws->itf->on_close(ws->closure, code, (size_t) ws->length);
447                         return 0;
448                 case OPCODE_PING:
449                         if (ws->itf->on_ping)
450                                 ws->itf->on_ping(ws->closure, ws->length);
451                         else {
452                                 websock_drop(ws);
453                                 websock_pong(ws, NULL, 0);
454                         }
455                         ws->state = STATE_INIT;
456                         if (!loop)
457                                 return 0;
458                         break;
459                 case OPCODE_PONG:
460                         if (ws->itf->on_pong)
461                                 ws->itf->on_pong(ws->closure, ws->length);
462                         else
463                                 websock_drop(ws);
464                         ws->state = STATE_INIT;
465                         if (!loop)
466                                 return 0;
467                         break;
468                 default:
469                         goto protocol_error;
470                 }
471                 break;
472
473         case STATE_DATA:
474                 if (ws->length)
475                         return 0;
476                 ws->state = STATE_INIT;
477                 break;
478         }
479         goto loop;
480
481  too_long_error:
482         websock_error(ws, WEBSOCKET_CODE_MESSAGE_TOO_LARGE, NULL, 0);
483         return 0;
484
485  protocol_error:
486         websock_error(ws, WEBSOCKET_CODE_PROTOCOL_ERROR, NULL, 0);
487         return 0;
488 }
489
490 static void unmask(struct websock * ws, void *buffer, size_t size)
491 {
492         uint32_t mask, *b32;
493         uint8_t m, *b8;
494
495         mask = ws->mask;
496         b8 = buffer;
497         while (size && ((sizeof(uint32_t) - 1) & (uintptr_t) b8)) {
498                 m = ((uint8_t *) & mask)[0];
499                 ((uint8_t *) & mask)[0] = ((uint8_t *) & mask)[1];
500                 ((uint8_t *) & mask)[1] = ((uint8_t *) & mask)[2];
501                 ((uint8_t *) & mask)[2] = ((uint8_t *) & mask)[3];
502                 ((uint8_t *) & mask)[3] = m;
503                 *b8++ ^= m;
504                 size--;
505         }
506         b32 = (uint32_t *) b8;
507         while (size >= sizeof(uint32_t)) {
508                 *b32++ ^= mask;
509                 size -= sizeof(uint32_t);
510         }
511         b8 = (uint8_t *) b32;
512         while (size) {
513                 m = ((uint8_t *) & mask)[0];
514                 ((uint8_t *) & mask)[0] = ((uint8_t *) & mask)[1];
515                 ((uint8_t *) & mask)[1] = ((uint8_t *) & mask)[2];
516                 ((uint8_t *) & mask)[2] = ((uint8_t *) & mask)[3];
517                 ((uint8_t *) & mask)[3] = m;
518                 *b8++ ^= m;
519                 size--;
520         }
521         ws->mask = mask;
522 }
523
524 ssize_t websock_read(struct websock * ws, void *buffer, size_t size)
525 {
526         ssize_t rc;
527
528         if (ws->state != STATE_DATA)
529                 return 0;
530
531         if (size > ws->length)
532                 size = (size_t) ws->length;
533
534         rc = ws_read(ws, buffer, size);
535         if (rc > 0) {
536                 size = (size_t) rc;
537                 ws->length -= size;
538
539                 if (ws->mask != 0)
540                         unmask(ws, buffer, size);
541         }
542         return rc;
543 }
544
545 int websock_drop(struct websock *ws)
546 {
547         char buffer[8000];
548
549         while (ws->length)
550                 if (websock_read(ws, buffer, sizeof buffer) < 0)
551                         return -1;
552         return 0;
553 }
554
555 struct websock *websock_create_v13(const struct websock_itf *itf, void *closure)
556 {
557         struct websock *result = calloc(1, sizeof *result);
558         if (result) {
559                 result->itf = itf;
560                 result->closure = closure;
561                 result->maxlength = 65000;
562         }
563         return result;
564 }
565
566 void websock_destroy(struct websock *ws)
567 {
568         free(ws);
569 }