4a074eeee87d38ab93aa844c619a1f0aa9204ea6
[src/app-framework-binder.git] / src / main.c
1 /*
2  * Copyright (C) 2015, 2016, 2017 "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 #define NO_BINDING_VERBOSE_MACRO
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <getopt.h>
29
30 #include <systemd/sd-event.h>
31
32 #include "afb-config.h"
33 #include "afb-hswitch.h"
34 #include "afb-apis.h"
35 #include "afb-api-so.h"
36 #include "afb-api-dbus.h"
37 #include "afb-api-ws.h"
38 #include "afb-hsrv.h"
39 #include "afb-context.h"
40 #include "afb-hreq.h"
41 #include "afb-sig-handler.h"
42 #include "afb-thread.h"
43 #include "session.h"
44 #include "verbose.h"
45 #include "afb-common.h"
46 #include "afb-hook.h"
47
48 #include <afb/afb-binding.h>
49
50 #if !defined(BINDING_INSTALL_DIR)
51 #error "you should define BINDING_INSTALL_DIR"
52 #endif
53
54 #define TRACEREQ_NO     0
55 #define TRACEREQ_COMMON 1
56 #define TRACEREQ_EXTRA  2
57 #define TRACEREQ_ALL    3
58
59 #define AFB_VERSION    "0.5"
60
61 // Define command line option
62 #define SET_VERBOSE        1
63 #define SET_BACKGROUND     2
64 #define SET_FORGROUND      3
65
66 #define SET_TCP_PORT       5
67 #define SET_ROOT_DIR       6
68 #define SET_ROOT_BASE      7
69 #define SET_ROOT_API       8
70 #define SET_ALIAS          9
71
72 #define SET_CACHE_TIMEOUT  10
73 #define SET_SESSION_DIR    11
74
75 #define SET_AUTH_TOKEN     12
76 #define SET_LDPATH         13
77 #define SET_APITIMEOUT     14
78 #define SET_CNTXTIMEOUT    15
79
80 #define DISPLAY_VERSION    16
81 #define DISPLAY_HELP       17
82
83 #define SET_MODE           18
84 #define SET_READYFD        19
85
86 #define DBUS_CLIENT        20
87 #define DBUS_SERVICE       21
88 #define SO_BINDING         22
89
90 #define SET_SESSIONMAX     23
91
92 #define WS_CLIENT          24
93 #define WS_SERVICE         25
94
95 #define SET_ROOT_HTTP      26
96
97 #define SET_TRACEREQ       27
98
99 // Command line structure hold cli --command + help text
100 typedef struct {
101   int  val;        // command number within application
102   int  has_arg;    // command number within application
103   char *name;      // command as used in --xxxx cli
104   char *help;      // help text
105 } AFB_options;
106
107
108 // Supported option
109 static  AFB_options cliOptions [] = {
110   {SET_VERBOSE      ,0,"verbose"         , "Verbose Mode, repeat to increase verbosity"},
111
112   {SET_FORGROUND    ,0,"foreground"      , "Get all in foreground mode"},
113   {SET_BACKGROUND   ,0,"daemon"          , "Get all in background mode"},
114
115   {SET_TCP_PORT     ,1,"port"            , "HTTP listening TCP port  [default 1234]"},
116   {SET_ROOT_DIR     ,1,"rootdir"         , "Root Directory [default $HOME/.AFB]"},
117   {SET_ROOT_HTTP    ,1,"roothttp"        , "HTTP Root Directory [default rootdir]"},
118   {SET_ROOT_BASE    ,1,"rootbase"        , "Angular Base Root URL [default /opa]"},
119   {SET_ROOT_API     ,1,"rootapi"         , "HTML Root API URL [default /api]"},
120   {SET_ALIAS        ,1,"alias"           , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
121
122   {SET_APITIMEOUT   ,1,"apitimeout"      , "Binding API timeout in seconds [default 10]"},
123   {SET_CNTXTIMEOUT  ,1,"cntxtimeout"     , "Client Session Context Timeout [default 900]"},
124   {SET_CACHE_TIMEOUT,1,"cache-eol"       , "Client cache end of live [default 3600]"},
125
126   {SET_SESSION_DIR  ,1,"sessiondir"      , "Sessions file path [default rootdir/sessions]"},
127
128   {SET_LDPATH       ,1,"ldpaths"         , "Load bindingss from dir1:dir2:... [default = "BINDING_INSTALL_DIR"]"},
129   {SET_AUTH_TOKEN   ,1,"token"           , "Initial Secret [default=no-session, --token="" for session without authentication]"},
130
131   {DISPLAY_VERSION  ,0,"version"         , "Display version and copyright"},
132   {DISPLAY_HELP     ,0,"help"            , "Display this help"},
133
134   {SET_MODE         ,1,"mode"            , "set the mode: either local, remote or global"},
135   {SET_READYFD      ,1,"readyfd"         , "set the #fd to signal when ready"},
136
137   {DBUS_CLIENT      ,1,"dbus-client"     , "bind to an afb service through dbus"},
138   {DBUS_SERVICE     ,1,"dbus-server"     , "provides an afb service through dbus"},
139   {WS_CLIENT        ,1,"ws-client"       , "bind to an afb service through websocket"},
140   {WS_SERVICE       ,1,"ws-server"       , "provides an afb service through websockets"},
141   {SO_BINDING       ,1,"binding"         , "load the binding of path"},
142
143   {SET_SESSIONMAX   ,1,"session-max"     , "max count of session simultaneously [default 10]"},
144
145   {SET_TRACEREQ     ,1,"tracereq"        , "log the requests: no, common, extra, all"},
146
147   {0, 0, NULL, NULL}
148  };
149
150 /*----------------------------------------------------------
151  | printversion
152  |   print version and copyright
153  +--------------------------------------------------------- */
154 static void printVersion (FILE *file)
155 {
156    fprintf(file, "\n----------------------------------------- \n");
157    fprintf(file, "  AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
158    fprintf(file, " \n");
159    fprintf(file, "  Copyright (C) 2015, 2016, 2017 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
160    fprintf(file, "  AFB comes with ABSOLUTELY NO WARRANTY.\n");
161    fprintf(file, "  Licence Apache 2\n\n");
162    exit (0);
163 }
164
165 /*----------------------------------------------------------
166  | printHelp
167  |   print information from long option array
168  +--------------------------------------------------------- */
169
170 static void printHelp(FILE *file, const char *name)
171 {
172     int ind;
173     char command[50];
174
175     fprintf (file, "%s:\nallowed options\n", name);
176     for (ind=0; cliOptions [ind].name != NULL;ind++)
177     {
178       // display options
179       if (cliOptions [ind].has_arg == 0 )
180       {
181              fprintf (file, "  --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
182       } else {
183          sprintf(command, "%s=xxxx", cliOptions [ind].name);
184          fprintf (file, "  --%-15s %s\n", command, cliOptions[ind].help);
185       }
186     }
187     fprintf (file, "Example:\n  %s\\\n  --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n", name);
188 }
189
190 // load config from disk and merge with CLI option
191 static void config_set_default (struct afb_config * config)
192 {
193    // default HTTP port
194    if (config->httpdPort == 0)
195         config->httpdPort = 1234;
196
197    // default binding API timeout
198    if (config->apiTimeout == 0)
199         config->apiTimeout = DEFLT_API_TIMEOUT;
200
201    // default AUTH_TOKEN
202    if (config->token == NULL)
203                 config->token = DEFLT_AUTH_TOKEN;
204
205    // cache timeout default one hour
206    if (config->cacheTimeout == 0)
207                 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
208
209    // cache timeout default one hour
210    if (config->cntxTimeout == 0)
211                 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
212
213    // max count of sessions
214    if (config->nbSessionMax == 0)
215        config->nbSessionMax = CTX_NBCLIENTS;
216
217    if (config->rootdir == NULL) {
218        config->rootdir = getenv("AFBDIR");
219        if (config->rootdir == NULL) {
220            config->rootdir = malloc (512);
221            strncpy (config->rootdir, getenv("HOME"),512);
222            strncat (config->rootdir, "/.AFB",512);
223        }
224        // if directory does not exist createit
225        mkdir (config->rootdir,  O_RDWR | S_IRWXU | S_IRGRP);
226    }
227
228    // if no Angular/HTML5 rootbase let's try '/' as default
229    if  (config->rootbase == NULL)
230        config->rootbase = "/opa";
231
232    if  (config->rootapi == NULL)
233        config->rootapi = "/api";
234
235    if  (config->ldpaths == NULL)
236        config->ldpaths = BINDING_INSTALL_DIR;
237
238    // if no session dir create a default path from rootdir
239    if  (config->sessiondir == NULL) {
240        config->sessiondir = malloc (512);
241        strncpy (config->sessiondir, config->rootdir, 512);
242        strncat (config->sessiondir, "/sessions",512);
243    }
244
245    // if no config dir create a default path from sessiondir
246    if  (config->console == NULL) {
247        config->console = malloc (512);
248        strncpy (config->console, config->sessiondir, 512);
249        strncat (config->console, "/AFB-console.out",512);
250    }
251 }
252
253
254 /*---------------------------------------------------------
255  | main
256  |   Parse option and launch action
257  +--------------------------------------------------------- */
258
259 static void add_item(struct afb_config *config, int kind, char *value)
260 {
261         struct afb_config_item *item = malloc(sizeof *item);
262         if (item == NULL) {
263                 ERROR("out of memory");
264                 exit(1);
265         }
266         item->kind = kind;
267         item->value = value;
268         item->previous = config->items;
269         config->items = item;
270 }
271
272 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
273 {
274   char*          programName = argv [0];
275   int            optionIndex = 0;
276   int            optc, ind;
277   int            nbcmd;
278   struct option *gnuOptions;
279
280   // ------------------ Process Command Line -----------------------
281
282   // if no argument print help and return
283   if (argc < 2) {
284        printHelp(stderr, programName);
285        exit(1);
286   }
287
288   // build GNU getopt info from cliOptions
289   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
290   gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
291   for (ind=0; ind < nbcmd;ind++) {
292     gnuOptions [ind].name    = cliOptions[ind].name;
293     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
294     gnuOptions [ind].flag    = 0;
295     gnuOptions [ind].val     = cliOptions[ind].val;
296   }
297
298   // get all options from command line
299   while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
300         != EOF)
301   {
302     switch (optc)
303     {
304      case SET_VERBOSE:
305        verbosity++;
306        break;
307
308     case SET_TCP_PORT:
309        if (optarg == 0) goto needValueForOption;
310        if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
311        break;
312
313     case SET_APITIMEOUT:
314        if (optarg == 0) goto needValueForOption;
315        if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
316        break;
317
318     case SET_CNTXTIMEOUT:
319        if (optarg == 0) goto needValueForOption;
320        if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
321        break;
322
323     case SET_ROOT_DIR:
324        if (optarg == 0) goto needValueForOption;
325        config->rootdir   = optarg;
326        INFO("Forcing Rootdir=%s",config->rootdir);
327        break;
328
329     case SET_ROOT_HTTP:
330        if (optarg == 0) goto needValueForOption;
331        config->roothttp   = optarg;
332        INFO("Forcing Root HTTP=%s",config->roothttp);
333        break;
334
335     case SET_ROOT_BASE:
336        if (optarg == 0) goto needValueForOption;
337        config->rootbase   = optarg;
338        INFO("Forcing Rootbase=%s",config->rootbase);
339        break;
340
341     case SET_ROOT_API:
342        if (optarg == 0) goto needValueForOption;
343        config->rootapi   = optarg;
344        INFO("Forcing Rootapi=%s",config->rootapi);
345        break;
346
347     case SET_ALIAS:
348        if (optarg == 0) goto needValueForOption;
349        if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
350             config->aliasdir[config->aliascount].url  = strsep(&optarg,":");
351             if (optarg == NULL) {
352               ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
353             } else {
354               config->aliasdir[config->aliascount].path = optarg;
355               INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
356               config->aliascount++;
357             }
358        } else {
359            ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
360        }
361        break;
362
363     case SET_AUTH_TOKEN:
364        if (optarg == 0) goto needValueForOption;
365        config->token   = optarg;
366        break;
367
368     case SET_LDPATH:
369        if (optarg == 0) goto needValueForOption;
370        config->ldpaths = optarg;
371        break;
372
373     case SET_SESSION_DIR:
374        if (optarg == 0) goto needValueForOption;
375        config->sessiondir   = optarg;
376        break;
377
378     case  SET_CACHE_TIMEOUT:
379        if (optarg == 0) goto needValueForOption;
380        if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
381        break;
382
383     case  SET_SESSIONMAX:
384        if (optarg == 0) goto needValueForOption;
385        if (!sscanf (optarg, "%d", &config->nbSessionMax)) goto notAnInteger;
386        break;
387
388     case SET_FORGROUND:
389        if (optarg != 0) goto noValueForOption;
390        config->background  = 0;
391        break;
392
393     case SET_BACKGROUND:
394        if (optarg != 0) goto noValueForOption;
395        config->background  = 1;
396        break;
397
398     case SET_MODE:
399        if (optarg == 0) goto needValueForOption;
400        if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
401        else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
402        else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
403        else goto badMode;
404        break;
405
406     case SET_READYFD:
407        if (optarg == 0) goto needValueForOption;
408        if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
409        break;
410
411     case DBUS_CLIENT:
412     case DBUS_SERVICE:
413     case WS_CLIENT:
414     case WS_SERVICE:
415     case SO_BINDING:
416        if (optarg == 0) goto needValueForOption;
417        add_item(config, optc, optarg);
418        break;
419
420     case SET_TRACEREQ:
421        if (optarg == 0) goto needValueForOption;
422        if (!strcmp(optarg, "no")) config->tracereq = TRACEREQ_NO;
423        else if (!strcmp(optarg, "common")) config->tracereq = TRACEREQ_COMMON;
424        else if (!strcmp(optarg, "extra")) config->tracereq = TRACEREQ_EXTRA;
425        else if (!strcmp(optarg, "all")) config->tracereq = TRACEREQ_ALL;
426        else goto badMode;
427        break;
428
429     case DISPLAY_VERSION:
430        if (optarg != 0) goto noValueForOption;
431        printVersion(stdout);
432        break;
433
434     case DISPLAY_HELP:
435      default:
436        printHelp(stdout, programName);
437        exit(0);
438     }
439   }
440   free(gnuOptions);
441
442   config_set_default  (config);
443   return;
444
445
446 needValueForOption:
447   ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
448           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
449   exit (1);
450
451 notAnInteger:
452   ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
453           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
454   exit (1);
455
456 noValueForOption:
457   ERROR("AFB-daemon option [--%s] don't take value"
458           ,gnuOptions[optionIndex].name);
459   exit (1);
460
461 badMode:
462   ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
463           ,gnuOptions[optionIndex].name);
464   exit (1);
465 }
466
467 /*----------------------------------------------------------
468  | closeSession
469  |   try to close everything before leaving
470  +--------------------------------------------------------- */
471 static void closeSession (int status, void *data) {
472         /* struct afb_config *config = data; */
473 }
474
475 /*----------------------------------------------------------
476  | daemonize
477  |   set the process in background
478  +--------------------------------------------------------- */
479 static void daemonize(struct afb_config *config)
480 {
481   int            consoleFD;
482   int            pid;
483
484       // open /dev/console to redirect output messAFBes
485       consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
486       if (consoleFD < 0) {
487                 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
488                 exit (1);
489       }
490
491       // fork process when running background mode
492       pid = fork ();
493
494       // if fail nothing much to do
495       if (pid == -1) {
496                 ERROR("AFB-daemon Failed to fork son process");
497                 exit (1);
498         }
499
500       // if in father process, just leave
501       if (pid != 0) _exit (0);
502
503       // son process get all data in standalone mode
504      NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
505
506       // redirect default I/O on console
507       close (2); dup(consoleFD);  // redirect stderr
508       close (1); dup(consoleFD);  // redirect stdout
509       close (0);           // no need for stdin
510       close (consoleFD);
511
512 #if 0
513          setsid();   // allow father process to fully exit
514      sleep (2);  // allow main to leave and release port
515 #endif
516 }
517
518 /*---------------------------------------------------------
519  | http server
520  |   Handles the HTTP server
521  +--------------------------------------------------------- */
522 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
523 {
524         int idx, dfd;
525
526         dfd = afb_common_rootdir_get_fd();
527
528         if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
529                 return 0;
530
531         if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
532                 return 0;
533
534         for (idx = 0; idx < config->aliascount; idx++)
535                 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, dfd, config->aliasdir[idx].path, 0, 0))
536                         return 0;
537
538         if (config->roothttp != NULL) {
539                 if (!afb_hsrv_add_alias(hsrv, "", dfd, config->roothttp, -10, 1))
540                         return 0;
541         }
542
543         if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
544                 return 0;
545
546         return 1;
547 }
548
549 static struct afb_hsrv *start_http_server(struct afb_config * config)
550 {
551         int rc;
552         struct afb_hsrv *hsrv;
553
554         if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
555                 ERROR("unable to set the tmp directory");
556                 return NULL;
557         }
558
559         hsrv = afb_hsrv_create();
560         if (hsrv == NULL) {
561                 ERROR("memory allocation failure");
562                 return NULL;
563         }
564
565         if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
566         || !init_http_server(hsrv, config)) {
567                 ERROR("initialisation of httpd failed");
568                 afb_hsrv_put(hsrv);
569                 return NULL;
570         }
571
572         NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
573         NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
574
575         rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
576         if (!rc) {
577                 ERROR("starting of httpd failed");
578                 afb_hsrv_put(hsrv);
579                 return NULL;
580         }
581
582         return hsrv;
583 }
584
585 static void start_items(struct afb_config_item *item)
586 {
587   if (item != NULL) {
588     /* keeps the order */
589     start_items(item->previous);
590     switch(item->kind) {
591     case DBUS_CLIENT:
592       if (afb_api_dbus_add_client(item->value) < 0) {
593         ERROR("can't start the afb-dbus client of path %s",item->value);
594         exit(1);
595       }
596       break;
597     case DBUS_SERVICE:
598       if (afb_api_dbus_add_server(item->value) < 0) {
599         ERROR("can't start the afb-dbus service of path %s",item->value);
600         exit(1);
601       }
602       break;
603     case WS_CLIENT:
604       if (afb_api_ws_add_client(item->value) < 0) {
605         ERROR("can't start the afb-websocket client of path %s",item->value);
606         exit(1);
607       }
608       break;
609     case WS_SERVICE:
610       if (afb_api_ws_add_server(item->value) < 0) {
611         ERROR("can't start the afb-websocket service of path %s",item->value);
612         exit(1);
613       }
614       break;
615     case SO_BINDING:
616       if (afb_api_so_add_binding(item->value) < 0) {
617         ERROR("can't start the binding of path %s",item->value);
618         exit(1);
619       }
620       break;
621     default:
622       ERROR("unexpected internal error");
623       exit(1);
624     }
625     /* frre the item */
626     free(item);
627   }
628 }
629
630 /*---------------------------------------------------------
631  | main
632  |   Parse option and launch action
633  +--------------------------------------------------------- */
634
635 int main(int argc, char *argv[])  {
636   struct afb_hsrv *hsrv;
637   struct afb_config *config;
638   struct sd_event *eventloop;
639
640   LOGAUTH("afb-daemon");
641
642   // ------------- Build session handler & init config -------
643   config = calloc (1, sizeof (struct afb_config));
644
645   on_exit(closeSession, config);
646   parse_arguments(argc, argv, config);
647
648   // ------------------ sanity check ----------------------------------------
649   if (config->httpdPort <= 0) {
650      ERROR("no port is defined");
651      exit (1);
652   }
653
654   afb_api_so_set_timeout(config->apiTimeout);
655   if (config->ldpaths) {
656     if (afb_api_so_add_pathset(config->ldpaths) < 0) {
657       ERROR("initialisation of bindings within %s failed", config->ldpaths);
658       exit(1);
659     }
660   }
661
662   start_items(config->items);
663   config->items = NULL;
664
665   ctxStoreInit(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
666   if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
667      ERROR("initialisation of cookies failed");
668      exit (1);
669   }
670
671   if (afb_sig_handler_init() < 0) {
672      ERROR("failed to initialise signal handlers");
673      return 1;
674   }
675
676   if (afb_common_rootdir_set(config->rootdir) < 0) {
677      ERROR("failed to set common root directory");
678      return 1;
679   }
680
681   if (afb_thread_init(3, 1, 20) < 0) {
682      ERROR("failed to initialise threading");
683      return 1;
684   }
685
686   // let's run this program with a low priority
687   nice (20);
688
689   // ------------------ Finaly Process Commands -----------------------------
690   // let's not take the risk to run as ROOT
691   //if (getuid() == 0)  goto errorNoRoot;
692
693   DEBUG("Init config done");
694
695   // --------- run -----------
696   if (config->background) {
697       // --------- in background mode -----------
698       INFO("entering background mode");
699       daemonize(config);
700   } else {
701       // ---- in foreground mode --------------------
702       INFO("entering foreground mode");
703   }
704
705   /* ignore any SIGPIPE */
706   signal(SIGPIPE, SIG_IGN);
707
708   /* install trace of requests */
709   switch(config->tracereq) {
710   default:
711   case TRACEREQ_NO:
712         break;
713   case TRACEREQ_COMMON:
714         afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_common, NULL, NULL);
715         break;
716   case TRACEREQ_EXTRA:
717         afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_extra, NULL, NULL);
718         break;
719   case TRACEREQ_ALL:
720         afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_all, NULL, NULL);
721         break;
722   }
723
724    /* start the HTTP server */
725    hsrv = start_http_server(config);
726    if (hsrv == NULL)
727         exit(1);
728
729    /* start the services */
730    if (afb_apis_start_all_services(1) < 0)
731         exit(1);
732
733    if (config->readyfd != 0) {
734                 static const char readystr[] = "READY=1";
735                 write(config->readyfd, readystr, sizeof(readystr) - 1);
736                 close(config->readyfd);
737   }
738
739    // infinite loop
740   eventloop = afb_common_get_event_loop();
741   for(;;)
742     sd_event_run(eventloop, 30000000);
743
744   WARNING("hoops returned from infinite loop [report bug]");
745
746   return 0;
747 }
748