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