Use names for constants
[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_ANSWER_SUCCESS   'T'
57 #define CHAR_FOR_ANSWER_FAIL      'F'
58 #define CHAR_FOR_EVT_BROADCAST    '*'
59 #define CHAR_FOR_EVT_ADD          '+'
60 #define CHAR_FOR_EVT_DEL          '-'
61 #define CHAR_FOR_EVT_PUSH         '!'
62 #define CHAR_FOR_EVT_SUBSCRIBE    'S'
63 #define CHAR_FOR_EVT_UNSUBSCRIBE  'U'
64
65 /*
66  */
67 struct api_ws
68 {
69         char *path;             /* path of the object for the API */
70         char *api;              /* api name of the interface */
71         int fd;                 /* file descriptor */
72         union {
73                 struct {
74                         uint32_t id;
75                         struct afb_ws *ws;
76                         struct api_ws_event *events;
77                         struct api_ws_memo *memos;
78                 } client;
79                 struct {
80                         sd_event_source *listensrc;
81                         struct afb_evt_listener *listener; /* listener for broadcasted events */
82                 } server;
83         };
84 };
85
86 #define RETOK   1
87 #define RETERR  2
88 #define RETRAW  3
89
90 /******************* websocket interface for client part **********************************/
91
92 static void api_ws_client_on_binary(void *closure, char *data, size_t size);
93
94 static const struct afb_ws_itf api_ws_client_ws_itf =
95 {
96         .on_close = NULL,
97         .on_text = NULL,
98         .on_binary = api_ws_client_on_binary,
99         .on_error = NULL,
100         .on_hangup = NULL
101 };
102
103 /******************* event structures for server part **********************************/
104
105 static void api_ws_server_event_add(void *closure, const char *event, int eventid);
106 static void api_ws_server_event_remove(void *closure, const char *event, int eventid);
107 static void api_ws_server_event_push(void *closure, const char *event, int eventid, struct json_object *object);
108 static void api_ws_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object);
109
110 /* the interface for events pushing */
111 static const struct afb_evt_itf api_ws_server_evt_itf = {
112         .broadcast = api_ws_server_event_broadcast,
113         .push = api_ws_server_event_push,
114         .add = api_ws_server_event_add,
115         .remove = api_ws_server_event_remove
116 };
117
118 /******************* client description part for server *****************************/
119
120 struct api_ws_client
121 {
122         /* the server ws-api */
123         const char *api;
124
125         /* count of references */
126         int refcount;
127
128         /* listener for events */
129         struct afb_evt_listener *listener;
130
131         /* file descriptor */
132         int fd;
133
134         /* websocket */
135         struct afb_ws *ws;
136
137         /* credentials */
138         struct afb_cred *cred;
139 };
140
141 /******************* websocket interface for client part **********************************/
142
143 static void api_ws_server_on_binary(void *closure, char *data, size_t size);
144 static void api_ws_server_on_hangup(void *closure);
145
146 static const struct afb_ws_itf api_ws_server_ws_itf =
147 {
148         .on_close = NULL,
149         .on_text = NULL,
150         .on_binary = api_ws_server_on_binary,
151         .on_error = NULL,
152         .on_hangup = api_ws_server_on_hangup
153 };
154
155 /******************* ws request part for server *****************/
156
157 /*
158  * structure for a ws request
159  */
160 struct api_ws_server_req {
161         struct afb_xreq xreq;           /* the xreq */
162         struct api_ws_client *client;   /* the client of the request */
163         char *rcvdata;                  /* the received data to free */
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_uint32(&wb, memo->msgid)
800          || !api_ws_write_uint32(&wb, (uint32_t)xreq->context.flags)
801          || !api_ws_write_string(&wb, xreq->verb)
802          || !api_ws_write_string(&wb, afb_session_uuid(xreq->context.session))
803          || !api_ws_write_string_length(&wb, raw, szraw))
804                 goto overflow;
805
806         /* send */
807         rc = afb_ws_binary_v(api->client.ws, wb.iovec, wb.count);
808         if (rc < 0)
809                 goto ws_send_error;
810         return;
811
812 ws_send_error:
813         afb_xreq_fail(xreq, "error", "websocket sending error");
814         goto clean_memo;
815
816 internal_error:
817         afb_xreq_fail(xreq, "error", "internal: raw is NULL!");
818         goto clean_memo;
819
820 overflow:
821         afb_xreq_fail(xreq, "error", "overflow: size doesn't match 32 bits!");
822
823 clean_memo:
824         api_ws_client_memo_destroy(memo);
825 }
826
827 static int api_ws_service_start_cb(void *closure, int share_session, int onneed)
828 {
829         struct api_ws *api = closure;
830
831         /* not an error when onneed */
832         if (onneed != 0)
833                 return 0;
834
835         /* already started: it is an error */
836         ERROR("The WS binding %s is not a startable service", api->path);
837         return -1;
838 }
839
840 /*  */
841 static void api_ws_client_disconnect(struct api_ws *api)
842 {
843         if (api->fd >= 0) {
844                 afb_ws_destroy(api->client.ws);
845                 api->client.ws = NULL;
846                 close(api->fd);
847                 api->fd = -1;
848         }
849 }
850
851 /*  */
852 static int api_ws_client_connect(struct api_ws *api)
853 {
854         struct afb_ws *ws;
855         int fd;
856
857         fd = api_ws_socket(api->path, 0);
858         if (fd >= 0) {
859                 ws = afb_ws_create(afb_common_get_event_loop(), fd, &api_ws_client_ws_itf, api);
860                 if (ws != NULL) {
861                         api->client.ws = ws;
862                         api->fd = fd;
863                         return 0;
864                 }
865                 close(fd);
866         }
867         return -1;
868 }
869
870 static struct afb_api_itf ws_api_itf = {
871         .call = api_ws_client_call_cb,
872         .service_start = api_ws_service_start_cb
873 };
874
875 /* adds a afb-ws-service client api */
876 int afb_api_ws_add_client(const char *path)
877 {
878         int rc;
879         struct api_ws *api;
880         struct afb_api afb_api;
881
882         /* create the ws client api */
883         api = api_ws_make(path);
884         if (api == NULL)
885                 goto error;
886
887         /* connect to the service */
888         rc = api_ws_client_connect(api);
889         if (rc < 0) {
890                 ERROR("can't connect to ws service %s", api->path);
891                 goto error2;
892         }
893
894         /* record it as an API */
895         afb_api.closure = api;
896         afb_api.itf = &ws_api_itf;
897         if (afb_apis_add(api->api, afb_api) < 0)
898                 goto error3;
899
900         return 0;
901
902 error3:
903         api_ws_client_disconnect(api);
904 error2:
905         free(api);
906 error:
907         return -1;
908 }
909
910 /******************* client description part for server *****************************/
911
912 static void api_ws_server_client_unref(struct api_ws_client *client)
913 {
914         if (!--client->refcount) {
915                 afb_evt_listener_unref(client->listener);
916                 afb_ws_destroy(client->ws);
917                 afb_cred_unref(client->cred);
918                 free(client);
919         }
920 }
921
922 /* on call, propagate it to the ws service */
923 static void api_ws_server_called(struct api_ws_client *client, struct readbuf *rb, char *data, size_t size)
924 {
925         struct api_ws_server_req *wreq;
926         const char *uuid, *verb;
927         uint32_t flags;
928
929         client->refcount++;
930
931         /* create the request */
932         wreq = calloc(1 , sizeof *wreq);
933         if (wreq == NULL)
934                 goto out_of_memory;
935
936         wreq->client = client;
937         wreq->rcvdata = data;
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         free(data);
970         api_ws_server_client_unref(client);
971 }
972
973 /* callback when receiving binary data */
974 static void api_ws_server_on_binary(void *closure, char *data, size_t size)
975 {
976         struct readbuf rb = { .head = data, .end = data + size };
977         api_ws_server_called(closure, &rb, data, size);
978 }
979
980 /* callback when receiving a hangup */
981 static void api_ws_server_on_hangup(void *closure)
982 {
983         struct api_ws_client *client = closure;
984
985         /* close the socket */
986         if (client->fd >= 0) {
987                 close(client->fd);
988                 client->fd = -1;
989         }
990
991         /* release the client */
992         api_ws_server_client_unref(client);
993 }
994
995 static void api_ws_server_accept(struct api_ws *api)
996 {
997         struct api_ws_client *client;
998         struct sockaddr addr;
999         socklen_t lenaddr;
1000
1001         client = calloc(1, sizeof *client);
1002         if (client != NULL) {
1003                 client->listener = afb_evt_listener_create(&api_ws_server_evt_itf, client);
1004                 if (client->listener != NULL) {
1005                         lenaddr = (socklen_t)sizeof addr;
1006                         client->fd = accept(api->fd, &addr, &lenaddr);
1007                         if (client->fd >= 0) {
1008                                 client->cred = afb_cred_create_for_socket(client->fd);
1009                                 fcntl(client->fd, F_SETFD, FD_CLOEXEC);
1010                                 fcntl(client->fd, F_SETFL, O_NONBLOCK);
1011                                 client->ws = afb_ws_create(afb_common_get_event_loop(), client->fd, &api_ws_server_ws_itf, client);
1012                                 if (client->ws != NULL) {
1013                                         client->api = api->api;
1014                                         client->refcount = 1;
1015                                         return;
1016                                 }
1017                                 afb_cred_unref(client->cred);
1018                                 close(client->fd);
1019                         }
1020                         afb_evt_listener_unref(client->listener);
1021                 }
1022                 free(client);
1023         }
1024 }
1025
1026 /******************* server part: manage events **********************************/
1027
1028 static void api_ws_server_event_send(struct api_ws_client *client, char order, const char *event, int eventid, const char *data)
1029 {
1030         int rc;
1031         struct writebuf wb = { .count = 0 };
1032
1033         if (api_ws_write_char(&wb, order)
1034          && api_ws_write_uint32(&wb, eventid)
1035          && api_ws_write_string(&wb, event)
1036          && (data == NULL || api_ws_write_string(&wb, data))) {
1037                 rc = afb_ws_binary_v(client->ws, wb.iovec, wb.count);
1038                 if (rc >= 0)
1039                         return;
1040         }
1041         ERROR("error while sending %c for event %s", order, event);
1042 }
1043
1044 static void api_ws_server_event_add(void *closure, const char *event, int eventid)
1045 {
1046         api_ws_server_event_send(closure, CHAR_FOR_EVT_ADD, event, eventid, NULL);
1047 }
1048
1049 static void api_ws_server_event_remove(void *closure, const char *event, int eventid)
1050 {
1051         api_ws_server_event_send(closure, CHAR_FOR_EVT_DEL, event, eventid, NULL);
1052 }
1053
1054 static void api_ws_server_event_push(void *closure, const char *event, int eventid, struct json_object *object)
1055 {
1056         const char *data = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
1057         api_ws_server_event_send(closure, CHAR_FOR_EVT_PUSH, event, eventid, data ? : "null");
1058         json_object_put(object);
1059 }
1060
1061 static void api_ws_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object)
1062 {
1063         int rc;
1064         struct api_ws_client *client = closure;
1065
1066         struct writebuf wb = { .count = 0 };
1067
1068         if (api_ws_write_char(&wb, CHAR_FOR_EVT_BROADCAST) && api_ws_write_string(&wb, event) && api_ws_write_object(&wb, object)) {
1069                 rc = afb_ws_binary_v(client->ws, wb.iovec, wb.count);
1070                 if (rc < 0)
1071                         ERROR("error while broadcasting event %s", event);
1072         } else
1073                 ERROR("error while broadcasting event %s", event);
1074         json_object_put(object);
1075 }
1076
1077 /******************* ws request part for server *****************/
1078
1079 /* decrement the reference count of the request and free/release it on falling to null */
1080 static void api_ws_server_req_destroy_cb(struct afb_xreq *xreq)
1081 {
1082         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1083
1084         afb_context_disconnect(&wreq->xreq.context);
1085         afb_cred_unref(wreq->xreq.cred);
1086         json_object_put(wreq->xreq.json);
1087         free(wreq->rcvdata);
1088         api_ws_server_client_unref(wreq->client);
1089         free(wreq);
1090 }
1091
1092 static void api_ws_server_req_success_cb(struct afb_xreq *xreq, struct json_object *obj, const char *info)
1093 {
1094         int rc;
1095         struct writebuf wb = { .count = 0 };
1096         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1097
1098         if (api_ws_write_char(&wb, CHAR_FOR_ANSWER_SUCCESS)
1099          && api_ws_write_uint32(&wb, wreq->msgid)
1100          && api_ws_write_uint32(&wb, (uint32_t)wreq->xreq.context.flags)
1101          && api_ws_write_string(&wb, info ? : "")
1102          && api_ws_write_object(&wb, obj)) {
1103                 rc = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1104                 if (rc >= 0)
1105                         goto success;
1106         }
1107         ERROR("error while sending success");
1108 success:
1109         json_object_put(obj);
1110 }
1111
1112 static void api_ws_server_req_fail_cb(struct afb_xreq *xreq, const char *status, const char *info)
1113 {
1114         int rc;
1115         struct writebuf wb = { .count = 0 };
1116         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1117
1118         if (api_ws_write_char(&wb, CHAR_FOR_ANSWER_FAIL)
1119          && api_ws_write_uint32(&wb, wreq->msgid)
1120          && api_ws_write_uint32(&wb, (uint32_t)wreq->xreq.context.flags)
1121          && api_ws_write_string(&wb, status)
1122          && api_ws_write_string(&wb, info ? : "")) {
1123                 rc = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1124                 if (rc >= 0)
1125                         return;
1126         }
1127         ERROR("error while sending fail");
1128 }
1129
1130 static int api_ws_server_req_subscribe_cb(struct afb_xreq *xreq, struct afb_event event)
1131 {
1132         int rc, rc2;
1133         struct writebuf wb = { .count = 0 };
1134         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1135
1136         rc = afb_evt_add_watch(wreq->client->listener, event);
1137         if (rc < 0)
1138                 return rc;
1139
1140         if (api_ws_write_char(&wb, CHAR_FOR_EVT_SUBSCRIBE)
1141          && api_ws_write_uint32(&wb, wreq->msgid)
1142          && api_ws_write_uint32(&wb, (uint32_t)afb_evt_event_id(event))
1143          && api_ws_write_string(&wb, afb_evt_event_name(event))) {
1144                 rc2 = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1145                 if (rc2 >= 0)
1146                         goto success;
1147         }
1148         ERROR("error while subscribing event");
1149 success:
1150         return rc;
1151 }
1152
1153 static int api_ws_server_req_unsubscribe_cb(struct afb_xreq *xreq, struct afb_event event)
1154 {
1155         int rc, rc2;
1156         struct writebuf wb = { .count = 0 };
1157         struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1158
1159         if (api_ws_write_char(&wb, CHAR_FOR_EVT_UNSUBSCRIBE)
1160          && api_ws_write_uint32(&wb, wreq->msgid)
1161          && api_ws_write_uint32(&wb, (uint32_t)afb_evt_event_id(event))
1162          && api_ws_write_string(&wb, afb_evt_event_name(event))) {
1163                 rc2 = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1164                 if (rc2 >= 0)
1165                         goto success;
1166         }
1167         ERROR("error while subscribing event");
1168 success:
1169         rc = afb_evt_remove_watch(wreq->client->listener, event);
1170         return rc;
1171 }
1172
1173 /******************* server part **********************************/
1174
1175 static int api_ws_server_connect(struct api_ws *api);
1176
1177 static int api_ws_server_listen_callback(sd_event_source *src, int fd, uint32_t revents, void *closure)
1178 {
1179         if ((revents & EPOLLIN) != 0)
1180                 api_ws_server_accept(closure);
1181         if ((revents & EPOLLHUP) != 0)
1182                 api_ws_server_connect(closure);
1183         return 0;
1184 }
1185
1186 static void api_ws_server_disconnect(struct api_ws *api)
1187 {
1188         if (api->server.listensrc != NULL) {
1189                 sd_event_source_unref(api->server.listensrc);
1190                 api->server.listensrc = NULL;
1191         }
1192         if (api->fd >= 0) {
1193                 close(api->fd);
1194                 api->fd = -1;
1195         }
1196 }
1197
1198 static int api_ws_server_connect(struct api_ws *api)
1199 {
1200         int rc;
1201
1202         /* ensure disconnected */
1203         api_ws_server_disconnect(api);
1204
1205         /* request the service object name */
1206         api->fd = api_ws_socket(api->path, 1);
1207         if (api->fd < 0)
1208                 ERROR("can't create socket %s", api->path);
1209         else {
1210                 /* listen for service */
1211                 rc = sd_event_add_io(afb_common_get_event_loop(), &api->server.listensrc, api->fd, EPOLLIN, api_ws_server_listen_callback, api);
1212                 if (rc >= 0)
1213                         return 0;
1214                 close(api->fd);
1215                 errno = -rc;
1216                 ERROR("can't add ws object %s", api->path);
1217         }
1218         return -1;
1219 }
1220
1221 /* create the service */
1222 int afb_api_ws_add_server(const char *path)
1223 {
1224         int rc;
1225         struct api_ws *api;
1226
1227         /* creates the ws api object */
1228         api = api_ws_make(path);
1229         if (api == NULL)
1230                 goto error;
1231
1232         /* connect for serving */
1233         rc = api_ws_server_connect(api);
1234         if (rc < 0)
1235                 goto error2;
1236
1237         return 0;
1238
1239 error2:
1240         free(api);
1241 error:
1242         return -1;
1243 }
1244
1245