afm-user-daemon: Update to future version of app-framework-binder
[src/app-framework-main.git] / src / afm-user-daemon.c
index 346c58b..14977b0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- Copyright 2015 IoT.bzh
+ Copyright (C) 2015-2018 IoT.bzh
 
  author: José Bollo <jose.bollo@iot.bzh>
 
  limitations under the License.
 */
 
+#define _GNU_SOURCE
 #include <unistd.h>
 #include <stdio.h>
 #include <time.h>
 #include <getopt.h>
+#include <string.h>
 
-#include <json.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include <json-c/json.h>
+
+#include <afb/afb-ws-client.h>
+#include <afb/afb-proto-ws.h>
 
 #include "verbose.h"
 #include "utils-jbus.h"
-#include "af-db.h"
-#include "af-run.h"
+#include "utils-json.h"
+
+#define AFM_USER_DBUS_PATH     "/org/AGL/afm/user"
 
+/*
+ * name of the application
+ */
 static const char appname[] = "afm-user-daemon";
 
-static void usage()
-{
-       printf(
-               "usage: %s [-q] [-v] [-r rootdir]... [-a appdir]...\n"
-               "\n"
-               "   -a appdir    adds an application directory\n"
-               "   -r rootdir   adds a root directory of applications\n"
-               "   -d           run as a daemon\n"
-               "   -q           quiet\n"
-               "   -v           verbose\n"
-               "\n",
-               appname
-       );
-}
+/*
+ * string for printing version
+ */
+static const char versionstr[] =
+       "\n"
+       "  %s  version="AFM_VERSION"\n"
+       "\n"
+       "  Copyright (C) 2015, 2016, 2017 \"IoT.bzh\"\n"
+       "  AFB comes with ABSOLUTELY NO WARRANTY.\n"
+       "  Licence Apache 2\n"
+       "\n";
+
+/*
+ * string for printing usage
+ */
+static const char usagestr[] =
+       "usage: %s [option(s)] afm-main-uri\n"
+       "\n"
+       "   -d           run as a daemon\n"
+       "   -u addr      address of user D-Bus to use\n"
+       "   -q           quiet\n"
+       "   -v           verbose\n"
+       "   -V           version\n"
+       "\n";
 
-static struct option options[] = {
-       { "root",        required_argument, NULL, 'r' },
-       { "application", required_argument, NULL, 'a' },
+/*
+ * Option definition for getopt_long
+ */
+static const char options_s[] = "hdqvVu:";
+static struct option options_l[] = {
+       { "user-dbus",   required_argument, NULL, 'u' },
        { "daemon",      no_argument,       NULL, 'd' },
        { "quiet",       no_argument,       NULL, 'q' },
        { "verbose",     no_argument,       NULL, 'v' },
        { "help",        no_argument,       NULL, 'h' },
+       { "version",     no_argument,       NULL, 'V' },
        { NULL, 0, NULL, 0 }
 };
 
-static struct jbus *jbus;
-static struct af_db *afdb;
-
-const char error_nothing[] = "[]";
-const char error_bad_request[] = "\"bad request\"";
-const char error_not_found[] = "\"not found\"";
-const char error_cant_start[] = "\"can't start\"";
-
-static const char *getappid(struct json_object *obj)
-{
-       return json_type_string == json_object_get_type(obj) ? json_object_get_string(obj) : NULL;
-}
+/*
+ * The methods propagated
+ */
+static const char *methods[] = {
+       "runnables",
+       "detail",
+       "start",
+       "once",
+       "terminate",
+       "pause",
+       "resume",
+       "stop",
+       "continue",
+       "runners",
+       "state",
+       "install",
+       "uninstall",
+       NULL
+};
 
-static int getrunid(struct json_object *obj)
-{
-       return json_type_int == json_object_get_type(obj) ? json_object_get_int(obj) : 0;
-}
+/*
+ * Connections
+ */
+static struct sd_event *evloop;
+static struct jbus *user_bus;
+static struct afb_proto_ws *pws;
+static char *sessionid;
+static const char *uri;
 
-static void reply(struct jreq *jreq, struct json_object *resp, const char *errstr)
-{
-       if (resp)
-               jbus_reply_j(jreq, resp);
-       else
-               jbus_reply_error_s(jreq, errstr);
-}
+/*
+ * 
+ */
+static void on_pws_hangup(void *closure);
+static void on_pws_reply(void *closure, void *request, struct json_object *obj, const char *error, const char *info);
+#if !defined(AFB_PROTO_WS_VERSION) || (AFB_PROTO_WS_VERSION < 3)
+static void on_pws_reply_success(void *closure, void *request, struct json_object *result, const char *info)
+       { on_pws_reply(closure, request, result, NULL, info); }
+static void on_pws_reply_fail(void *closure, void *request, const char *error, const char *info)
+       { on_pws_reply(closure, request, NULL, error, info); }
+#endif
+static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data);
+
+/* the callback interface for pws */
+static struct afb_proto_ws_client_itf pws_itf = {
+#if !defined(AFB_PROTO_WS_VERSION) || (AFB_PROTO_WS_VERSION < 3)
+       .on_reply_success = on_pws_reply_success,
+       .on_reply_fail = on_pws_reply_fail,
+#else
+       .on_reply = on_pws_reply,
+#endif
+       .on_event_broadcast = on_pws_event_broadcast,
+};
 
