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