Added Session Management
[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_SMACK          140
75  #define SET_PLUGINS        141
76  #define SET_APITIMEOUT     142
77  #define SET_CNTXTIMEOUT    143
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_SMACK        ,1,"smack"           , "Set Smack Label [default demo]"},
110   {SET_PLUGINS      ,1,"mods"            , "Enable module [default all]"},
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 --smack=xxxx --mods=alsa:dbus\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_SMACK:
346        if (optarg == 0) goto needValueForOption;
347        fprintf (stderr, "Not Implemented yet\n");
348        cliconfig.smack   = optarg;
349        break;
350
351     case SET_PLUGINS:
352        if (optarg == 0) goto needValueForOption;
353        fprintf (stderr, "Not Implemented yet\n");
354        cliconfig.plugins = optarg;
355        break;
356
357     case SET_PID_FILE:
358        if (optarg == 0) goto needValueForOption;
359        cliconfig.pidfile   = optarg;
360        break;
361
362     case SET_SESSION_DIR:
363        if (optarg == 0) goto needValueForOption;
364        cliconfig.sessiondir   = optarg;
365        break;
366
367     case  SET_CONFIG_FILE:
368        if (optarg == 0) goto needValueForOption;
369        cliconfig.configfile   = optarg;
370        break;
371
372     case  SET_CACHE_TO:
373        if (optarg == 0) goto needValueForOption;
374        if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
375        break;
376
377     case SET_CONFIG_EXIT:
378        if (optarg != 0) goto noValueForOption;
379        session->configsave  = 1;
380        session->forceexit   = 1;
381        break;
382
383     case SET_CONFIG_SAVE:
384        if (optarg != 0) goto noValueForOption;
385        session->configsave  = 1;
386        break;
387
388     case SET_USERID:
389        if (optarg == 0) goto needValueForOption;
390        if (!sscanf (optarg, "%s", &cliconfig.setuid)) goto notAnInteger;
391        break;
392
393     case SET_FAKE_MOD:
394        if (optarg != 0) goto noValueForOption;
395        session->fakemod  = 1;
396        break;
397
398     case SET_FORGROUND:
399        if (optarg != 0) goto noValueForOption;
400        session->foreground  = 1;
401        break;
402
403     case SET_BACKGROUND:
404        if (optarg != 0) goto noValueForOption;
405        session->background  = 1;
406        break;
407
408      case KILL_PREV_REST:
409        if (optarg != 0) goto noValueForOption;
410        session->killPrevious  = 1;
411        break;
412
413      case KILL_PREV_EXIT:
414        if (optarg != 0) goto noValueForOption;
415        session->killPrevious  = 2;
416        break;
417
418     case DISPLAY_VERSION:
419        if (optarg != 0) goto noValueForOption;
420        printVersion();
421        goto normalExit;
422
423     case DISPLAY_HELP:
424      default:
425        printHelp(programName);
426        goto normalExit;
427
428   }
429   }
430   // Create session config
431   configInit (/* session & config are initialized globally */);
432
433   // if exist merge config file with CLI arguments
434   configLoadFile  (session, &cliconfig);
435
436   // ------------------ sanity check ----------------------------------------
437   if  ((session->background) && (session->foreground)) {
438     fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
439      exit (-1);
440   }
441
442   // ------------------ Some useful default values -------------------------
443   if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
444
445   // open syslog if ever needed
446   openlog("AGB-log", 0, LOG_DAEMON);
447
448   // -------------- Try to kill any previsou process if asked ---------------------
449   if (session->killPrevious) {
450     pid = readPidFile (session->config);  // enforce commandline option
451     switch (pid) {
452     case -1:
453       fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
454       break;
455     case 0:
456       fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
457       break;
458     default:
459       status = kill (pid,SIGINT );
460       if (status == 0) {
461              if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
462       } else {
463          // try kill -9
464          status = kill (pid,9);
465          if (status != 0)  fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
466       }
467     } // end switch pid
468
469     if (session->killPrevious >= 2) goto normalExit;
470   } // end killPrevious
471
472
473   // ------------------ clean exit on CTR-C signal ------------------------
474   if (signal (SIGINT, signalQuit) == SIG_ERR) {
475     fprintf (stderr, "%s Quit Signal received.",configTime());
476     return (-1);
477   }
478
479   // save exitPoint context when returning from longjmp closeSession and exit
480   status = setjmp (exitPoint); // return !+ when coming from longjmp
481   if (status != 0) {
482     if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
483     closeSession (session);
484     goto exitOnSignal;
485   }
486
487   // let's run this program with a low priority
488   status=nice (20);
489
490   // ------------------ Finaly Process Commands -----------------------------
491    // if --save then store config on disk upfront
492    if (session->configsave) configStoreFile (session);
493    if (session->forceexit)  exit (0);
494
495     if (session->config->setuid) {
496         int err;
497         struct passwd *passwd;
498         passwd=getpwnam(session->config->setuid);
499         
500         if (passwd == NULL) goto errorSetuid;
501         
502         err = setuid(passwd->pw_uid);
503         if (err) goto errorSetuid;
504     }
505
506     // let's not take the risk to run as ROOT
507     if (getuid() == 0)  goto errorNoRoot;
508
509     // check session dir and create if it does not exist
510     if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
511     if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
512
513
514
515     // ---- run in foreground mode --------------------
516     if (session->foreground) {
517
518         if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
519
520         // write a pid file for --kill-previous and --raise-debug option
521         status = writePidFile (session->config, getpid());
522         if (status == -1) goto errorPidFile;
523
524         // enter listening loop in foreground
525         listenLoop(session);
526         goto exitInitLoop;
527   } // end foreground
528
529
530   // --------- run in background mode -----------
531   if (session->background) {
532
533        // if (status != 0) goto errorCommand;
534       if (verbose) printf ("AFB: Entering background mode\n");
535
536       // open /dev/console to redirect output messAFBes
537       consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
538       if (consoleFD < 0) goto errConsole;
539
540       // fork process when running background mode
541       pid = fork ();
542
543       // son process get all data in standalone mode
544       if (pid == 0) {
545
546              printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
547              if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
548
549          // redirect default I/O on console
550          close (2); status=dup(consoleFD);  // redirect stderr
551          close (1); status=dup(consoleFD);  // redirect stdout
552          close (0);           // no need for stdin
553          close (consoleFD);
554
555          setsid();   // allow father process to fully exit
556              sleep (2);  // allow main to leave and release port
557
558          fprintf (stderr, "----------------------------\n");
559          fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
560          fflush  (stderr);
561
562          // if everything look OK then look forever
563          syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
564
565          // should normally never return from this loop
566          listenLoop(session);
567          syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
568
569          goto exitInitLoop;
570       }
571
572       // if fail nothing much to do
573       if (pid == -1) goto errorFork;
574
575       // fork worked and we are in father process
576       status = writePidFile (session->config, pid);
577       if (status == -1) goto errorPidFile;
578
579       // we are in father process, we don't need this one
580       exit (0);
581
582   } // end background-foreground
583
584 normalExit:
585   closeSession (session);   // try to close everything before leaving
586   if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
587   exit (0);
588
589 // ------------- Fatal ERROR display error and quit  -------------
590 errorSetuid:
591   fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
592   exit (-1);
593   
594 errorNoRoot:
595   fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
596   exit (-1);
597
598 errorPidFile:
599   fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
600   exit (-1);
601
602 errorFork:
603   fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
604   exit (-1);
605
606 needValueForOption:
607   fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
608           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
609   exit (-1);
610
611 noValueForOption:
612   fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
613           ,gnuOptions[optionIndex].name);
614   exit (-1);
615
616 notAnInteger:
617   fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
618           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
619   exit (-1);
620
621 exitOnSignal:
622   fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
623                  ,configTime(), getpid());
624   exit (-1);
625
626 errConsole:
627   fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
628   exit (-1);
629
630 errSessiondir:
631   fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
632   exit (-1);
633
634 errSoundCard:
635   fprintf (stderr,"\nERR:AFB-daemon fail to probe sound cards\n\n");
636   exit (-1);
637
638 exitInitLoop:
639   // try to unlink pid file if any
640   if (session->background && session->config->pidfile != NULL)  unlink (session->config->pidfile);
641   exit (-1);
642
643 }; /* END AFB-daemon() */
644