-static void reply_status(struct jreq *jreq, int status)
+static int try_connect_pws()
 {
-       if (status)
-               jbus_reply_error_s(jreq, error_not_found);
-       else
-               jbus_reply_s(jreq, "true");
+       pws = afb_ws_client_connect_api(evloop, uri, &pws_itf, NULL);
+       if (pws == NULL) {
+               fprintf(stderr, "connection to %s failed: %m\n", uri);
+               return 0;
+       }
+       afb_proto_ws_on_hangup(pws, on_pws_hangup);
+       return 1;
 }
 
-static void on_runnables(struct jreq *jreq, struct json_object *obj)
-{
-       struct json_object *resp = af_db_application_list(afdb);
-       jbus_reply_j(jreq, resp);
-       json_object_put(obj);
-}
+static void attempt_connect_pws(int count);
 
-static void on_detail(struct jreq *jreq, struct json_object *obj)
+static int timehand(sd_event_source *s, uint64_t usec, void *userdata)
 {
-       const char *appid = getappid(obj);
-       struct json_object *resp = af_db_get_application_public(afdb, appid);
-       reply(jreq, resp, error_not_found);
-       json_object_put(obj);
+       sd_event_source_unref(s);
+       attempt_connect_pws((int)(intptr_t)userdata);
+       return 0;
 }
 
