b681bd09689880573451a234c8adf098af3e0478
[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
33 static sigjmp_buf exitpoint; // context save for set/longjmp
34 static sigjmp_buf restartpoint; // 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_cardid         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_SMACK          140
75  #define SET_PLUGINS        141
76  #define SET_APITIMEOUT     142
77
78  #define DISPLAY_VERSION    150
79  #define DISPLAY_HELP       151
80
81
82 // Supported option
83 static  AFB_options cliOptions [] = {
84   {SET_VERBOSE      ,0,"verbose"         , "Verbose Mode"},
85
86   {SET_FORGROUND    ,0,"foreground"      , "Get all in foreground mode"},
87   {SET_BACKGROUND   ,0,"daemon"          , "Get all in background mode"},
88   {KILL_PREV_EXIT   ,0,"kill"            , "Kill active process if any and exit"},
89   {KILL_PREV_REST   ,0,"restart"         , "Kill active process if any and restart"},
90
91   {SET_TCP_PORT     ,1,"port"            , "HTTP listening TCP port  [default 1234]"},
92   {SET_ROOT_DIR     ,1,"rootdir"         , "HTTP Root Directory [default $HOME/.AFB"},
93   {SET_ROOT_BASE    ,1,"rootbase"        , "Angular Base Root URL [default /opa"},
94   {SET_ROOT_API     ,1,"rootapi"         , "HTML Root API URL [default /api"},
95   {SET_ROOT_ALIAS   ,1,"alias"           , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
96   {SET_APITIMEOUT   ,1,"apitimeout"      , "Plugin API timeout in seconds [default 10]"},
97
98   {SET_CACHE_TO     ,1,"cache-eol"       , "Client cache end of live [default 3600s]"},
99   {SET_cardid       ,1,"setuid"          , "Change user id [default don't change]"},
100   {SET_PID_FILE     ,1,"pidfile"         , "PID file path [default none]"},
101   {SET_SESSION_DIR  ,1,"sessiondir"      , "Sessions file path [default rootdir/sessions]"},
102   {SET_CONFIG_FILE  ,1,"config"          , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
103   {SET_CONFIG_SAVE  ,0,"save"            , "Save config on disk [default no]"},
104   {SET_CONFIG_EXIT  ,0,"saveonly"        , "Save config on disk and then exit"},
105
106   {SET_SMACK        ,1,"smack"           , "Set Smack Label [default=demo"},
107   {SET_PLUGINS      ,1,"mods"            , "Enable module [default=all"},
108   
109   {DISPLAY_VERSION  ,0,"version"         , "Display version and copyright"},
110   {DISPLAY_HELP     ,0,"help"            , "Display this help"},
111   {0, 0, 0}
112  };
113
114 static AFB_aliasdir aliasdir[MAX_ALIAS];
115 static int aliascount=0;
116
117 /*----------------------------------------------------------
118  | signalQuit
119  |  return to intitial exitpoint on order to close backend
120  |  before exiting.
121  +--------------------------------------------------------- */
122 void signalQuit (int signum)
123 {
124   if (verbose) printf ("INF:signalQuit received signal to quit\n");
125   longjmp (exitpoint, signum);
126 }
127
128 /*----------------------------------------------------------
129  | timeout signalQuit
130  |
131  +--------------------------------------------------------- */
132 void signalFail (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:getAllBlock acquisition timeout\n",configTime());
142   syslog (LOG_ERR, "Daemon fail and restart [please report bug]");
143   longjmp (restartpoint, 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 --smack=xxxx --mods=alsa:dbus\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 /*----------------------------------------------------------
233  | listenLoop
234  |   Main listening HTTP loop
235  +--------------------------------------------------------- */
236 static void listenLoop (AFB_session *session) {
237   AFB_error  err;
238
239   if (signal (SIGABRT, signalFail) == SIG_ERR) {
240         fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
241         return;
242   }
243
244   // ------ Start httpd server
245   if (session->config->httpdPort > 0) {
246
247         err = httpdStart (session);
248         if (err != AFB_SUCCESS) return;
249
250         // infinite loop
251         httpdLoop(session);
252
253         fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
254   }
255 }
256
257
258 /*---------------------------------------------------------
259  | main
260  |   Parse option and launch action
261  +--------------------------------------------------------- */
262
263 int main(int argc, char *argv[])  {
264   AFB_session    *session;
265   char*          programName = argv [0];
266   int            optionIndex = 0;
267   int            optc, ind, consoleFD;
268   int            pid, nbcmd, status;
269   AFB_config     cliconfig; // temp structure to store CLI option before file config upload
270
271   // ------------- Build session handler & init config -------
272   session =  configInit ();
273   memset(&cliconfig,0,sizeof(cliconfig));
274   memset(&aliasdir  ,0,sizeof(aliasdir));
275   cliconfig.aliasdir = aliasdir;
276
277   // GNU CLI getopts nterface.
278   struct option ggcOption;
279   struct option *gnuOptions;
280
281   // ------------------ Process Command Line -----------------------
282
283   // if no argument print help and return
284   if (argc < 2) {
285        printHelp(programName);
286        return (-1);
287   }
288
289   // build GNU getopt info from cliOptions
290   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
291   gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
292   for (ind=0; ind < nbcmd;ind++) {
293     gnuOptions [ind].name    = cliOptions[ind].name;
294     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
295     gnuOptions [ind].flag    = 0;
296     gnuOptions [ind].val     = cliOptions[ind].val;
297   }
298
299   // get all options from command line
300   while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
301         != EOF)
302   {
303     switch (optc)
304     {
305      case SET_VERBOSE:
306        verbose = 1;
307        break;
308
309     case SET_TCP_PORT:
310        if (optarg == 0) goto needValueForOption;
311        if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
312        break;
313        
314     case SET_APITIMEOUT:
315        if (optarg == 0) goto needValueForOption;
316        if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
317        break;
318
319     case SET_ROOT_DIR:
320        if (optarg == 0) goto needValueForOption;
321        cliconfig.rootdir   = optarg;
322        if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
323        break;       
324        
325     case SET_ROOT_BASE:
326        if (optarg == 0) goto needValueForOption;
327        cliconfig.rootbase   = optarg;
328        if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
329        break;
330
331     case SET_ROOT_API:
332        if (optarg == 0) goto needValueForOption;
333        cliconfig.rootapi   = optarg;
334        if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
335        break;
336        
337     case SET_ROOT_ALIAS:
338        if (optarg == 0) goto needValueForOption;
339        if (aliascount < MAX_ALIAS) {
340             aliasdir[aliascount].url  = strsep(&optarg,":");
341             aliasdir[aliascount].path = strsep(&optarg,":");
342             aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
343             if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
344             aliascount++;
345        } else {
346            fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
347        }
348        
349       
350        break;
351        
352     case SET_SMACK:
353        if (optarg == 0) goto needValueForOption;
354        fprintf (stderr, "Not Implemented yet\n");
355        cliconfig.smack   = optarg;
356        break;
357
358     case SET_PLUGINS:
359        if (optarg == 0) goto needValueForOption;
360        fprintf (stderr, "Not Implemented yet\n");
361        cliconfig.plugins = optarg;
362        break;
363
364     case SET_PID_FILE:
365        if (optarg == 0) goto needValueForOption;
366        cliconfig.pidfile   = optarg;
367        break;
368
369     case SET_SESSION_DIR:
370        if (optarg == 0) goto needValueForOption;
371        cliconfig.sessiondir   = optarg;
372        break;
373
374     case  SET_CONFIG_FILE:
375        if (optarg == 0) goto needValueForOption;
376        cliconfig.configfile   = optarg;
377        break;
378
379     case  SET_CACHE_TO:
380        if (optarg == 0) goto needValueForOption;
381        if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
382        break;
383
384     case SET_CONFIG_EXIT:
385        if (optarg != 0) goto noValueForOption;
386        session->configsave  = 1;
387        session->forceexit   = 1;
388        break;
389
390     case SET_CONFIG_SAVE:
391        if (optarg != 0) goto noValueForOption;
392        session->configsave  = 1;
393        break;
394
395     case SET_cardid:
396        if (optarg == 0) goto needValueForOption;
397        if (!sscanf (optarg, "%d", &cliconfig.setuid)) goto notAnInteger;
398        break;
399
400     case SET_FAKE_MOD:
401        if (optarg != 0) goto noValueForOption;
402        session->fakemod  = 1;
403        break;
404
405     case SET_FORGROUND:
406        if (optarg != 0) goto noValueForOption;
407        session->foreground  = 1;
408        break;
409
410     case SET_BACKGROUND:
411        if (optarg != 0) goto noValueForOption;
412        session->background  = 1;
413        break;
414
415      case KILL_PREV_REST:
416        if (optarg != 0) goto noValueForOption;
417        session->killPrevious  = 1;
418        break;
419
420      case KILL_PREV_EXIT:
421        if (optarg != 0) goto noValueForOption;
422        session->killPrevious  = 2;
423        break;
424
425     case DISPLAY_VERSION:
426        if (optarg != 0) goto noValueForOption;
427        printVersion();
428        goto normalExit;
429
430     case DISPLAY_HELP:
431      default:
432        printHelp(programName);
433        goto normalExit;
434
435   }
436   }
437   // Create session config
438   configInit (/* session & config are initialized globally */);
439
440   // if exist merge config file with CLI arguments
441   configLoadFile  (session, &cliconfig);
442
443   // ------------------ sanity check ----------------------------------------
444   if  ((session->background) && (session->foreground)) {
445     fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
446      exit (-1);
447   }
448
449   // ------------------ Some useful default values -------------------------
450   if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
451
452   // open syslog if ever needed
453   openlog("AGB-log", 0, LOG_DAEMON);
454
455   // -------------- Try to kill any previsou process if asked ---------------------
456   if (session->killPrevious) {
457     pid = readPidFile (session->config);  // enforce commandline option
458     switch (pid) {
459     case -1:
460       fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
461       break;
462     case 0:
463       fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
464       break;
465     default:
466       status = kill (pid,SIGINT );
467       if (status == 0) {
468              if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
469       } else {
470          // try kill -9
471          status = kill (pid,9);
472          if (status != 0)  fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
473       }
474     } // end switch pid
475
476     if (session->killPrevious >= 2) goto normalExit;
477   } // end killPrevious
478
479
480   // ------------------ clean exit on CTR-C signal ------------------------
481   if (signal (SIGINT, signalQuit) == SIG_ERR) {
482     fprintf (stderr, "%s Quit Signal received.",configTime());
483     return (-1);
484   }
485
486   // save exitpoint context when returning from longjmp closeSession and exit
487   status = setjmp (exitpoint); // return !+ when coming from longjmp
488   if (status != 0) {
489     if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
490     closeSession (session);
491     goto exitOnSignal;
492   }
493
494   // let's run this program with a low priority
495   status=nice (20);
496
497
498   // ------------------ Finaly Process Commands -----------------------------
499
500
501
502    // if --save then store config on disk upfront
503    if (session->configsave) configStoreFile (session);
504    if (session->forceexit)  exit (0);
505
506     if (session->config->setuid) {
507         int err;
508
509         err = setuid(session->config->setuid);
510         if (err) fprintf (stderr, "Fail to change program cardid error=%s", strerror(err));
511     }
512
513     // let's not take the risk to run as ROOT
514     if (getuid() == 0)  status=setuid(65534);  // run as nobody
515
516     // check session dir and create if it does not exist
517     if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
518     if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
519
520
521
522     // ---- run in foreground mode --------------------
523     if (session->foreground) {
524
525         if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
526
527         // write a pid file for --kill-previous and --raise-debug option
528         status = writePidFile (session->config, getpid());
529         if (status == -1) goto errorPidFile;
530
531         // enter listening loop in foreground
532         listenLoop(session);
533         goto exitInitLoop;
534   } // end foreground
535
536
537   // --------- run in background mode -----------
538   if (session->background) {
539
540        // if (status != 0) goto errorCommand;
541       if (verbose) printf ("AFB: Entering background mode\n");
542
543       // open /dev/console to redirect output messAFBes
544       consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
545       if (consoleFD < 0) goto errConsole;
546
547       // fork process when running background mode
548       pid = fork ();
549
550       // son process get all data in standalone mode
551       if (pid == 0) {
552
553              printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
554              if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
555
556          // redirect default I/O on console
557          close (2); status=dup(consoleFD);  // redirect stderr
558          close (1); status=dup(consoleFD);  // redirect stdout
559          close (0);           // no need for stdin
560          close (consoleFD);
561
562          setsid();   // allow father process to fully exit
563              sleep (2);  // allow main to leave and release port
564
565          fprintf (stderr, "----------------------------\n");
566          fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
567          fflush  (stderr);
568
569          // if everything look OK then look forever
570          syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
571
572          // should normally never return from this loop
573          listenLoop(session);
574          syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
575
576          goto exitInitLoop;
577       }
578
579       // if fail nothing much to do
580       if (pid == -1) goto errorFork;
581
582       // fork worked and we are in father process
583       status = writePidFile (session->config, pid);
584       if (status == -1) goto errorPidFile;
585
586       // we are in father process, we don't need this one
587       exit (0);
588
589   } // end background-foreground
590
591 normalExit:
592   closeSession (session);   // try to close everything before leaving
593   if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
594   exit (0);
595
596 // ------------- Fatal ERROR display error and quit  -------------
597 errorPidFile:
598   fprintf (stderr,"\nERR:main Failled to write pid file [%s]\n\n", session->config->pidfile);
599   exit (-1);
600
601 errorFork:
602   fprintf (stderr,"\nERR:main Failled to fork son process\n\n");
603   exit (-1);
604
605 needValueForOption:
606   fprintf (stderr,"\nERR:main option [--%s] need a value i.e. --%s=xxx\n\n"
607           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
608   exit (-1);
609
610 noValueForOption:
611   fprintf (stderr,"\nERR:main option [--%s] don't take value\n\n"
612           ,gnuOptions[optionIndex].name);
613   exit (-1);
614
615 notAnInteger:
616   fprintf (stderr,"\nERR:main option [--%s] requirer an interger i.e. --%s=9\n\n"
617           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
618   exit (-1);
619
620 exitOnSignal:
621   fprintf (stderr,"\n%s INF:main pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
622                  ,configTime(), getpid());
623   exit (-1);
624
625 errConsole:
626   fprintf (stderr,"\nERR:cannot open /dev/console (use --foreground)\n\n");
627   exit (-1);
628
629 errSessiondir:
630   fprintf (stderr,"\nERR:cannot read/write session dir\n\n");
631   exit (-1);
632
633 errSoundCard:
634   fprintf (stderr,"\nERR:fail to probe sound cards\n\n");
635   exit (-1);
636
637 exitInitLoop:
638   // try to unlink pid file if any
639   if (session->background && session->config->pidfile != NULL)  unlink (session->config->pidfile);
640   exit (-1);
641
642 }; /* END main() */
643