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
26 #include <systemd/sd-bus.h>
27 #include <json-c/json.h>
29 #include <afb/afb-req-itf.h>
31 #include "afb-common.h"
33 #include "afb-session.h"
34 #include "afb-msg-json.h"
36 #include "afb-api-so.h"
37 #include "afb-context.h"
42 static const char DEFAULT_PATH_PREFIX[] = "/org/agl/afb/api/";
49 * The path given are of the form
50 * system:/org/agl/afb/api/...
52 * user:/org/agl/afb/api/...
56 struct sd_bus *sdbus; /* the bus */
57 char *path; /* path of the object for the API */
58 char *name; /* name/interface of the object */
59 char *api; /* api name of the interface */
62 struct sd_bus_slot *slot_broadcast;
63 struct sd_bus_slot *slot_event;
64 struct dbus_event *events;
65 struct dbus_memo *memos;
68 struct sd_bus_slot *slot_call;
69 struct afb_evt_listener *listener; /* listener for broadcasted events */
70 struct destination *destinations;
78 /******************* common part **********************************/
81 * create a structure api_dbus connected on either the system
82 * bus if 'system' is not null or on the user bus. The connection
83 * is established for either emiting/receiving on 'path' being of length
86 static struct api_dbus *make_api_dbus_3(int system, const char *path, size_t pathlen)
92 /* allocates the structure */
93 api = calloc(1, sizeof *api + 1 + pathlen + pathlen);
99 /* init the structure's strings */
101 /* path is copied after the struct */
102 api->path = (void*)(api+1);
103 strcpy(api->path, path);
105 /* api name is at the end of the path */
106 api->api = strrchr(api->path, '/');
107 if (api->api == NULL) {
112 if (!afb_apis_is_valid_api_name(api->api)) {
117 /* the name/interface is copied after the path */
118 api->name = &api->path[pathlen + 1];
119 strcpy(api->name, &path[1]);
120 ptr = strchr(api->name, '/');
123 ptr = strchr(ptr, '/');
127 sdbus = (system ? afb_common_get_system_bus : afb_common_get_user_bus)();
141 * create a structure api_dbus connected on either the system
142 * bus if 'system' is not null or on the user bus. The connection
143 * is established for either emiting/receiving on 'path'.
144 * If 'path' is not absolute, it is prefixed with DEFAULT_PATH_PREFIX.
146 static struct api_dbus *make_api_dbus_2(int system, const char *path)
151 /* check the length of the path */
158 /* if the path is absolute, creation now */
160 return make_api_dbus_3(system, path, len);
162 /* compute the path prefixed with DEFAULT_PATH_PREFIX */
163 assert(strlen(DEFAULT_PATH_PREFIX) > 0);
164 assert(DEFAULT_PATH_PREFIX[strlen(DEFAULT_PATH_PREFIX) - 1] == '/');
165 len += strlen(DEFAULT_PATH_PREFIX);
166 ptr = alloca(len + 1);
167 strcpy(stpcpy(ptr, DEFAULT_PATH_PREFIX), path);
169 /* creation for prefixed path */
170 return make_api_dbus_3(system, ptr, len);
174 * create a structure api_dbus connected either emiting/receiving
176 * The path can be prefixed with "system:" or "user:" to select
177 * either the user or the system D-Bus. If none is set then user's
179 * If remaining 'path' is not absolute, it is prefixed with
180 * DEFAULT_PATH_PREFIX.
182 static struct api_dbus *make_api_dbus(const char *path)
187 /* retrieves the prefix "scheme-like" part */
188 ptr = strchr(path, ':');
190 return make_api_dbus_2(0, path);
192 /* check the prefix part */
193 preflen = (size_t)(ptr - path);
194 if (strncmp(path, "system", preflen) == 0)
195 return make_api_dbus_2(1, ptr + 1);
197 if (strncmp(path, "user", preflen) == 0)
198 return make_api_dbus_2(0, ptr + 1);
200 /* TODO: connect to a foreign D-Bus? */
205 static void destroy_api_dbus(struct api_dbus *api)
210 /******************* client part **********************************/
213 * structure for recording query data
216 struct dbus_memo *next; /* the next memo */
217 struct api_dbus *api; /* the dbus api */
218 struct afb_xreq *xreq; /* the request */
219 uint64_t msgid; /* the message identifier */
224 struct dbus_event *next;
225 struct afb_event event;
230 /* allocates and init the memorizing data */
231 static struct dbus_memo *api_dbus_client_memo_make(struct api_dbus *api, struct afb_xreq *xreq)
233 struct dbus_memo *memo;
235 memo = malloc(sizeof *memo);
237 afb_xreq_addref(xreq);
241 memo->next = api->client.memos;
242 api->client.memos = memo;
247 /* free and release the memorizing data */
248 static void api_dbus_client_memo_destroy(struct dbus_memo *memo)
250 struct dbus_memo **prv;
252 prv = &memo->api->client.memos;
253 while (*prv != NULL) {
261 afb_xreq_unref(memo->xreq);
265 /* search a memorized request */
266 static struct dbus_memo *api_dbus_client_memo_search(struct api_dbus *api, uint64_t msgid)
268 struct dbus_memo *memo;
270 memo = api->client.memos;
271 while (memo != NULL && memo->msgid != msgid)
277 /* callback when received answer */
278 static int api_dbus_client_on_reply(sd_bus_message *message, void *userdata, sd_bus_error *ret_error)
281 struct dbus_memo *memo;
282 const char *first, *second;
286 /* retrieve the recorded data */
290 rc = sd_bus_message_read(message, "yssu", &type, &first, &second, &flags);
292 /* failing to have the answer */
293 afb_xreq_fail(memo->xreq, "error", "dbus error");
295 /* report the answer */
296 memo->xreq->context.flags = (unsigned)flags;
299 afb_xreq_success(memo->xreq, json_tokener_parse(first), *second ? second : NULL);
302 afb_xreq_fail(memo->xreq, first, *second ? second : NULL);
305 afb_xreq_fail(memo->xreq, "error", "dbus link broken");
309 api_dbus_client_memo_destroy(memo);
313 /* on call, propagate it to the dbus service */
314 static void api_dbus_client_call(void *closure, struct afb_xreq *xreq)
316 struct api_dbus *api = closure;
319 struct dbus_memo *memo;
320 struct sd_bus_message *msg;
322 /* create the recording data */
323 memo = api_dbus_client_memo_make(api, xreq);
325 afb_xreq_fail(xreq, "error", "out of memory");
329 /* creates the message */
331 rc = sd_bus_message_new_method_call(api->sdbus, &msg, api->name, api->path, api->name, xreq->verb);
335 rc = sd_bus_message_append(msg, "ssu",
336 afb_xreq_raw(xreq, &size),
337 afb_session_uuid(xreq->context.session),
338 (uint32_t)xreq->context.flags);
343 rc = sd_bus_call_async(api->sdbus, NULL, msg, api_dbus_client_on_reply, memo, (uint64_t)-1);
347 rc = sd_bus_message_get_cookie(msg, &memo->msgid);
352 /* if there was an error report it directly */
354 afb_xreq_fail(xreq, "error", "dbus error");
355 api_dbus_client_memo_destroy(memo);
357 sd_bus_message_unref(msg);
360 static int api_dbus_service_start(void *closure, int share_session, int onneed)
362 struct api_dbus *api = closure;
364 /* not an error when onneed */
368 /* already started: it is an error */
369 ERROR("The Dbus binding %s is not a startable service", api->name);
373 /* receives broadcasted events */
374 static int api_dbus_client_on_broadcast_event(sd_bus_message *m, void *userdata, sd_bus_error *ret_error)
376 struct json_object *object;
377 const char *event, *data;
378 int rc = sd_bus_message_read(m, "ss", &event, &data);
380 ERROR("unreadable broadcasted event");
382 object = json_tokener_parse(data);
383 afb_evt_broadcast(event, object);
388 /* search the event */
389 static struct dbus_event *api_dbus_client_event_search(struct api_dbus *api, int id, const char *name)
391 struct dbus_event *ev;
393 ev = api->client.events;
394 while (ev != NULL && (ev->id != id || 0 != strcmp(afb_evt_event_name(ev->event), name)))
401 static void api_dbus_client_event_create(struct api_dbus *api, int id, const char *name)
403 struct dbus_event *ev;
405 /* check conflicts */
406 ev = api_dbus_client_event_search(api, id, name);
412 /* no conflict, try to add it */
413 ev = malloc(sizeof *ev);
415 ev->event = afb_evt_create_event(name);
416 if (ev->event.closure == NULL)
421 ev->next = api->client.events;
422 api->client.events = ev;
426 ERROR("can't create event %s, out of memory", name);
429 /* removes an event */
430 static void api_dbus_client_event_drop(struct api_dbus *api, int id, const char *name)
432 struct dbus_event *ev, **prv;
434 /* retrieves the event */
435 ev = api_dbus_client_event_search(api, id, name);
437 ERROR("event %s not found", name);
441 /* decrease the reference count */
445 /* unlinks the event */
446 prv = &api->client.events;
451 /* destroys the event */
452 afb_event_drop(ev->event);
457 static void api_dbus_client_event_push(struct api_dbus *api, int id, const char *name, const char *data)
459 struct json_object *object;
460 struct dbus_event *ev;
462 /* retrieves the event */
463 ev = api_dbus_client_event_search(api, id, name);
465 ERROR("event %s not found", name);
469 /* destroys the event */
470 object = json_tokener_parse(data);
471 afb_event_push(ev->event, object);
474 /* subscribes an event */
475 static void api_dbus_client_event_subscribe(struct api_dbus *api, int id, const char *name, uint64_t msgid)
478 struct dbus_event *ev;
479 struct dbus_memo *memo;
481 /* retrieves the event */
482 ev = api_dbus_client_event_search(api, id, name);
484 ERROR("event %s not found", name);
488 /* retrieves the memo */
489 memo = api_dbus_client_memo_search(api, msgid);
491 ERROR("message not found");
495 /* subscribe the request to the event */
496 rc = afb_xreq_subscribe(memo->xreq, ev->event);
498 ERROR("can't subscribe: %m");
501 /* unsubscribes an event */
502 static void api_dbus_client_event_unsubscribe(struct api_dbus *api, int id, const char *name, uint64_t msgid)
505 struct dbus_event *ev;
506 struct dbus_memo *memo;
508 /* retrieves the event */
509 ev = api_dbus_client_event_search(api, id, name);
511 ERROR("event %s not found", name);
515 /* retrieves the memo */
516 memo = api_dbus_client_memo_search(api, msgid);
518 ERROR("message not found");
522 /* unsubscribe the request from the event */
523 rc = afb_xreq_unsubscribe(memo->xreq, ev->event);
525 ERROR("can't unsubscribe: %m");
528 /* receives calls for event */
529 static int api_dbus_client_on_manage_event(sd_bus_message *m, void *userdata, sd_bus_error *ret_error)
531 const char *eventname, *data;
535 struct api_dbus *api;
538 /* check if expected message */
540 if (0 != strcmp(api->name, sd_bus_message_get_interface(m)))
541 return 0; /* not the expected interface */
542 if (0 != strcmp("event", sd_bus_message_get_member(m)))
543 return 0; /* not the expected member */
544 if (sd_bus_message_get_expect_reply(m))
545 return 0; /* not the expected type of message */
547 /* reads the message */
548 rc = sd_bus_message_read(m, "yisst", &order, &eventid, &eventname, &data, &msgid);
550 ERROR("unreadable event");
554 /* what is the order ? */
555 switch ((char)order) {
556 case '+': /* creates the event */
557 api_dbus_client_event_create(api, eventid, eventname);
559 case '-': /* drops the event */
560 api_dbus_client_event_drop(api, eventid, eventname);
562 case '!': /* pushs the event */
563 api_dbus_client_event_push(api, eventid, eventname, data);
565 case 'S': /* subscribe event for a request */
566 api_dbus_client_event_subscribe(api, eventid, eventname, msgid);
568 case 'U': /* unsubscribe event for a request */
569 api_dbus_client_event_unsubscribe(api, eventid, eventname, msgid);
572 /* unexpected order */
573 ERROR("unexpected order '%c' received", (char)order);
579 /* adds a afb-dbus-service client api */
580 int afb_api_dbus_add_client(const char *path)
583 struct api_dbus *api;
584 struct afb_api afb_api;
587 /* create the dbus client api */
588 api = make_api_dbus(path);
592 /* connect to broadcasted events */
593 rc = asprintf(&match, "type='signal',path='%s',interface='%s',member='broadcast'", api->path, api->name);
596 ERROR("out of memory");
599 rc = sd_bus_add_match(api->sdbus, &api->client.slot_broadcast, match, api_dbus_client_on_broadcast_event, api);
603 ERROR("can't add dbus match %s for %s", api->path, api->name);
607 /* connect to event management */
608 rc = sd_bus_add_object(api->sdbus, &api->client.slot_event, api->path, api_dbus_client_on_manage_event, api);
611 ERROR("can't add dbus object %s for %s", api->path, api->name);
615 /* record it as an API */
616 afb_api.closure = api;
617 afb_api.call = api_dbus_client_call;
618 afb_api.service_start = api_dbus_service_start;
619 afb_api.update_hooks = NULL;
620 if (afb_apis_add(api->api, afb_api) < 0)
626 destroy_api_dbus(api);
631 /******************* event structures for server part **********************************/
633 static void afb_api_dbus_server_event_add(void *closure, const char *event, int eventid);
634 static void afb_api_dbus_server_event_remove(void *closure, const char *event, int eventid);
635 static void afb_api_dbus_server_event_push(void *closure, const char *event, int eventid, struct json_object *object);
636 static void afb_api_dbus_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object);
638 /* the interface for events broadcasting */
639 static const struct afb_evt_itf evt_broadcast_itf = {
640 .broadcast = afb_api_dbus_server_event_broadcast,
643 /* the interface for events pushing */
644 static const struct afb_evt_itf evt_push_itf = {
645 .push = afb_api_dbus_server_event_push,
646 .add = afb_api_dbus_server_event_add,
647 .remove = afb_api_dbus_server_event_remove
650 /******************* destination description part for server *****************************/
654 /* link to next different destination */
655 struct destination *next;
657 /* the server dbus-api */
658 struct api_dbus *api;
660 /* count of references */
663 /* the destination */
667 static struct destination *afb_api_dbus_server_destination_get(struct api_dbus *api, const char *sender)
669 struct destination *destination;
671 /* searchs for an existing destination */
672 destination = api->server.destinations;
673 while (destination != NULL) {
674 if (0 == strcmp(destination->name, sender)) {
675 destination->refcount++;
678 destination = destination->next;
681 /* not found, create it */
682 destination = malloc(strlen(sender) + sizeof *destination);
683 if (destination == NULL)
686 destination->api = api;
687 destination->refcount = 1;
688 strcpy(destination->name, sender);
689 destination->next = api->server.destinations;
690 api->server.destinations = destination;
695 static void afb_api_dbus_server_destination_unref(struct destination *destination)
697 if (!--destination->refcount) {
698 struct destination **prv;
700 prv = &destination->api->server.destinations;
701 while(*prv != destination)
703 *prv = destination->next;
710 /* link to next different destination */
711 struct destination *destination;
713 /* the listener of events */
714 struct afb_evt_listener *listener;
717 static void afb_api_dbus_server_listener_free(struct listener *listener)
719 afb_evt_listener_unref(listener->listener);
720 afb_api_dbus_server_destination_unref(listener->destination);
724 static struct listener *afb_api_dbus_server_listerner_get(struct api_dbus *api, const char *sender, struct afb_session *session)
727 struct listener *listener;
728 struct destination *destination;
730 /* get the destination */
731 destination = afb_api_dbus_server_destination_get(api, sender);
732 if (destination == NULL)
735 /* retrieves the stored listener */
736 listener = afb_session_get_cookie(session, destination);
737 if (listener != NULL) {
739 afb_api_dbus_server_destination_unref(destination);
743 /* creates the listener */
744 listener = malloc(sizeof *listener);
745 if (listener == NULL)
748 listener->destination = destination;
749 listener->listener = afb_evt_listener_create(&evt_push_itf, destination);
750 if (listener->listener != NULL) {
751 rc = afb_session_set_cookie(session, destination, listener, (void*)afb_api_dbus_server_listener_free);
754 afb_evt_listener_unref(listener->listener);
758 afb_api_dbus_server_destination_unref(destination);
762 /******************* dbus request part for server *****************/
765 * Structure for a dbus request
768 struct afb_xreq xreq; /**< the xreq of the request */
769 sd_bus_message *message; /**< the incoming request message */
770 const char *request; /**< the readen request as string */
771 struct json_object *json; /**< the readen request as object */
772 struct listener *listener; /**< the listener for events */
775 /* decrement the reference count of the request and free/release it on falling to null */
776 static void dbus_req_destroy(void *closure)
778 struct dbus_req *dreq = closure;
780 afb_context_disconnect(&dreq->xreq.context);
781 json_object_put(dreq->json);
782 sd_bus_message_unref(dreq->message);
786 /* get the object of the request */
787 static struct json_object *dbus_req_json(void *closure)
789 struct dbus_req *dreq = closure;
794 /* get the argument of the request of 'name' */
795 static void dbus_req_reply(struct dbus_req *dreq, uint8_t type, const char *first, const char *second)
798 rc = sd_bus_reply_method_return(dreq->message,
799 "yssu", type, first ? : "", second ? : "", (uint32_t)dreq->xreq.context.flags);
801 ERROR("sending the reply failed");
804 static void dbus_req_success(void *closure, struct json_object *obj, const char *info)
806 struct dbus_req *dreq = closure;
808 dbus_req_reply(dreq, RETOK, json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN), info);
811 static void dbus_req_fail(void *closure, const char *status, const char *info)
813 struct dbus_req *dreq = closure;
815 dbus_req_reply(dreq, RETERR, status, info);
818 static void afb_api_dbus_server_event_send(struct destination *destination, char order, const char *event, int eventid, const char *data, uint64_t msgid);
820 static int dbus_req_subscribe(void *closure, struct afb_event event)
822 struct dbus_req *dreq = closure;
826 rc = afb_evt_add_watch(dreq->listener->listener, event);
827 sd_bus_message_get_cookie(dreq->message, &msgid);
828 afb_api_dbus_server_event_send(dreq->listener->destination, 'S', afb_evt_event_name(event), afb_evt_event_id(event), "", msgid);
832 static int dbus_req_unsubscribe(void *closure, struct afb_event event)
834 struct dbus_req *dreq = closure;
838 sd_bus_message_get_cookie(dreq->message, &msgid);
839 afb_api_dbus_server_event_send(dreq->listener->destination, 'U', afb_evt_event_name(event), afb_evt_event_id(event), "", msgid);
840 rc = afb_evt_remove_watch(dreq->listener->listener, event);
844 const struct afb_xreq_query_itf afb_api_dbus_xreq_itf = {
845 .json = dbus_req_json,
846 .success = dbus_req_success,
847 .fail = dbus_req_fail,
848 .unref = dbus_req_destroy,
849 .subscribe = dbus_req_subscribe,
850 .unsubscribe = dbus_req_unsubscribe
853 /******************* server part **********************************/
855 static void afb_api_dbus_server_event_send(struct destination *destination, char order, const char *event, int eventid, const char *data, uint64_t msgid)
858 struct api_dbus *api;
859 struct sd_bus_message *msg;
861 api = destination->api;
864 rc = sd_bus_message_new_method_call(api->sdbus, &msg, destination->name, api->path, api->name, "event");
868 rc = sd_bus_message_append(msg, "yisst", (uint8_t)order, (int32_t)eventid, event, data, msgid);
872 rc = sd_bus_send(api->sdbus, msg, NULL); /* NULL for cookie implies no expected reply */
877 ERROR("error while send event %c%s(%d) to %s", order, event, eventid, destination->name);
879 sd_bus_message_unref(msg);
882 static void afb_api_dbus_server_event_add(void *closure, const char *event, int eventid)
884 afb_api_dbus_server_event_send(closure, '+', event, eventid, "", 0);
887 static void afb_api_dbus_server_event_remove(void *closure, const char *event, int eventid)
889 afb_api_dbus_server_event_send(closure, '-', event, eventid, "", 0);
892 static void afb_api_dbus_server_event_push(void *closure, const char *event, int eventid, struct json_object *object)
894 const char *data = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
895 afb_api_dbus_server_event_send(closure, '!', event, eventid, data, 0);
896 json_object_put(object);
899 static void afb_api_dbus_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object)
902 struct api_dbus *api;
905 rc = sd_bus_emit_signal(api->sdbus, api->path, api->name, "broadcast",
906 "ss", event, json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN));
908 ERROR("error while broadcasting event %s", event);
909 json_object_put(object);
912 /* called when the object for the service is called */
913 static int api_dbus_server_on_object_called(sd_bus_message *message, void *userdata, sd_bus_error *ret_error)
918 struct dbus_req *dreq;
919 struct api_dbus *api = userdata;
921 struct afb_session *session;
922 struct listener *listener;
924 /* check the interface */
925 if (strcmp(sd_bus_message_get_interface(message), api->name) != 0)
929 method = sd_bus_message_get_member(message);
931 /* create the request */
932 dreq = calloc(1 , sizeof *dreq);
937 rc = sd_bus_message_read(message, "ssu", &dreq->request, &uuid, &flags);
939 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_INVALID_SIGNATURE, "invalid signature");
943 /* connect to the context */
944 if (afb_context_connect(&dreq->xreq.context, uuid, NULL) < 0)
946 session = dreq->xreq.context.session;
948 /* get the listener */
949 listener = afb_api_dbus_server_listerner_get(api, sd_bus_message_get_sender(message), session);
950 if (listener == NULL)
953 /* fulfill the request and emit it */
954 dreq->xreq.context.flags = flags;
955 dreq->message = sd_bus_message_ref(message);
956 dreq->json = json_tokener_parse(dreq->request);
957 if (dreq->json == NULL && strcmp(dreq->request, "null")) {
958 /* lazy error detection of json request. Is it to improve? */
959 dreq->json = json_object_new_string(dreq->request);
961 dreq->listener = listener;
962 dreq->xreq.refcount = 1;
963 dreq->xreq.query = dreq;
964 dreq->xreq.queryitf = &afb_api_dbus_xreq_itf;
965 dreq->xreq.api = api->api;
966 dreq->xreq.verb = method;
967 afb_apis_call(&dreq->xreq);
968 afb_xreq_unref(&dreq->xreq);
972 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_NO_MEMORY, "out of memory");
978 /* create the service */
979 int afb_api_dbus_add_server(const char *path)
982 struct api_dbus *api;
984 /* get the dbus api object connected */
985 api = make_api_dbus(path);
989 /* request the service object name */
990 rc = sd_bus_request_name(api->sdbus, api->name, 0);
993 ERROR("can't register name %s", api->name);
997 /* connect the service to the dbus object */
998 rc = sd_bus_add_object(api->sdbus, &api->server.slot_call, api->path, api_dbus_server_on_object_called, api);
1001 ERROR("can't add dbus object %s for %s", api->path, api->name);
1004 INFO("afb service over dbus installed, name %s, path %s", api->name, api->path);
1006 api->server.listener = afb_evt_listener_create(&evt_broadcast_itf, api);
1009 sd_bus_release_name(api->sdbus, api->name);
1011 destroy_api_dbus(api);