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