local-def: dispatch some definitions
[src/app-framework-binder.git] / src / main.c
1 /* 
2  * Copyright (C) 2015 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 /* 
20  * File:   main.c
21  * Author: "Fulup Ar Foll"
22  *
23  * Created on 05 December 2015, 15:38
24  */
25
26 #include "local-def.h"
27
28 #include <syslog.h>
29 #include <setjmp.h>
30 #include <signal.h>
31 #include <getopt.h>
32 #include <pwd.h>
33
34 #define AFB_VERSION    "0.1"
35
36 static sigjmp_buf exitPoint; // context save for set/longjmp
37
38 /*----------------------------------------------------------
39  | printversion
40  |   print version and copyright
41  +--------------------------------------------------------- */
42  static void printVersion (void) {
43
44    fprintf (stderr,"\n----------------------------------------- \n");
45    fprintf (stderr,"|  AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
46    fprintf (stderr,"----------------------------------------- \n");
47    fprintf (stderr,"|  Copyright(C) 2015 Fulup Ar Foll /IoT.bzh [fulup -at- iot.bzh]\n");
48    fprintf (stderr,"|  AFB comes with ABSOLUTELY NO WARRANTY.\n");
49    fprintf (stderr,"|  Licence [what ever makes you happy] until you fix bugs by yourself :)\n\n");
50    exit (0);
51  } // end printVersion
52
53
54 // Define command line option
55 #define SET_VERBOSE        101
56 #define SET_BACKGROUND     105
57 #define SET_FORGROUND      106
58 #define KILL_PREV_EXIT     107
59 #define KILL_PREV_REST     108
60 #define SET_FAKE_MOD       109
61
62 #define SET_TCP_PORT       120
63 #define SET_ROOT_DIR       121
64 #define SET_ROOT_BASE      122
65 #define SET_ROOT_API       123
66 #define SET_ROOT_ALIAS     124
67
68 #define SET_CACHE_TO       130
69 #define SET_USERID         131
70 #define SET_PID_FILE       132
71 #define SET_SESSION_DIR    133
72 #define SET_CONFIG_FILE    134
73 #define SET_CONFIG_SAVE    135
74 #define SET_CONFIG_EXIT    138
75
76 #define SET_AUTH_TOKEN     141
77 #define SET_LDPATH         142
78 #define SET_APITIMEOUT     143
79 #define SET_CNTXTIMEOUT    144
80
81 #define DISPLAY_VERSION    150
82 #define DISPLAY_HELP       151
83
84 #define SET_MODE           160
85 #define SET_READYFD        161
86
87
88 // Supported option
89 static  AFB_options cliOptions [] = {
90   {SET_VERBOSE      ,0,"verbose"         , "Verbose Mode"},
91
92   {SET_FORGROUND    ,0,"foreground"      , "Get all in foreground mode"},
93   {SET_BACKGROUND   ,0,"daemon"          , "Get all in background mode"},
94   {KILL_PREV_EXIT   ,0,"kill"            , "Kill active process if any and exit"},
95   {KILL_PREV_REST   ,0,"restart"         , "Kill active process if any and restart"},
96
97   {SET_TCP_PORT     ,1,"port"            , "HTTP listening TCP port  [default 1234]"},
98   {SET_ROOT_DIR     ,1,"rootdir"         , "HTTP Root Directory [default $HOME/.AFB]"},
99   {SET_ROOT_BASE    ,1,"rootbase"        , "Angular Base Root URL [default /opa]"},
100   {SET_ROOT_API     ,1,"rootapi"         , "HTML Root API URL [default /api]"},
101   {SET_ROOT_ALIAS   ,1,"alias"           , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
102   
103   {SET_APITIMEOUT   ,1,"apitimeout"      , "Plugin API timeout in seconds [default 10]"},
104   {SET_CNTXTIMEOUT  ,1,"cntxtimeout"     , "Client Session Context Timeout [default 900]"},
105   {SET_CACHE_TO     ,1,"cache-eol"       , "Client cache end of live [default 3600s]"},
106   
107   {SET_USERID       ,1,"setuid"          , "Change user id [default don't change]"},
108   {SET_PID_FILE     ,1,"pidfile"         , "PID file path [default none]"},
109   {SET_SESSION_DIR  ,1,"sessiondir"      , "Sessions file path [default rootdir/sessions]"},
110   {SET_CONFIG_FILE  ,1,"config"          , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
111   {SET_CONFIG_SAVE  ,0,"save"            , "Save config on disk [default no]"},
112   {SET_CONFIG_EXIT  ,0,"saveonly"        , "Save config on disk and then exit"},
113
114   {SET_LDPATH       ,1,"ldpaths"         , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
115   {SET_AUTH_TOKEN   ,1,"token"           , "Initial Secret [default=no-session, --token="" for session without authentication]"},
116   
117   {DISPLAY_VERSION  ,0,"version"         , "Display version and copyright"},
118   {DISPLAY_HELP     ,0,"help"            , "Display this help"},
119
120   {SET_MODE         ,1,"mode"            , "set the mode: either local, remote or global"},
121   {SET_READYFD      ,1,"readyfd"         , "set the #fd to signal when ready"},
122   {0, 0, NULL, NULL}
123  };
124
125 static AFB_aliasdir aliasdir[MAX_ALIAS];
126 static int aliascount=0;
127
128 /*----------------------------------------------------------
129  | timeout signalQuit
130  |
131  +--------------------------------------------------------- */
132 void signalQuit (int signum) {
133
134   sigset_t sigset;
135
136   // unlock timeout signal to allow a new signal to come
137   sigemptyset (&sigset);
138   sigaddset   (&sigset, SIGABRT);
139   sigprocmask (SIG_UNBLOCK, &sigset, 0);
140
141   fprintf (stderr, "%s ERR:Received signal quit\n",configTime());
142   syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
143   longjmp (exitPoint, signum);
144 }
145
146
147 /*----------------------------------------------------------
148  | printHelp
149  |   print information from long option array
150  +--------------------------------------------------------- */
151
152  static void printHelp(char *name) {
153     int ind;
154     char command[20];
155
156     fprintf (stderr,"%s:\nallowed options\n", name);
157     for (ind=0; cliOptions [ind].name != NULL;ind++)
158     {
159       // display options
160       if (cliOptions [ind].has_arg == 0 )
161       {
162              fprintf (stderr,"  --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
163       } else {
164          sprintf(command,"%s=xxxx", cliOptions [ind].name);
165          fprintf (stderr,"  --%-15s %s\n", command, cliOptions[ind].help);
166       }
167     }
168     fprintf (stderr,"Example:\n  %s\\\n  --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
169 } // end printHelp
170
171 /*----------------------------------------------------------
172  | writePidFile
173  |   write a file in /var/run/AFB with pid
174  +--------------------------------------------------------- */
175 static int writePidFile (AFB_config *config, int pid) {
176   FILE *file;
177
178   // if no pid file configure just return
179   if (config->pidfile == NULL) return 0;
180
181   // open pid file in write mode
182   file = fopen(config->pidfile,"w");
183   if (file == NULL) {
184     fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
185     return -1;
186   }
187
188   // write pid in file and close
189   fprintf (file, "%d\n", pid);
190   fclose  (file);
191   return 0;
192 }
193
194 /*----------------------------------------------------------
195  | readPidFile
196  |   read file in /var/run/AFB with pid
197  +--------------------------------------------------------- */
198 static int readPidFile (AFB_config *config) {
199   int  pid;
200   FILE *file;
201   int  status;
202
203   if (config->pidfile == NULL) return -1;
204
205   // open pid file in write mode
206   file = fopen(config->pidfile,"r");
207   if (file == NULL) {
208     fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
209     return -1;
210   }
211
212   // write pid in file and close
213   status = fscanf  (file, "%d\n", &pid);
214   fclose  (file);
215
216   // never kill pid 0
217   if (status != 1) return -1;
218
219   return (pid);
220 }
221
222 /*----------------------------------------------------------
223  | closeSession
224  |   try to close everything before leaving
225  +--------------------------------------------------------- */
226 static void closeSession (AFB_session *session) {
227
228
229 }
230
231 /*----------------------------------------------------------
232  | listenLoop
233  |   Main listening HTTP loop
234  +--------------------------------------------------------- */
235 static void listenLoop (AFB_session *session) {
236   AFB_error  err;
237
238   if (signal (SIGABRT, signalQuit) == SIG_ERR) {
239         fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
240         return;
241   }
242
243   // ------ Start httpd server
244   if (session->config->httpdPort > 0) {
245
246         err = httpdStart (session);
247         if (err != AFB_SUCCESS) return;
248
249         if (session->readyfd != 0) {
250                 static const char readystr[] = "READY=1";
251                 write(session->readyfd, readystr, sizeof(readystr) - 1);
252                 close(session->readyfd);
253         }
254
255         // infinite loop
256         httpdLoop(session);
257
258         fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
259   }
260 }
261   
262 /*---------------------------------------------------------
263  | main
264  |   Parse option and launch action
265  +--------------------------------------------------------- */
266
267 int main(int argc, char *argv[])  {
268   AFB_session    *session;
269   char*          programName = argv [0];
270   int            optionIndex = 0;
271   int            optc, ind, consoleFD;
272   int            pid, nbcmd, status;
273   AFB_config     cliconfig; // temp structure to store CLI option before file config upload
274
275   // ------------- Build session handler & init config -------
276   session = configInit ();
277   memset(&cliconfig,0,sizeof(cliconfig));
278   memset(&aliasdir  ,0,sizeof(aliasdir));
279   cliconfig.aliasdir = aliasdir;
280
281   // GNU CLI getopts nterface.
282   struct option ggcOption;
283   struct option *gnuOptions;
284
285   // ------------------ Process Command Line -----------------------
286
287   // if no argument print help and return
288   if (argc < 2) {
289        printHelp(programName);
290        return (-1);
291   }
292
293   // build GNU getopt info from cliOptions
294   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
295   gnuOptions = malloc (sizeof (ggcOption) * (unsigned)nbcmd);
296   for (ind=0; ind < nbcmd;ind++) {
297     gnuOptions [ind].name    = cliOptions[ind].name;
298     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
299     gnuOptions [ind].flag    = 0;
300     gnuOptions [ind].val     = cliOptions[ind].val;
301   }
302
303   // get all options from command line
304   while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
305         != EOF)
306   {
307     switch (optc)
308     {
309      case SET_VERBOSE:
310        verbose = 1;
311        break;
312
313     case SET_TCP_PORT:
314        if (optarg == 0) goto needValueForOption;
315        if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
316        break;
317        
318     case SET_APITIMEOUT:
319        if (optarg == 0) goto needValueForOption;
320        if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
321        break;
322
323     case SET_CNTXTIMEOUT:
324        if (optarg == 0) goto needValueForOption;
325        if (!sscanf (optarg, "%d", &cliconfig.cntxTimeout)) goto notAnInteger;
326        break;
327
328     case SET_ROOT_DIR:
329        if (optarg == 0) goto needValueForOption;
330        cliconfig.rootdir   = optarg;
331        if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
332        break;       
333        
334     case SET_ROOT_BASE:
335        if (optarg == 0) goto needValueForOption;
336        cliconfig.rootbase   = optarg;
337        if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
338        break;
339
340     case SET_ROOT_API:
341        if (optarg == 0) goto needValueForOption;
342        cliconfig.rootapi   = optarg;
343        if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
344        break;
345        
346     case SET_ROOT_ALIAS:
347        if (optarg == 0) goto needValueForOption;
348        if (aliascount < MAX_ALIAS) {
349             aliasdir[aliascount].url  = strsep(&optarg,":");
350             if (optarg == NULL) {
351               fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
352             } else {
353               aliasdir[aliascount].path = optarg;
354               aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
355               if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
356               aliascount++;
357             }
358        } else {
359            fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
360        }     
361        break;
362        
363     case SET_AUTH_TOKEN:
364        if (optarg == 0) goto needValueForOption;
365        cliconfig.token   = optarg;
366        break;
367
368     case SET_LDPATH:
369        if (optarg == 0) goto needValueForOption;
370        cliconfig.ldpaths = optarg;
371        break;
372
373     case SET_PID_FILE:
374        if (optarg == 0) goto needValueForOption;
375        cliconfig.pidfile   = optarg;
376        break;
377
378     case SET_SESSION_DIR:
379        if (optarg == 0) goto needValueForOption;
380        cliconfig.sessiondir   = optarg;
381        break;
382
383     case  SET_CONFIG_FILE:
384        if (optarg == 0) goto needValueForOption;
385        cliconfig.configfile   = optarg;
386        break;
387
388     case  SET_CACHE_TO:
389        if (optarg == 0) goto needValueForOption;
390        if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
391        break;
392
393     case SET_CONFIG_EXIT:
394        if (optarg != 0) goto noValueForOption;
395        session->configsave  = 1;
396        session->forceexit   = 1;
397        break;
398
399     case SET_CONFIG_SAVE:
400        if (optarg != 0) goto noValueForOption;
401        session->configsave  = 1;
402        break;
403
404     case SET_USERID:
405        if (optarg == 0) goto needValueForOption;
406        cliconfig.setuid = optarg;
407        break;
408
409     case SET_FAKE_MOD:
410        if (optarg != 0) goto noValueForOption;
411        session->fakemod  = 1;
412        break;
413
414     case SET_FORGROUND:
415        if (optarg != 0) goto noValueForOption;
416        session->foreground  = 1;
417        break;
418
419     case SET_BACKGROUND:
420        if (optarg != 0) goto noValueForOption;
421        session->background  = 1;
422        break;
423
424      case KILL_PREV_REST:
425        if (optarg != 0) goto noValueForOption;
426        session->killPrevious  = 1;
427        break;
428
429      case KILL_PREV_EXIT:
430        if (optarg != 0) goto noValueForOption;
431        session->killPrevious  = 2;
432        break;
433
434     case SET_MODE:
435        if (optarg == 0) goto needValueForOption;
436        if (!strcmp(optarg, "local")) cliconfig.mode = AFB_MODE_LOCAL;
437        else if (!strcmp(optarg, "remote")) cliconfig.mode = AFB_MODE_REMOTE;
438        else if (!strcmp(optarg, "global")) cliconfig.mode = AFB_MODE_GLOBAL;
439        else goto badMode;
440        break;
441
442     case SET_READYFD:
443        if (optarg == 0) goto needValueForOption;
444        if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
445        break;
446
447     case DISPLAY_VERSION:
448        if (optarg != 0) goto noValueForOption;
449        printVersion();
450        goto normalExit;
451
452     case DISPLAY_HELP:
453      default:
454        printHelp(programName);
455        goto normalExit;
456
457     }
458   }
459  
460   // if exist merge config file with CLI arguments
461   configLoadFile  (session, &cliconfig);
462   initPlugins(session);
463
464   // ------------------ sanity check ----------------------------------------
465   if  ((session->background) && (session->foreground)) {
466     fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
467      exit (-1);
468   }
469
470   // ------------------ Some useful default values -------------------------
471   if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
472
473   // open syslog if ever needed
474   openlog("AFB-log", 0, LOG_DAEMON);
475
476   // -------------- Try to kill any previous process if asked ---------------------
477   if (session->killPrevious) {
478     pid = readPidFile (session->config);  // enforce commandline option
479     switch (pid) {
480     case -1:
481       fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
482       break;
483     case 0:
484       fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
485       break;
486     default:
487       status = kill (pid,SIGINT );
488       if (status == 0) {
489              if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
490       } else {
491          // try kill -9
492          status = kill (pid,9);
493          if (status != 0)  fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
494       }
495     } // end switch pid
496
497     if (session->killPrevious >= 2) goto normalExit;
498   } // end killPrevious
499
500
501   // ------------------ clean exit on CTR-C signal ------------------------
502   if (signal (SIGINT, signalQuit) == SIG_ERR) {
503     fprintf (stderr, "%s Quit Signal received.",configTime());
504     return (-1);
505   }
506
507   // save exitPoint context when returning from longjmp closeSession and exit
508   status = setjmp (exitPoint); // return !+ when coming from longjmp
509   if (status != 0) {
510     if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
511     closeSession (session);
512     goto exitOnSignal;
513   }
514
515   // let's run this program with a low priority
516   status=nice (20);
517
518   // ------------------ Finaly Process Commands -----------------------------
519    // if --save then store config on disk upfront
520    if (session->configsave) configStoreFile (session);
521    if (session->forceexit)  exit (0);
522
523     if (session->config->setuid) {
524         int err;
525         struct passwd *passwd;
526         passwd=getpwnam(session->config->setuid);
527         
528         if (passwd == NULL) goto errorSetuid;
529         
530         err = setuid(passwd->pw_uid);
531         if (err) goto errorSetuid;
532     }
533
534     // let's not take the risk to run as ROOT
535     //if (getuid() == 0)  goto errorNoRoot;
536
537     // check session dir and create if it does not exist
538     if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
539     if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
540
541
542
543     // ---- run in foreground mode --------------------
544     if (session->foreground) {
545
546         if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
547
548         // write a pid file for --kill-previous and --raise-debug option
549         status = writePidFile (session->config, getpid());
550         if (status == -1) goto errorPidFile;
551
552         // enter listening loop in foreground
553         listenLoop(session);
554         goto exitInitLoop;
555   } // end foreground
556
557
558   // --------- run in background mode -----------
559   if (session->background) {
560
561        // if (status != 0) goto errorCommand;
562       if (verbose) printf ("AFB: Entering background mode\n");
563
564       // open /dev/console to redirect output messAFBes
565       consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
566       if (consoleFD < 0) goto errConsole;
567
568       // fork process when running background mode
569       pid = fork ();
570
571       // son process get all data in standalone mode
572       if (pid == 0) {
573
574              printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
575              if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
576
577          // redirect default I/O on console
578          close (2); status=dup(consoleFD);  // redirect stderr
579          close (1); status=dup(consoleFD);  // redirect stdout
580          close (0);           // no need for stdin
581          close (consoleFD);
582
583          setsid();   // allow father process to fully exit
584              sleep (2);  // allow main to leave and release port
585
586          fprintf (stderr, "----------------------------\n");
587          fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
588          fflush  (stderr);
589
590          // if everything look OK then look forever
591          syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
592
593          // should normally never return from this loop
594          listenLoop(session);
595          syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
596
597          goto exitInitLoop;
598       }
599
600       // if fail nothing much to do
601       if (pid == -1) goto errorFork;
602
603       // fork worked and we are in father process
604       status = writePidFile (session->config, pid);
605       if (status == -1) goto errorPidFile;
606
607       // we are in father process, we don't need this one
608       _exit (0);
609
610   } // end background-foreground
611
612 normalExit:
613   closeSession (session);   // try to close everything before leaving
614   if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
615   exit(0);
616
617 // ------------- Fatal ERROR display error and quit  -------------
618 errorSetuid:
619   fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
620   exit (-1);
621   
622 //errorNoRoot:
623 //  fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
624 //  exit (-1);
625
626 errorPidFile:
627   fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
628   exit (-1);
629
630 errorFork:
631   fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
632   exit (-1);
633
634 needValueForOption:
635   fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
636           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
637   exit (-1);
638
639 noValueForOption:
640   fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
641           ,gnuOptions[optionIndex].name);
642   exit (-1);
643
644 notAnInteger:
645   fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
646           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
647   exit (-1);
648
649 badMode:
650   fprintf (stderr,"\nERR:AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
651           ,gnuOptions[optionIndex].name);
652   exit (-1);
653
654 exitOnSignal:
655   fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
656                  ,configTime(), getpid());
657   exit (-1);
658
659 errConsole:
660   fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
661   exit (-1);
662
663 errSessiondir:
664   fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
665   exit (-1);
666
667 exitInitLoop:
668   // try to unlink pid file if any
669   if (session->background && session->config->pidfile != NULL)  unlink (session->config->pidfile);
670   exit (-1);
671
672 } /* END AFB-daemon() */
673