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