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