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