fix bug
[src/app-framework-binder.git] / src / websock.c
1 /*
2  * Copyright 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_OPCODE(BYTE)       ((BYTE) & 0x0F)
44 #define FRAME_SET_MASK(BYTE)        (((BYTE) & 0x01) << 7)
45 #define FRAME_SET_LENGTH(X64, IDX)  (unsigned char)(((X64) >> ((IDX)*8)) & 0xFF)
46
47 #define OPCODE_CONTINUATION 0x0
48 #define OPCODE_TEXT         0x1
49 #define OPCODE_BINARY       0x2
50 #define OPCODE_CLOSE        0x8
51 #define OPCODE_PING         0x9
52 #define OPCODE_PONG         0xA
53
54 #define STATE_INIT    0
55 #define STATE_START   1
56 #define STATE_LENGTH  2
57 #define STATE_DATA    3
58 #define STATE_CLOSED  4
59
60 struct websock {
61         int state;
62         uint64_t maxlength;
63         int lenhead, szhead;
64         uint64_t length;
65         uint32_t mask;
66         unsigned char header[14];       /* 2 + 8 + 4 */
67         const struct websock_itf *itf;
68         void *closure;
69 };
70
71 static ssize_t ws_writev(struct websock *ws, const struct iovec *iov, int iovcnt)
72 {
73         return ws->itf->writev(ws->closure, iov, iovcnt);
74 }
75
76 static ssize_t ws_readv(struct websock *ws, const struct iovec *iov, int iovcnt)
77 {
78         return ws->itf->readv(ws->closure, iov, iovcnt);
79 }
80
81 #if 0
82 static ssize_t ws_write(struct websock *ws, const void *buffer, size_t buffer_size)
83 {
84         struct iovec iov;
85         iov.iov_base = (void *)buffer;  /* const cast */
86         iov.iov_len = buffer_size;
87         return ws_writev(ws, &iov, 1);
88 }
89 #endif
90
91 static ssize_t ws_read(struct websock *ws, void *buffer, size_t buffer_size)
92 {
93         struct iovec iov;
94         iov.iov_base = buffer;
95         iov.iov_len = buffer_size;
96         return ws_readv(ws, &iov, 1);
97 }
98
99 static ssize_t websock_send(struct websock *ws, unsigned char opcode,
100                             const void *buffer, size_t buffer_size)
101 {
102         struct iovec iov[2];
103         size_t pos;
104         ssize_t rc;
105         unsigned char header[32];
106
107         if (ws->state == STATE_CLOSED)
108                 return 0;
109
110         pos = 0;
111         header[pos++] = (unsigned char)(FRAME_SET_FIN(1) | FRAME_SET_OPCODE(opcode));
112         buffer_size = (uint64_t) buffer_size;
113         if (buffer_size < 126) {
114                 header[pos++] =
115                     FRAME_SET_MASK(0) | FRAME_SET_LENGTH(buffer_size, 0);
116         } else {
117                 if (buffer_size < 65536) {
118                         header[pos++] = FRAME_SET_MASK(0) | 126;
119                 } else {
120                         header[pos++] = FRAME_SET_MASK(0) | 127;
121                         header[pos++] = FRAME_SET_LENGTH(buffer_size, 7);
122                         header[pos++] = FRAME_SET_LENGTH(buffer_size, 6);
123                         header[pos++] = FRAME_SET_LENGTH(buffer_size, 5);
124                         header[pos++] = FRAME_SET_LENGTH(buffer_size, 4);
125                         header[pos++] = FRAME_SET_LENGTH(buffer_size, 3);
126                         header[pos++] = FRAME_SET_LENGTH(buffer_size, 2);
127                 }
128                 header[pos++] = FRAME_SET_LENGTH(buffer_size, 1);
129                 header[pos++] = FRAME_SET_LENGTH(buffer_size, 0);
130         }
131
132         iov[0].iov_base = header;
133         iov[0].iov_len = pos;
134         iov[1].iov_base = (void *)buffer;       /* const cast */
135         iov[1].iov_len = buffer_size;
136
137         rc = ws_writev(ws, iov, 1 + !!buffer_size);
138
139         if (opcode == OPCODE_CLOSE) {
140                 ws->length = 0;
141                 ws->state = STATE_CLOSED;
142                 ws->itf->disconnect(ws->closure);
143         }
144         return rc;
145 }
146
147 void websock_close(struct websock *ws)
148 {
149         websock_send(ws, OPCODE_CLOSE, NULL, 0);
150 }
151
152 void websock_close_code(struct websock *ws, uint16_t code)
153 {
154         unsigned char buffer[2];
155         /* Send server-side closing handshake */
156         buffer[0] = (unsigned char)((code >> 8) & 0xFF);
157         buffer[1] = (unsigned char)(code & 0xFF);
158         websock_send(ws, OPCODE_CLOSE, buffer, 2);
159 }
160
161 void websock_ping(struct websock *ws)
162 {
163         websock_send(ws, OPCODE_PING, NULL, 0);
164 }
165
166 void websock_pong(struct websock *ws)
167 {
168         websock_send(ws, OPCODE_PONG, NULL, 0);
169 }
170
171 void websock_text(struct websock *ws, const char *text, size_t length)
172 {
173         websock_send(ws, OPCODE_TEXT, NULL, 0);
174 }
175
176 void websock_binary(struct websock *ws, const void *data, size_t length)
177 {
178         websock_send(ws, OPCODE_BINARY, NULL, 0);
179 }
180
181 static int read_header(struct websock *ws)
182 {
183         if (ws->lenhead < ws->szhead) {
184                 ssize_t rbc =
185                     ws_read(ws, &ws->header[ws->lenhead], (size_t)(ws->szhead - ws->lenhead));
186                 if (rbc < 0)
187                         return -1;
188                 ws->lenhead += (int)rbc;
189         }
190         return 0;
191 }
192
193 int websock_dispatch(struct websock *ws)
194 {
195  loop:
196         switch (ws->state) {
197         case STATE_INIT:
198                 ws->lenhead = 0;
199                 ws->szhead = 2;
200                 ws->state = STATE_START;
201
202         case STATE_START:
203                 /* read the header */
204                 if (!read_header(ws))
205                         return -1;
206                 else if (ws->lenhead < ws->szhead)
207                         return 0;
208                 /* sanity checks */
209                 if (FRAME_GET_RSV1(ws->header[0]) != 0)
210                         goto protocol_error;
211                 if (FRAME_GET_RSV2(ws->header[0]) != 0)
212                         goto protocol_error;
213                 if (FRAME_GET_RSV3(ws->header[0]) != 0)
214                         goto protocol_error;
215                 /* fast track */
216                 switch (FRAME_GET_OPCODE(ws->header[0])) {
217                 case OPCODE_CONTINUATION:
218                 case OPCODE_TEXT:
219                 case OPCODE_BINARY:
220                         break;
221                 case OPCODE_CLOSE:
222                         if (FRAME_GET_MASK(ws->header[1]))
223                                 goto protocol_error;
224                         if (FRAME_GET_PAYLOAD_LEN(ws->header[1]) == 1)
225                                 goto protocol_error;
226                         if (FRAME_GET_PAYLOAD_LEN(ws->header[1]))
227                                 ws->szhead += 2;
228                         break;
229                 case OPCODE_PING:
230                         if (FRAME_GET_MASK(ws->header[1]))
231                                 goto protocol_error;
232                         if (FRAME_GET_PAYLOAD_LEN(ws->header[1]) != 0)
233                                 goto protocol_error;
234                         if (ws->itf->on_ping)
235                                 ws->itf->on_ping(ws->closure);
236                         else
237                                 websock_pong(ws);
238                         ws->state = STATE_INIT;
239                         goto loop;
240                 case OPCODE_PONG:
241                         if (FRAME_GET_MASK(ws->header[1]))
242                                 goto protocol_error;
243                         if (FRAME_GET_PAYLOAD_LEN(ws->header[1]) != 0)
244                                 goto protocol_error;
245                         if (ws->itf->on_pong)
246                                 ws->itf->on_pong(ws->closure);
247                         ws->state = STATE_INIT;
248                         goto loop;
249                 default:
250                         goto protocol_error;
251                 }
252                 /* update heading size */
253                 switch (FRAME_GET_PAYLOAD_LEN(ws->header[1])) {
254                 case 127:
255                         ws->szhead += 6;
256                 case 126:
257                         ws->szhead += 2;
258                 default:
259                         ws->szhead += 4 * FRAME_GET_MASK(ws->header[1]);
260                 }
261                 ws->state = STATE_LENGTH;
262
263         case STATE_LENGTH:
264                 /* continue to read the header */
265                 if (!read_header(ws))
266                         return -1;
267                 else if (ws->lenhead < ws->szhead)
268                         return 0;
269                 /* compute header values */
270                 switch (FRAME_GET_PAYLOAD_LEN(ws->header[1])) {
271                 case 127:
272                         ws->length = (((uint64_t) ws->header[2]) << 56)
273                             | (((uint64_t) ws->header[3]) << 48)
274                             | (((uint64_t) ws->header[4]) << 40)
275                             | (((uint64_t) ws->header[5]) << 32)
276                             | (((uint64_t) ws->header[6]) << 24)
277                             | (((uint64_t) ws->header[7]) << 16)
278                             | (((uint64_t) ws->header[8]) << 8)
279                             | (uint64_t) ws->header[9];
280                         break;
281                 case 126:
282                         ws->length = (((uint64_t) ws->header[2]) << 8)
283                             | (uint64_t) ws->header[3];
284                         break;
285                 default:
286                         ws->length = FRAME_GET_PAYLOAD_LEN(ws->header[1]);
287                         break;
288                 }
289                 if (ws->length > ws->maxlength)
290                         goto too_long_error;
291                 if (FRAME_GET_MASK(ws->header[1])) {
292                         ((unsigned char *)&ws->mask)[0] = ws->header[ws->szhead - 4];
293                         ((unsigned char *)&ws->mask)[1] = ws->header[ws->szhead - 3];
294                         ((unsigned char *)&ws->mask)[2] = ws->header[ws->szhead - 2];
295                         ((unsigned char *)&ws->mask)[3] = ws->header[ws->szhead - 1];
296                 } else
297                         ws->mask = 0;
298                 ws->state = STATE_DATA;
299                 switch (FRAME_GET_OPCODE(ws->header[0])) {
300                 case OPCODE_CONTINUATION:
301                         ws->itf->on_continue(ws->closure,
302                                              FRAME_GET_FIN(ws->header[0]),
303                                              (size_t) ws->length);
304                         break;
305                 case OPCODE_TEXT:
306                         ws->itf->on_text(ws->closure,
307                                          FRAME_GET_FIN(ws->header[0]),
308                                          (size_t) ws->length);
309                         break;
310                 case OPCODE_BINARY:
311                         ws->itf->on_binary(ws->closure,
312                                            FRAME_GET_FIN(ws->header[0]),
313                                            (size_t) ws->length);
314                         break;
315                 case OPCODE_CLOSE:
316                         ws->state = STATE_CLOSED;
317                         if (ws->length)
318                                 ws->itf->on_close(ws->closure,
319                                                   (uint16_t)((((uint16_t) ws-> header[2]) << 8) | ((uint16_t) ws->header[3])),
320                                                   (size_t) ws->length);
321                         else
322                                 ws->itf->on_close(ws->closure,
323                                                   STATUS_CODE_UNSET, 0);
324                         ws->itf->disconnect(ws->closure);
325                         return 0;
326                 }
327                 break;
328
329         case STATE_DATA:
330                 if (ws->length)
331                         return 0;
332                 ws->state = STATE_INIT;
333                 break;
334
335         case STATE_CLOSED:
336                 return 0;
337         }
338         goto loop;
339
340  too_long_error:
341         websock_close_code(ws, STATUS_CODE_MESSAGE_TOO_LARGE);
342         return 0;
343
344  protocol_error:
345         websock_close_code(ws, STATUS_CODE_PROTOCOL_ERROR);
346         return 0;
347 }
348
349 ssize_t websock_read(struct websock * ws, void *buffer, size_t size)
350 {
351         uint32_t mask, *b32;
352         uint8_t m, *b8;
353         ssize_t rc;
354
355         if (ws->state != STATE_DATA && ws->state != STATE_CLOSED)
356                 return 0;
357
358         if (size > ws->length)
359                 size = (size_t) ws->length;
360
361         rc = ws_read(ws, buffer, size);
362         if (rc > 0) {
363                 size = (size_t) rc;
364                 ws->length -= size;
365
366                 if (ws->mask) {
367                         mask = ws->mask;
368                         b8 = buffer;
369                         while (size && ((sizeof(uint32_t) - 1) & (uintptr_t) b8)) {
370                                 m = ((uint8_t *) & mask)[0];
371                                 ((uint8_t *) & mask)[0] = ((uint8_t *) & mask)[1];
372                                 ((uint8_t *) & mask)[1] = ((uint8_t *) & mask)[2];
373                                 ((uint8_t *) & mask)[2] = ((uint8_t *) & mask)[3];
374                                 ((uint8_t *) & mask)[3] = m;
375                                 *b8++ ^= m;
376                                 size--;
377                         }
378                         b32 = (uint32_t *) b8;
379                         while (size >= sizeof(uint32_t)) {
380                                 *b32++ ^= mask;
381                                 size -= sizeof(uint32_t);
382                         }
383                         b8 = (uint8_t *) b32;
384                         while (size) {
385                                 m = ((uint8_t *) & mask)[0];
386                                 ((uint8_t *) & mask)[0] = ((uint8_t *) & mask)[1];
387                                 ((uint8_t *) & mask)[1] = ((uint8_t *) & mask)[2];
388                                 ((uint8_t *) & mask)[2] = ((uint8_t *) & mask)[3];
389                                 ((uint8_t *) & mask)[3] = m;
390                                 *b8++ ^= m;
391                                 size--;
392                         }
393                         ws->mask = mask;
394                 }
395         }
396         return rc;
397 }
398
399 void websock_drop(struct websock *ws)
400 {
401         char buffer[4096];
402
403         while (ws->length && ws_read(ws, buffer, sizeof buffer) >= 0) ;
404 }
405
406 struct websock *websock_create(const struct websock_itf *itf, void *closure)
407 {
408         struct websock *result = calloc(1, sizeof *result);
409         if (result) {
410                 result->itf = itf;
411                 result->closure = closure;
412         }
413         return result;
414 }
415
416 void websock_destroy(struct websock *ws)
417 {
418         free(ws);
419 }