typo
[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-req-itf.h"
32 #include "afb-method.h"
33 #include "afb-hreq.h"
34 #include "afb-websock.h"
35 #include "afb-apis.h"
36 #include "session.h"
37 #include "utils-upoll.h"
38
39 /**************** WebSocket connection upgrade ****************************/
40
41 static const char websocket_s[] = "websocket";
42 static const char sec_websocket_key_s[] = "Sec-WebSocket-Key";
43 static const char sec_websocket_version_s[] = "Sec-WebSocket-Version";
44 static const char sec_websocket_accept_s[] = "Sec-WebSocket-Accept";
45 static const char sec_websocket_protocol_s[] = "Sec-WebSocket-Protocol";
46 static const char websocket_guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
47
48 static void enc64(unsigned char *in, char *out)
49 {
50         static const char tob64[] =
51                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
52                 "abcdefghijklmnopqrstuvwxyz"
53                 "0123456789+/";
54         out[0] = tob64[in[0] >> 2];
55         out[1] = tob64[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
56         out[2] = tob64[((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)];
57         out[3] = tob64[in[2] & 0x3f];
58 }
59
60 static void make_accept_value(const char *key, char result[29])
61 {
62         unsigned char md[SHA_DIGEST_LENGTH+1];
63         size_t len = strlen(key);
64         char *buffer = alloca(len + sizeof websocket_guid - 1);
65         memcpy(buffer, key, len);
66         memcpy(buffer + len, websocket_guid, sizeof websocket_guid - 1);
67         SHA1((const unsigned char *)buffer, (unsigned long)(len + sizeof websocket_guid - 1), md);
68         assert(SHA_DIGEST_LENGTH == 20);
69         md[20] = 0;
70         enc64(&md[0], &result[0]);
71         enc64(&md[3], &result[4]);
72         enc64(&md[6], &result[8]);
73         enc64(&md[9], &result[12]);
74         enc64(&md[12], &result[16]);
75         enc64(&md[15], &result[20]);
76         enc64(&md[18], &result[24]);
77         result[27] = '=';
78         result[28] = 0;
79 }
80
81 static int headerhas(const char *header, const char *needle)
82 {
83         static const char sep[] = " \t,";
84         size_t len, n;
85
86         n = strlen(needle);
87         for(;;) {
88                 header += strspn(header, sep);
89                 if (!*header)
90                         return 0;
91                 len = strcspn(header, sep);
92                 if (n == len && 0 == strncasecmp(needle, header, n))
93                         return 1;
94                 header += len;
95         }
96 }
97
98 int afb_websock_check(struct afb_hreq *hreq, int *later)
99 {
100         const char *connection, *upgrade, *key, *version, *protocols;
101         char acceptval[29];
102         int vernum;
103         struct MHD_Response *response;
104
105         /* is an upgrade to websocket ? */
106         upgrade = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_UPGRADE);
107         if (upgrade == NULL || strcasecmp(upgrade, websocket_s))
108                 return 0;
109
110         /* is a connection for upgrade ? */
111         connection = afb_hreq_get_header(hreq, MHD_HTTP_HEADER_CONNECTION);
112         if (connection == NULL || !headerhas (connection, MHD_HTTP_HEADER_UPGRADE))
113                 return 0;
114
115         /* is a get ? */
116         if(hreq->method != afb_method_get || strcasecmp(hreq->version, MHD_HTTP_VERSION_1_1))
117                 return 0;
118
119         /* has a key and a version ? */
120         key = afb_hreq_get_header(hreq, sec_websocket_key_s);
121         version = afb_hreq_get_header(hreq, sec_websocket_version_s);
122         if (key == NULL || version == NULL)
123                 return 0;
124
125         /* is a supported version ? */
126         vernum = atoi(version);
127         if (vernum != 13) {
128                 response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
129                 MHD_add_response_header (response, sec_websocket_version_s, "13");
130                 MHD_queue_response (hreq->connection, MHD_HTTP_BAD_REQUEST, response);
131                 MHD_destroy_response (response);
132                 *later = 1;
133                 return 1;
134         }
135
136         /* is the protocol supported ? */
137         protocols = afb_hreq_get_header(hreq, sec_websocket_protocol_s);
138
139         /* send the accept connection */
140         make_accept_value(key, acceptval);
141         response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
142         MHD_add_response_header (response, sec_websocket_accept_s, acceptval);
143         MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, MHD_HTTP_HEADER_UPGRADE);
144         MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, websocket_s);
145         MHD_queue_response (hreq->connection, MHD_HTTP_SWITCHING_PROTOCOLS, response);
146         MHD_destroy_response (response);
147
148         *later = 0;
149         return 1;
150 }
151
152 /**************** WebSocket handling ****************************/
153
154 static ssize_t aws_writev(struct afb_websock *ws, const struct iovec *iov, int iovcnt);
155 static ssize_t aws_readv(struct afb_websock *ws, const struct iovec *iov, int iovcnt);
156 static void aws_disconnect(struct afb_websock *ws);
157 static void aws_on_close(struct afb_websock *ws, uint16_t code, size_t size);
158 static void aws_on_content(struct afb_websock *ws, int last, size_t size);
159 static void aws_on_readable(struct afb_websock *ws);
160
161 static struct websock_itf aws_itf = {
162         .writev = (void*)aws_writev,
163         .readv = (void*)aws_readv,
164         .disconnect = (void*)aws_disconnect,
165
166         .on_ping = NULL,
167         .on_pong = NULL,
168         .on_close = (void*)aws_on_close,
169         .on_text = (void*)aws_on_content,
170         .on_binary = (void*)aws_on_content,
171         .on_continue = (void*)aws_on_content,
172         .on_extension = NULL
173 };
174
175 struct afb_wsreq
176 {
177         struct afb_websock *aws;
178         struct afb_wsreq *next;
179         struct json_object *id;
180         struct json_object *name;
181         struct json_object *token;
182         struct json_object *request;
183 };
184
185 struct afb_websock
186 {
187         int fd;
188         struct MHD_Connection *connection;
189         struct websock *ws;
190         struct upoll *up;
191         struct AFB_clientCtx *context;
192         struct json_tokener *tokener;
193         struct afb_wsreq *requests;
194 };
195
196 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name);
197 static void wsreq_iterate(struct afb_wsreq *wsreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
198 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info);
199 static void wsreq_success(struct afb_wsreq *wsreq, struct json_object *obj, const char *info);
200 static int wsreq_session_create(struct afb_wsreq *wsreq);
201 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh);
202 static void wsreq_session_close(struct afb_wsreq *wsreq);
203
204 static const struct afb_req_itf wsreq_itf = {
205         .get = (void*)wsreq_get,
206         .iterate = (void*)wsreq_iterate,
207         .fail = (void*)wsreq_fail,
208         .success = (void*)wsreq_success,
209         .session_create = (void*)wsreq_session_create,
210         .session_check = (void*)wsreq_session_check,
211         .session_close = (void*)wsreq_session_close
212 };
213
214 struct afb_websock *afb_websock_create(struct afb_hreq *hreq)
215 {
216         int fd;
217         struct afb_websock *result;
218
219         fd = MHD_get_connection_info(hreq->connection,
220                                 MHD_CONNECTION_INFO_CONNECTION_FD)->connect_fd;
221         fd = dup(fd);
222         if (fd < 0)
223                 return NULL;
224
225         result = malloc(sizeof * result);
226         if (result == NULL)
227                 goto error;
228
229         result->connection = hreq->connection;
230         result->fd = fd;
231         result->context = ctxClientGet(afb_hreq_context(hreq));
232         if (result->context == NULL)
233                 goto error2;
234
235         result->tokener = json_tokener_new();
236         if (result->tokener == NULL)
237                 goto error3;
238
239         result->ws = websock_create_v13(&aws_itf, result);
240         if (result->ws == NULL)
241                 goto error4;
242
243         result->up = upoll_open(result->fd, result);
244         if (result->up == NULL)
245                 goto error5;
246
247         upoll_on_readable(result->up, (void*)aws_on_readable);
248         upoll_on_hangup(result->up, (void*)aws_disconnect);
249         return result;
250 error5:
251         websock_destroy(result->ws);
252 error4:
253         json_tokener_free(result->tokener);
254 error3:
255         ctxClientPut(result->context);
256 error2:
257         free(result);
258 error:
259         close(fd);
260         return NULL;
261 }
262
263 static ssize_t aws_writev(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
264 {
265         ssize_t rc;
266         do {
267                 rc = writev(ws->fd, iov, iovcnt);
268         } while(rc == -1 && errno == EINTR);
269         return rc;
270 }
271
272 static ssize_t aws_readv(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
273 {
274         ssize_t rc;
275         do {
276                 rc = readv(ws->fd, iov, iovcnt);
277         } while(rc == -1 && errno == EINTR);
278         return rc;
279 }
280
281 static void aws_disconnect(struct afb_websock *ws)
282 {
283         upoll_close(ws->up);
284         websock_destroy(ws->ws);
285         close(ws->fd);
286         MHD_resume_connection (ws->connection);
287         ctxClientPut(ws->context);
288         json_tokener_free(ws->tokener);
289         free(ws);
290 }
291
292 static void aws_on_close(struct afb_websock *ws, uint16_t code, size_t size)
293 {
294         /* do nothing */
295 }
296
297 static void aws_on_readable(struct afb_websock *ws)
298 {
299         websock_dispatch(ws->ws);
300 }
301
302 static int aws_handle_json(struct afb_websock *aws, struct json_object *obj)
303 {
304         struct afb_req r;
305         int count, num;
306         struct json_object *type, *id, *name, *req, *token;
307         struct afb_wsreq *wsreq;
308         const char *api, *verb;
309         size_t lenapi, lenverb;
310
311         /* protocol inspired by http://www.gir.fr/ocppjs/ocpp_srpc_spec.shtml */
312
313         /* the object must be an array of 4 or 5 elements */
314         if (!json_object_is_type(obj, json_type_array))
315                 goto error;
316         count = json_object_array_length(obj);
317         if (count < 4 || count > 5)
318                 goto error;
319
320         /* get the 5 elements: type id name request token */
321         type = json_object_array_get_idx(obj, 0);
322         id = json_object_array_get_idx(obj, 1);
323         name = json_object_array_get_idx(obj, 2);
324         req = json_object_array_get_idx(obj, 3);
325         token = json_object_array_get_idx(obj, 4);
326
327         /* check the types: int string string object string */
328         if (!json_object_is_type(type, json_type_int))
329                 goto error;
330         if (!json_object_is_type(id, json_type_string))
331                 goto error;
332         if (!json_object_is_type(name, json_type_string))
333                 goto error;
334         if (!json_object_is_type(req, json_type_object))
335                 goto error;
336         if (token != NULL && !json_object_is_type(token, json_type_string))
337                 goto error;
338
339         /* the type is only 2 */
340         num = json_object_get_int(type);
341         if (num != 2)
342                 goto error;
343
344         /* checks the api/verb structure of name */
345         api = json_object_get_string(name);
346         for (lenapi = 0 ; api[lenapi] && api[lenapi] != '/' ; lenapi++);
347         if (!lenapi || !api[lenapi])
348                 goto error;
349         verb = &api[lenapi+1];
350         for (lenverb = 0 ; verb[lenverb] && verb[lenverb] != '/' ; lenverb++);
351         if (!lenverb || verb[lenverb])
352                 goto error;
353
354         /* allocates the request data */
355         wsreq = malloc(sizeof *wsreq);
356         if (wsreq == NULL)
357                 goto error;
358
359         /* fill and record the request */
360         wsreq->aws = aws;
361         wsreq->id = json_object_get(id);
362         wsreq->name = json_object_get(name);
363         wsreq->token = json_object_get(token);
364         wsreq->request = json_object_get(req);
365         wsreq->next = aws->requests;
366         aws->requests = wsreq;
367         json_object_put(obj);
368
369         r.data = wsreq;
370         r.itf = &wsreq_itf;
371         afb_apis_call(r, aws->context, api, lenapi, verb, lenverb);
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 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name)
408 {
409         struct afb_arg arg;
410         struct json_object *value;
411
412         if (json_object_object_get_ex(wsreq->request, name, &value)) {
413                 arg.name = name;
414                 arg.value = json_object_get_string(value);
415                 arg.size = strlen(arg.value);
416         } else {
417                 arg.name = NULL;
418                 arg.value = NULL;
419                 arg.size = 0;
420         }
421         arg.path = NULL;
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.path = NULL;
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         json_object_put(reply);
506
507         /* TODO eliminates the wsreq */
508 }
509
510 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info)
511 {
512         wsreq_reply(wsreq, 4, status, info, NULL);
513 }
514
515 static void wsreq_success(struct afb_wsreq *wsreq, json_object *obj, const char *info)
516 {
517         wsreq_reply(wsreq, 3, "success", info, obj);
518 }
519