Enhance client->server protocol
[src/app-framework-binder.git] / src / afb-api-ws.c
1 /*
2  * Copyright (C) 2015, 2016, 2017 "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 #define NO_PLUGIN_VERBOSE_MACRO
20
21 #include <stdlib.h>
22 #include <string.h>
23 #include <assert.h>
24 #include <fcntl.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <endian.h>
28 #include <netdb.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32
33 #include <json-c/json.h>
34 #include <systemd/sd-event.h>
35
36 #include <afb/afb-req-itf.h>
37
38 #include "afb-common.h"
39
40 #include "afb-session.h"
41 #include "afb-cred.h"
42 #include "afb-ws.h"
43 #include "afb-msg-json.h"
44 #include "afb-apis.h"
45 #include "afb-api-so.h"
46 #include "afb-context.h"
47 #include "afb-evt.h"
48 #include "afb-xreq.h"
49 #include "verbose.h"
50 #include "sd-fds.h"
51
52 struct api_ws_memo;
53 struct api_ws_event;
54 struct api_ws_client;
55
56 #define CHAR_FOR_CALL             'C'
57 #define CHAR_FOR_ANSWER_SUCCESS   'T'
58 #define CHAR_FOR_ANSWER_FAIL      'F'
59 #define CHAR_FOR_EVT_BROADCAST    '*'
60 #define CHAR_FOR_EVT_ADD          '+'
61 #define CHAR_FOR_EVT_DEL          '-'
62 #define CHAR_FOR_EVT_PUSH         '!'
63 #define CHAR_FOR_EVT_SUBSCRIBE    'S'
64 #define CHAR_FOR_EVT_UNSUBSCRIBE  'U'
65
66 /*
67  */
68 struct api_ws
69 {
70         char *path;             /* path of the object for the API */
71         char *api;              /* api name of the interface */
72         int fd;                 /* file descriptor */
73         union {
74                 struct {
75                         uint32_t id;
76                         struct afb_ws *ws;
77                         struct api_ws_event *events;
78                         struct api_ws_memo *memos;
79                 } client;
80                 struct {
81                         sd_event_source *listensrc;
82                         struct afb_evt_listener *listener; /* listener for broadcasted events */
83                 } server;
84         };
85 };
86
87 #define RETOK   1
88 #define RETERR  2
89 #define RETRAW  3
90
91 /******************* websocket interface for client part **********************************/
92
93 static void api_ws_client_on_binary(void *closure, char *data, size_t size);
94
95 static const struct afb_ws_itf api_ws_client_ws_itf =
96 {
97         .on_close = NULL,
98         .on_text = NULL,
99         .on_binary = api_ws_client_on_binary,
100         .on_error = NULL,
101         .on_hangup = NULL
102 };
103
104 /******************* event structures for server part **********************************/
105
106 static void api_ws_server_event_add(void *closure, const char *event, int eventid);
107 static void api_ws_server_event_remove(void *closure, const char *event, int eventid);
108 static void api_ws_server_event_push(void *closure, const char *event, int eventid, struct json_object *object);
109 static void api_ws_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object);
110
111 /* the interface for events pushing */
112 static const struct afb_evt_itf api_ws_server_evt_itf = {
113         .broadcast = api_ws_server_event_broadcast,
114         .push = api_ws_server_event_push,
115         .add = api_ws_server_event_add,
116         .remove = api_ws_server_event_remove
117 };
118
119 /******************* client description part for server *****************************/
120
121 struct api_ws_client
122 {
123         /* the server ws-api */
124         const char *api;
125
126         /* count of references */
127         int refcount;
128
129         /* listener for events */
130         struct afb_evt_listener *listener;
131
132         /* file descriptor */
133         int fd;
134
135         /* websocket */
136         struct afb_ws *ws;
137
138         /* credentials */
139         struct afb_cred *cred;
140 };
141
142 /******************* websocket interface for client part **********************************/
143
144 static void api_ws_server_on_binary(void *closure, char *data, size_t size);
145 static void api_ws_server_on_hangup(void *closure);
146
147 static const struct afb_ws_itf api_ws_server_ws_itf =
148 {
149         .on_close = NULL,
150         .on_text = NULL,
151         .on_binary = api_ws_server_on_binary,
152         .on_error = NULL,
153         .on_hangup = api_ws_server_on_hangup
154 };
155
156 /******************* ws request part for server *****************/
157
158 /*
159  * structure for a ws request
160  */
161 struct api_ws_server_req {
162         struct afb_xreq xreq;           /* the xreq */
163         struct api_ws_client *client;   /* the client of the request */
164         const char *request;            /* the readen request as string */
165         size_t lenreq;                  /* the length of the request */
166         uint32_t msgid;                 /* the incoming request msgid */
167 };
168
169 static void api_ws_server_req_success_cb(struct afb_xreq *xreq, struct json_object *obj, const char *info);
170 static void api_ws_server_req_fail_cb(struct afb_xreq *xreq, const char *status, const char *info);
171 static void api_ws_server_req_destroy_cb(struct afb_xreq *xreq);
172 static int api_ws_server_req_subscribe_cb(struct afb_xreq *xreq, struct afb_event event);
173 static int api_ws_server_req_unsubscribe_cb(struct afb_xreq *xreq, struct afb_event event);
174
175 const struct afb_xreq_query_itf afb_api_ws_xreq_itf = {
176         .success = api_ws_server_req_success_cb,
177         .fail = api_ws_server_req_fail_cb,
178         .unref = api_ws_server_req_destroy_cb,
179         .subscribe = api_ws_server_req_subscribe_cb,
180         .unsubscribe = api_ws_server_req_unsubscribe_cb
181 };
182
183 /******************* common part **********************************/
184
185 /*
186  * create a structure api_ws not connected to the 'path'.
187  */
188 static struct api_ws *api_ws_make(const char *path)
189 {
190         struct api_ws *api;
191         size_t length;
192
193         /* allocates the structure */
194         length = strlen(path);
195         api = calloc(1, sizeof *api + 1 + length);
196         if (api == NULL) {
197                 errno = ENOMEM;
198                 goto error;
199         }
200
201         /* path is copied after the struct */
202         api->path = (char*)(api+1);
203         memcpy(api->path, path, length + 1);
204
205         /* api name is at the end of the path */
206         while (length && path[length - 1] != '/' && path[length - 1] != ':')
207                 length = length - 1;
208         api->api = &api->path[length];
209         if (api->api == NULL || !afb_apis_is_valid_api_name(api->api)) {
210                 errno = EINVAL;
211                 goto error2;
212         }
213
214         api->fd = -1;
215         return api;
216
217 error2:
218         free(api);
219 error:
220         return NULL;
221 }
222
223 static int api_ws_socket_unix(const char *path, int server)
224 {
225         int fd, rc;
226         struct sockaddr_un addr;
227         size_t length;
228
229         length = strlen(path);
230         if (length >= 108) {
231                 errno = ENAMETOOLONG;
232                 return -1;
233         }
234
235         if (server)
236                 unlink(path);
237
238         fd = socket(AF_UNIX, SOCK_STREAM, 0);
239         if (fd < 0)
240                 return fd;
241
242         memset(&addr, 0, sizeof addr);
243         addr.sun_family = AF_UNIX;
244         strcpy(addr.sun_path, path);
245         if (server) {
246                 rc = bind(fd, (struct sockaddr *) &addr, (socklen_t)(sizeof addr));
247         } else {
248                 rc = connect(fd, (struct sockaddr *) &addr, (socklen_t)(sizeof addr));
249         }
250         if (rc < 0) {
251                 close(fd);
252                 return rc;
253         }
254         return fd;
255 }
256
257 static int api_ws_socket_inet(const char *path, int server)
258 {
259         int rc, fd;
260         const char *service, *host, *api;
261         struct addrinfo hint, *rai, *iai;
262
263         /* scan the uri */
264         api = strrchr(path, '/');
265         service = strrchr(path, ':');
266         if (api == NULL || service == NULL || api < service) {
267                 errno = EINVAL;
268                 return -1;
269         }
270         host = strndupa(path, service++ - path);
271         service = strndupa(service, api - service);
272
273         /* get addr */
274         memset(&hint, 0, sizeof hint);
275         hint.ai_family = AF_INET;
276         hint.ai_socktype = SOCK_STREAM;
277         rc = getaddrinfo(host, service, &hint, &rai);
278         if (rc != 0) {
279                 errno = EINVAL;
280                 return -1;
281         }
282
283         /* get the socket */
284         iai = rai;
285         while (iai != NULL) {
286                 fd = socket(iai->ai_family, iai->ai_socktype, iai->ai_protocol);
287                 if (fd >= 0) {
288                         if (server) {
289                                 rc = bind(fd, iai->ai_addr, iai->ai_addrlen);
290                         } else {
291                                 rc = connect(fd, iai->ai_addr, iai->ai_addrlen);
292                         }
293                         if (rc == 0) {
294                                 freeaddrinfo(rai);
295                                 return fd;
296                         }
297                         close(fd);
298                 }
299                 iai = iai->ai_next;
300         }
301         freeaddrinfo(rai);
302         return -1;
303         
304 }
305
306 static int api_ws_socket(const char *path, int server)
307 {
308         int fd, rc;
309
310         /* check for systemd socket */
311         if (0 == strncmp(path, "sd:", 3))
312                 fd = sd_fds_for(path + 3);
313         else {
314                 /* check for unix socket */
315                 if (0 == strncmp(path, "unix:", 5))
316                         /* unix socket */
317                         fd = api_ws_socket_unix(path + 5, server);
318                 else
319                         /* inet socket */
320                         fd = api_ws_socket_inet(path, server);
321
322                 if (fd >= 0 && server) {
323                         rc = 1;
324                         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &rc, sizeof rc);
325                         rc = listen(fd, 5);
326                 }
327         }
328         /* configure the socket */
329         if (fd >= 0) {
330                 fcntl(fd, F_SETFD, FD_CLOEXEC);
331                 fcntl(fd, F_SETFL, O_NONBLOCK);
332         }
333         return fd;
334 }
335
336 /******************* serialisation part **********************************/
337
338 struct readbuf
339 {
340         char *head, *end;
341 };
342
343 #define WRITEBUF_COUNT_MAX  32
344 struct writebuf
345 {
346         struct iovec iovec[WRITEBUF_COUNT_MAX];
347         uint32_t uints[WRITEBUF_COUNT_MAX];
348         int count;
349 };
350
351 static char *api_ws_read_get(struct readbuf *rb, uint32_t length)
352 {
353         char *before = rb->head;
354         char *after = before + length;
355         if (after > rb->end)
356                 return 0;
357         rb->head = after;
358         return before;
359 }
360
361 static int api_ws_read_uint32(struct readbuf *rb, uint32_t *value)
362 {
363         char *after = rb->head + sizeof *value;
364         if (after > rb->end)
365                 return 0;
366         memcpy(value, rb->head, sizeof *value);
367         rb->head = after;
368         *value = le32toh(*value);
369         return 1;
370 }
371
372 static int api_ws_read_string(struct readbuf *rb, const char **value, size_t *length)
373 {
374         uint32_t len;
375         if (!api_ws_read_uint32(rb, &len) || !len)
376                 return 0;
377         if (length)
378                 *length = (size_t)(len - 1);
379         return (*value = api_ws_read_get(rb, len)) != NULL &&  rb->head[-1] == 0;
380 }
381
382 static int api_ws_read_object(struct readbuf *rb, struct json_object **object)
383 {
384         size_t length;
385         const char *string;
386         return api_ws_read_string(rb, &string, &length) && ((*object = json_tokener_parse(string)) != NULL) == (strcmp(string, "null") != 0);
387 }
388
389 static int api_ws_write_put(struct writebuf *wb, const void *value, size_t length)
390 {
391         int i = wb->count;
392         if (i == WRITEBUF_COUNT_MAX)
393                 return 0;
394         wb->iovec[i].iov_base = (void*)value;
395         wb->iovec[i].iov_len = length;
396         wb->count = i + 1;
397         return 1;
398 }
399
400 static int api_ws_write_char(struct writebuf *wb, char value)
401 {
402         int i = wb->count;
403         if (i == WRITEBUF_COUNT_MAX)
404                 return 0;
405         *(char*)&wb->uints[i] = value;
406         wb->iovec[i].iov_base = &wb->uints[i];
407         wb->iovec[i].iov_len = 1;
408         wb->count = i + 1;
409         return 1;
410 }
411
412 static int api_ws_write_uint32(struct writebuf *wb, uint32_t value)
413 {
414         int i = wb->count;
415         if (i == WRITEBUF_COUNT_MAX)
416                 return 0;
417         wb->uints[i] = htole32(value);
418         wb->iovec[i].iov_base = &wb->uints[i];
419         wb->iovec[i].iov_len = sizeof wb->uints[i];
420         wb->count = i + 1;
421         return 1;
422 }
423
424 static int api_ws_write_string_length(struct writebuf *wb, const char *value, size_t length)
425 {
426         uint32_t len = (uint32_t)++length;
427         return (size_t)len == length && len && api_ws_write_uint32(wb, len) && api_ws_write_put(wb, value, length);
428 }
429
430 static int api_ws_write_string(struct writebuf *wb, const char *value)
431 {
432         return api_ws_write_string_length(wb, value, strlen(value));
433 }
434
435 static int api_ws_write_object(struct writebuf *wb, struct json_object *object)
436 {
437         const char *string = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
438         return string != NULL && api_ws_write_string(wb, string);
439 }
440
441
442
443
444 /******************* client part **********************************/
445
446 /*
447  * structure for recording query data
448  */
449 struct api_ws_memo {
450         struct api_ws_memo *next;               /* the next memo */
451         struct api_ws *api;             /* the ws api */
452         struct afb_xreq *xreq;          /* the request handle */
453 #if 0
454         struct afb_req req;             /* the request handle */
455         struct afb_context *context;    /* the context of the query */
456 #endif
457         uint32_t msgid;                 /* the message identifier */
458 };
459
460 struct api_ws_event
461 {
462         struct api_ws_event *next;
463         struct afb_event event;
464         int eventid;
465         int refcount;
466 };
467
468 /* search a memorized request */
469 static struct api_ws_memo *api_ws_client_memo_search(struct api_ws *api, uint32_t msgid)
470 {
471         struct api_ws_memo *memo;
472
473         memo = api->client.memos;
474         while (memo != NULL && memo->msgid != msgid)
475                 memo = memo->next;
476
477         return memo;
478 }
479
480 /* search the event */
481 static struct api_ws_event *api_ws_client_event_search(struct api_ws *api, uint32_t eventid, const char *name)
482 {
483         struct api_ws_event *ev;
484
485         ev = api->client.events;
486         while (ev != NULL && (ev->eventid != eventid || 0 != strcmp(afb_evt_event_name(ev->event), name)))
487                 ev = ev->next;
488
489         return ev;
490 }
491
492
493 /* allocates and init the memorizing data */
494 static struct api_ws_memo *api_ws_client_memo_make(struct api_ws *api, struct afb_xreq *xreq)
495 {
496         struct api_ws_memo *memo;
497
498         memo = malloc(sizeof *memo);
499         if (memo != NULL) {
500                 afb_xreq_addref(xreq);
501                 memo->xreq = xreq;
502                 do { memo->msgid = ++api->client.id; } while(api_ws_client_memo_search(api, memo->msgid) != NULL);
503                 memo->api = api;
504                 memo->next = api->client.memos;
505                 api->client.memos = memo;
506         }
507         return memo;
508 }
509
510 /* free and release the memorizing data */
511 static void api_ws_client_memo_destroy(struct api_ws_memo *memo)
512 {
513         struct api_ws_memo **prv;
514
515         prv = &memo->api->client.memos;
516         while (*prv != NULL) {
517                 if (*prv == memo) {
518                         *prv = memo->next;
519                         break;
520                 }
521                 prv = &(*prv)->next;
522         }
523
524         afb_xreq_unref(memo->xreq);
525         free(memo);
526 }
527
528 /* get event data from the message */
529 static int api_ws_client_msg_event_read(struct readbuf *rb, uint32_t *eventid, const char **name)
530 {
531         return api_ws_read_uint32(rb, eventid) && api_ws_read_string(rb, name, NULL);
532 }
533
534 /* get event from the message */
535 static int api_ws_client_msg_event_get(struct api_ws *api, struct readbuf *rb, struct api_ws_event **ev)
536 {
537         const char *name;
538         uint32_t eventid;
539
540         /* get event data from the message */
541         if (!api_ws_client_msg_event_read(rb, &eventid, &name)) {
542                 ERROR("Invalid message");
543                 return 0;
544         }
545
546         /* check conflicts */
547         *ev = api_ws_client_event_search(api, eventid, name);
548         if (*ev == NULL) {
549                 ERROR("event %s not found", name);
550                 return 0;
551         }
552
553         return 1;
554 }
555
556 /* get event from the message */
557 static int api_ws_client_msg_memo_get(struct api_ws *api, struct readbuf *rb, struct api_ws_memo **memo)
558 {
559         uint32_t msgid;
560
561         /* get event data from the message */
562         if (!api_ws_read_uint32(rb, &msgid)) {
563                 ERROR("Invalid message");
564                 return 0;
565         }
566
567         /* get the memo */
568         *memo = api_ws_client_memo_search(api, msgid);
569         if (*memo == NULL) {
570                 ERROR("message not found");
571                 return 0;
572         }
573
574         return 1;
575 }
576
577 /* read a subscrition message */
578 static int api_ws_client_msg_subscription_get(struct api_ws *api, struct readbuf *rb, struct api_ws_event **ev, struct api_ws_memo **memo)
579 {
580         return api_ws_client_msg_memo_get(api, rb, memo) && api_ws_client_msg_event_get(api, rb, ev);
581 }
582
583 /* adds an event */
584 static void api_ws_client_event_create(struct api_ws *api, struct readbuf *rb)
585 {
586         size_t offset;
587         const char *name;
588         uint32_t eventid;
589         struct api_ws_event *ev;
590
591         /* get event data from the message */
592         offset = api_ws_client_msg_event_read(rb, &eventid, &name);
593         if (offset == 0) {
594                 ERROR("Invalid message");
595                 return;
596         }
597
598         /* check conflicts */
599         ev = api_ws_client_event_search(api, eventid, name);
600         if (ev != NULL) {
601                 ev->refcount++;
602                 return;
603         }
604
605         /* no conflict, try to add it */
606         ev = malloc(sizeof *ev);
607         if (ev != NULL) {
608                 ev->event = afb_evt_create_event(name);
609                 if (ev->event.closure == NULL)
610                         free(ev);
611                 else {
612                         ev->refcount = 1;
613                         ev->eventid = eventid;
614                         ev->next = api->client.events;
615                         api->client.events = ev;
616                         return;
617                 }
618         }
619         ERROR("can't create event %s, out of memory", name);
620 }
621
622 /* removes an event */
623 static void api_ws_client_event_drop(struct api_ws *api, struct readbuf *rb)
624 {
625         struct api_ws_event *ev, **prv;
626
627         /* retrieves the event */
628         if (!api_ws_client_msg_event_get(api, rb, &ev))
629                 return;
630
631         /* decrease the reference count */
632         if (--ev->refcount)
633                 return;
634
635         /* unlinks the event */
636         prv = &api->client.events;
637         while (*prv != ev)
638                 prv = &(*prv)->next;
639         *prv = ev->next;
640
641         /* destroys the event */
642         afb_event_drop(ev->event);
643         free(ev);
644 }
645
646 /* subscribes an event */
647 static void api_ws_client_event_subscribe(struct api_ws *api, struct readbuf *rb)
648 {
649         struct api_ws_event *ev;
650         struct api_ws_memo *memo;
651
652         if (api_ws_client_msg_subscription_get(api, rb, &ev, &memo)) {
653                 /* subscribe the request from the event */
654                 if (afb_xreq_subscribe(memo->xreq, ev->event) < 0)
655                         ERROR("can't subscribe: %m");
656         }
657 }
658
659 /* unsubscribes an event */
660 static void api_ws_client_event_unsubscribe(struct api_ws *api, struct readbuf *rb)
661 {
662         struct api_ws_event *ev;
663         struct api_ws_memo *memo;
664
665         if (api_ws_client_msg_subscription_get(api, rb, &ev, &memo)) {
666                 /* unsubscribe the request from the event */
667                 if (afb_xreq_unsubscribe(memo->xreq, ev->event) < 0)
668                         ERROR("can't unsubscribe: %m");
669         }
670 }
671
672 /* receives broadcasted events */
673 static void api_ws_client_event_broadcast(struct api_ws *api, struct readbuf *rb)
674 {
675         struct json_object *object;
676         const char *event;
677
678         if (api_ws_read_string(rb, &event, NULL) && api_ws_read_object(rb, &object))
679                 afb_evt_broadcast(event, object);
680         else
681                 ERROR("unreadable broadcasted event");
682 }
683
684 /* pushs an event */
685 static void api_ws_client_event_push(struct api_ws *api, struct readbuf *rb)
686 {
687         struct api_ws_event *ev;
688         struct json_object *object;
689
690         if (api_ws_client_msg_event_get(api, rb, &ev) && api_ws_read_object(rb, &object))
691                 afb_event_push(ev->event, object);
692         else
693                 ERROR("unreadable push event");
694 }
695
696 static void api_ws_client_reply_success(struct api_ws *api, struct readbuf *rb)
697 {
698         struct api_ws_memo *memo;
699         struct json_object *object;
700         const char *info;
701         uint32_t flags;
702
703         /* retrieve the message data */
704         if (!api_ws_client_msg_memo_get(api, rb, &memo))
705                 return;
706
707         if (api_ws_read_uint32(rb, &flags)
708          && api_ws_read_string(rb, &info, NULL)
709          && api_ws_read_object(rb, &object)) {
710                 memo->xreq->context.flags = (unsigned)flags;
711                 afb_xreq_success(memo->xreq, object, *info ? info : NULL);
712         } else {
713                 /* failing to have the answer */
714                 afb_xreq_fail(memo->xreq, "error", "ws error");
715         }
716         api_ws_client_memo_destroy(memo);
717 }
718
719 static void api_ws_client_reply_fail(struct api_ws *api, struct readbuf *rb)
720 {
721         struct api_ws_memo *memo;
722         const char *info, *status;
723         uint32_t flags;
724
725         /* retrieve the message data */
726         if (!api_ws_client_msg_memo_get(api, rb, &memo))
727                 return;
728
729         if (api_ws_read_uint32(rb, &flags)
730          && api_ws_read_string(rb, &status, NULL)
731          && api_ws_read_string(rb, &info, NULL)) {
732                 memo->xreq->context.flags = (unsigned)flags;
733                 afb_xreq_fail(memo->xreq, status, *info ? info : NULL);
734         } else {
735                 /* failing to have the answer */
736                 afb_xreq_fail(memo->xreq, "error", "ws error");
737         }
738         api_ws_client_memo_destroy(memo);
739 }
740
741 /* callback when receiving binary data */
742 static void api_ws_client_on_binary(void *closure, char *data, size_t size)
743 {
744         if (size > 0) {
745                 struct readbuf rb = { .head = data, .end = data + size };
746                 switch (*rb.head++) {
747                 case CHAR_FOR_ANSWER_SUCCESS: /* success */
748                         api_ws_client_reply_success(closure, &rb);
749                         break;
750                 case CHAR_FOR_ANSWER_FAIL: /* fail */
751                         api_ws_client_reply_fail(closure, &rb);
752                         break;
753                 case CHAR_FOR_EVT_BROADCAST: /* broadcast */
754                         api_ws_client_event_broadcast(closure, &rb);
755                         break;
756                 case CHAR_FOR_EVT_ADD: /* creates the event */
757                         api_ws_client_event_create(closure, &rb);
758                         break;
759                 case CHAR_FOR_EVT_DEL: /* drops the event */
760                         api_ws_client_event_drop(closure, &rb);
761                         break;
762                 case CHAR_FOR_EVT_PUSH: /* pushs the event */
763                         api_ws_client_event_push(closure, &rb);
764                         break;
765                 case CHAR_FOR_EVT_SUBSCRIBE: /* subscribe event for a request */
766                         api_ws_client_event_subscribe(closure, &rb);
767                         break;
768                 case CHAR_FOR_EVT_UNSUBSCRIBE: /* unsubscribe event for a request */
769                         api_ws_client_event_unsubscribe(closure, &rb);
770                         break;
771                 default: /* unexpected message */
772                         break;
773                 }
774         }
775         free(data);
776 }
777
778 /* on call, propagate it to the ws service */
779 static void api_ws_client_call_cb(void * closure, struct afb_xreq *xreq)
780 {
781         int rc;
782         struct api_ws_memo *memo;
783         struct writebuf wb = { .count = 0 };
784         const char *raw;
785         size_t szraw;
786         struct api_ws *api = closure;
787
788         /* create the recording data */
789         memo = api_ws_client_memo_make(api, xreq);
790         if (memo == NULL) {
791                 afb_xreq_fail_f(xreq, "error", "out of memory");
792                 return;
793         }
794
795         /* creates the call message */
796         raw = afb_xreq_raw(xreq, &szraw);
797         if (raw == NULL)
798                 goto internal_error;
799         if (!api_ws_write_char(&wb, CHAR_FOR_CALL)
800          || !api_ws_write_uint32(&wb, memo->msgid)
801          || !api_ws_write_uint32(&wb, (uint32_t)xreq->context.flags)
802          || !api_ws_write_string(&wb, xreq->verb)
803          || !api_ws_write_string(&wb, afb_session_uuid(xreq->context.session))
804          || !api_ws_write_string_length(&wb, raw, szraw))
805                 goto overflow;
806
807         /* send */
808         rc = afb_ws_binary_v(api->client.ws, wb.iovec, wb.count);
809         if (rc < 0)
810                 goto ws_send_error;
811         return;
812
813 ws_send_error:
814         afb_xreq_fail(xreq, "error", "websocket sending error");
815         goto clean_memo;
816
817 internal_error:
818         afb_xreq_fail(xreq, "error", "internal: raw is NULL!");
819         goto clean_memo;
820
821 overflow:
822         afb_xreq_fail(xreq, "error", "overflow: size doesn't match 32 bits!");
823
824 clean_memo:
825         api_ws_client_memo_destroy(memo);
826 }
827
828 static int api_ws_service_start_cb(void *closure, int share_session, int onneed)
829 {
830         struct api_ws *api = closure;
831
832         /* not an error when onneed */
833         if (onneed != 0)
834                 return 0;
835
836         /* already started: it is an error */
837         ERROR("The WS binding %s is not a startable service", api->path);
838         return -1;
839 }
840
841 /*  */
842 static void api_ws_client_disconnect(struct api_ws *api)
843 {
844         if (api->fd >= 0) {
845                 afb_ws_destroy(api->client.ws);
846                 api->client.ws = NULL;
847                 close(api->fd);
848                 api->fd = -1;
849         }
850 }
851
852 /*  */
853 static int api_ws_client_connect(struct api_ws *api)
854 {
855         struct afb_ws *ws;
856         int fd;
857
858         fd = api_ws_socket(api->path, 0);
859         if (fd >= 0) {
860                 ws = afb_ws_create(afb_common_get_event_loop(), fd, &api_ws_client_ws_itf, api);
861                 if (ws != NULL) {
862                         api->client.ws = ws;
863                         api->fd = fd;
864                         return 0;
865                 }
866                 close(fd);
867         }
868         return -1;
869 }
870
871 static struct afb_api_itf ws_api_itf = {
872         .call = api_ws_client_call_cb,
873         .service_start = api_ws_service_start_cb
874 };
875
876 /* adds a afb-ws-service client api */
877 int afb_api_ws_add_client(const char *path)
878 {
879         int rc;
880         struct api_ws *api;
881         struct afb_api afb_api;
882
883         /* create the ws client api */
884         api = api_ws_make(path);
885         if (api == NULL)
886                 goto error;
887
888         /* connect to the service */
889         rc = api_ws_client_connect(api);
890         if (rc < 0) {
891                 ERROR("can't connect to ws service %s", api->path);
892                 goto error2;
893         }
894
895         /* record it as an API */
896         afb_api.closure = api;
897         afb_api.itf = &ws_api_itf;
898         if (afb_apis_add(api->api, afb_api) < 0)
899                 goto error3;
900
901         return 0;
902
903 error3:
904         api_ws_client_disconnect(api);
905 error2:
906         free(api);
907 error:
908         return -1;
909 }
910
911 /******************* client description part for server *****************************/
912
913 static void api_ws_server_client_unref(struct api_ws_client *client)
914 {
915         if (!--client->refcount) {
916                 afb_evt_listener_unref(client->listener);
917                 afb_ws_destroy(client->ws);
918                 afb_cred_unref(client->cred);
919                 free(client);
920         }
921 }
922
923 /* on call, propagate it to the ws service */
924 static void api_ws_server_on_call(struct api_ws_client *client, struct readbuf *rb)
925 {
926         struct api_ws_server_req *wreq;
927         const char *uuid, *verb;
928         uint32_t flags;
929
930         client->refcount++;
931
932         /* create the request */
933         wreq = calloc(1 , sizeof *wreq);
934         if (wreq == NULL)
935                 goto out_of_memory;
936
937         wreq->client = client;
938
939         /* reads the call message data */
940         if (!api_ws_read_uint32(rb, &wreq->msgid)
941          || !api_ws_read_uint32(rb, &flags)
942          || !api_ws_read_string(rb, &verb, NULL)
943          || !api_ws_read_string(rb, &uuid, NULL)
944          || !api_ws_read_string(rb, &wreq->request, &wreq->lenreq))
945                 goto overflow;
946
947         afb_xreq_init(&wreq->xreq, &afb_api_ws_xreq_itf);
948         wreq->xreq.json = json_tokener_parse(wreq->request);
949         if (wreq->xreq.json == NULL && strcmp(wreq->request, "null")) {
950                 wreq->xreq.json = json_object_new_string(wreq->request);
951         }
952
953         /* init the context */
954         if (afb_context_connect(&wreq->xreq.context, uuid, NULL) < 0)
955                 goto out_of_memory;
956         wreq->xreq.context.flags = flags;
957
958         /* makes the call */
959         wreq->xreq.cred = afb_cred_addref(client->cred);
960         wreq->xreq.api = client->api;
961         wreq->xreq.verb = verb;
962         afb_apis_call(&wreq->xreq);
963         afb_xreq_unref(&wreq->xreq);
964         return;
965
966 out_of_memory:
967 overflow:
968         free(wreq);
969         api_ws_server_client_unref(client);
970 }
971
972 /* callback when receiving binary data */
973 static void api_ws_server_on_binary(void *closure, char *data, size_t size)
974 {
975         if (size > 0) {
976                 struct readbuf rb = { .head = data, .end = data + size };
977                 switch (*rb.head++) {
978                 case CHAR_FOR_CALL:
979                         api_ws_server_on_call(closure, &rb);
980                         break;
981                 default: /* unexpected message */
982                         /* TODO: close the connection */
983                         break;
984                 }
985         }
986         free(data);
987 }
988
989 /* callback when receiving a hangup */
990 static void api_ws_server_on_hangup(void *closure)
991 {
992         struct api_ws_client *client = closure;
993
994         /* close the socket */
995         if (client->fd >= 0) {
996                 close(client->fd);
997                 client->fd = -1;
998         }
999
1000         /* release the client */
1001         api_ws_server_client_unref(client);
1002 }
1003
1004 static void api_ws_server_accept(struct api_ws *api)
1005 {
1006         struct api_ws_client *client;
1007         struct sockaddr addr;
1008         socklen_t lenaddr;
1009
1010         client = calloc(1, sizeof *client);
1011         if (client != NULL) {
1012                 client->listener = afb_evt_listener_create(&api_ws_server_evt_itf, client);
1013                 if (client->listener != NULL) {
1014                         lenaddr = (socklen_t)sizeof addr;
1015                         client->fd = accept(api->fd, &addr, &lenaddr);
1016                         if (client->fd >= 0) {
1017                                 client->cred = afb_cred_create_for_socket(client->fd);
1018                                 fcntl(client->fd, F_SETFD, FD_CLOEXEC);
1019                                 fcntl(client->fd, F_SETFL, O_NONBLOCK);
1020                                 client->ws = afb_ws_create(afb_common_get_event_loop(), client->fd, &api_ws_server_ws_itf, client);
1021                                 if (client->ws != NULL) {
1022                                         client->api = api->api;
1023                                         client->refcount = 1;
1024                                         return;
1025                                 }
1026                                 afb_cred_unref(client->cred);
1027                                 close(client->fd);
1028                         }
1029                         afb_evt_listener_unref(client->listener);
1030                 }
1031                 free(client);
1032         }
1033 }
1034
1035 /******************* server part: manage events **********************************/
1036
1037 static void api_ws_server_event_send(struct api_ws_client *client, char order, const char *event, int eventid, const char *data)
1038 {
1039         int rc;
1040         struct writebuf wb = { .count = 0 };
1041
1042         if (api_ws_write_char(&wb, order)
1043          && api_ws_write_uint32(&wb, eventid)
1044          && api_ws_write_string(&wb, event)
1045          && (data == NULL || api_ws_write_string(&wb, data))) {
1046                 rc = afb_ws_binary_v(client->ws, wb.iovec, wb.count);
1047                 if (rc >= 0)
1048                         return;
1049         }
1050         ERROR("error while sending %c for event %s", order, event);
1051 }
1052
1053 static void api_ws_server_event_add(void *closure, const char *event, int eventid)
1054 {
1055         api_ws_server_event_send(closure, CHAR_FOR_EVT_ADD, event, eventid, NULL);
1056 }
1057
1058 static void api_ws_server_event_remove(void *closure, const char *event, int eventid)
1059 {
1060         api_ws_server_event_send(closure, CHAR_FOR_EVT_DEL, event, eventid, NULL);
1061 }
1062
1063 static void api_ws_server_event_push(void *closure, const char *event, int eventid, struct json_object *object)
1064 {
1065         const char *data = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
1066         api_ws_server_event_send(closure, CHAR_FOR_EVT_PUSH, event, eventid, data ? : "null");
1067         json_object_put(object);
1068 }
1069
1070 static void api_ws_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object)
1071 {
1072         int rc;
1073         struct api_ws_client *client = closure;
1074
1075         struct writebuf wb = { .count = 0 };
1076
1077         if (api_ws_write_char(&wb, CHAR_FOR_EVT_BROADCAST) && api_ws_write_string(&wb, event) && api_ws_write_object(&wb, object)) {
1078                 rc = afb_ws_binary_v(client->ws, wb.iovec, wb.count);
1079                 if (rc < 0)
1080                         ERROR("error while broadcasting event %s", event);
1081         } else
1082                 ERROR("error while broadcasting event %s", event);
1083         json_object_put(object);
1084 }
1085
1086 /******************* ws request part for server *****************/
1087
1088 /* decrement the reference count of the request and free/release it on falling to null */
1089 static void api_ws_server_req_destroy_cb(struct afb_xreq *xreq)
1090 {
1091         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1092
1093         afb_context_disconnect(&wreq->xreq.context);
1094         afb_cred_unref(wreq->xreq.cred);
1095         json_object_put(wreq->xreq.json);
1096         api_ws_server_client_unref(wreq->client);
1097         free(wreq);
1098 }
1099
1100 static void api_ws_server_req_success_cb(struct afb_xreq *xreq, struct json_object *obj, const char *info)
1101 {
1102         int rc;
1103         struct writebuf wb = { .count = 0 };
1104         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1105
1106         if (api_ws_write_char(&wb, CHAR_FOR_ANSWER_SUCCESS)
1107          && api_ws_write_uint32(&wb, wreq->msgid)
1108          && api_ws_write_uint32(&wb, (uint32_t)wreq->xreq.context.flags)
1109          && api_ws_write_string(&wb, info ? : "")
1110          && api_ws_write_object(&wb, obj)) {
1111                 rc = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1112                 if (rc >= 0)
1113                         goto success;
1114         }
1115         ERROR("error while sending success");
1116 success:
1117         json_object_put(obj);
1118 }
1119
1120 static void api_ws_server_req_fail_cb(struct afb_xreq *xreq, const char *status, const char *info)
1121 {
1122         int rc;
1123         struct writebuf wb = { .count = 0 };
1124         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1125
1126         if (api_ws_write_char(&wb, CHAR_FOR_ANSWER_FAIL)
1127          && api_ws_write_uint32(&wb, wreq->msgid)
1128          && api_ws_write_uint32(&wb, (uint32_t)wreq->xreq.context.flags)
1129          && api_ws_write_string(&wb, status)
1130          && api_ws_write_string(&wb, info ? : "")) {
1131                 rc = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1132                 if (rc >= 0)
1133                         return;
1134         }
1135         ERROR("error while sending fail");
1136 }
1137
1138 static int api_ws_server_req_subscribe_cb(struct afb_xreq *xreq, struct afb_event event)
1139 {
1140         int rc, rc2;
1141         struct writebuf wb = { .count = 0 };
1142         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1143
1144         rc = afb_evt_add_watch(wreq->client->listener, event);
1145         if (rc < 0)
1146                 return rc;
1147
1148         if (api_ws_write_char(&wb, CHAR_FOR_EVT_SUBSCRIBE)
1149          && api_ws_write_uint32(&wb, wreq->msgid)
1150          && api_ws_write_uint32(&wb, (uint32_t)afb_evt_event_id(event))
1151          && api_ws_write_string(&wb, afb_evt_event_name(event))) {
1152                 rc2 = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1153                 if (rc2 >= 0)
1154                         goto success;
1155         }
1156         ERROR("error while subscribing event");
1157 success:
1158         return rc;
1159 }
1160
1161 static int api_ws_server_req_unsubscribe_cb(struct afb_xreq *xreq, struct afb_event event)
1162 {
1163         int rc, rc2;
1164         struct writebuf wb = { .count = 0 };
1165         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1166
1167         if (api_ws_write_char(&wb, CHAR_FOR_EVT_UNSUBSCRIBE)
1168          && api_ws_write_uint32(&wb, wreq->msgid)
1169          && api_ws_write_uint32(&wb, (uint32_t)afb_evt_event_id(event))
1170          && api_ws_write_string(&wb, afb_evt_event_name(event))) {
1171                 rc2 = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1172                 if (rc2 >= 0)
1173                         goto success;
1174         }
1175         ERROR("error while subscribing event");
1176 success:
1177         rc = afb_evt_remove_watch(wreq->client->listener, event);
1178         return rc;
1179 }
1180
1181 /******************* server part **********************************/
1182
1183 static int api_ws_server_connect(struct api_ws *api);
1184
1185 static int api_ws_server_listen_callback(sd_event_source *src, int fd, uint32_t revents, void *closure)
1186 {
1187         if ((revents & EPOLLIN) != 0)
1188                 api_ws_server_accept(closure);
1189         if ((revents & EPOLLHUP) != 0)
1190                 api_ws_server_connect(closure);
1191         return 0;
1192 }
1193
1194 static void api_ws_server_disconnect(struct api_ws *api)
1195 {
1196         if (api->server.listensrc != NULL) {
1197                 sd_event_source_unref(api->server.listensrc);
1198                 api->server.listensrc = NULL;
1199         }
1200         if (api->fd >= 0) {
1201                 close(api->fd);
1202                 api->fd = -1;
1203         }
1204 }
1205
1206 static int api_ws_server_connect(struct api_ws *api)
1207 {
1208         int rc;
1209
1210         /* ensure disconnected */
1211         api_ws_server_disconnect(api);
1212
1213         /* request the service object name */
1214         api->fd = api_ws_socket(api->path, 1);
1215         if (api->fd < 0)
1216                 ERROR("can't create socket %s", api->path);
1217         else {
1218                 /* listen for service */
1219                 rc = sd_event_add_io(afb_common_get_event_loop(), &api->server.listensrc, api->fd, EPOLLIN, api_ws_server_listen_callback, api);
1220                 if (rc >= 0)
1221                         return 0;
1222                 close(api->fd);
1223                 errno = -rc;
1224                 ERROR("can't add ws object %s", api->path);
1225         }
1226         return -1;
1227 }
1228
1229 /* create the service */
1230 int afb_api_ws_add_server(const char *path)
1231 {
1232         int rc;
1233         struct api_ws *api;
1234
1235         /* creates the ws api object */
1236         api = api_ws_make(path);
1237         if (api == NULL)
1238                 goto error;
1239
1240         /* connect for serving */
1241         rc = api_ws_server_connect(api);
1242         if (rc < 0)
1243                 goto error2;
1244
1245         return 0;
1246
1247 error2:
1248         free(api);
1249 error:
1250         return -1;
1251 }
1252
1253