2 * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3 * Author José Bollo <jose.bollo@iot.bzh>
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #define NO_PLUGIN_VERBOSE_MACRO
29 #include <sys/types.h>
30 #include <sys/socket.h>
34 #include <json-c/json.h>
35 #include <systemd/sd-event.h>
37 #include <afb/afb-req-itf.h>
39 #include "afb-common.h"
41 #include "afb-session.h"
44 #include "afb-msg-json.h"
46 #include "afb-apiset.h"
47 #include "afb-api-so.h"
48 #include "afb-context.h"
58 #define CHAR_FOR_CALL 'C'
59 #define CHAR_FOR_ANSWER_SUCCESS 'T'
60 #define CHAR_FOR_ANSWER_FAIL 'F'
61 #define CHAR_FOR_EVT_BROADCAST '*'
62 #define CHAR_FOR_EVT_ADD '+'
63 #define CHAR_FOR_EVT_DEL '-'
64 #define CHAR_FOR_EVT_PUSH '!'
65 #define CHAR_FOR_EVT_SUBSCRIBE 'S'
66 #define CHAR_FOR_EVT_UNSUBSCRIBE 'U'
67 #define CHAR_FOR_SUBCALL_CALL 'B'
68 #define CHAR_FOR_SUBCALL_REPLY 'R'
74 char *path; /* path of the object for the API */
75 char *api; /* api name of the interface */
76 int fd; /* file descriptor */
77 pthread_mutex_t mutex; /**< resource control */
82 struct api_ws_event *events;
83 struct api_ws_memo *memos;
86 sd_event_source *listensrc; /**< systemd source for server socket */
87 struct afb_apiset *apiset;
96 /******************* websocket interface for client part **********************************/
98 static void api_ws_client_on_binary(void *closure, char *data, size_t size);
100 static const struct afb_ws_itf api_ws_client_ws_itf =
104 .on_binary = api_ws_client_on_binary,
109 /******************* event structures for server part **********************************/
111 static void api_ws_server_event_add(void *closure, const char *event, int eventid);
112 static void api_ws_server_event_remove(void *closure, const char *event, int eventid);
113 static void api_ws_server_event_push(void *closure, const char *event, int eventid, struct json_object *object);
114 static void api_ws_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object);
116 /* the interface for events pushing */
117 static const struct afb_evt_itf api_ws_server_evt_itf = {
118 .broadcast = api_ws_server_event_broadcast,
119 .push = api_ws_server_event_push,
120 .add = api_ws_server_event_add,
121 .remove = api_ws_server_event_remove
124 /******************* handling subcalls *****************************/
127 * Structure on server side for recording pending
130 struct api_ws_subcall
132 struct api_ws_subcall *next; /**< next subcall for the client */
133 uint32_t subcallid; /**< the subcallid */
134 void (*callback)(void*, int, struct json_object*); /**< callback on completion */
135 void *closure; /**< closure of the callback */
139 * Structure for sending back replies on client side
143 struct api_ws *apiws; /**< api descriptor */
144 uint32_t subcallid; /**< subcallid for the reply */
147 /******************* client description part for server *****************************/
151 /* the server ws-api */
154 /* count of references */
157 /* file descriptor */
160 /* resource control */
161 pthread_mutex_t mutex;
163 /* listener for events */
164 struct afb_evt_listener *listener;
170 struct afb_cred *cred;
172 /* pending subcalls */
173 struct api_ws_subcall *subcalls;
176 struct afb_apiset *apiset;
179 /******************* websocket interface for client part **********************************/
181 static void api_ws_server_on_binary(void *closure, char *data, size_t size);
182 static void api_ws_server_on_hangup(void *closure);
184 static const struct afb_ws_itf api_ws_server_ws_itf =
188 .on_binary = api_ws_server_on_binary,
190 .on_hangup = api_ws_server_on_hangup
193 /******************* ws request part for server *****************/
196 * structure for a ws request
198 struct api_ws_server_req {
199 struct afb_xreq xreq; /* the xreq */
200 struct api_ws_client *client; /* the client of the request */
201 uint32_t msgid; /* the incoming request msgid */
204 static void api_ws_server_req_success_cb(struct afb_xreq *xreq, struct json_object *obj, const char *info);
205 static void api_ws_server_req_fail_cb(struct afb_xreq *xreq, const char *status, const char *info);
206 static void api_ws_server_req_destroy_cb(struct afb_xreq *xreq);
207 static int api_ws_server_req_subscribe_cb(struct afb_xreq *xreq, struct afb_event event);
208 static int api_ws_server_req_unsubscribe_cb(struct afb_xreq *xreq, struct afb_event event);
209 static void api_ws_server_req_subcall_cb(struct afb_xreq *xreq, const char *api, const char *verb, struct json_object *args, void (*callback)(void*, int, struct json_object*), void *cb_closure);
211 const struct afb_xreq_query_itf afb_api_ws_xreq_itf = {
212 .success = api_ws_server_req_success_cb,
213 .fail = api_ws_server_req_fail_cb,
214 .unref = api_ws_server_req_destroy_cb,
215 .subcall = api_ws_server_req_subcall_cb,
216 .subscribe = api_ws_server_req_subscribe_cb,
217 .unsubscribe = api_ws_server_req_unsubscribe_cb
220 /******************* common part **********************************/
223 * create a structure api_ws not connected to the 'path'.
225 static struct api_ws *api_ws_make(const char *path)
230 /* allocates the structure */
231 length = strlen(path);
232 api = calloc(1, sizeof *api + 1 + length);
238 /* path is copied after the struct */
239 api->path = (char*)(api+1);
240 memcpy(api->path, path, length + 1);
242 /* api name is at the end of the path */
243 while (length && path[length - 1] != '/' && path[length - 1] != ':')
245 api->api = &api->path[length];
246 if (api->api == NULL || !afb_api_is_valid_name(api->api)) {
250 pthread_mutex_init(&api->mutex, NULL);
261 static int api_ws_socket_unix(const char *path, int server)
264 struct sockaddr_un addr;
267 length = strlen(path);
269 errno = ENAMETOOLONG;
276 fd = socket(AF_UNIX, SOCK_STREAM, 0);
280 memset(&addr, 0, sizeof addr);
281 addr.sun_family = AF_UNIX;
282 strcpy(addr.sun_path, path);
284 rc = bind(fd, (struct sockaddr *) &addr, (socklen_t)(sizeof addr));
286 rc = connect(fd, (struct sockaddr *) &addr, (socklen_t)(sizeof addr));
295 static int api_ws_socket_inet(const char *path, int server)
298 const char *service, *host, *api;
299 struct addrinfo hint, *rai, *iai;
302 api = strrchr(path, '/');
303 service = strrchr(path, ':');
304 if (api == NULL || service == NULL || api < service) {
308 host = strndupa(path, service++ - path);
309 service = strndupa(service, api - service);
312 memset(&hint, 0, sizeof hint);
313 hint.ai_family = AF_INET;
314 hint.ai_socktype = SOCK_STREAM;
315 rc = getaddrinfo(host, service, &hint, &rai);
323 while (iai != NULL) {
324 fd = socket(iai->ai_family, iai->ai_socktype, iai->ai_protocol);
327 rc = bind(fd, iai->ai_addr, iai->ai_addrlen);
329 rc = connect(fd, iai->ai_addr, iai->ai_addrlen);
344 static int api_ws_socket(const char *path, int server)
348 /* check for systemd socket */
349 if (0 == strncmp(path, "sd:", 3))
350 fd = sd_fds_for(path + 3);
352 /* check for unix socket */
353 if (0 == strncmp(path, "unix:", 5))
355 fd = api_ws_socket_unix(path + 5, server);
358 fd = api_ws_socket_inet(path, server);
360 if (fd >= 0 && server) {
362 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &rc, sizeof rc);
366 /* configure the socket */
368 fcntl(fd, F_SETFD, FD_CLOEXEC);
369 fcntl(fd, F_SETFL, O_NONBLOCK);
374 /******************* serialisation part **********************************/
381 #define WRITEBUF_COUNT_MAX 32
384 struct iovec iovec[WRITEBUF_COUNT_MAX];
385 uint32_t uints[WRITEBUF_COUNT_MAX];
389 static char *api_ws_read_get(struct readbuf *rb, uint32_t length)
391 char *before = rb->head;
392 char *after = before + length;
399 static int api_ws_read_char(struct readbuf *rb, char *value)
401 if (rb->head >= rb->end)
403 *value = *rb->head++;
407 static int api_ws_read_uint32(struct readbuf *rb, uint32_t *value)
409 char *after = rb->head + sizeof *value;
412 memcpy(value, rb->head, sizeof *value);
414 *value = le32toh(*value);
418 static int api_ws_read_string(struct readbuf *rb, const char **value, size_t *length)
421 if (!api_ws_read_uint32(rb, &len) || !len)
424 *length = (size_t)(len - 1);
425 return (*value = api_ws_read_get(rb, len)) != NULL && rb->head[-1] == 0;
428 static int api_ws_read_object(struct readbuf *rb, struct json_object **object)
431 struct json_object *o;
432 int rc = api_ws_read_string(rb, &string, NULL);
434 o = json_tokener_parse(string);
435 if (o == NULL && strcmp(string, "null"))
436 o = json_object_new_string(string);
442 static int api_ws_write_put(struct writebuf *wb, const void *value, size_t length)
445 if (i == WRITEBUF_COUNT_MAX)
447 wb->iovec[i].iov_base = (void*)value;
448 wb->iovec[i].iov_len = length;
453 static int api_ws_write_char(struct writebuf *wb, char value)
456 if (i == WRITEBUF_COUNT_MAX)
458 *(char*)&wb->uints[i] = value;
459 wb->iovec[i].iov_base = &wb->uints[i];
460 wb->iovec[i].iov_len = 1;
465 static int api_ws_write_uint32(struct writebuf *wb, uint32_t value)
468 if (i == WRITEBUF_COUNT_MAX)
470 wb->uints[i] = htole32(value);
471 wb->iovec[i].iov_base = &wb->uints[i];
472 wb->iovec[i].iov_len = sizeof wb->uints[i];
477 static int api_ws_write_string_length(struct writebuf *wb, const char *value, size_t length)
479 uint32_t len = (uint32_t)++length;
480 return (size_t)len == length && len && api_ws_write_uint32(wb, len) && api_ws_write_put(wb, value, length);
483 static int api_ws_write_string(struct writebuf *wb, const char *value)
485 return api_ws_write_string_length(wb, value, strlen(value));
488 static int api_ws_write_object(struct writebuf *wb, struct json_object *object)
490 const char *string = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
491 return string != NULL && api_ws_write_string(wb, string);
494 /******************* client part **********************************/
497 * structure for recording query data
500 struct api_ws_memo *next; /* the next memo */
501 struct api_ws *api; /* the ws api */
502 struct afb_xreq *xreq; /* the request handle */
503 uint32_t msgid; /* the message identifier */
508 struct api_ws_event *next;
509 struct afb_event event;
514 /* search a memorized request */
515 static struct api_ws_memo *api_ws_client_memo_search(struct api_ws *api, uint32_t msgid)
517 struct api_ws_memo *memo;
519 memo = api->client.memos;
520 while (memo != NULL && memo->msgid != msgid)
526 /* search the event */
527 static struct api_ws_event *api_ws_client_event_search(struct api_ws *api, uint32_t eventid, const char *name)
529 struct api_ws_event *ev;
531 ev = api->client.events;
532 while (ev != NULL && (ev->eventid != eventid || 0 != strcmp(afb_evt_event_name(ev->event), name)))
539 /* allocates and init the memorizing data */
540 static struct api_ws_memo *api_ws_client_memo_make(struct api_ws *api, struct afb_xreq *xreq)
542 struct api_ws_memo *memo;
544 memo = malloc(sizeof *memo);
546 afb_xreq_addref(xreq);
548 do { memo->msgid = ++api->client.id; } while(api_ws_client_memo_search(api, memo->msgid) != NULL);
550 memo->next = api->client.memos;
551 api->client.memos = memo;
556 /* free and release the memorizing data */
557 static void api_ws_client_memo_destroy(struct api_ws_memo *memo)
559 struct api_ws_memo **prv;
561 prv = &memo->api->client.memos;
562 while (*prv != NULL) {
570 afb_xreq_unref(memo->xreq);
574 /* get event data from the message */
575 static int api_ws_client_msg_event_read(struct readbuf *rb, uint32_t *eventid, const char **name)
577 return api_ws_read_uint32(rb, eventid) && api_ws_read_string(rb, name, NULL);
580 /* get event from the message */
581 static int api_ws_client_msg_event_get(struct api_ws *api, struct readbuf *rb, struct api_ws_event **ev)
586 /* get event data from the message */
587 if (!api_ws_client_msg_event_read(rb, &eventid, &name)) {
588 ERROR("Invalid message");
592 /* check conflicts */
593 *ev = api_ws_client_event_search(api, eventid, name);
595 ERROR("event %s not found", name);
602 /* get event from the message */
603 static int api_ws_client_msg_memo_get(struct api_ws *api, struct readbuf *rb, struct api_ws_memo **memo)
607 /* get event data from the message */
608 if (!api_ws_read_uint32(rb, &msgid)) {
609 ERROR("Invalid message");
614 *memo = api_ws_client_memo_search(api, msgid);
616 ERROR("message not found");
623 /* read a subscrition message */
624 static int api_ws_client_msg_subscription_get(struct api_ws *api, struct readbuf *rb, struct api_ws_memo **memo, struct api_ws_event **ev)
626 return api_ws_client_msg_memo_get(api, rb, memo) && api_ws_client_msg_event_get(api, rb, ev);
630 static void api_ws_client_event_create(struct api_ws *api, struct readbuf *rb)
635 struct api_ws_event *ev;
637 /* get event data from the message */
638 offset = api_ws_client_msg_event_read(rb, &eventid, &name);
640 ERROR("Invalid message");
644 /* check conflicts */
645 ev = api_ws_client_event_search(api, eventid, name);
651 /* no conflict, try to add it */
652 ev = malloc(sizeof *ev);
654 ev->event = afb_evt_create_event(name);
655 if (ev->event.closure == NULL)
659 ev->eventid = eventid;
660 ev->next = api->client.events;
661 api->client.events = ev;
665 ERROR("can't create event %s, out of memory", name);
668 /* removes an event */
669 static void api_ws_client_event_drop(struct api_ws *api, struct readbuf *rb)
671 struct api_ws_event *ev, **prv;
673 /* retrieves the event */
674 if (!api_ws_client_msg_event_get(api, rb, &ev))
677 /* decrease the reference count */
681 /* unlinks the event */
682 prv = &api->client.events;
687 /* destroys the event */
688 afb_event_drop(ev->event);
692 /* subscribes an event */
693 static void api_ws_client_event_subscribe(struct api_ws *api, struct readbuf *rb)
695 struct api_ws_event *ev;
696 struct api_ws_memo *memo;
698 if (api_ws_client_msg_subscription_get(api, rb, &memo, &ev)) {
699 /* subscribe the request from the event */
700 if (afb_xreq_subscribe(memo->xreq, ev->event) < 0)
701 ERROR("can't subscribe: %m");
705 /* unsubscribes an event */
706 static void api_ws_client_event_unsubscribe(struct api_ws *api, struct readbuf *rb)
708 struct api_ws_event *ev;
709 struct api_ws_memo *memo;
711 if (api_ws_client_msg_subscription_get(api, rb, &memo, &ev)) {
712 /* unsubscribe the request from the event */
713 if (afb_xreq_unsubscribe(memo->xreq, ev->event) < 0)
714 ERROR("can't unsubscribe: %m");
718 /* receives broadcasted events */
719 static void api_ws_client_event_broadcast(struct api_ws *api, struct readbuf *rb)
721 struct json_object *object;
724 if (api_ws_read_string(rb, &event, NULL) && api_ws_read_object(rb, &object))
725 afb_evt_broadcast(event, object);
727 ERROR("unreadable broadcasted event");
731 static void api_ws_client_event_push(struct api_ws *api, struct readbuf *rb)
733 struct api_ws_event *ev;
734 struct json_object *object;
736 if (api_ws_client_msg_event_get(api, rb, &ev) && api_ws_read_object(rb, &object))
737 afb_event_push(ev->event, object);
739 ERROR("unreadable push event");
742 static void api_ws_client_reply_success(struct api_ws *api, struct readbuf *rb)
744 struct api_ws_memo *memo;
745 struct json_object *object;
749 /* retrieve the message data */
750 if (!api_ws_client_msg_memo_get(api, rb, &memo))
753 if (api_ws_read_uint32(rb, &flags)
754 && api_ws_read_string(rb, &info, NULL)
755 && api_ws_read_object(rb, &object)) {
756 memo->xreq->context.flags = (unsigned)flags;
757 afb_xreq_success(memo->xreq, object, *info ? info : NULL);
759 /* failing to have the answer */
760 afb_xreq_fail(memo->xreq, "error", "ws error");
762 api_ws_client_memo_destroy(memo);
765 static void api_ws_client_reply_fail(struct api_ws *api, struct readbuf *rb)
767 struct api_ws_memo *memo;
768 const char *info, *status;
771 /* retrieve the message data */
772 if (!api_ws_client_msg_memo_get(api, rb, &memo))
775 if (api_ws_read_uint32(rb, &flags)
776 && api_ws_read_string(rb, &status, NULL)
777 && api_ws_read_string(rb, &info, NULL)) {
778 memo->xreq->context.flags = (unsigned)flags;
779 afb_xreq_fail(memo->xreq, status, *info ? info : NULL);
781 /* failing to have the answer */
782 afb_xreq_fail(memo->xreq, "error", "ws error");
784 api_ws_client_memo_destroy(memo);
787 /* send a subcall reply */
788 static void api_ws_client_send_subcall_reply(struct api_ws_reply *reply, int iserror, json_object *object)
791 struct writebuf wb = { .count = 0 };
792 char ie = (char)!!iserror;
794 if (!api_ws_write_char(&wb, CHAR_FOR_SUBCALL_REPLY)
795 || !api_ws_write_uint32(&wb, reply->subcallid)
796 || !api_ws_write_char(&wb, ie)
797 || !api_ws_write_object(&wb, object)) {
802 rc = afb_ws_binary_v(reply->apiws->client.ws, wb.iovec, wb.count);
805 ERROR("error while sending subcall reply");
808 /* callback for subcall reply */
809 static void api_ws_client_subcall_reply_cb(void *closure, int iserror, json_object *object)
811 api_ws_client_send_subcall_reply(closure, iserror, object);
815 /* received a subcall request */
816 static void api_ws_client_subcall(struct api_ws *apiws, struct readbuf *rb)
818 struct api_ws_reply *reply;
819 struct api_ws_memo *memo;
820 const char *api, *verb;
822 struct json_object *object;
824 reply = malloc(sizeof *reply);
828 /* retrieve the message data */
829 if (!api_ws_client_msg_memo_get(apiws, rb, &memo))
832 if (api_ws_read_uint32(rb, &subcallid)
833 && api_ws_read_string(rb, &api, NULL)
834 && api_ws_read_string(rb, &verb, NULL)
835 && api_ws_read_object(rb, &object)) {
836 reply->apiws = apiws;
837 reply->subcallid = subcallid;
838 afb_xreq_subcall(memo->xreq, api, verb, object, api_ws_client_subcall_reply_cb, reply);
842 /* callback when receiving binary data */
843 static void api_ws_client_on_binary(void *closure, char *data, size_t size)
846 struct api_ws *apiws = closure;
847 struct readbuf rb = { .head = data, .end = data + size };
849 pthread_mutex_lock(&apiws->mutex);
850 switch (*rb.head++) {
851 case CHAR_FOR_ANSWER_SUCCESS: /* success */
852 api_ws_client_reply_success(apiws, &rb);
854 case CHAR_FOR_ANSWER_FAIL: /* fail */
855 api_ws_client_reply_fail(apiws, &rb);
857 case CHAR_FOR_EVT_BROADCAST: /* broadcast */
858 api_ws_client_event_broadcast(apiws, &rb);
860 case CHAR_FOR_EVT_ADD: /* creates the event */
861 api_ws_client_event_create(apiws, &rb);
863 case CHAR_FOR_EVT_DEL: /* drops the event */
864 api_ws_client_event_drop(apiws, &rb);
866 case CHAR_FOR_EVT_PUSH: /* pushs the event */
867 api_ws_client_event_push(apiws, &rb);
869 case CHAR_FOR_EVT_SUBSCRIBE: /* subscribe event for a request */
870 api_ws_client_event_subscribe(apiws, &rb);
872 case CHAR_FOR_EVT_UNSUBSCRIBE: /* unsubscribe event for a request */
873 api_ws_client_event_unsubscribe(apiws, &rb);
875 case CHAR_FOR_SUBCALL_CALL: /* subcall */
876 api_ws_client_subcall(apiws, &rb);
878 default: /* unexpected message */
879 /* TODO: close the connection */
882 pthread_mutex_unlock(&apiws->mutex);
887 /* on call, propagate it to the ws service */
888 static void api_ws_client_call_cb(void * closure, struct afb_xreq *xreq)
891 struct api_ws_memo *memo;
892 struct writebuf wb = { .count = 0 };
895 struct api_ws *apiws = closure;
897 pthread_mutex_lock(&apiws->mutex);
899 /* create the recording data */
900 memo = api_ws_client_memo_make(apiws, xreq);
902 afb_xreq_fail_f(xreq, "error", "out of memory");
906 /* creates the call message */
907 raw = afb_xreq_raw(xreq, &szraw);
910 if (!api_ws_write_char(&wb, CHAR_FOR_CALL)
911 || !api_ws_write_uint32(&wb, memo->msgid)
912 || !api_ws_write_uint32(&wb, (uint32_t)xreq->context.flags)
913 || !api_ws_write_string(&wb, xreq->verb)
914 || !api_ws_write_string(&wb, afb_session_uuid(xreq->context.session))
915 || !api_ws_write_string_length(&wb, raw, szraw))
919 rc = afb_ws_binary_v(apiws->client.ws, wb.iovec, wb.count);
923 afb_xreq_fail(xreq, "error", "websocket sending error");
927 afb_xreq_fail(xreq, "error", "internal: raw is NULL!");
931 afb_xreq_fail(xreq, "error", "overflow: size doesn't match 32 bits!");
934 api_ws_client_memo_destroy(memo);
936 pthread_mutex_unlock(&apiws->mutex);
940 static void api_ws_client_disconnect(struct api_ws *api)
943 afb_ws_destroy(api->client.ws);
944 api->client.ws = NULL;
951 static int api_ws_client_connect(struct api_ws *api)
956 fd = api_ws_socket(api->path, 0);
958 ws = afb_ws_create(afb_common_get_event_loop(), fd, &api_ws_client_ws_itf, api);
969 static struct afb_api_itf ws_api_itf = {
970 .call = api_ws_client_call_cb
973 /* adds a afb-ws-service client api */
974 int afb_api_ws_add_client(const char *path, struct afb_apiset *apiset)
978 struct afb_api afb_api;
980 /* create the ws client api */
981 api = api_ws_make(path);
985 /* connect to the service */
986 rc = api_ws_client_connect(api);
988 ERROR("can't connect to ws service %s", api->path);
992 /* record it as an API */
993 afb_api.closure = api;
994 afb_api.itf = &ws_api_itf;
995 if (afb_apiset_add(apiset, api->api, afb_api) < 0)
1001 api_ws_client_disconnect(api);
1008 /******************* client description part for server *****************************/
1010 static void api_ws_server_client_unref(struct api_ws_client *client)
1012 struct api_ws_subcall *sc, *nsc;
1014 if (!__atomic_sub_fetch(&client->refcount, 1, __ATOMIC_RELAXED)) {
1015 afb_evt_listener_unref(client->listener);
1016 afb_ws_destroy(client->ws);
1017 nsc = client->subcalls;
1021 sc->callback(sc->closure, 1, NULL);
1024 afb_cred_unref(client->cred);
1025 afb_apiset_unref(client->apiset);
1030 static void api_ws_server_client_addref(struct api_ws_client *client)
1032 __atomic_add_fetch(&client->refcount, 1, __ATOMIC_RELAXED);
1035 /* on call, propagate it to the ws service */
1036 static void api_ws_server_on_call(struct api_ws_client *client, struct readbuf *rb)
1038 struct api_ws_server_req *wreq;
1040 const char *uuid, *verb;
1041 uint32_t flags, msgid;
1043 struct json_object *object;
1045 api_ws_server_client_addref(client);
1047 /* reads the call message data */
1048 if (!api_ws_read_uint32(rb, &msgid)
1049 || !api_ws_read_uint32(rb, &flags)
1050 || !api_ws_read_string(rb, &verb, &lenverb)
1051 || !api_ws_read_string(rb, &uuid, NULL)
1052 || !api_ws_read_object(rb, &object))
1055 /* create the request */
1056 wreq = malloc(++lenverb + sizeof *wreq);
1060 afb_xreq_init(&wreq->xreq, &afb_api_ws_xreq_itf);
1061 wreq->client = client;
1062 wreq->msgid = msgid;
1063 cverb = (char*)&wreq[1];
1064 memcpy(cverb, verb, lenverb);
1066 /* init the context */
1067 if (afb_context_connect(&wreq->xreq.context, uuid, NULL) < 0)
1069 wreq->xreq.context.flags = flags;
1071 /* makes the call */
1072 wreq->xreq.cred = afb_cred_addref(client->cred);
1073 wreq->xreq.api = client->api;
1074 wreq->xreq.verb = cverb;
1075 wreq->xreq.json = object;
1076 afb_xreq_process(&wreq->xreq, client->apiset);
1082 json_object_put(object);
1084 api_ws_server_client_unref(client);
1087 /* on subcall reply */
1088 static void api_ws_server_on_subcall_reply(struct api_ws_client *client, struct readbuf *rb)
1092 struct json_object *object;
1093 struct api_ws_subcall *sc, **psc;
1095 /* reads the call message data */
1096 if (!api_ws_read_uint32(rb, &subcallid)
1097 || !api_ws_read_char(rb, &iserror)
1098 || !api_ws_read_object(rb, &object)) {
1099 /* TODO bad protocol */
1103 /* search the subcall and unlink it */
1104 pthread_mutex_lock(&client->mutex);
1105 psc = &client->subcalls;
1106 while ((sc = *psc) && sc->subcallid != subcallid)
1109 pthread_mutex_unlock(&client->mutex);
1110 /* TODO subcall not found */
1113 pthread_mutex_unlock(&client->mutex);
1114 sc->callback(sc->closure, (int)iserror, object);
1117 json_object_put(object);
1120 /* callback when receiving binary data */
1121 static void api_ws_server_on_binary(void *closure, char *data, size_t size)
1124 struct readbuf rb = { .head = data, .end = data + size };
1125 switch (*rb.head++) {
1127 api_ws_server_on_call(closure, &rb);
1129 case CHAR_FOR_SUBCALL_REPLY:
1130 api_ws_server_on_subcall_reply(closure, &rb);
1132 default: /* unexpected message */
1133 /* TODO: close the connection */
1140 /* callback when receiving a hangup */
1141 static void api_ws_server_on_hangup(void *closure)
1143 struct api_ws_client *client = closure;
1145 /* close the socket */
1146 if (client->fd >= 0) {
1151 /* release the client */
1152 api_ws_server_client_unref(client);
1155 static void api_ws_server_accept(struct api_ws *api)
1157 struct api_ws_client *client;
1158 struct sockaddr addr;
1161 client = calloc(1, sizeof *client);
1162 if (client != NULL) {
1163 client->listener = afb_evt_listener_create(&api_ws_server_evt_itf, client);
1164 if (client->listener != NULL) {
1165 lenaddr = (socklen_t)sizeof addr;
1166 client->fd = accept(api->fd, &addr, &lenaddr);
1167 if (client->fd >= 0) {
1168 client->cred = afb_cred_create_for_socket(client->fd);
1169 fcntl(client->fd, F_SETFD, FD_CLOEXEC);
1170 fcntl(client->fd, F_SETFL, O_NONBLOCK);
1171 client->ws = afb_ws_create(afb_common_get_event_loop(), client->fd, &api_ws_server_ws_itf, client);
1172 if (client->ws != NULL) {
1173 client->api = api->api;
1174 client->apiset = afb_apiset_addref(api->server.apiset);
1175 client->refcount = 1;
1176 client->subcalls = NULL;
1179 afb_cred_unref(client->cred);
1182 afb_evt_listener_unref(client->listener);
1188 /******************* server part: manage events **********************************/
1190 static void api_ws_server_event_send(struct api_ws_client *client, char order, const char *event, int eventid, const char *data)
1193 struct writebuf wb = { .count = 0 };
1195 if (api_ws_write_char(&wb, order)
1196 && api_ws_write_uint32(&wb, eventid)
1197 && api_ws_write_string(&wb, event)
1198 && (data == NULL || api_ws_write_string(&wb, data))) {
1199 rc = afb_ws_binary_v(client->ws, wb.iovec, wb.count);
1203 ERROR("error while sending %c for event %s", order, event);
1206 static void api_ws_server_event_add(void *closure, const char *event, int eventid)
1208 api_ws_server_event_send(closure, CHAR_FOR_EVT_ADD, event, eventid, NULL);
1211 static void api_ws_server_event_remove(void *closure, const char *event, int eventid)
1213 api_ws_server_event_send(closure, CHAR_FOR_EVT_DEL, event, eventid, NULL);
1216 static void api_ws_server_event_push(void *closure, const char *event, int eventid, struct json_object *object)
1218 const char *data = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
1219 api_ws_server_event_send(closure, CHAR_FOR_EVT_PUSH, event, eventid, data ? : "null");
1220 json_object_put(object);
1223 static void api_ws_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object)
1226 struct api_ws_client *client = closure;
1228 struct writebuf wb = { .count = 0 };
1230 if (api_ws_write_char(&wb, CHAR_FOR_EVT_BROADCAST) && api_ws_write_string(&wb, event) && api_ws_write_object(&wb, object)) {
1231 rc = afb_ws_binary_v(client->ws, wb.iovec, wb.count);
1233 ERROR("error while broadcasting event %s", event);
1235 ERROR("error while broadcasting event %s", event);
1236 json_object_put(object);
1239 /******************* ws request part for server *****************/
1241 /* decrement the reference count of the request and free/release it on falling to null */
1242 static void api_ws_server_req_destroy_cb(struct afb_xreq *xreq)
1244 struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1246 afb_context_disconnect(&wreq->xreq.context);
1247 afb_cred_unref(wreq->xreq.cred);
1248 json_object_put(wreq->xreq.json);
1249 api_ws_server_client_unref(wreq->client);
1253 static void api_ws_server_req_success_cb(struct afb_xreq *xreq, struct json_object *obj, const char *info)
1256 struct writebuf wb = { .count = 0 };
1257 struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1259 if (api_ws_write_char(&wb, CHAR_FOR_ANSWER_SUCCESS)
1260 && api_ws_write_uint32(&wb, wreq->msgid)
1261 && api_ws_write_uint32(&wb, (uint32_t)wreq->xreq.context.flags)
1262 && api_ws_write_string(&wb, info ? : "")
1263 && api_ws_write_object(&wb, obj)) {
1264 rc = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1268 ERROR("error while sending success");
1270 json_object_put(obj);
1273 static void api_ws_server_req_fail_cb(struct afb_xreq *xreq, const char *status, const char *info)
1276 struct writebuf wb = { .count = 0 };
1277 struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1279 if (api_ws_write_char(&wb, CHAR_FOR_ANSWER_FAIL)
1280 && api_ws_write_uint32(&wb, wreq->msgid)
1281 && api_ws_write_uint32(&wb, (uint32_t)wreq->xreq.context.flags)
1282 && api_ws_write_string(&wb, status)
1283 && api_ws_write_string(&wb, info ? : "")) {
1284 rc = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1288 ERROR("error while sending fail");
1291 static void api_ws_server_req_subcall_cb(struct afb_xreq *xreq, const char *api, const char *verb, struct json_object *args, void (*callback)(void*, int, struct json_object*), void *cb_closure)
1294 struct writebuf wb = { .count = 0 };
1295 struct api_ws_subcall *sc, *osc;
1296 struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1297 struct api_ws_client *client = wreq->client;
1299 sc = malloc(sizeof *sc);
1303 sc->callback = callback;
1304 sc->closure = cb_closure;
1306 pthread_mutex_unlock(&client->mutex);
1307 sc->subcallid = (uint32_t)(((intptr_t)sc) >> 6);
1310 osc = client->subcalls;
1311 while(osc && osc->subcallid != sc->subcallid)
1314 sc->next = client->subcalls;
1315 client->subcalls = sc;
1316 pthread_mutex_unlock(&client->mutex);
1318 if (api_ws_write_char(&wb, CHAR_FOR_SUBCALL_CALL)
1319 && api_ws_write_uint32(&wb, wreq->msgid)
1320 && api_ws_write_uint32(&wb, sc->subcallid)
1321 && api_ws_write_string(&wb, api)
1322 && api_ws_write_string(&wb, verb)
1323 && api_ws_write_object(&wb, args)) {
1324 rc = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1328 ERROR("error while sending fail");
1332 static int api_ws_server_req_subscribe_cb(struct afb_xreq *xreq, struct afb_event event)
1335 struct writebuf wb = { .count = 0 };
1336 struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1338 rc = afb_evt_add_watch(wreq->client->listener, event);
1342 if (api_ws_write_char(&wb, CHAR_FOR_EVT_SUBSCRIBE)
1343 && api_ws_write_uint32(&wb, wreq->msgid)
1344 && api_ws_write_uint32(&wb, (uint32_t)afb_evt_event_id(event))
1345 && api_ws_write_string(&wb, afb_evt_event_name(event))) {
1346 rc2 = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1350 ERROR("error while subscribing event");
1355 static int api_ws_server_req_unsubscribe_cb(struct afb_xreq *xreq, struct afb_event event)
1358 struct writebuf wb = { .count = 0 };
1359 struct api_ws_server_req *wreq = CONTAINER_OF_XREQ(struct api_ws_server_req, xreq);
1361 if (api_ws_write_char(&wb, CHAR_FOR_EVT_UNSUBSCRIBE)
1362 && api_ws_write_uint32(&wb, wreq->msgid)
1363 && api_ws_write_uint32(&wb, (uint32_t)afb_evt_event_id(event))
1364 && api_ws_write_string(&wb, afb_evt_event_name(event))) {
1365 rc2 = afb_ws_binary_v(wreq->client->ws, wb.iovec, wb.count);
1369 ERROR("error while subscribing event");
1371 rc = afb_evt_remove_watch(wreq->client->listener, event);
1375 /******************* server part **********************************/
1377 static int api_ws_server_connect(struct api_ws *api);
1379 static int api_ws_server_listen_callback(sd_event_source *src, int fd, uint32_t revents, void *closure)
1381 if ((revents & EPOLLIN) != 0)
1382 api_ws_server_accept(closure);
1383 if ((revents & EPOLLHUP) != 0)
1384 api_ws_server_connect(closure);
1388 static void api_ws_server_disconnect(struct api_ws *api)
1390 if (api->server.listensrc != NULL) {
1391 sd_event_source_unref(api->server.listensrc);
1392 api->server.listensrc = NULL;
1400 static int api_ws_server_connect(struct api_ws *api)
1404 /* ensure disconnected */
1405 api_ws_server_disconnect(api);
1407 /* request the service object name */
1408 api->fd = api_ws_socket(api->path, 1);
1410 ERROR("can't create socket %s", api->path);
1412 /* listen for service */
1413 rc = sd_event_add_io(afb_common_get_event_loop(), &api->server.listensrc, api->fd, EPOLLIN, api_ws_server_listen_callback, api);
1418 ERROR("can't add ws object %s", api->path);
1423 /* create the service */
1424 int afb_api_ws_add_server(const char *path, struct afb_apiset *apiset)
1429 /* creates the ws api object */
1430 api = api_ws_make(path);
1434 /* connect for serving */
1435 rc = api_ws_server_connect(api);
1439 api->server.apiset = afb_apiset_addref(apiset);