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