Allow to remove systemd library
[src/app-framework-binder.git] / src / main-afb-daemon.c
1 /*
2  * Copyright (C) 2015-2019 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  * Author José Bollo <jose.bollo@iot.bzh>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #define _GNU_SOURCE
20
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <stdint.h>
24 #include <signal.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <limits.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <sys/stat.h>
31 #include <sys/wait.h>
32
33 #if !defined(NO_CALL_PERSONALITY)
34 #include <sys/personality.h>
35 #endif
36
37 #include <json-c/json.h>
38
39 #if WITH_SYSTEMD
40 #   include <systemd/sd-daemon.h>
41 #endif
42
43 #include "afb-args.h"
44 #include "afb-hswitch.h"
45 #include "afb-apiset.h"
46 #include "afb-autoset.h"
47 #include "afb-api-so.h"
48 #if WITH_DBUS_TRANSPARENCY
49 #   include "afb-api-dbus.h"
50 #endif
51 #include "afb-api-ws.h"
52 #include "afb-hsrv.h"
53 #include "afb-hreq.h"
54 #include "afb-xreq.h"
55 #include "afb-session.h"
56 #include "verbose.h"
57 #include "afb-common.h"
58 #include "afb-export.h"
59 #include "afb-monitor.h"
60 #if WITH_AFB_HOOK
61 #include "afb-hook.h"
62 #include "afb-hook-flags.h"
63 #endif
64 #include "afb-debug.h"
65 #if WITH_SUPERVISION
66 #   include "afb-supervision.h"
67 #endif
68
69 #include "process-name.h"
70 #include "wrap-json.h"
71 #include "jobs.h"
72 #include "sig-monitor.h"
73 #include "watchdog.h"
74
75 #if !defined(DEFAULT_BINDER_INTERFACE)
76 #  define DEFAULT_BINDER_INTERFACE NULL
77 #endif
78
79 /*
80    if SELF_PGROUP == 0 the launched command is the group leader
81    if SELF_PGROUP != 0 afb-daemon is the group leader
82 */
83 #define SELF_PGROUP 0
84
85 struct afb_apiset *main_apiset;
86 struct json_object *main_config;
87
88 static pid_t childpid;
89
90 /**
91  * Tiny helper around putenv: add the variable name=value
92  *
93  * @param name name of the variable to set
94  * @param value value to set to the variable
95  *
96  * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
97  */
98 static int addenv(const char *name, const char *value)
99 {
100         char *head, *middle;
101
102         head = malloc(2 + strlen(name) + strlen(value));
103         if (head == NULL) {
104                 errno = ENOMEM;
105                 return -1;
106         }
107         middle = stpcpy(head, name);
108         middle[0] = '=';
109         strcpy(&middle[1], value);
110         return putenv(head);
111 }
112
113 /**
114  * Tiny helper around addenv that export the real path
115  *
116  * @param name name of the variable to set
117  * @param path the path value to export to the variable
118  *
119  * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
120  */
121 static int addenv_realpath(const char *name, const char *path)
122 {
123         char buffer[PATH_MAX];
124         char *p = realpath(path, buffer);
125         return p ? addenv(name, p) : -1;
126 }
127
128 /**
129  * Tiny helper around addenv that export an integer
130  *
131  * @param name name of the variable to set
132  * @param value the integer value to export
133  *
134  * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
135  */
136 static int addenv_int(const char *name, int value)
137 {
138         char buffer[64];
139         snprintf(buffer, sizeof buffer, "%d", value);
140         return addenv(name, buffer);
141 }
142
143 /*----------------------------------------------------------
144  |   helpers for handling list of arguments
145  +--------------------------------------------------------- */
146
147 static const char *run_for_config_array_opt(const char *name,
148                                             int (*run) (void *closure, const char *value),
149                                             void *closure)
150 {
151         int i, n, rc;
152         struct json_object *array, *value;
153
154         if (json_object_object_get_ex(main_config, name, &array)) {
155                 if (!json_object_is_type(array, json_type_array))
156                         return json_object_get_string(array);
157                 n = (int)json_object_array_length(array);
158                 for (i = 0 ; i < n ; i++) {
159                         value = json_object_array_get_idx(array, i);
160                         rc = run(closure, json_object_get_string(value));
161                         if (!rc)
162                                 return json_object_get_string(value);
163                 }
164         }
165         return NULL;
166 }
167
168 static int run_start(void *closure, const char *value)
169 {
170         int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set) = closure;
171         return starter(value, main_apiset, main_apiset) >= 0;
172 }
173
174 static void apiset_start_list(const char *name,
175                         int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set),
176                         const char *message)
177 {
178         const char *item = run_for_config_array_opt(name, run_start, starter);
179         if (item) {
180                 ERROR("can't start %s %s", message, item);
181                 exit(1);
182         }
183 }
184
185 /*----------------------------------------------------------
186  | exit_handler
187  |   Handles on exit specific actions
188  +--------------------------------------------------------- */
189 static void exit_handler()
190 {
191         struct sigaction siga;
192
193         memset(&siga, 0, sizeof siga);
194         siga.sa_handler = SIG_IGN;
195         sigaction(SIGTERM, &siga, NULL);
196
197         if (SELF_PGROUP)
198                 killpg(0, SIGTERM);
199         else if (childpid > 0)
200                 killpg(childpid, SIGTERM);
201 }
202
203 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
204 {
205         NOTICE("Received SIGTERM");
206         exit(0);
207 }
208
209 static void on_sighup(int signum, siginfo_t *info, void *uctx)
210 {
211         NOTICE("Received SIGHUP");
212         /* TODO */
213 }
214
215 static void setup_daemon()
216 {
217         struct sigaction siga;
218
219         /* install signal handlers */
220         memset(&siga, 0, sizeof siga);
221         siga.sa_flags = SA_SIGINFO;
222
223         siga.sa_sigaction = on_sigterm;
224         sigaction(SIGTERM, &siga, NULL);
225
226         siga.sa_sigaction = on_sighup;
227         sigaction(SIGHUP, &siga, NULL);
228
229         /* handle groups */
230         atexit(exit_handler);
231
232         /* ignore any SIGPIPE */
233         signal(SIGPIPE, SIG_IGN);
234 }
235
236 /*----------------------------------------------------------
237  | daemonize
238  |   set the process in background
239  +--------------------------------------------------------- */
240 static void daemonize()
241 {
242         int fd = 0, daemon, nostdin;
243         const char *output;
244         pid_t pid;
245
246         daemon = 0;
247         output = NULL;
248         wrap_json_unpack(main_config, "{s?b s?s}", "daemon", &daemon, "output", &output);
249         nostdin = 0;
250
251         if (output) {
252                 fd = open(output, O_WRONLY | O_APPEND | O_CREAT, 0640);
253                 if (fd < 0) {
254                         ERROR("Can't open output %s", output);
255                         exit(1);
256                 }
257         }
258
259         if (daemon) {
260                 INFO("entering background mode");
261
262                 pid = fork();
263                 if (pid == -1) {
264                         ERROR("Failed to fork daemon process");
265                         exit(1);
266                 }
267                 if (pid != 0)
268                         _exit(0);
269
270                 nostdin = 1;
271         }
272
273         /* closes the input */
274         if (output) {
275                 NOTICE("Redirecting output to %s", output);
276                 close(2);
277                 dup(fd);
278                 close(1);
279                 dup(fd);
280                 close(fd);
281         }
282
283         if (nostdin)
284                 close(0); /* except if 'daemon', ctrl+C still works after that */
285 }
286
287 /*---------------------------------------------------------
288  | http server
289  |   Handles the HTTP server
290  +--------------------------------------------------------- */
291 static int init_alias(void *closure, const char *spec)
292 {
293         struct afb_hsrv *hsrv = closure;
294         char *path = strchr(spec, ':');
295
296         if (path == NULL) {
297                 ERROR("Missing ':' in alias %s. Alias ignored", spec);
298                 return 1;
299         }
300         *path++ = 0;
301         INFO("Alias for url=%s to path=%s", spec, path);
302         return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
303                                   0, 0);
304 }
305
306 static int init_http_server(struct afb_hsrv *hsrv)
307 {
308         int rc;
309         const char *rootapi, *roothttp, *rootbase;
310
311         roothttp = NULL;
312         rc = wrap_json_unpack(main_config, "{ss ss s?s}",
313                                 "rootapi", &rootapi,
314                                 "rootbase", &rootbase,
315                                 "roothttp", &roothttp);
316         if (rc < 0) {
317                 ERROR("Can't get HTTP server config");
318                 exit(1);
319         }
320
321         if (!afb_hsrv_add_handler(hsrv, rootapi,
322                         afb_hswitch_websocket_switch, main_apiset, 20))
323                 return 0;
324
325         if (!afb_hsrv_add_handler(hsrv, rootapi,
326                         afb_hswitch_apis, main_apiset, 10))
327                 return 0;
328
329         if (run_for_config_array_opt("alias", init_alias, hsrv))
330                 return 0;
331
332         if (roothttp != NULL) {
333                 if (!afb_hsrv_add_alias(hsrv, "",
334                         afb_common_rootdir_get_fd(), roothttp, -10, 1))
335                         return 0;
336         }
337
338         if (!afb_hsrv_add_handler(hsrv, rootbase,
339                         afb_hswitch_one_page_api_redirect, NULL, -20))
340                 return 0;
341
342         return 1;
343 }
344
345 static struct afb_hsrv *start_http_server()
346 {
347         int rc;
348         const char *uploaddir, *rootdir;
349         struct afb_hsrv *hsrv;
350         int cache_timeout, http_port;
351
352         rc = wrap_json_unpack(main_config, "{ss ss si si}",
353                                 "uploaddir", &uploaddir,
354                                 "rootdir", &rootdir,
355                                 "cache-eol", &cache_timeout,
356                                 "port", &http_port);
357         if (rc < 0) {
358                 ERROR("Can't get HTTP server start config");
359                 exit(1);
360         }
361
362         if (afb_hreq_init_download_path(uploaddir)) {
363                 ERROR("unable to set the upload directory %s", uploaddir);
364                 return NULL;
365         }
366
367         hsrv = afb_hsrv_create();
368         if (hsrv == NULL) {
369                 ERROR("memory allocation failure");
370                 return NULL;
371         }
372
373         if (!afb_hsrv_set_cache_timeout(hsrv, cache_timeout)
374             || !init_http_server(hsrv)) {
375                 ERROR("initialisation of httpd failed");
376                 afb_hsrv_put(hsrv);
377                 return NULL;
378         }
379
380         NOTICE("Waiting port=%d rootdir=%s", http_port, rootdir);
381         NOTICE("Browser URL= http://localhost:%d", http_port);
382
383         rc = afb_hsrv_start(hsrv, 15);
384         if (!rc) {
385                 ERROR("starting of httpd failed");
386                 afb_hsrv_put(hsrv);
387                 return NULL;
388         }
389
390         rc = afb_hsrv_add_interface_tcp(hsrv, DEFAULT_BINDER_INTERFACE, (uint16_t) http_port);
391         if (!rc) {
392                 ERROR("setting interface failed");
393                 afb_hsrv_put(hsrv);
394                 return NULL;
395         }
396
397         return hsrv;
398 }
399
400 /*---------------------------------------------------------
401  | execute_command
402  +--------------------------------------------------------- */
403
404 static void wait_child_and_exit()
405 {
406         pid_t pidchld = childpid;
407
408         childpid = 0;
409         if (!SELF_PGROUP)
410                 killpg(pidchld, SIGKILL);
411         waitpid(pidchld, NULL, 0);
412         exit(0);
413 }
414
415 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
416 {
417         if (info->si_pid == childpid) {
418                 switch (info->si_code) {
419                 case CLD_EXITED:
420                 case CLD_KILLED:
421                 case CLD_DUMPED:
422                         jobs_exit(wait_child_and_exit);
423                 default:
424                         break;
425                 }
426         }
427 }
428
429 /*
430 # @@ @
431 # @p port
432 # @t token
433 */
434
435 #define SUBST_CHAR  '@'
436 #define SUBST_STR   "@"
437
438 static char *instanciate_string(const char *arg, const char *port, const char *token)
439 {
440         char *resu, *it, *wr;
441         int chg, dif;
442
443         /* get the changes */
444         chg = 0;
445         dif = 0;
446         it = strchrnul(arg, SUBST_CHAR);
447         while (*it) {
448                 switch(*++it) {
449                 case 'p': chg++; dif += (int)strlen(port) - 2; break;
450                 case 't': chg++; dif += (int)strlen(token) - 2; break;
451                 case SUBST_CHAR: it++; chg++; dif--; break;
452                 default: break;
453                 }
454                 it = strchrnul(it, SUBST_CHAR);
455         }
456
457         /* return arg when no change */
458         if (!chg)
459                 return strdup(arg);
460
461         /* allocates the result */
462         resu = malloc((it - arg) + dif + 1);
463         if (!resu) {
464                 ERROR("out of memory");
465                 return NULL;
466         }
467
468         /* instanciate the arguments */
469         wr = resu;
470         for (;;) {
471                 it = strchrnul(arg, SUBST_CHAR);
472                 wr = mempcpy(wr, arg, it - arg);
473                 if (!*it)
474                         break;
475                 switch(*++it) {
476                 case 'p': wr = stpcpy(wr, port); break;
477                 case 't': wr = stpcpy(wr, token); break;
478                 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
479                 case SUBST_CHAR: *wr++ = *it;
480                 }
481                 arg = ++it;
482         }
483
484         *wr = 0;
485         return resu;
486 }
487
488 static int instanciate_environ(const char *port, const char *token)
489 {
490         extern char **environ;
491         char *repl;
492         int i;
493
494         /* instantiate the environment */
495         for (i = 0 ; environ[i] ; i++) {
496                 repl = instanciate_string(environ[i], port, token);
497                 if (!repl)
498                         return -1;
499                 environ[i] = repl;
500         }
501         return 0;
502 }
503
504 static char **instanciate_command_args(struct json_object *exec, const char *port, const char *token)
505 {
506         char **result;
507         char *repl;
508         int i, n;
509
510         /* allocates the result */
511         n = (int)json_object_array_length(exec);
512         result = malloc((n + 1) * sizeof * result);
513         if (!result) {
514                 ERROR("out of memory");
515                 return NULL;
516         }
517
518         /* instanciate the arguments */
519         for (i = 0 ; i < n ; i++) {
520                 repl = instanciate_string(json_object_get_string(json_object_array_get_idx(exec, i)), port, token);
521                 if (!repl) {
522                         while(i)
523                                 free(result[--i]);
524                         free(result);
525                         return NULL;
526                 }
527                 result[i] = repl;
528         }
529         result[i] = NULL;
530         return result;
531 }
532
533 static int execute_command()
534 {
535         struct json_object *exec, *oport;
536         struct sigaction siga;
537         char port[20];
538         const char *token;
539         char **args;
540         int rc;
541
542         /* check whether a command is to execute or not */
543         if (!json_object_object_get_ex(main_config, "exec", &exec))
544                 return 0;
545
546         if (SELF_PGROUP)
547                 setpgid(0, 0);
548
549         /* install signal handler */
550         memset(&siga, 0, sizeof siga);
551         siga.sa_sigaction = on_sigchld;
552         siga.sa_flags = SA_SIGINFO;
553         sigaction(SIGCHLD, &siga, NULL);
554
555         /* fork now */
556         childpid = fork();
557         if (childpid)
558                 return 0;
559
560         /* compute the string for port */
561         if (json_object_object_get_ex(main_config, "port", &oport))
562                 rc = snprintf(port, sizeof port, "%s", json_object_get_string(oport));
563         else
564                 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
565         if (rc < 0 || rc >= (int)(sizeof port)) {
566                 ERROR("port->txt failed");
567         }
568         else {
569                 /* instantiate arguments and environment */
570                 token = afb_session_initial_token();
571                 args = instanciate_command_args(exec, port, token);
572                 if (args && instanciate_environ(port, token) >= 0) {
573                         /* run */
574                         if (!SELF_PGROUP)
575                                 setpgid(0, 0);
576                         execv(args[0], args);
577                         ERROR("can't launch %s: %m", args[0]);
578                 }
579         }
580         exit(1);
581         return -1;
582 }
583
584 /*---------------------------------------------------------
585  | startup calls
586  +--------------------------------------------------------- */
587
588 struct startup_req
589 {
590         struct afb_xreq xreq;
591         char *api;
592         char *verb;
593         struct json_object *calls;
594         int index;
595         int count;
596         const char *callspec;
597         struct afb_session *session;
598 };
599
600 static void startup_call_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
601 {
602         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
603
604         info = info ?: "";
605         if (!error) {
606                 NOTICE("startup call %s returned %s (%s)", sreq->callspec, json_object_get_string(object), info);
607                 json_object_put(object);
608         } else {
609                 ERROR("startup call %s ERROR! %s (%s)", sreq->callspec, error, info);
610                 exit(1);
611         }
612 }
613
614 static void startup_call_current(struct startup_req *sreq);
615
616 static void startup_call_unref(struct afb_xreq *xreq)
617 {
618         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
619
620         free(sreq->api);
621         free(sreq->verb);
622         json_object_put(sreq->xreq.json);
623         if (++sreq->index < sreq->count)
624                 startup_call_current(sreq);
625         else {
626                 afb_session_close(sreq->session);
627                 afb_session_unref(sreq->session);
628                 free(sreq);
629         }
630 }
631
632 static struct afb_xreq_query_itf startup_xreq_itf =
633 {
634         .reply = startup_call_reply,
635         .unref = startup_call_unref
636 };
637
638 static void startup_call_current(struct startup_req *sreq)
639 {
640         const char *api, *verb, *json;
641         enum json_tokener_error jerr;
642
643         sreq->callspec = json_object_get_string(json_object_array_get_idx(sreq->calls, sreq->index)),
644         api = sreq->callspec;
645         verb = strchr(api, '/');
646         if (verb) {
647                 json = strchr(verb, ':');
648                 if (json) {
649                         afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
650                         afb_context_init(&sreq->xreq.context, sreq->session, NULL);
651                         sreq->xreq.context.validated = 1;
652                         sreq->api = strndup(api, verb - api);
653                         sreq->verb = strndup(verb + 1, json - verb - 1);
654                         sreq->xreq.request.called_api = sreq->api;
655                         sreq->xreq.request.called_verb = sreq->verb;
656                         sreq->xreq.json = json_tokener_parse_verbose(json + 1, &jerr);
657                         if (sreq->api && sreq->verb && jerr == json_tokener_success) {
658                                 afb_xreq_process(&sreq->xreq, main_apiset);
659                                 return;
660                         }
661                 }
662         }
663         ERROR("Bad call specification %s", sreq->callspec);
664         exit(1);
665 }
666
667 static void run_startup_calls()
668 {
669         struct json_object *calls;
670         struct startup_req *sreq;
671         int count;
672
673         if (json_object_object_get_ex(main_config, "call", &calls)
674          && json_object_is_type(calls, json_type_array)
675          && (count = (int)json_object_array_length(calls))) {
676                 sreq = calloc(1, sizeof *sreq);
677                 sreq->session = afb_session_create(3600);
678                 sreq->calls = calls;
679                 sreq->index = 0;
680                 sreq->count = count;
681                 startup_call_current(sreq);
682         }
683 }
684
685 /*---------------------------------------------------------
686  | job for starting the daemon
687  +--------------------------------------------------------- */
688
689 static void start(int signum, void *arg)
690 {
691 #if WITH_AFB_HOOK
692         const char *tracereq = NULL, *traceapi = NULL, *traceevt = NULL,
693 #if !defined(REMOVE_LEGACY_TRACE)
694                 *tracesvc = NULL, *traceditf = NULL,
695 #endif
696                 *traceses = NULL, *traceglob = NULL;
697 #endif
698         const char *workdir, *rootdir, *token, *rootapi;
699         struct json_object *settings;
700         struct afb_hsrv *hsrv;
701         int max_session_count, session_timeout, api_timeout;
702         int no_httpd, http_port;
703         int rc;
704
705
706         afb_debug("start-entry");
707
708         if (signum) {
709                 ERROR("start aborted: received signal %s", strsignal(signum));
710                 exit(1);
711         }
712
713         settings = NULL;
714         no_httpd = 0;
715         http_port = -1;
716         rootapi = token = NULL;
717         rc = wrap_json_unpack(main_config, "{"
718                         "ss ss s?s"
719                         "si si si"
720                         "s?b s?i s?s"
721 #if WITH_AFB_HOOK
722 #if !defined(REMOVE_LEGACY_TRACE)
723                         "s?s s?s"
724 #endif
725                         "s?s s?s s?s s?s s?s"
726 #endif
727                         "s?o"
728                         "}",
729
730                         "rootdir", &rootdir,
731                         "workdir", &workdir,
732                         "token", &token,
733
734                         "apitimeout", &api_timeout,
735                         "cntxtimeout", &session_timeout,
736                         "session-max", &max_session_count,
737
738                         "no-httpd", &no_httpd,
739                         "port", &http_port,
740                         "rootapi", &rootapi,
741
742 #if WITH_AFB_HOOK
743 #if !defined(REMOVE_LEGACY_TRACE)
744                         "tracesvc", &tracesvc,
745                         "traceditf", &traceditf,
746 #endif
747                         "tracereq", &tracereq,
748                         "traceapi", &traceapi,
749                         "traceevt", &traceevt,
750                         "traceses",  &traceses,
751                         "traceglob", &traceglob,
752 #endif
753                         "set", &settings
754                         );
755         if (rc < 0) {
756                 ERROR("Unable to get start config");
757                 exit(1);
758         }
759
760         /* initialize session handling */
761         if (afb_session_init(max_session_count, session_timeout, token)) {
762                 ERROR("initialisation of session manager failed");
763                 goto error;
764         }
765
766         /* set the directories */
767         mkdir(workdir, S_IRWXU | S_IRGRP | S_IXGRP);
768         if (chdir(workdir) < 0) {
769                 ERROR("Can't enter working dir %s", workdir);
770                 goto error;
771         }
772         if (afb_common_rootdir_set(rootdir) < 0) {
773                 ERROR("failed to set common root directory %s", rootdir);
774                 goto error;
775         }
776         if (addenv_realpath("AFB_WORKDIR", "."     /* resolved by realpath */)
777          || addenv_realpath("AFB_ROOTDIR", rootdir /* relative to current directory */)) {
778                 ERROR("can't set DIR environment");
779                 goto error;
780         }
781
782         /* setup HTTP */
783         if (!no_httpd) {
784                 if (http_port < 0) {
785                         ERROR("no port is defined");
786                         goto error;
787                 }
788                 if (http_port == 0) {
789                         ERROR("random port is not implemented");
790                         goto error;
791                 }
792                 if (addenv_int("AFB_PORT", http_port)
793                  || addenv("AFB_TOKEN", afb_session_initial_token())) {
794                         ERROR("can't set HTTP environment");
795                         goto error;
796                 }
797         }
798
799         /* configure the daemon */
800         afb_export_set_config(settings);
801         main_apiset = afb_apiset_create("main", api_timeout);
802         if (!main_apiset) {
803                 ERROR("can't create main api set");
804                 goto error;
805         }
806         if (afb_monitor_init(main_apiset, main_apiset) < 0) {
807                 ERROR("failed to setup monitor");
808                 goto error;
809         }
810 #if WITH_SUPERVISION
811         if (afb_supervision_init(main_apiset, main_config) < 0) {
812                 ERROR("failed to setup supervision");
813                 goto error;
814         }
815 #endif
816
817 #if WITH_AFB_HOOK
818         /* install hooks */
819         if (tracereq)
820                 afb_hook_create_xreq(NULL, NULL, NULL, afb_hook_flags_xreq_from_text(tracereq), NULL, NULL);
821 #if !defined(REMOVE_LEGACY_TRACE)
822         if (traceapi || tracesvc || traceditf)
823                 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi)
824                         | afb_hook_flags_legacy_ditf_from_text(traceditf)
825                         | afb_hook_flags_legacy_svc_from_text(tracesvc), NULL, NULL);
826 #else
827         if (traceapi)
828                 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi), NULL, NULL);
829 #endif
830         if (traceevt)
831                 afb_hook_create_evt(NULL, afb_hook_flags_evt_from_text(traceevt), NULL, NULL);
832         if (traceses)
833                 afb_hook_create_session(NULL, afb_hook_flags_session_from_text(traceses), NULL, NULL);
834         if (traceglob)
835                 afb_hook_create_global(afb_hook_flags_global_from_text(traceglob), NULL, NULL);
836 #endif
837
838         /* load bindings and apis */
839         afb_debug("start-load");
840 #if WITH_DYNAMIC_BINDING
841         apiset_start_list("binding", afb_api_so_add_binding, "the binding");
842         apiset_start_list("ldpaths", afb_api_so_add_pathset_fails, "the binding path set");
843         apiset_start_list("weak-ldpaths", afb_api_so_add_pathset_nofails, "the weak binding path set");
844 #endif
845         apiset_start_list("auto-api", afb_autoset_add_any, "the automatic api path set");
846 #if WITH_DBUS_TRANSPARENCY
847         apiset_start_list("dbus-client", afb_api_dbus_add_client, "the afb-dbus client");
848 #endif
849         apiset_start_list("ws-client", afb_api_ws_add_client_weak, "the afb-websocket client");
850
851         DEBUG("Init config done");
852
853         /* start the services */
854         afb_debug("start-start");
855 #if !defined(NO_CALL_PERSONALITY)
856         personality((unsigned long)-1L);
857 #endif
858         if (afb_apiset_start_all_services(main_apiset) < 0)
859                 goto error;
860
861         /* export started apis */
862         apiset_start_list("ws-server", afb_api_ws_add_server, "the afb-websocket service");
863 #if WITH_DBUS_TRANSPARENCY
864         apiset_start_list("dbus-server", afb_api_dbus_add_server, "the afb-dbus service");
865 #endif
866
867         /* start the HTTP server */
868         afb_debug("start-http");
869         if (!no_httpd) {
870                 if (!afb_hreq_init_cookie(http_port, rootapi, session_timeout)) {
871                         ERROR("initialisation of HTTP cookies failed");
872                         goto error;
873                 }
874
875                 hsrv = start_http_server();
876                 if (hsrv == NULL)
877                         goto error;
878         }
879
880         /* run the startup calls */
881         afb_debug("start-call");
882         run_startup_calls();
883
884         /* run the command */
885         afb_debug("start-exec");
886         if (execute_command() < 0)
887                 goto error;
888
889         /* ready */
890 #if WITH_SYSTEMD
891         sd_notify(1, "READY=1");
892 #endif
893
894         /* activate the watchdog */
895 #if HAS_WATCHDOG
896         if (watchdog_activate() < 0)
897                 ERROR("can't start the watchdog");
898 #endif
899
900         return;
901 error:
902         exit(1);
903 }
904
905 /*---------------------------------------------------------
906  | main
907  |   Parse option and launch action
908  +--------------------------------------------------------- */
909
910 int main(int argc, char *argv[])
911 {
912         struct json_object *obj;
913         afb_debug("main-entry");
914
915         // ------------- Build session handler & init config -------
916         main_config = afb_args_parse(argc, argv);
917         if (sig_monitor_init(
918                 !json_object_object_get_ex(main_config, "trap-faults", &obj)
919                         || json_object_get_boolean(obj)) < 0) {
920                 ERROR("failed to initialise signal handlers");
921                 return 1;
922         }
923
924
925         if (json_object_object_get_ex(main_config, "name", &obj)) {
926                 verbose_set_name(json_object_get_string(obj), 0);
927                 process_name_set_name(json_object_get_string(obj));
928                 process_name_replace_cmdline(argv, json_object_get_string(obj));
929         }
930         afb_debug("main-args");
931
932         // --------- run -----------
933         daemonize();
934         INFO("running with pid %d", getpid());
935
936         /* set the daemon environment */
937         setup_daemon();
938
939         afb_debug("main-start");
940
941         /* enter job processing */
942         jobs_start(3, 0, 50, start, NULL);
943         WARNING("hoops returned from jobs_enter! [report bug]");
944         return 1;
945 }
946