more simplification
[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 "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 };
175
176 struct afb_wsreq
177 {
178         struct afb_websock *aws;
179         struct afb_wsreq *next;
180         struct json_object *id;
181         struct json_object *name;
182         struct json_object *token;
183         struct json_object *request;
184 };
185
186 struct afb_websock
187 {
188         int fd;
189         struct MHD_Connection *connection;
190         struct websock *ws;
191         struct upoll *up;
192         struct AFB_clientCtx *context;
193         struct json_tokener *tokener;
194         struct afb_wsreq *requests;
195 };
196
197 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name);
198 static void wsreq_iterate(struct afb_wsreq *wsreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure);
199 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info);
200 static void wsreq_success(struct afb_wsreq *wsreq, struct json_object *obj, const char *info);
201 static int wsreq_session_create(struct afb_wsreq *wsreq);
202 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh);
203 static void wsreq_session_close(struct afb_wsreq *wsreq);
204
205 static const struct afb_req_itf wsreq_itf = {
206         .get = (void*)wsreq_get,
207         .iterate = (void*)wsreq_iterate,
208         .fail = (void*)wsreq_fail,
209         .success = (void*)wsreq_success,
210         .session_create = (void*)wsreq_session_create,
211         .session_check = (void*)wsreq_session_check,
212         .session_close = (void*)wsreq_session_close
213 };
214
215 struct afb_websock *afb_websock_create(struct afb_hreq *hreq)
216 {
217         int fd;
218         struct afb_websock *result;
219
220         fd = MHD_get_connection_info(hreq->connection,
221                                 MHD_CONNECTION_INFO_CONNECTION_FD)->connect_fd;
222         fd = dup(fd);
223         if (fd < 0)
224                 return NULL;
225
226         result = malloc(sizeof * result);
227         if (result == NULL)
228                 goto error;
229
230         result->connection = hreq->connection;
231         result->fd = 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         close(fd);
259         return NULL;
260 }
261
262 static ssize_t aws_writev(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
263 {
264         ssize_t rc;
265         do {
266                 rc = writev(ws->fd, iov, iovcnt);
267         } while(rc == -1 && errno == EINTR);
268         return rc;
269 }
270
271 static ssize_t aws_readv(struct afb_websock *ws, const struct iovec *iov, int iovcnt)
272 {
273         ssize_t rc;
274         do {
275                 rc = readv(ws->fd, iov, iovcnt);
276         } while(rc == -1 && errno == EINTR);
277         return rc;
278 }
279
280 static void aws_disconnect(struct afb_websock *ws)
281 {
282         upoll_close(ws->up);
283         websock_destroy(ws->ws);
284         close(ws->fd);
285         MHD_resume_connection (ws->connection);
286         ctxClientPut(ws->context);
287         json_tokener_free(ws->tokener);
288         free(ws);
289 }
290
291 static void aws_on_close(struct afb_websock *ws, uint16_t code, size_t size)
292 {
293         /* do nothing */
294 }
295
296 static void aws_on_readable(struct afb_websock *ws)
297 {
298         websock_dispatch(ws->ws);
299 }
300
301 static int aws_handle_json(struct afb_websock *aws, struct json_object *obj)
302 {
303         struct afb_req r;
304         int count, num, rc;
305         struct json_object *type, *id, *name, *req, *token;
306         struct afb_wsreq *wsreq;
307         const char *api, *verb;
308         size_t lenapi, lenverb;
309
310         /* protocol inspired by http://www.gir.fr/ocppjs/ocpp_srpc_spec.shtml */
311
312         /* the object must be an array of 4 or 5 elements */
313         if (!json_object_is_type(obj, json_type_array))
314                 goto error;
315         count = json_object_array_length(obj);
316         if (count < 4 || count > 5)
317                 goto error;
318
319         /* get the 5 elements: type id name request token */
320         type = json_object_array_get_idx(obj, 0);
321         id = json_object_array_get_idx(obj, 1);
322         name = json_object_array_get_idx(obj, 2);
323         req = json_object_array_get_idx(obj, 3);
324         token = json_object_array_get_idx(obj, 4);
325
326         /* check the types: int string string object string */
327         if (!json_object_is_type(type, json_type_int))
328                 goto error;
329         if (!json_object_is_type(id, json_type_string))
330                 goto error;
331         if (!json_object_is_type(name, json_type_string))
332                 goto error;
333         if (!json_object_is_type(req, json_type_object))
334                 goto error;
335         if (token != NULL && !json_object_is_type(token, json_type_string))
336                 goto error;
337
338         /* the type is only 2 */
339         num = json_object_get_int(type);
340         if (num != 2)
341                 goto error;
342
343         /* checks the api/verb structure of name */
344         api = json_object_get_string(name);
345         for (lenapi = 0 ; api[lenapi] && api[lenapi] != '/' ; lenapi++);
346         if (!lenapi || !api[lenapi])
347                 goto error;
348         verb = &api[lenapi+1];
349         for (lenverb = 0 ; verb[lenverb] && verb[lenverb] != '/' ; lenverb++);
350         if (!lenverb || verb[lenverb])
351                 goto error;
352
353         /* allocates the request data */
354         wsreq = malloc(sizeof *wsreq);
355         if (wsreq == NULL)
356                 goto error;
357
358         /* fill and record the request */
359         wsreq->aws = aws;
360         wsreq->id = json_object_get(id);
361         wsreq->name = json_object_get(name);
362         wsreq->token = json_object_get(token);
363         wsreq->request = json_object_get(req);
364         wsreq->next = aws->requests;
365         aws->requests = wsreq;
366         json_object_put(obj);
367
368         r.data = wsreq;
369         r.itf = &wsreq_itf;
370         rc = afb_apis_handle(r, aws->context, api, lenapi, verb, lenverb);
371         if (rc == 0)
372                 wsreq_fail(wsreq, "ail", "api not found");
373         return 1;
374
375 error:
376         json_object_put(obj);
377         return 0;
378 }
379
380 static void aws_on_content(struct afb_websock *ws, int last, size_t size)
381 {
382         ssize_t rrc;
383         char buffer[8000];
384         struct json_object *obj;
385
386         json_tokener_reset(ws->tokener);
387         while(size) {
388                 rrc = websock_read(ws->ws, buffer,
389                                 size > sizeof buffer ? sizeof buffer : size);
390                 if (rrc < 0) {
391                         websock_close(ws->ws);
392                         return;
393                 }
394                 size -= (size_t)rrc;
395                 obj = json_tokener_parse_ex(ws->tokener, buffer, (int)rrc);
396                 if (obj != NULL) {
397                         if (!aws_handle_json(ws, obj)) {
398                                 websock_close(ws->ws);
399                                 return;
400                         }
401                 } else if (json_tokener_get_error(ws->tokener) != json_tokener_continue) {
402                         websock_close(ws->ws);
403                         return;
404                 }
405         }
406 }
407
408
409 static struct afb_arg wsreq_get(struct afb_wsreq *wsreq, const char *name)
410 {
411         struct afb_arg arg;
412         struct json_object *value;
413
414         if (json_object_object_get_ex(wsreq->request, name, &value)) {
415                 arg.name = name;
416                 arg.value = json_object_get_string(value);
417         } else {
418                 arg.name = NULL;
419                 arg.value = NULL;
420         }
421         arg.size = 0;
422         arg.path = NULL;
423         return arg;
424 }
425
426 static void wsreq_iterate(struct afb_wsreq *wsreq, int (*iterator)(void *closure, struct afb_arg arg), void *closure)
427 {
428         struct afb_arg arg;
429         struct json_object_iterator it = json_object_iter_begin(wsreq->request);
430         struct json_object_iterator end = json_object_iter_end(wsreq->request);
431
432         arg.size = 0;
433         arg.path = NULL;
434         while(!json_object_iter_equal(&it, &end)) {
435                 arg.name = json_object_iter_peek_name(&it);
436                 arg.value = json_object_get_string(json_object_iter_peek_value(&it));
437                 if (!iterator(closure, arg))
438                         break;
439                 json_object_iter_next(&it);
440         }
441 }
442
443 static int wsreq_session_create(struct afb_wsreq *wsreq)
444 {
445         struct AFB_clientCtx *context = wsreq->aws->context;
446         if (context->created)
447                 return 0;
448         return wsreq_session_check(wsreq, 1);
449 }
450
451 static int wsreq_session_check(struct afb_wsreq *wsreq, int refresh)
452 {
453         const char *token;
454         struct AFB_clientCtx *context = wsreq->aws->context;
455
456         if (wsreq->token == NULL)
457                 return 0;
458
459         token = json_object_get_string(wsreq->token);
460         if (token == NULL)
461                 return 0;
462
463         if (!ctxTokenCheck (context, token))
464                 return 0;
465
466         if (refresh) {
467                 ctxTokenNew (context);
468         }
469
470         return 1;
471 }
472
473 static void wsreq_session_close(struct afb_wsreq *wsreq)
474 {
475         struct AFB_clientCtx *context = wsreq->aws->context;
476         ctxClientClose(context);
477 }
478
479
480 static void wsreq_reply(struct afb_wsreq *wsreq, int retcode, const char *status, const char *info, json_object *resp)
481 {
482         json_object *root, *request, *reply;
483         const char *message;
484
485         /* builds the answering structure */
486         root = json_object_new_object();
487         json_object_object_add(root, "jtype", json_object_new_string("afb-reply"));
488         request = json_object_new_object();
489         json_object_object_add(root, "request", request);
490         json_object_object_add(request, "status", json_object_new_string(status));
491         if (info)
492                 json_object_object_add(request, "info", json_object_new_string(info));
493         if (resp)
494                 json_object_object_add(root, "response", resp);
495
496         /* make the reply */
497         reply = json_object_new_array();
498         json_object_array_add(reply, json_object_new_int(retcode));
499         json_object_array_add(reply, wsreq->id);
500         json_object_array_add(reply, root);
501         json_object_array_add(reply, json_object_new_string(wsreq->aws->context->token));
502
503         /* emits the reply */
504         message = json_object_to_json_string(reply);
505         websock_text(wsreq->aws->ws, message, strlen(message));
506         json_object_put(reply);
507
508         /* TODO eliminates the wsreq */
509 }
510
511 static void wsreq_fail(struct afb_wsreq *wsreq, const char *status, const char *info)
512 {
513         wsreq_reply(wsreq, 4, status, info, NULL);
514 }
515
516 static void wsreq_success(struct afb_wsreq *wsreq, json_object *obj, const char *info)
517 {
518         wsreq_reply(wsreq, 3, "success", info, obj);
519 }
520