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