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