hook: adding of hook feature for requests
[src/app-framework-binder.git] / src / main.c
1 /*
2  * Copyright (C) 2015, 2016 "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 \"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->roothttp == NULL)
230        config->roothttp = ".";
231
232    if  (config->rootbase == NULL)
233        config->rootbase = "/opa";
234
235    if  (config->rootapi == NULL)
236        config->rootapi = "/api";
237
238    if  (config->ldpaths == NULL)
239        config->ldpaths = BINDING_INSTALL_DIR;
240
241    // if no session dir create a default path from rootdir
242    if  (config->sessiondir == NULL) {
243        config->sessiondir = malloc (512);
244        strncpy (config->sessiondir, config->rootdir, 512);
245        strncat (config->sessiondir, "/sessions",512);
246    }
247
248    // if no config dir create a default path from sessiondir
249    if  (config->console == NULL) {
250        config->console = malloc (512);
251        strncpy (config->console, config->sessiondir, 512);
252        strncat (config->console, "/AFB-console.out",512);
253    }
254 }
255
256
257 /*---------------------------------------------------------
258  | main
259  |   Parse option and launch action
260  +--------------------------------------------------------- */
261
262 static void add_item(struct afb_config *config, int kind, char *value)
263 {
264         struct afb_config_item *item = malloc(sizeof *item);
265         if (item == NULL) {
266                 ERROR("out of memory");
267                 exit(1);
268         }
269         item->kind = kind;
270         item->value = value;
271         item->previous = config->items;
272         config->items = item;
273 }
274
275 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
276 {
277   char*          programName = argv [0];
278   int            optionIndex = 0;
279   int            optc, ind;
280   int            nbcmd;
281   struct option *gnuOptions;
282
283   // ------------------ Process Command Line -----------------------
284
285   // if no argument print help and return
286   if (argc < 2) {
287        printHelp(stderr, programName);
288        exit(1);
289   }
290
291   // build GNU getopt info from cliOptions
292   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
293   gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
294   for (ind=0; ind < nbcmd;ind++) {
295     gnuOptions [ind].name    = cliOptions[ind].name;
296     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
297     gnuOptions [ind].flag    = 0;
298     gnuOptions [ind].val     = cliOptions[ind].val;
299   }
300
301   // get all options from command line
302   while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
303         != EOF)
304   {
305     switch (optc)
306     {
307      case SET_VERBOSE:
308        verbosity++;
309        break;
310
311     case SET_TCP_PORT:
312        if (optarg == 0) goto needValueForOption;
313        if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
314        break;
315
316     case SET_APITIMEOUT:
317        if (optarg == 0) goto needValueForOption;
318        if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
319        break;
320
321     case SET_CNTXTIMEOUT:
322        if (optarg == 0) goto needValueForOption;
323        if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
324        break;
325
326     case SET_ROOT_DIR:
327        if (optarg == 0) goto needValueForOption;
328        config->rootdir   = optarg;
329        INFO("Forcing Rootdir=%s",config->rootdir);
330        break;
331
332     case SET_ROOT_HTTP:
333        if (optarg == 0) goto needValueForOption;
334        config->roothttp   = optarg;
335        INFO("Forcing Root HTTP=%s",config->roothttp);
336        break;
337
338     case SET_ROOT_BASE:
339        if (optarg == 0) goto needValueForOption;
340        config->rootbase   = optarg;
341        INFO("Forcing Rootbase=%s",config->rootbase);
342        break;
343
344     case SET_ROOT_API:
345        if (optarg == 0) goto needValueForOption;
346        config->rootapi   = optarg;
347        INFO("Forcing Rootapi=%s",config->rootapi);
348        break;
349
350     case SET_ALIAS:
351        if (optarg == 0) goto needValueForOption;
352        if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
353             config->aliasdir[config->aliascount].url  = strsep(&optarg,":");
354             if (optarg == NULL) {
355               ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
356             } else {
357               config->aliasdir[config->aliascount].path = optarg;
358               INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
359               config->aliascount++;
360             }
361        } else {
362            ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
363        }
364        break;
365
366     case SET_AUTH_TOKEN:
367        if (optarg == 0) goto needValueForOption;
368        config->token   = optarg;
369        break;
370
371     case SET_LDPATH:
372        if (optarg == 0) goto needValueForOption;
373        config->ldpaths = optarg;
374        break;
375
376     case SET_SESSION_DIR:
377        if (optarg == 0) goto needValueForOption;
378        config->sessiondir   = optarg;
379        break;
380
381     case  SET_CACHE_TIMEOUT:
382        if (optarg == 0) goto needValueForOption;
383        if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
384        break;
385
386     case  SET_SESSIONMAX:
387        if (optarg == 0) goto needValueForOption;
388        if (!sscanf (optarg, "%d", &config->nbSessionMax)) goto notAnInteger;
389        break;
390
391     case SET_FORGROUND:
392        if (optarg != 0) goto noValueForOption;
393        config->background  = 0;
394        break;
395
396     case SET_BACKGROUND:
397        if (optarg != 0) goto noValueForOption;
398        config->background  = 1;
399        break;
400
401     case SET_MODE:
402        if (optarg == 0) goto needValueForOption;
403        if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
404        else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
405        else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
406        else goto badMode;
407        break;
408
409     case SET_READYFD:
410        if (optarg == 0) goto needValueForOption;
411        if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
412        break;
413
414     case DBUS_CLIENT:
415     case DBUS_SERVICE:
416     case WS_CLIENT:
417     case WS_SERVICE:
418     case SO_BINDING:
419        if (optarg == 0) goto needValueForOption;
420        add_item(config, optc, optarg);
421        break;
422
423     case SET_TRACEREQ:
424        if (optarg == 0) goto needValueForOption;
425        if (!strcmp(optarg, "no")) config->tracereq = TRACEREQ_NO;
426        else if (!strcmp(optarg, "common")) config->tracereq = TRACEREQ_COMMON;
427        else if (!strcmp(optarg, "extra")) config->tracereq = TRACEREQ_EXTRA;
428        else if (!strcmp(optarg, "all")) config->tracereq = TRACEREQ_ALL;
429        else goto badMode;
430        break;
431
432     case DISPLAY_VERSION:
433        if (optarg != 0) goto noValueForOption;
434        printVersion(stdout);
435        break;
436
437     case DISPLAY_HELP:
438      default:
439        printHelp(stdout, programName);
440        exit(0);
441     }
442   }
443   free(gnuOptions);
444
445   config_set_default  (config);
446   return;
447
448
449 needValueForOption:
450   ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
451           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
452   exit (1);
453
454 notAnInteger:
455   ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
456           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
457   exit (1);
458
459 noValueForOption:
460   ERROR("AFB-daemon option [--%s] don't take value"
461           ,gnuOptions[optionIndex].name);
462   exit (1);
463
464 badMode:
465   ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
466           ,gnuOptions[optionIndex].name);
467   exit (1);
468 }
469
470 /*----------------------------------------------------------
471  | closeSession
472  |   try to close everything before leaving
473  +--------------------------------------------------------- */
474 static void closeSession (int status, void *data) {
475         /* struct afb_config *config = data; */
476 }
477
478 /*----------------------------------------------------------
479  | daemonize
480  |   set the process in background
481  +--------------------------------------------------------- */
482 static void daemonize(struct afb_config *config)
483 {
484   int            consoleFD;
485   int            pid;
486
487       // open /dev/console to redirect output messAFBes
488       consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
489       if (consoleFD < 0) {
490                 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
491                 exit (1);
492       }
493
494       // fork process when running background mode
495       pid = fork ();
496
497       // if fail nothing much to do
498       if (pid == -1) {
499                 ERROR("AFB-daemon Failed to fork son process");
500                 exit (1);
501         }
502
503       // if in father process, just leave
504       if (pid != 0) _exit (0);
505
506       // son process get all data in standalone mode
507      NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
508
509       // redirect default I/O on console
510       close (2); dup(consoleFD);  // redirect stderr
511       close (1); dup(consoleFD);  // redirect stdout
512       close (0);           // no need for stdin
513       close (consoleFD);
514
515 #if 0
516          setsid();   // allow father process to fully exit
517      sleep (2);  // allow main to leave and release port
518 #endif
519 }
520
521 /*---------------------------------------------------------
522  | http server
523  |   Handles the HTTP server
524  +--------------------------------------------------------- */
525 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
526 {
527         int idx, dfd;
528
529         dfd = afb_common_rootdir_get_fd();
530
531         if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
532                 return 0;
533
534         if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
535                 return 0;
536
537         for (idx = 0; idx < config->aliascount; idx++)
538                 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, dfd, config->aliasdir[idx].path, 0, 0))
539                         return 0;
540
541         if (!afb_hsrv_add_alias(hsrv, "", dfd, config->roothttp, -10, 1))
542                 return 0;
543
544         if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
545                 return 0;
546
547         return 1;
548 }
549
550 static struct afb_hsrv *start_http_server(struct afb_config * config)
551 {
552         int rc;
553         struct afb_hsrv *hsrv;
554
555         if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
556                 ERROR("unable to set the tmp directory");
557                 return NULL;
558         }
559
560         hsrv = afb_hsrv_create();
561         if (hsrv == NULL) {
562                 ERROR("memory allocation failure");
563                 return NULL;
564         }
565
566         if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
567         || !init_http_server(hsrv, config)) {
568                 ERROR("initialisation of httpd failed");
569                 afb_hsrv_put(hsrv);
570                 return NULL;
571         }
572
573         NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
574         NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
575
576         rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
577         if (!rc) {
578                 ERROR("starting of httpd failed");
579                 afb_hsrv_put(hsrv);
580                 return NULL;
581         }
582
583         return hsrv;
584 }
585
586 static void start_items(struct afb_config_item *item)
587 {
588   if (item != NULL) {
589     /* keeps the order */
590     start_items(item->previous);
591     switch(item->kind) {
592     case DBUS_CLIENT:
593       if (afb_api_dbus_add_client(item->value) < 0) {
594         ERROR("can't start the afb-dbus client of path %s",item->value);
595         exit(1);
596       }
597       break;
598     case DBUS_SERVICE:
599       if (afb_api_dbus_add_server(item->value) < 0) {
600         ERROR("can't start the afb-dbus service of path %s",item->value);
601         exit(1);
602       }
603       break;
604     case WS_CLIENT:
605       if (afb_api_ws_add_client(item->value) < 0) {
606         ERROR("can't start the afb-websocket client of path %s",item->value);
607         exit(1);
608       }
609       break;
610     case WS_SERVICE:
611       if (afb_api_ws_add_server(item->value) < 0) {
612         ERROR("can't start the afb-websocket service of path %s",item->value);
613         exit(1);
614       }
615       break;
616     case SO_BINDING:
617       if (afb_api_so_add_binding(item->value) < 0) {
618         ERROR("can't start the binding of path %s",item->value);
619         exit(1);
620       }
621       break;
622     default:
623       ERROR("unexpected internal error");
624       exit(1);
625     }
626     /* frre the item */
627     free(item);
628   }
629 }
630
631 /*---------------------------------------------------------
632  | main
633  |   Parse option and launch action
634  +--------------------------------------------------------- */
635
636 int main(int argc, char *argv[])  {
637   struct afb_hsrv *hsrv;
638   struct afb_config *config;
639   struct sd_event *eventloop;
640
641   LOGAUTH("afb-daemon");
642
643   // ------------- Build session handler & init config -------
644   config = calloc (1, sizeof (struct afb_config));
645
646   on_exit(closeSession, config);
647   parse_arguments(argc, argv, config);
648
649   // ------------------ sanity check ----------------------------------------
650   if (config->httpdPort <= 0) {
651      ERROR("no port is defined");
652      exit (1);
653   }
654
655   afb_api_so_set_timeout(config->apiTimeout);
656   if (config->ldpaths) {
657     if (afb_api_so_add_pathset(config->ldpaths) < 0) {
658       ERROR("initialisation of bindings within %s failed", config->ldpaths);
659       exit(1);
660     }
661   }
662
663   start_items(config->items);
664   config->items = NULL;
665
666   ctxStoreInit(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
667   if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
668      ERROR("initialisation of cookies failed");
669      exit (1);
670   }
671
672   if (afb_sig_handler_init() < 0) {
673      ERROR("failed to initialise signal handlers");
674      return 1;
675   }
676
677   if (afb_common_rootdir_set(config->rootdir) < 0) {
678      ERROR("failed to set common root directory");
679      return 1;
680   }
681
682   if (afb_thread_init(3, 1, 20) < 0) {
683      ERROR("failed to initialise threading");
684      return 1;
685   }
686
687   // let's run this program with a low priority
688   nice (20);
689
690   // ------------------ Finaly Process Commands -----------------------------
691   // let's not take the risk to run as ROOT
692   //if (getuid() == 0)  goto errorNoRoot;
693
694   DEBUG("Init config done");
695
696   // --------- run -----------
697   if (config->background) {
698       // --------- in background mode -----------
699       INFO("entering background mode");
700       daemonize(config);
701   } else {
702       // ---- in foreground mode --------------------
703       INFO("entering foreground mode");
704   }
705
706   /* ignore any SIGPIPE */
707   signal(SIGPIPE, SIG_IGN);
708
709   /* install trace of requests */
710   switch(config->tracereq) {
711   default:
712   case TRACEREQ_NO:
713         break;
714   case TRACEREQ_COMMON:
715         afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_common, NULL, NULL);
716         break;
717   case TRACEREQ_EXTRA:
718         afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_extra, NULL, NULL);
719         break;
720   case TRACEREQ_ALL:
721         afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_all, NULL, NULL);
722         break;
723   }
724
725    /* start the HTTP server */
726    hsrv = start_http_server(config);
727    if (hsrv == NULL)
728         exit(1);
729
730    /* start the services */
731    if (afb_apis_start_all_services(1) < 0)
732         exit(1);
733
734    if (config->readyfd != 0) {
735                 static const char readystr[] = "READY=1";
736                 write(config->readyfd, readystr, sizeof(readystr) - 1);
737                 close(config->readyfd);
738   }
739
740    // infinite loop
741   eventloop = afb_common_get_event_loop();
742   for(;;)
743     sd_event_run(eventloop, 30000000);
744
745   WARNING("hoops returned from infinite loop [report bug]");
746
747   return 0;
748 }
749