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