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