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