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