-static void on_start(struct jreq *jreq, struct json_object *obj)
+static void attempt_connect_pws(int count)
 {
-       const char *appid;
-       struct json_object *appli;
-       int runid;
-       char runidstr[20];
-
-       appid = getappid(obj);
-       if (appid == NULL)
-               jbus_reply_error_s(jreq, error_bad_request);
-       else {
-               appli = af_db_get_application(afdb, appid);
-               if (appli == NULL)
-                       jbus_reply_error_s(jreq, error_not_found);
-               else {
-                       runid = af_run_start(appli);
-                       if (runid <= 0)
-                               jbus_reply_error_s(jreq, error_cant_start);
-                       else {
-                               snprintf(runidstr, sizeof runidstr, "%d", runid);
-                               runidstr[sizeof runidstr - 1] = 0;
-                               jbus_reply_s(jreq, runidstr);
-                       }
+       sd_event_source *s;
+       if (!try_connect_pws()) {
+               if (--count <= 0) {
+                       ERROR("Definitely disconnected");
+                       exit(1);
                }
+               sd_event_add_time(evloop, &s, CLOCK_MONOTONIC, 5000000, 0, timehand, (void*)(intptr_t)count);
        }
-       json_object_put(obj);
 }
 
-static void on_stop(struct jreq *jreq, struct json_object *obj)
+static void on_pws_reply(void *closure, void *request, struct json_object *obj, const char *error, const char *info)
 {
-       int runid = getrunid(obj);
-       int status = af_run_stop(runid);
-       reply_status(jreq, status);
-       json_object_put(obj);
+       struct sd_bus_message *smsg = request;
+       if (error)
+               jbus_reply_error_s(smsg, error);
+       else
+               jbus_reply_j(smsg, obj);
 }
 
-static void on_continue(struct jreq *jreq, struct json_object *obj)
+static void on_pws_event_broadcast(void *closure, const char *event_name, struct json_object *data)
 {
-       int runid = getrunid(obj);
-       int status = af_run_continue(runid);
-       reply_status(jreq, status);
-       json_object_put(obj);
+       jbus_send_signal_j(user_bus, "changed", data);
 }
 
-static void on_terminate(struct jreq *jreq, struct json_object *obj)
+/* called when pws hangsup */
+static void on_pws_hangup(void *closure)
 {
-       int runid = getrunid(obj);
-       int status = af_run_terminate(runid);
-       reply_status(jreq, status);
-       json_object_put(obj);
+       struct afb_proto_ws *apw = pws;
+       pws = NULL;
+       afb_proto_ws_unref(apw);
+       attempt_connect_pws(10);
 }
 
-static void on_runners(struct jreq *jreq, struct json_object *obj)
+/* propagate the call to the service */
+static void propagate(struct sd_bus_message *smsg, struct json_object *obj, void *closure)
 {
-       struct json_object *resp = af_run_list();
-       jbus_reply_j(jreq, resp);
-       json_object_put(resp);
-       json_object_put(obj);
-}
+       int rc;
+       const char *verb = closure;
+       const char *onbehalf = NULL; /* TODO: on behalf of the client */
 
-static void on_state(struct jreq *jreq, struct json_object *obj)
-{
-       int runid = getrunid(obj);
-       struct json_object *resp = af_run_state(runid);
-       reply(jreq, resp, error_not_found);
-       json_object_put(resp);
-       json_object_put(obj);
+       INFO("method %s propagated for %s", verb, json_object_to_json_string(obj));
+       if (!pws)
+               jbus_reply_error_s(smsg, "disconnected");
+       else {
+#if defined(AFB_PROTO_WS_VERSION) && (AFB_PROTO_WS_VERSION >= 3)
+               rc = afb_proto_ws_client_call(pws, verb, obj, sessionid, smsg, onbehalf);
+#else
+               rc = afb_proto_ws_client_call(pws, verb, obj, sessionid, smsg);
+#endif
+               if (rc < 0)
+                       ERROR("calling %s(%s) failed: %m\n", verb, json_object_to_json_string(obj));
+       } 
 }
 
+/*
+ * Tiny routine to daemonize the program
+ * Return 0 on success or -1 on failure.
+ */
 static int daemonize()
 {
        int rc = fork();
@@ -183,17 +223,66 @@ static int daemonize()
        return 0;
 }
 
+/*
+ * Opens a sd-bus connection and returns it in 'ret'.
+ * The sd-bus connexion is intended to be for user if 'isuser'
+ * is not null. The adress is the default address when 'address'
+ * is NULL or, otherwise, the given address.
+ * It might be necessary to pass the address as an argument because
+ * library systemd uses secure_getenv to retrieves the default
+ * addresses and secure_getenv might return NULL in some cases.
+ */
+static int open_bus(sd_bus **ret, int isuser, const char *address)
+{
+       sd_bus *b;
+       int rc;
+
+       if (address == NULL)
+               return (isuser ? sd_bus_default_user : sd_bus_default_system)(ret);
+
+       rc = sd_bus_new(&b);
+       if (rc < 0)
+               return rc;
+
+       rc = sd_bus_set_address(b, address);
+       if (rc < 0)
+               goto fail;
+
+       sd_bus_set_bus_client(b, 1);
+
+       rc = sd_bus_start(b);
+       if (rc < 0)
+               goto fail;
+
+       *ret = b;
+       return 0;
+
+fail:
+       sd_bus_unref(b);
+       return rc;
+}
+
+/*
+ * ENTRY POINT OF AFM-USER-DAEMON
+ */
 int main(int ac, char **av)
 {
-       int i, daemon = 0;
+       int i, daemon = 0, rc;
+       struct sd_bus *usrbus;
+       const char *usr_bus_addr;
+       const char **iter;
 
        LOGAUTH(appname);
 
        /* first interpretation of arguments */
-       while ((i = getopt_long(ac, av, "hdqvr:a:", options, NULL)) >= 0) {
+       usr_bus_addr = NULL;
+       while ((i = getopt_long(ac, av, options_s, options_l, NULL)) >= 0) {
                switch (i) {
                case 'h':
-                       usage();
+                       printf(usagestr, appname);
+                       return 0;
+               case 'V':
+                       printf(versionstr, appname);
                        return 0;
                case 'q':
                        if (verbosity)
@@ -205,9 +294,8 @@ int main(int ac, char **av)
                case 'd':
                        daemon = 1;
                        break;
-               case 'r':
-                       break;
-               case 'a':
+               case 'u':
+                       usr_bus_addr = optarg;
                        break;
                case ':':
                        ERROR("missing argument value");
@@ -218,80 +306,73 @@ int main(int ac, char **av)
                }
        }
 
-       /* init random generator */
-       srandom((unsigned int)time(NULL));
-
-       /* init runners */
-       if (af_run_init()) {
-               ERROR("af_run_init failed");
+       /* check argument count */
+       if (optind >= ac) {
+               ERROR("Uri to the framework is missing");
                return 1;
        }
-
-       /* init framework */
-       afdb = af_db_create();
-       if (!afdb) {
-               ERROR("af_create failed");
+       if (optind + 1 != ac) {
+               ERROR("Extra parameters found");
                return 1;
        }
-       if (af_db_add_root(afdb, FWK_APP_DIR)) {
-               ERROR("can't add root %s", FWK_APP_DIR);
+       uri = av[optind];
+
+       /* init sessionid */
+       asprintf(&sessionid, "%d-%s", (int)getuid(), appname);
+
+       /* daemonize if requested */
+       if (daemon && daemonize()) {
+               ERROR("daemonization failed");
                return 1;
        }
 
-       /* second interpretation of arguments */
-       optind = 1;
-       while ((i = getopt_long(ac, av, "hdqvr:a:", options, NULL)) >= 0) {
-               switch (i) {
-               case 'r':
-                       if (af_db_add_root(afdb, optarg)) {
-                               ERROR("can't add root %s", optarg);
-                               return 1;
-                       }
-                       break;
-               case 'a':
-                       if (af_db_add_application(afdb, optarg)) {
-                                ERROR("can't add application %s", optarg);
-                                return 1;
-                        }
-                       break;
-               }
+       /* get systemd objects */
+       rc = sd_event_new(&evloop);
+       if (rc < 0) {
+               ERROR("can't create event loop");
+               return 1;
        }
-
-       /* update the database */
-       if (af_db_update_applications(afdb)) {
-               ERROR("af_update_applications failed");
+       rc = open_bus(&usrbus, 1, usr_bus_addr);
+       if (rc < 0) {
+               ERROR("can't create user bus");
+               return 1;
+       }
+       rc = sd_bus_attach_event(usrbus, evloop, 0);
+       if (rc < 0) {
+               ERROR("can't attach user bus to event loop");
                return 1;
        }
 
-       if (daemon && daemonize()) {
-               ERROR("daemonization failed");
+       /* connect to framework */
+       if (!try_connect_pws()) {
+               ERROR("connection to %s failed: %m\n", uri);
                return 1;
        }
 
-       /* init service */
-       jbus = create_jbus(1, "/org/AGL/afmMain");
-       if (!jbus) {
+       /* connect to the session bus */
+       user_bus = create_jbus(usrbus, AFM_USER_DBUS_PATH);
+       if (!user_bus) {
                ERROR("create_jbus failed");
                return 1;
        }
-       if(jbus_add_service_j(jbus, "runnables", on_runnables)
-       || jbus_add_service_j(jbus, "detail", on_detail)
-       || jbus_add_service_j(jbus, "start", on_start)
-       || jbus_add_service_j(jbus, "terminate", on_terminate)
-       || jbus_add_service_j(jbus, "stop", on_stop)
-       || jbus_add_service_j(jbus, "continue", on_continue)
-       || jbus_add_service_j(jbus, "runners", on_runners)
-       || jbus_add_service_j(jbus, "state", on_state)) {
-               ERROR("adding services failed");
-               return 1;
+
+       /* init services */
+       for (iter = methods ; *iter ; iter ++) {
+               if (jbus_add_service_j(user_bus, *iter, propagate, (void*)*iter)) {
+                       ERROR("adding services failed");
+                       return 1;
+               }
        }
 
-       /* start and run */
-       if (jbus_start_serving(jbus)) {
-               ERROR("cant start server");
+       /* start servicing */
+       if (jbus_start_serving(user_bus) < 0) {
+               ERROR("can't start server");
                return 1;
        }
-       while (!jbus_read_write_dispatch(jbus, -1));
+
+       /* run until error */
+       for(;;)
+               sd_event_run(evloop, (uint64_t)-1);
        return 0;
 }