1e8b3544a494683c87e99d5a89e8c2e67bd80252
[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, 1);
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 int add_interface(void *closure, const char *value)
344 {
345         struct afb_hsrv *hsrv = closure;
346         int rc;
347
348         rc = afb_hsrv_add_interface(hsrv, value);
349         return rc > 0;
350 }
351
352 static struct afb_hsrv *start_http_server()
353 {
354         int rc;
355         const char *uploaddir, *rootdir, *errs;
356         struct afb_hsrv *hsrv;
357         int cache_timeout, http_port;
358         struct json_object *junk;
359
360         http_port = -1;
361         rc = wrap_json_unpack(main_config, "{ss ss si s?i}",
362                                 "uploaddir", &uploaddir,
363                                 "rootdir", &rootdir,
364                                 "cache-eol", &cache_timeout,
365                                 "port", &http_port);
366         if (rc < 0) {
367                 ERROR("Can't get HTTP server start config");
368                 exit(1);
369         }
370
371         if (afb_hreq_init_download_path(uploaddir)) {
372                 static const char fallback_uploaddir[] = "/tmp";
373                 WARNING("unable to set the upload directory %s", uploaddir);
374                 if (afb_hreq_init_download_path(fallback_uploaddir)) {
375                         ERROR("unable to fallback to upload directory %s", fallback_uploaddir);
376                         return NULL;
377                 }
378                 uploaddir = fallback_uploaddir;
379         }
380
381         hsrv = afb_hsrv_create();
382         if (hsrv == NULL) {
383                 ERROR("memory allocation failure");
384                 return NULL;
385         }
386
387         if (!afb_hsrv_set_cache_timeout(hsrv, cache_timeout)
388             || !init_http_server(hsrv)) {
389                 ERROR("initialisation of httpd failed");
390                 afb_hsrv_put(hsrv);
391                 return NULL;
392         }
393
394         rc = afb_hsrv_start(hsrv, 15);
395         if (!rc) {
396                 ERROR("starting of httpd failed");
397                 afb_hsrv_put(hsrv);
398                 return NULL;
399         }
400
401         NOTICE("Serving rootdir=%s uploaddir=%s", rootdir, uploaddir);
402
403         /* check if port is set */
404         if (http_port < 0) {
405                 /* not set, check existing interfaces */
406                 if (!json_object_object_get_ex(main_config, "interface", &junk)) {
407                         ERROR("No port and no interface ");
408                 }
409         } else {
410                 rc = afb_hsrv_add_interface_tcp(hsrv, DEFAULT_BINDER_INTERFACE, (uint16_t) http_port);
411                 if (!rc) {
412                         ERROR("setting interface failed");
413                         afb_hsrv_put(hsrv);
414                         return NULL;
415                 }
416                 NOTICE("Browser URL= http://localhost:%d", http_port);
417         }
418
419         errs = run_for_config_array_opt("interface", add_interface, hsrv);
420         if (errs) {
421                 ERROR("setting interface %s failed", errs);
422                 afb_hsrv_put(hsrv);
423                 return NULL;
424         }
425
426         return hsrv;
427 }
428
429 /*---------------------------------------------------------
430  | execute_command
431  +--------------------------------------------------------- */
432
433 static void exit_at_end()
434 {
435         exit(0);
436 }
437
438 static void wait_child(int signum, void* arg)
439 {
440         pid_t pid = (pid_t)(intptr_t)arg;
441         pid_t pidchld = childpid;
442
443         if (pidchld == pid) {
444                 childpid = 0;
445                 if (!SELF_PGROUP)
446                         killpg(pidchld, SIGKILL);
447                 waitpid(pidchld, NULL, 0);
448                 jobs_exit(exit_at_end);
449         } else {
450                 waitpid(pid, NULL, 0);
451         }
452 }
453
454 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
455 {
456         if (info->si_pid == childpid) {
457                 switch (info->si_code) {
458                 case CLD_EXITED:
459                 case CLD_KILLED:
460                 case CLD_DUMPED:
461                         jobs_queue_lazy(0, 0, wait_child, (void*)(intptr_t)info->si_pid);
462                 default:
463                         break;
464                 }
465         }
466 }
467
468 /*
469 # @@ @
470 # @p port
471 # @t token
472 */
473
474 #define SUBST_CHAR  '@'
475 #define SUBST_STR   "@"
476
477 static char *instanciate_string(char *arg, const char *port, const char *token)
478 {
479         char *resu, *it, *wr, c;
480         int chg, dif;
481
482         /* get the changes */
483         chg = 0;
484         dif = 0;
485         it = strchrnul(arg, SUBST_CHAR);
486         while (*it) {
487                 c = *++it;
488                 if (c == 'p' && port) {
489                         chg++;
490                         dif += (int)strlen(port) - 2;
491                 } else if (c == 't' && token) {
492                         chg++;
493                         dif += (int)strlen(token) - 2;
494                 } else if (c == SUBST_CHAR) {
495                         it++;
496                         chg++;
497                         dif--;
498                 }
499                 it = strchrnul(it, SUBST_CHAR);
500         }
501
502         /* return arg when no change */
503         if (!chg)
504                 return arg;
505
506         /* allocates the result */
507         resu = malloc((it - arg) + dif + 1);
508         if (!resu) {
509                 ERROR("out of memory");
510                 return NULL;
511         }
512
513         /* instanciate the arguments */
514         wr = resu;
515         for (;;) {
516                 it = strchrnul(arg, SUBST_CHAR);
517                 wr = mempcpy(wr, arg, it - arg);
518                 if (!*it)
519                         break;
520                 c = *++it;
521                 if (c == 'p' && port)
522                         wr = stpcpy(wr, port);
523                 else if (c == 't' && token)
524                         wr = stpcpy(wr, token);
525                 else {
526                         if (c != SUBST_CHAR)
527                                 *wr++ = SUBST_CHAR;
528                         *wr++ = *it;
529                 }
530                 arg = ++it;
531         }
532
533         *wr = 0;
534         return resu;
535 }
536
537 static int instanciate_environ(const char *port, const char *token)
538 {
539         extern char **environ;
540         char *repl;
541         int i;
542
543         /* instantiate the environment */
544         for (i = 0 ; environ[i] ; i++) {
545                 repl = instanciate_string(environ[i], port, token);
546                 if (!repl)
547                         return -1;
548                 environ[i] = repl;
549         }
550         return 0;
551 }
552
553 static char **instanciate_command_args(struct json_object *exec, const char *port, const char *token)
554 {
555         char **result;
556         char *repl, *item;
557         int i, n;
558
559         /* allocates the result */
560         n = (int)json_object_array_length(exec);
561         result = malloc((n + 1) * sizeof * result);
562         if (!result) {
563                 ERROR("out of memory");
564                 return NULL;
565         }
566
567         /* instanciate the arguments */
568         for (i = 0 ; i < n ; i++) {
569                 item = (char*)json_object_get_string(json_object_array_get_idx(exec, i));
570                 repl = instanciate_string(item, port, token);
571                 if (!repl) {
572                         free(result);
573                         return NULL;
574                 }
575                 result[i] = repl;
576         }
577         result[i] = NULL;
578         return result;
579 }
580
581 static int execute_command()
582 {
583         struct json_object *exec, *oport, *otok;
584         struct sigaction siga;
585         const char *token, *port;
586         char **args;
587
588         /* check whether a command is to execute or not */
589         if (!json_object_object_get_ex(main_config, "exec", &exec))
590                 return 0;
591
592         if (SELF_PGROUP)
593                 setpgid(0, 0);
594
595         /* install signal handler */
596         memset(&siga, 0, sizeof siga);
597         siga.sa_sigaction = on_sigchld;
598         siga.sa_flags = SA_SIGINFO;
599         sigaction(SIGCHLD, &siga, NULL);
600
601         /* fork now */
602         childpid = fork();
603         if (childpid)
604                 return 0;
605
606         /* compute the string for port */
607         if (json_object_object_get_ex(main_config, "port", &oport))
608                 port = json_object_get_string(oport);
609         else
610                 port = 0;
611         /* instantiate arguments and environment */
612         if (json_object_object_get_ex(main_config, "token", &otok))
613                 token = json_object_get_string(otok);
614         else
615                 token = 0;
616         args = instanciate_command_args(exec, port, token);
617         if (args && instanciate_environ(port, token) >= 0) {
618                 /* run */
619                 if (!SELF_PGROUP)
620                         setpgid(0, 0);
621                 execv(args[0], args);
622                 ERROR("can't launch %s: %m", args[0]);
623         }
624         exit(1);
625         return -1;
626 }
627
628 /*---------------------------------------------------------
629  | startup calls
630  +--------------------------------------------------------- */
631
632 struct startup_req
633 {
634         struct afb_xreq xreq;
635         char *api;
636         char *verb;
637         struct json_object *calls;
638         int index;
639         int count;
640         const char *callspec;
641         struct afb_session *session;
642 };
643
644 static void startup_call_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
645 {
646         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
647
648         info = info ?: "";
649         if (!error) {
650                 NOTICE("startup call %s returned %s (%s)", sreq->callspec, json_object_get_string(object), info);
651                 json_object_put(object);
652         } else {
653                 ERROR("startup call %s ERROR! %s (%s)", sreq->callspec, error, info);
654                 exit(1);
655         }
656 }
657
658 static void startup_call_current(struct startup_req *sreq);
659
660 static void startup_call_unref(struct afb_xreq *xreq)
661 {
662         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
663
664         free(sreq->api);
665         free(sreq->verb);
666         json_object_put(sreq->xreq.json);
667         if (++sreq->index < sreq->count)
668                 startup_call_current(sreq);
669         else {
670                 afb_session_close(sreq->session);
671                 afb_session_unref(sreq->session);
672                 free(sreq);
673         }
674 }
675
676 static struct afb_xreq_query_itf startup_xreq_itf =
677 {
678         .reply = startup_call_reply,
679         .unref = startup_call_unref
680 };
681
682 static void startup_call_current(struct startup_req *sreq)
683 {
684         const char *api, *verb, *json;
685         enum json_tokener_error jerr;
686
687         sreq->callspec = json_object_get_string(json_object_array_get_idx(sreq->calls, sreq->index)),
688         api = sreq->callspec;
689         verb = strchr(api, '/');
690         if (verb) {
691                 json = strchr(verb, ':');
692                 if (json) {
693                         afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
694                         afb_context_init_validated(&sreq->xreq.context, sreq->session, NULL, NULL);
695                         sreq->api = strndup(api, verb - api);
696                         sreq->verb = strndup(verb + 1, json - verb - 1);
697                         sreq->xreq.request.called_api = sreq->api;
698                         sreq->xreq.request.called_verb = sreq->verb;
699                         sreq->xreq.json = json_tokener_parse_verbose(json + 1, &jerr);
700                         if (sreq->api && sreq->verb && jerr == json_tokener_success) {
701                                 afb_xreq_process(&sreq->xreq, main_apiset);
702                                 return;
703                         }
704                 }
705         }
706         ERROR("Bad call specification %s", sreq->callspec);
707         exit(1);
708 }
709
710 static void run_startup_calls()
711 {
712         struct json_object *calls;
713         struct startup_req *sreq;
714         int count;
715
716         if (json_object_object_get_ex(main_config, "call", &calls)
717          && json_object_is_type(calls, json_type_array)
718          && (count = (int)json_object_array_length(calls))) {
719                 sreq = calloc(1, sizeof *sreq);
720                 sreq->session = afb_session_create(3600);
721                 sreq->calls = calls;
722                 sreq->index = 0;
723                 sreq->count = count;
724                 startup_call_current(sreq);
725         }
726 }
727
728 /*---------------------------------------------------------
729  | job for starting the daemon
730  +--------------------------------------------------------- */
731
732 static void start(int signum, void *arg)
733 {
734 #if WITH_AFB_HOOK
735         const char *tracereq = NULL, *traceapi = NULL, *traceevt = NULL,
736 #if !defined(REMOVE_LEGACY_TRACE)
737                 *tracesvc = NULL, *traceditf = NULL,
738 #endif
739                 *traceses = NULL, *traceglob = NULL;
740 #endif
741         const char *workdir, *rootdir, *token, *rootapi;
742         struct json_object *settings;
743         struct afb_hsrv *hsrv;
744         int max_session_count, session_timeout, api_timeout;
745         int no_httpd, http_port;
746         int rc;
747
748
749         afb_debug("start-entry");
750
751         if (signum) {
752                 ERROR("start aborted: received signal %s", strsignal(signum));
753                 exit(1);
754         }
755
756         settings = NULL;
757         no_httpd = 0;
758         http_port = -1;
759         rootapi = token = NULL;
760         rc = wrap_json_unpack(main_config, "{"
761                         "ss ss s?s"
762                         "si si si"
763                         "s?b s?i s?s"
764                         "s?o"
765                         "}",
766
767                         "rootdir", &rootdir,
768                         "workdir", &workdir,
769                         "token", &token,
770
771                         "apitimeout", &api_timeout,
772                         "cntxtimeout", &session_timeout,
773                         "session-max", &max_session_count,
774
775                         "no-httpd", &no_httpd,
776                         "port", &http_port,
777                         "rootapi", &rootapi,
778
779                         "set", &settings
780                         );
781         if (rc < 0) {
782                 ERROR("Unable to get start config");
783                 exit(1);
784         }
785
786 #if WITH_AFB_HOOK
787         rc = wrap_json_unpack(main_config, "{"
788 #if !defined(REMOVE_LEGACY_TRACE)
789                         "s?s s?s"
790 #endif
791                         "s?s s?s s?s s?s s?s"
792                         "}",
793
794 #if !defined(REMOVE_LEGACY_TRACE)
795                         "tracesvc", &tracesvc,
796                         "traceditf", &traceditf,
797 #endif
798                         "tracereq", &tracereq,
799                         "traceapi", &traceapi,
800                         "traceevt", &traceevt,
801                         "traceses",  &traceses,
802                         "traceglob", &traceglob
803                         );
804         if (rc < 0) {
805                 ERROR("Unable to get hook config");
806                 exit(1);
807         }
808 #endif
809
810         /* initialize session handling */
811         if (afb_session_init(max_session_count, session_timeout)) {
812                 ERROR("initialisation of session manager failed");
813                 goto error;
814         }
815
816         /* set the directories */
817         mkdir(workdir, S_IRWXU | S_IRGRP | S_IXGRP);
818         if (chdir(workdir) < 0) {
819                 ERROR("Can't enter working dir %s", workdir);
820                 goto error;
821         }
822         if (afb_common_rootdir_set(rootdir) < 0) {
823                 ERROR("failed to set common root directory %s", rootdir);
824                 goto error;
825         }
826         if (addenv_realpath("AFB_WORKDIR", "."     /* resolved by realpath */)
827          || addenv_realpath("AFB_ROOTDIR", rootdir /* relative to current directory */)) {
828                 ERROR("can't set DIR environment");
829                 goto error;
830         }
831
832         /* setup HTTP */
833         if (!no_httpd) {
834                 if (http_port == 0) {
835                         ERROR("random port is not implemented");
836                         goto error;
837                 }
838                 if ((http_port > 0 && addenv_int("AFB_PORT", http_port))
839                  || (token && addenv("AFB_TOKEN", token))) {
840                         ERROR("can't set HTTP environment");
841                         goto error;
842                 }
843         }
844
845         /* configure the daemon */
846         afb_export_set_config(settings);
847         main_apiset = afb_apiset_create("main", api_timeout);
848         if (!main_apiset) {
849                 ERROR("can't create main api set");
850                 goto error;
851         }
852         if (afb_monitor_init(main_apiset, main_apiset) < 0) {
853                 ERROR("failed to setup monitor");
854                 goto error;
855         }
856 #if WITH_SUPERVISION
857         if (afb_supervision_init(main_apiset, main_config) < 0) {
858                 ERROR("failed to setup supervision");
859                 goto error;
860         }
861 #endif
862
863 #if WITH_AFB_HOOK
864         /* install hooks */
865         if (tracereq)
866                 afb_hook_create_xreq(NULL, NULL, NULL, afb_hook_flags_xreq_from_text(tracereq), NULL, NULL);
867 #if !defined(REMOVE_LEGACY_TRACE)
868         if (traceapi || tracesvc || traceditf)
869                 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi)
870                         | afb_hook_flags_legacy_ditf_from_text(traceditf)
871                         | afb_hook_flags_legacy_svc_from_text(tracesvc), NULL, NULL);
872 #else
873         if (traceapi)
874                 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi), NULL, NULL);
875 #endif
876         if (traceevt)
877                 afb_hook_create_evt(NULL, afb_hook_flags_evt_from_text(traceevt), NULL, NULL);
878         if (traceses)
879                 afb_hook_create_session(NULL, afb_hook_flags_session_from_text(traceses), NULL, NULL);
880         if (traceglob)
881                 afb_hook_create_global(afb_hook_flags_global_from_text(traceglob), NULL, NULL);
882 #endif
883
884         /* load bindings and apis */
885         afb_debug("start-load");
886 #if WITH_DYNAMIC_BINDING
887         apiset_start_list("binding", afb_api_so_add_binding, "the binding");
888         apiset_start_list("ldpaths", afb_api_so_add_pathset_fails, "the binding path set");
889         apiset_start_list("weak-ldpaths", afb_api_so_add_pathset_nofails, "the weak binding path set");
890 #endif
891         apiset_start_list("auto-api", afb_autoset_add_any, "the automatic api path set");
892 #if WITH_DBUS_TRANSPARENCY
893         apiset_start_list("dbus-client", afb_api_dbus_add_client, "the afb-dbus client");
894 #endif
895         apiset_start_list("ws-client", afb_api_ws_add_client_weak, "the afb-websocket client");
896
897         DEBUG("Init config done");
898
899         /* start the services */
900         afb_debug("start-start");
901 #if !defined(NO_CALL_PERSONALITY)
902         personality((unsigned long)-1L);
903 #endif
904         if (afb_apiset_start_all_services(main_apiset) < 0)
905                 goto error;
906
907         /* export started apis */
908         apiset_start_list("ws-server", afb_api_ws_add_server, "the afb-websocket service");
909 #if WITH_DBUS_TRANSPARENCY
910         apiset_start_list("dbus-server", afb_api_dbus_add_server, "the afb-dbus service");
911 #endif
912
913         /* start the HTTP server */
914         afb_debug("start-http");
915         if (!no_httpd) {
916                 if (!afb_hreq_init_cookie(http_port, rootapi, session_timeout)) {
917                         ERROR("initialisation of HTTP cookies failed");
918                         goto error;
919                 }
920
921                 hsrv = start_http_server();
922                 if (hsrv == NULL)
923                         goto error;
924         }
925
926         /* run the startup calls */
927         afb_debug("start-call");
928         run_startup_calls();
929
930         /* run the command */
931         afb_debug("start-exec");
932         if (execute_command(http_port, token) < 0)
933                 goto error;
934
935         /* ready */
936         sd_notify(1, "READY=1");
937
938         /* activate the watchdog */
939 #if HAS_WATCHDOG
940         if (watchdog_activate() < 0)
941                 ERROR("can't start the watchdog");
942 #endif
943
944         return;
945 error:
946         exit(1);
947 }
948
949 /*---------------------------------------------------------
950  | main
951  |   Parse option and launch action
952  +--------------------------------------------------------- */
953
954 int main(int argc, char *argv[])
955 {
956         struct json_object *obj;
957         afb_debug("main-entry");
958
959         // ------------- Build session handler & init config -------
960         main_config = afb_args_parse(argc, argv);
961         if (sig_monitor_init(
962                 !json_object_object_get_ex(main_config, "trap-faults", &obj)
963                         || json_object_get_boolean(obj)) < 0) {
964                 ERROR("failed to initialise signal handlers");
965                 return 1;
966         }
967
968
969         if (json_object_object_get_ex(main_config, "name", &obj)) {
970                 verbose_set_name(json_object_get_string(obj), 0);
971                 process_name_set_name(json_object_get_string(obj));
972                 process_name_replace_cmdline(argv, json_object_get_string(obj));
973         }
974         afb_debug("main-args");
975
976         // --------- run -----------
977         daemonize();
978         INFO("running with pid %d", getpid());
979
980         /* set the daemon environment */
981         setup_daemon();
982
983         afb_debug("main-start");
984
985         /* enter job processing */
986         jobs_start(3, 0, 100, start, NULL);
987         WARNING("hoops returned from jobs_enter! [report bug]");
988         return 1;
989 }
990