refactored websockets
[src/app-framework-binder.git] / src / afb-websock.c
1 /*
2  * Copyright 2016 IoT.bzh
3  * Author: José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19 #include <microhttpd.h>
20 #include <assert.h>
21 #include <errno.h>
22 #include <sys/uio.h>
23 #include <string.h>
24
25 #include <json.h>
26
27 #include <openssl/sha.h>
28
29 #include "websock.h"
30
31 #include "afb-ws-json.h"
32
33 #include "afb-req-itf.h"
34 #include "afb-method.h"
35 #include "afb-hreq.h"
36 #include "afb-websock.h"
37 #include "afb-apis.h"
38 #include "session.h"
39 #include "utils-upoll.h"
40
41 /**************** WebSocket connection upgrade ****************************/
42
43 static const char websocket_s[] = "websocket";
44 static const char sec_websocket_key_s[] = "Sec-WebSocket-Key";
45 static const char sec_websocket_version_s[] = "Sec-WebSocket-Version";
46 static const char sec_websocket_accept_s[] = "Sec-WebSocket-Accept";
47 static const char sec_websocket_protocol_s[] = "Sec-WebSocket-Protocol";
48 static const char websocket_guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
49
50 static void enc64(unsigned char *in, char *out)
51 {
52         static const char tob64[] =
53                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
54                 "abcdefghijklmnopqrstuvwxyz"
55                 "0123456789+/";
56         out[0] = tob64[in[0] >> 2];
57         out[1] = tob64[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
58         out[2] = tob64[((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)];
59         out[3] = tob64[in[2] & 0x3f];
60 }
61
62 static void make_accept_value(const char *key, char result[29])
63 {
64         unsigned char md[SHA_DIGEST_LENGTH+1];
65         size_t len = strlen(key);
66         char *buffer = alloca(len + sizeof websocket_guid - 1);
67         memcpy(buffer, key, len);
68         memcpy(buffer + len, websocket_guid, sizeof websocket_guid - 1);
69         SHA1((const unsigned char *)buffer, (unsigned long)(len + sizeof websocket_guid - 1), md);
70         assert(SHA_DIGEST_LENGTH == 20);
71         md[20] = 0;
72         enc64(&md[0], &result[0]);
73         enc64(&md[3], &result[4]);
74         enc64(&md[6], &result[8]);
75         enc64(&md[9], &result[12]);
76         enc64(&md[12], &result[16]);
77         enc64(&md[15], &result[20]);
78         enc64(&md[18], &result[24]);
79         result[27] = '=';
80         result[28] = 0;
81 }
82
83 static int headerhas(const char *header, const char *needle)
84 {
85         static const char sep[] = " \t,";
86         size_t len, n;
87
88         n = strlen(needle);
89         for(;;) {
90                 header += strspn(header, sep);
91                 if (!*header)
92                         return 0;
93                 len = strcspn(header, sep);
94                 if (n == len && 0 == strncasecmp(needle, header, n))
95                         return 1;
96                 header += len;
97         }
98 }
99
100 int afb_websock_check(struct afb_hreq *hreq, int *later)
101 {
102         const char *connection, *upgrade, *key, *version, *protocols;
103         char acceptval[29];
104         int vernum;
105         struct MHD_Response *response;
106
107         /* is an upgrade to websocket ? */
108         upgrade = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_UPGRADE);
109         if (upgrade == NULL || strcasecmp(upgrade, websocket_s))
110                 return 0;
111
112         /* is a connection for upgrade ? */
113         connection = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONNECTION);
114         if (connection == NULL || !headerhas (connection, MHD_HTTP_HEADER_UPGRADE))
115                 return 0;
116
117         /* is a get ? */
118         if(hreq->method != afb_method_get || strcasecmp(hreq->version, MHD_HTTP_VERSION_1_1))
119                 return 0;
120
121         /* has a key and a version ? */
122         key = afb_hreq_get_header(hreq, sec_websocket_key_s);
123         version = afb_hreq_get_header(hreq, sec_websocket_version_s);
124         if (key == NULL || version == NULL)
125                 return 0;
126
127         /* is a supported version ? */
128         vernum = atoi(version);
129         if (vernum != 13) {
130                 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
131                 MHD_add_response_header (response, sec_websocket_version_s, "13");
132                 MHD_queue_response (hreq->connection, MHD_HTTP_BAD_REQUEST, response);
133                 MHD_destroy_response (response);
134                 *later = 1;
135                 return 1;
136         }
137
138         /* is the protocol supported ? */
139         protocols = afb_hreq_get_header(hreq, sec_websocket_protocol_s);
140
141         /* send the accept connection */
142         make_accept_value(key, acceptval);
143         response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
144         MHD_add_response_header (response, sec_websocket_accept_s, acceptval);
145         MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, MHD_HTTP_HEADER_UPGRADE);
146         MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, websocket_s);
147         MHD_queue_response (hreq->connection, MHD_HTTP_SWITCHING_PROTOCOLS, response);
148         MHD_destroy_response (response);
149
150         *later = 0;
151         return 1;
152 }
153
154 /**************** WebSocket handling ****************************/
155
156 static ssize_t aws_writev(struct afb_websock *ws, const struct iovec *iov, int iovcnt);
157 static ssize_t aws_readv(struct afb_websock *ws, const struct iovec *iov, int iovcnt);
158 static void aws_disconnect(struct afb_websock *ws);
159 static void aws_on_close(struct afb_websock *ws, uint16_t code, size_t size);
160 static void aws_on_content(struct afb_websock *ws, int last, size_t size);
161 static void aws_on_readable(struct afb_websock *ws);
162
163 static struct websock_itf aws_itf = {
164         .writev = (void*)aws_writev,
165         .readv = (void*)aws_readv,
166         .disconnect = (void*)aws_disconnect,
167
168         .on_ping = NULL,
169         .on_pong = NULL,
170         .on_close = (void*)aws_on_close,
171         .on_text = (void*)aws_on_content,
172         .on_binary = (void*)aws_on_content,
173         .on_continue = (void*)aws_on_content,
174         .on_extension = NULL
175 };
176
177 struct afb_wsreq
178 {
179         struct afb_websock *aws;
180         struct afb_wsreq *next;
181         struct json_object *id;
182         struct json_object *name;
183         struct json_object *token;
184         struct json_object *request;
185 };
186
187 struct afb_websock
188 {
189         int fd;
190         struct afb_wsreq *requests;
191         struct MHD_Connection *connection;
192         struct AFB_clientCtx *context;
193         struct websock *ws;
194         struct upoll *up;
195         struct json_tokener *tokener;
196 };
197
198 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name);
199 static void wsreq_iterate(struct afb_wsreq *wsreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
200 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info);
201 static void wsreq_success(struct afb_wsreq *wsreq, struct json_object *obj, const char *info);
202 static int wsreq_session_create(struct afb_wsreq *wsreq);
203 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh);
204 static void wsreq_session_close(struct afb_wsreq *wsreq);
205
206 static const struct afb_req_itf wsreq_itf = {
207         .get = (void*)wsreq_get,
208         .iterate = (void*)wsreq_iterate,
209         .fail = (void*)wsreq_fail,
210         .success = (void*)wsreq_success,
211         .session_create = (void*)wsreq_session_create,
212         .session_check = (void*)wsreq_session_check,
213         .session_close = (void*)wsreq_session_close
214 };
215
216 struct afb_websock *afb_websock_create(struct afb_hreq *hreq)
217 {
218         return (void*)afb_ws_json_create(
219                         dup(MHD_get_connection_info(hreq->connection,MHD_CONNECTION_INFO_CONNECTION_FD)->connect_fd),
220                         afb_hreq_context(hreq),
221                         (void*)MHD_resume_connection,
222                         hreq->connection);
223 }
224
225 struct afb_websock *_afb_websock_create(struct afb_hreq *hreq)
226 {
227         int fd;
228         struct afb_websock *result;
229
230         fd = MHD_get_connection_info(hreq->connection,
231                                 MHD_CONNECTION_INFO_CONNECTION_FD)->connect_fd;
232         fd = dup(fd);
233         if (fd < 0)
234                 return NULL;
235
236         result = malloc(sizeof * result);
237         if (result == NULL)
238                 goto error;
239
240         result->fd = fd;
241         result->requests = NULL;
242         result->connection = hreq->connection;
243         result->context = ctxClientGet(afb_hreq_context(hreq));
244         if (result->context == NULL)
245                 goto error2;
246
247         result->tokener = json_tokener_new();
248         if (result->tokener == NULL)
249                 goto error3;
250
251         result->ws = websock_create_v13(&aws_itf, result);
252         if (result->ws == NULL)
253                 goto error4;
254
255         result->up = upoll_open(result->fd, result);
256         if (result->up == NULL)
257                 goto error5;
258
259         upoll_on_readable(result->up, (void*)aws_on_readable);
260         upoll_on_hangup(result->up, (void*)aws_disconnect);
261         return result;
262 error5:
263         websock_destroy(result->ws);
264 error4:
265         json_tokener_free(result->tokener);
266 error3:
267         ctxClientPut(result->context);
268 error2:
269         free(result);
270 error:
271         close(fd);
272         return NULL;
273 }
274
275 static ssize_t aws_writev(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
276 {
277         ssize_t rc;
278         do {
279                 rc = writev(ws->fd, iov, iovcnt);
280         } while(rc == -1 && errno == EINTR);
281         return rc;
282 }
283
284 static ssize_t aws_readv(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
285 {
286         ssize_t rc;
287         do {
288                 rc = readv(ws->fd, iov, iovcnt);
289         } while(rc == -1 && errno == EINTR);
290         return rc;
291 }
292
293 static void aws_disconnect(struct afb_websock *ws)
294 {
295         upoll_close(ws->up);
296         websock_destroy(ws->ws);
297         close(ws->fd);
298         MHD_resume_connection (ws->connection);
299         ctxClientPut(ws->context);
300         json_tokener_free(ws->tokener);
301         free(ws);
302 }
303
304 static void aws_on_close(struct afb_websock *ws, uint16_t code, size_t size)
305 {
306         /* do nothing */
307 }
308
309 static void aws_on_readable(struct afb_websock *ws)
310 {
311         websock_dispatch(ws->ws);
312 }
313
314 static int aws_handle_json(struct afb_websock *aws, struct json_object *obj)
315 {
316         struct afb_req r;
317         int count, num;
318         struct json_object *type, *id, *name, *req, *token;
319         struct afb_wsreq *wsreq;
320         const char *api, *verb;
321         size_t lenapi, lenverb;
322
323         /* protocol inspired by http://www.gir.fr/ocppjs/ocpp_srpc_spec.shtml */
324
325         /* the object must be an array of 4 or 5 elements */
326         if (!json_object_is_type(obj, json_type_array))
327                 goto error;
328         count = json_object_array_length(obj);
329         if (count < 4 || count > 5)
330                 goto error;
331
332         /* get the 5 elements: type id name request token */
333         type = json_object_array_get_idx(obj, 0);
334         id = json_object_array_get_idx(obj, 1);
335         name = json_object_array_get_idx(obj, 2);
336         req = json_object_array_get_idx(obj, 3);
337         token = json_object_array_get_idx(obj, 4);
338
339         /* check the types: int string string object string */
340         if (!json_object_is_type(type, json_type_int))
341                 goto error;
342         if (!json_object_is_type(id, json_type_string))
343                 goto error;
344         if (!json_object_is_type(name, json_type_string))
345                 goto error;
346         if (!json_object_is_type(req, json_type_object))
347                 goto error;
348         if (token != NULL && !json_object_is_type(token, json_type_string))
349                 goto error;
350
351         /* the type is only 2 */
352         num = json_object_get_int(type);
353         if (num != 2)
354                 goto error;
355
356         /* checks the api/verb structure of name */
357         api = json_object_get_string(name);
358         for (lenapi = 0 ; api[lenapi] && api[lenapi] != '/' ; lenapi++);
359         if (!lenapi || !api[lenapi])
360                 goto error;
361         verb = &api[lenapi+1];
362         for (lenverb = 0 ; verb[lenverb] && verb[lenverb] != '/' ; lenverb++);
363         if (!lenverb || verb[lenverb])
364                 goto error;
365
366         /* allocates the request data */
367         wsreq = malloc(sizeof *wsreq);
368         if (wsreq == NULL)
369                 goto error;
370
371         /* fill and record the request */
372         wsreq->aws = aws;
373         wsreq->id = json_object_get(id);
374         wsreq->name = json_object_get(name);
375         wsreq->token = json_object_get(token);
376         wsreq->request = json_object_get(req);
377         wsreq->next = aws->requests;
378         aws->requests = wsreq;
379         json_object_put(obj);
380
381         r.data = wsreq;
382         r.itf = &wsreq_itf;
383         afb_apis_call(r, aws->context, api, lenapi, verb, lenverb);
384         return 1;
385
386 error:
387         json_object_put(obj);
388         return 0;
389 }
390
391 static void aws_on_content(struct afb_websock *ws, int last, size_t size)
392 {
393         ssize_t rrc;
394         char buffer[8000];
395         struct json_object *obj;
396
397         json_tokener_reset(ws->tokener);
398         while(size) {
399                 rrc = websock_read(ws->ws, buffer,
400                                 size > sizeof buffer ? sizeof buffer : size);
401                 if (rrc < 0) {
402                         websock_close(ws->ws);
403                         return;
404                 }
405                 size -= (size_t)rrc;
406                 obj = json_tokener_parse_ex(ws->tokener, buffer, (int)rrc);
407                 if (obj != NULL) {
408                         if (!aws_handle_json(ws, obj)) {
409                                 websock_close(ws->ws);
410                                 return;
411                         }
412                 } else if (json_tokener_get_error(ws->tokener) != json_tokener_continue) {
413                         websock_close(ws->ws);
414                         return;
415                 }
416         }
417 }
418
419 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name)
420 {
421         struct afb_arg arg;
422         struct json_object *value;
423
424         if (json_object_object_get_ex(wsreq->request, name, &value)) {
425                 arg.name = name;
426                 arg.value = json_object_get_string(value);
427                 arg.size = strlen(arg.value);
428         } else {
429                 arg.name = NULL;
430                 arg.value = NULL;
431                 arg.size = 0;
432         }
433         arg.path = NULL;
434         return arg;
435 }
436
437 static void wsreq_iterate(struct afb_wsreq *wsreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
438 {
439         struct afb_arg arg;
440         struct json_object_iterator it = json_object_iter_begin(wsreq->request);
441         struct json_object_iterator end = json_object_iter_end(wsreq->request);
442
443         arg.size = 0;
444         arg.path = NULL;
445         while(!json_object_iter_equal(&it, &end)) {
446                 arg.name = json_object_iter_peek_name(&it);
447                 arg.value = json_object_get_string(json_object_iter_peek_value(&it));
448                 if (!iterator(closure, arg))
449                         break;
450                 json_object_iter_next(&it);
451         }
452 }
453
454 static int wsreq_session_create(struct afb_wsreq *wsreq)
455 {
456         struct AFB_clientCtx *context = wsreq->aws->context;
457         if (context->created)
458                 return 0;
459         return wsreq_session_check(wsreq, 1);
460 }
461
462 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh)
463 {
464         const char *token;
465         struct AFB_clientCtx *context = wsreq->aws->context;
466
467         if (wsreq->token == NULL)
468                 return 0;
469
470         token = json_object_get_string(wsreq->token);
471         if (token == NULL)
472                 return 0;
473
474         if (!ctxTokenCheck (context, token))
475                 return 0;
476
477         if (refresh) {
478                 ctxTokenNew (context);
479         }
480
481         return 1;
482 }
483
484 static void wsreq_session_close(struct afb_wsreq *wsreq)
485 {
486         struct AFB_clientCtx *context = wsreq->aws->context;
487         ctxClientClose(context);
488 }
489
490
491 static void wsreq_reply(struct afb_wsreq *wsreq, int retcode, const char *status, const char *info, json_object *resp)
492 {
493         json_object *root, *request, *reply;
494         const char *message;
495
496         /* builds the answering structure */
497         root = json_object_new_object();
498         json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
499         request = json_object_new_object();
500         json_object_object_add(root, "request", request);
501         json_object_object_add(request, "status", json_object_new_string(status));
502         if (info)
503                 json_object_object_add(request, "info", json_object_new_string(info));
504         if (resp)
505                 json_object_object_add(root, "response", resp);
506
507         /* make the reply */
508         reply = json_object_new_array();
509         json_object_array_add(reply, json_object_new_int(retcode));
510         json_object_array_add(reply, wsreq->id);
511         json_object_array_add(reply, root);
512         json_object_array_add(reply, json_object_new_string(wsreq->aws->context->token));
513
514         /* emits the reply */
515         message = json_object_to_json_string(reply);
516         websock_text(wsreq->aws->ws, message, strlen(message));
517         json_object_put(reply);
518
519         /* TODO eliminates the wsreq */
520 }
521
522 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info)
523 {
524         wsreq_reply(wsreq, 4, status, info, NULL);
525 }
526
527 static void wsreq_success(struct afb_wsreq *wsreq, json_object *obj, const char *info)
528 {
529         wsreq_reply(wsreq, 3, "success", info, obj);
530 }
531