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