aa0e9bcdcc6d7206bd71d80101ba56e205ae7a48
[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_AUTH_TOKEN     141
76  #define SET_PLUGINS        142
77  #define SET_APITIMEOUT     143
78  #define SET_CNTXTIMEOUT    144
79
80  #define DISPLAY_VERSION    150
81  #define DISPLAY_HELP       151
82
83
84 // Supported option
85 static  AFB_options cliOptions [] = {
86   {SET_VERBOSE      ,0,"verbose"         , "Verbose Mode"},
87
88   {SET_FORGROUND    ,0,"foreground"      , "Get all in foreground mode"},
89   {SET_BACKGROUND   ,0,"daemon"          , "Get all in background mode"},
90   {KILL_PREV_EXIT   ,0,"kill"            , "Kill active process if any and exit"},
91   {KILL_PREV_REST   ,0,"restart"         , "Kill active process if any and restart"},
92
93   {SET_TCP_PORT     ,1,"port"            , "HTTP listening TCP port  [default 1234]"},
94   {SET_ROOT_DIR     ,1,"rootdir"         , "HTTP Root Directory [default $HOME/.AFB]"},
95   {SET_ROOT_BASE    ,1,"rootbase"        , "Angular Base Root URL [default /opa]"},
96   {SET_ROOT_API     ,1,"rootapi"         , "HTML Root API URL [default /api]"},
97   {SET_ROOT_ALIAS   ,1,"alias"           , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
98   
99   {SET_APITIMEOUT   ,1,"apitimeout"      , "Plugin API timeout in seconds [default 10]"},
100   {SET_CNTXTIMEOUT  ,1,"cntxtimeout"     , "Client Session Context Timeout [default 900]"},
101   {SET_CACHE_TO     ,1,"cache-eol"       , "Client cache end of live [default 3600s]"},
102   
103   {SET_USERID       ,1,"setuid"          , "Change user id [default don't change]"},
104   {SET_PID_FILE     ,1,"pidfile"         , "PID file path [default none]"},
105   {SET_SESSION_DIR  ,1,"sessiondir"      , "Sessions file path [default rootdir/sessions]"},
106   {SET_CONFIG_FILE  ,1,"config"          , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
107   {SET_CONFIG_SAVE  ,0,"save"            , "Save config on disk [default no]"},
108   {SET_CONFIG_EXIT  ,0,"saveonly"        , "Save config on disk and then exit"},
109
110   {SET_SMACK        ,1,"smack"           , "Set Smack Label [default demo]"},
111   {SET_PLUGINS      ,1,"mods"            , "Enable module [default all]"},
112   {SET_AUTH_TOKEN   ,1,"token"           , "Initial Secret [default=no-session, --token="" for session without authentication]"},
113   
114   {DISPLAY_VERSION  ,0,"version"         , "Display version and copyright"},
115   {DISPLAY_HELP     ,0,"help"            , "Display this help"},
116   {0, 0, 0}
117  };
118
119 static AFB_aliasdir aliasdir[MAX_ALIAS];
120 static int aliascount=0;
121
122 /*----------------------------------------------------------
123  | timeout signalQuit
124  |
125  +--------------------------------------------------------- */
126 void signalQuit (int signum) {
127
128   sigset_t sigset;
129
130   // unlock timeout signal to allow a new signal to come
131   sigemptyset (&sigset);
132   sigaddset   (&sigset, SIGABRT);
133   sigprocmask (SIG_UNBLOCK, &sigset, 0);
134
135   fprintf (stderr, "%s ERR:Received signal quit\n",configTime());
136   syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
137   longjmp (exitPoint, signum);
138 }
139
140
141 /*----------------------------------------------------------
142  | printHelp
143  |   print information from long option array
144  +--------------------------------------------------------- */
145
146  static void printHelp(char *name) {
147     int ind;
148     char command[20];
149
150     fprintf (stderr,"%s:\nallowed options\n", name);
151     for (ind=0; cliOptions [ind].name != NULL;ind++)
152     {
153       // display options
154       if (cliOptions [ind].has_arg == 0 )
155       {
156              fprintf (stderr,"  --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
157       } else {
158          sprintf(command,"%s=xxxx", cliOptions [ind].name);
159          fprintf (stderr,"  --%-15s %s\n", command, cliOptions[ind].help);
160       }
161     }
162     fprintf (stderr,"Example:\n  %s\\\n  --verbose --port=1234 --smack=xxxx --token='azerty' --mods=alsa:dbus\n", name);
163 } // end printHelp
164
165 /*----------------------------------------------------------
166  | writePidFile
167  |   write a file in /var/run/AFB with pid
168  +--------------------------------------------------------- */
169 static int writePidFile (AFB_config *config, int pid) {
170   FILE *file;
171
172   // if no pid file configure just return
173   if (config->pidfile == NULL) return 0;
174
175   // open pid file in write mode
176   file = fopen(config->pidfile,"w");
177   if (file == NULL) {
178     fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
179     return -1;
180   }
181
182   // write pid in file and close
183   fprintf (file, "%d\n", pid);
184   fclose  (file);
185   return 0;
186 }
187
188 /*----------------------------------------------------------
189  | readPidFile
190  |   read file in /var/run/AFB with pid
191  +--------------------------------------------------------- */
192 static int readPidFile (AFB_config *config) {
193   int  pid;
194   FILE *file;
195   int  status;
196
197   if (config->pidfile == NULL) return -1;
198
199   // open pid file in write mode
200   file = fopen(config->pidfile,"r");
201   if (file == NULL) {
202     fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
203     return -1;
204   }
205
206   // write pid in file and close
207   status = fscanf  (file, "%d\n", &pid);
208   fclose  (file);
209
210   // never kill pid 0
211   if (status != 1) return -1;
212
213   return (pid);
214 }
215
216 /*----------------------------------------------------------
217  | closeSession
218  |   try to close everything before leaving
219  +--------------------------------------------------------- */
220 static void closeSession (AFB_session *session) {
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, signalQuit) == 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  | main
252  |   Parse option and launch action
253  +--------------------------------------------------------- */
254
255 int main(int argc, char *argv[])  {
256   AFB_session    *session;
257   char*          programName = argv [0];
258   int            optionIndex = 0;
259   int            optc, ind, consoleFD;
260   int            pid, nbcmd, status;
261   AFB_config     cliconfig; // temp structure to store CLI option before file config upload
262
263   // ------------- Build session handler & init config -------
264   session = configInit ();
265   memset(&cliconfig,0,sizeof(cliconfig));
266   memset(&aliasdir  ,0,sizeof(aliasdir));
267   cliconfig.aliasdir = aliasdir;
268
269   // GNU CLI getopts nterface.
270   struct option ggcOption;
271   struct option *gnuOptions;
272
273   // ------------------ Process Command Line -----------------------
274
275   // if no argument print help and return
276   if (argc < 2) {
277        printHelp(programName);
278        return (-1);
279   }
280
281   // build GNU getopt info from cliOptions
282   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
283   gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
284   for (ind=0; ind < nbcmd;ind++) {
285     gnuOptions [ind].name    = cliOptions[ind].name;
286     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
287     gnuOptions [ind].flag    = 0;
288     gnuOptions [ind].val     = cliOptions[ind].val;
289   }
290
291   // get all options from command line
292   while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
293         != EOF)
294   {
295     switch (optc)
296     {
297      case SET_VERBOSE:
298        verbose = 1;
299        break;
300
301     case SET_TCP_PORT:
302        if (optarg == 0) goto needValueForOption;
303        if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
304        break;
305        
306     case SET_APITIMEOUT:
307        if (optarg == 0) goto needValueForOption;
308        if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
309        break;
310
311     case SET_CNTXTIMEOUT:
312        if (optarg == 0) goto needValueForOption;
313        if (!sscanf (optarg, "%d", &cliconfig.cntxTimeout)) goto notAnInteger;
314        break;
315
316     case SET_ROOT_DIR:
317        if (optarg == 0) goto needValueForOption;
318        cliconfig.rootdir   = optarg;
319        if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
320        break;       
321        
322     case SET_ROOT_BASE:
323        if (optarg == 0) goto needValueForOption;
324        cliconfig.rootbase   = optarg;
325        if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
326        break;
327
328     case SET_ROOT_API:
329        if (optarg == 0) goto needValueForOption;
330        cliconfig.rootapi   = optarg;
331        if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
332        break;
333        
334     case SET_ROOT_ALIAS:
335        if (optarg == 0) goto needValueForOption;
336        if (aliascount < MAX_ALIAS) {
337             aliasdir[aliascount].url  = strsep(&optarg,":");
338             aliasdir[aliascount].path = strsep(&optarg,":");
339             aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
340             if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
341             aliascount++;
342        } else {
343            fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
344        }     
345        break;
346        
347     case SET_SMACK:
348        if (optarg == 0) goto needValueForOption;
349        fprintf (stderr, "Not Implemented yet\n");
350        cliconfig.smack   = optarg;
351        break;
352
353     case SET_AUTH_TOKEN:
354        if (optarg == 0) goto needValueForOption;
355        cliconfig.token   = 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_USERID:
396        if (optarg == 0) goto needValueForOption;
397        if (!sscanf (optarg, "%s", &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  
438   // if exist merge config file with CLI arguments
439   configLoadFile  (session, &cliconfig);
440   initPlugins(session);
441
442   // ------------------ sanity check ----------------------------------------
443   if  ((session->background) && (session->foreground)) {
444     fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
445      exit (-1);
446   }
447
448   // ------------------ Some useful default values -------------------------
449   if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
450
451   // open syslog if ever needed
452   openlog("AGB-log", 0, LOG_DAEMON);
453
454   // -------------- Try to kill any previsou process if asked ---------------------
455   if (session->killPrevious) {
456     pid = readPidFile (session->config);  // enforce commandline option
457     switch (pid) {
458     case -1:
459       fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
460       break;
461     case 0:
462       fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
463       break;
464     default:
465       status = kill (pid,SIGINT );
466       if (status == 0) {
467              if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
468       } else {
469          // try kill -9
470          status = kill (pid,9);
471          if (status != 0)  fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
472       }
473     } // end switch pid
474
475     if (session->killPrevious >= 2) goto normalExit;
476   } // end killPrevious
477
478
479   // ------------------ clean exit on CTR-C signal ------------------------
480   if (signal (SIGINT, signalQuit) == SIG_ERR) {
481     fprintf (stderr, "%s Quit Signal received.",configTime());
482     return (-1);
483   }
484
485   // save exitPoint context when returning from longjmp closeSession and exit
486   status = setjmp (exitPoint); // return !+ when coming from longjmp
487   if (status != 0) {
488     if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
489     closeSession (session);
490     goto exitOnSignal;
491   }
492
493   // let's run this program with a low priority
494   status=nice (20);
495
496   // ------------------ Finaly Process Commands -----------------------------
497    // if --save then store config on disk upfront
498    if (session->configsave) configStoreFile (session);
499    if (session->forceexit)  exit (0);
500
501     if (session->config->setuid) {
502         int err;
503         struct passwd *passwd;
504         passwd=getpwnam(session->config->setuid);
505         
506         if (passwd == NULL) goto errorSetuid;
507         
508         err = setuid(passwd->pw_uid);
509         if (err) goto errorSetuid;
510     }
511
512     // let's not take the risk to run as ROOT
513     //if (getuid() == 0)  goto errorNoRoot;
514
515     // check session dir and create if it does not exist
516     if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
517     if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
518
519
520
521     // ---- run in foreground mode --------------------
522     if (session->foreground) {
523
524         if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
525
526         // write a pid file for --kill-previous and --raise-debug option
527         status = writePidFile (session->config, getpid());
528         if (status == -1) goto errorPidFile;
529
530         // enter listening loop in foreground
531         listenLoop(session);
532         goto exitInitLoop;
533   } // end foreground
534
535
536   // --------- run in background mode -----------
537   if (session->background) {
538
539        // if (status != 0) goto errorCommand;
540       if (verbose) printf ("AFB: Entering background mode\n");
541
542       // open /dev/console to redirect output messAFBes
543       consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
544       if (consoleFD < 0) goto errConsole;
545
546       // fork process when running background mode
547       pid = fork ();
548
549       // son process get all data in standalone mode
550       if (pid == 0) {
551
552              printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
553              if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
554
555          // redirect default I/O on console
556          close (2); status=dup(consoleFD);  // redirect stderr
557          close (1); status=dup(consoleFD);  // redirect stdout
558          close (0);           // no need for stdin
559          close (consoleFD);
560
561          setsid();   // allow father process to fully exit
562              sleep (2);  // allow main to leave and release port
563
564          fprintf (stderr, "----------------------------\n");
565          fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
566          fflush  (stderr);
567
568          // if everything look OK then look forever
569          syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
570
571          // should normally never return from this loop
572          listenLoop(session);
573          syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
574
575          goto exitInitLoop;
576       }
577
578       // if fail nothing much to do
579       if (pid == -1) goto errorFork;
580
581       // fork worked and we are in father process
582       status = writePidFile (session->config, pid);
583       if (status == -1) goto errorPidFile;
584
585       // we are in father process, we don't need this one
586       exit (0);
587
588   } // end background-foreground
589
590 normalExit:
591   closeSession (session);   // try to close everything before leaving
592   if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
593   exit (0);
594
595 // ------------- Fatal ERROR display error and quit  -------------
596 errorSetuid:
597   fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
598   exit (-1);
599   
600 //errorNoRoot:
601 //  fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
602 //  exit (-1);
603
604 errorPidFile:
605   fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
606   exit (-1);
607
608 errorFork:
609   fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
610   exit (-1);
611
612 needValueForOption:
613   fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
614           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
615   exit (-1);
616
617 noValueForOption:
618   fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
619           ,gnuOptions[optionIndex].name);
620   exit (-1);
621
622 notAnInteger:
623   fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
624           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
625   exit (-1);
626
627 exitOnSignal:
628   fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
629                  ,configTime(), getpid());
630   exit (-1);
631
632 errConsole:
633   fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
634   exit (-1);
635
636 errSessiondir:
637   fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
638   exit (-1);
639
640 errSoundCard:
641   fprintf (stderr,"\nERR:AFB-daemon fail to probe sound cards\n\n");
642   exit (-1);
643
644 exitInitLoop:
645   // try to unlink pid file if any
646   if (session->background && session->config->pidfile != NULL)  unlink (session->config->pidfile);
647   exit (-1);
648
649 }; /* END AFB-daemon() */
650