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