Added Netbean to work with cmake
[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  | main
246  |   Parse option and launch action
247  +--------------------------------------------------------- */
248
249 int main(int argc, char *argv[])  {
250   AFB_session    *session;
251   char*          programName = argv [0];
252   int            optionIndex = 0;
253   int            optc, ind, consoleFD;
254   int            pid, nbcmd, status;
255   AFB_config     cliconfig; // temp structure to store CLI option before file config upload
256
257   // ------------- Build session handler & init config -------
258   session = configInit ();
259   memset(&cliconfig,0,sizeof(cliconfig));
260   memset(&aliasdir  ,0,sizeof(aliasdir));
261   cliconfig.aliasdir = aliasdir;
262
263   // GNU CLI getopts nterface.
264   struct option ggcOption;
265   struct option *gnuOptions;
266
267   // ------------------ Process Command Line -----------------------
268
269   // if no argument print help and return
270   if (argc < 2) {
271        printHelp(programName);
272        return (-1);
273   }
274
275   // build GNU getopt info from cliOptions
276   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
277   gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
278   for (ind=0; ind < nbcmd;ind++) {
279     gnuOptions [ind].name    = cliOptions[ind].name;
280     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
281     gnuOptions [ind].flag    = 0;
282     gnuOptions [ind].val     = cliOptions[ind].val;
283   }
284
285   // get all options from command line
286   while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
287         != EOF)
288   {
289     switch (optc)
290     {
291      case SET_VERBOSE:
292        verbose = 1;
293        break;
294
295     case SET_TCP_PORT:
296        if (optarg == 0) goto needValueForOption;
297        if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
298        break;
299        
300     case SET_APITIMEOUT:
301        if (optarg == 0) goto needValueForOption;
302        if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
303        break;
304
305     case SET_ROOT_DIR:
306        if (optarg == 0) goto needValueForOption;
307        cliconfig.rootdir   = optarg;
308        if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
309        break;       
310        
311     case SET_ROOT_BASE:
312        if (optarg == 0) goto needValueForOption;
313        cliconfig.rootbase   = optarg;
314        if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
315        break;
316
317     case SET_ROOT_API:
318        if (optarg == 0) goto needValueForOption;
319        cliconfig.rootapi   = optarg;
320        if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
321        break;
322        
323     case SET_ROOT_ALIAS:
324        if (optarg == 0) goto needValueForOption;
325        if (aliascount < MAX_ALIAS) {
326             aliasdir[aliascount].url  = strsep(&optarg,":");
327             aliasdir[aliascount].path = strsep(&optarg,":");
328             aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
329             if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
330             aliascount++;
331        } else {
332            fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
333        }     
334        break;
335        
336     case SET_SMACK:
337        if (optarg == 0) goto needValueForOption;
338        fprintf (stderr, "Not Implemented yet\n");
339        cliconfig.smack   = optarg;
340        break;
341
342     case SET_PLUGINS:
343        if (optarg == 0) goto needValueForOption;
344        fprintf (stderr, "Not Implemented yet\n");
345        cliconfig.plugins = optarg;
346        break;
347
348     case SET_PID_FILE:
349        if (optarg == 0) goto needValueForOption;
350        cliconfig.pidfile   = optarg;
351        break;
352
353     case SET_SESSION_DIR:
354        if (optarg == 0) goto needValueForOption;
355        cliconfig.sessiondir   = optarg;
356        break;
357
358     case  SET_CONFIG_FILE:
359        if (optarg == 0) goto needValueForOption;
360        cliconfig.configfile   = optarg;
361        break;
362
363     case  SET_CACHE_TO:
364        if (optarg == 0) goto needValueForOption;
365        if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
366        break;
367
368     case SET_CONFIG_EXIT:
369        if (optarg != 0) goto noValueForOption;
370        session->configsave  = 1;
371        session->forceexit   = 1;
372        break;
373
374     case SET_CONFIG_SAVE:
375        if (optarg != 0) goto noValueForOption;
376        session->configsave  = 1;
377        break;
378
379     case SET_cardid:
380        if (optarg == 0) goto needValueForOption;
381        if (!sscanf (optarg, "%d", &cliconfig.setuid)) goto notAnInteger;
382        break;
383
384     case SET_FAKE_MOD:
385        if (optarg != 0) goto noValueForOption;
386        session->fakemod  = 1;
387        break;
388
389     case SET_FORGROUND:
390        if (optarg != 0) goto noValueForOption;
391        session->foreground  = 1;
392        break;
393
394     case SET_BACKGROUND:
395        if (optarg != 0) goto noValueForOption;
396        session->background  = 1;
397        break;
398
399      case KILL_PREV_REST:
400        if (optarg != 0) goto noValueForOption;
401        session->killPrevious  = 1;
402        break;
403
404      case KILL_PREV_EXIT:
405        if (optarg != 0) goto noValueForOption;
406        session->killPrevious  = 2;
407        break;
408
409     case DISPLAY_VERSION:
410        if (optarg != 0) goto noValueForOption;
411        printVersion();
412        goto normalExit;
413
414     case DISPLAY_HELP:
415      default:
416        printHelp(programName);
417        goto normalExit;
418
419   }
420   }
421   // Create session config
422   configInit (/* session & config are initialized globally */);
423
424   // if exist merge config file with CLI arguments
425   configLoadFile  (session, &cliconfig);
426
427   // ------------------ sanity check ----------------------------------------
428   if  ((session->background) && (session->foreground)) {
429     fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
430      exit (-1);
431   }
432
433   // ------------------ Some useful default values -------------------------
434   if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
435
436   // open syslog if ever needed
437   openlog("AGB-log", 0, LOG_DAEMON);
438
439   // -------------- Try to kill any previsou process if asked ---------------------
440   if (session->killPrevious) {
441     pid = readPidFile (session->config);  // enforce commandline option
442     switch (pid) {
443     case -1:
444       fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
445       break;
446     case 0:
447       fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
448       break;
449     default:
450       status = kill (pid,SIGINT );
451       if (status == 0) {
452              if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
453       } else {
454          // try kill -9
455          status = kill (pid,9);
456          if (status != 0)  fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
457       }
458     } // end switch pid
459
460     if (session->killPrevious >= 2) goto normalExit;
461   } // end killPrevious
462
463
464   // ------------------ clean exit on CTR-C signal ------------------------
465   if (signal (SIGINT, signalQuit) == SIG_ERR) {
466     fprintf (stderr, "%s Quit Signal received.",configTime());
467     return (-1);
468   }
469
470   // save exitPoint context when returning from longjmp closeSession and exit
471   status = setjmp (exitPoint); // return !+ when coming from longjmp
472   if (status != 0) {
473     if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
474     closeSession (session);
475     goto exitOnSignal;
476   }
477
478   // let's run this program with a low priority
479   status=nice (20);
480
481   // ------------------ Finaly Process Commands -----------------------------
482    // if --save then store config on disk upfront
483    if (session->configsave) configStoreFile (session);
484    if (session->forceexit)  exit (0);
485
486     if (session->config->setuid) {
487         int err;
488
489         err = setuid(session->config->setuid);
490         if (err) fprintf (stderr, "Fail to change program cardid error=%s", strerror(err));
491     }
492
493     // let's not take the risk to run as ROOT
494     if (getuid() == 0)  status=setuid(65534);  // run as nobody
495
496     // check session dir and create if it does not exist
497     if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
498     if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
499
500
501
502     // ---- run in foreground mode --------------------
503     if (session->foreground) {
504
505         if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
506
507         // write a pid file for --kill-previous and --raise-debug option
508         status = writePidFile (session->config, getpid());
509         if (status == -1) goto errorPidFile;
510
511         // enter listening loop in foreground
512         listenLoop(session);
513         goto exitInitLoop;
514   } // end foreground
515
516
517   // --------- run in background mode -----------
518   if (session->background) {
519
520        // if (status != 0) goto errorCommand;
521       if (verbose) printf ("AFB: Entering background mode\n");
522
523       // open /dev/console to redirect output messAFBes
524       consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
525       if (consoleFD < 0) goto errConsole;
526
527       // fork process when running background mode
528       pid = fork ();
529
530       // son process get all data in standalone mode
531       if (pid == 0) {
532
533              printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
534              if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
535
536          // redirect default I/O on console
537          close (2); status=dup(consoleFD);  // redirect stderr
538          close (1); status=dup(consoleFD);  // redirect stdout
539          close (0);           // no need for stdin
540          close (consoleFD);
541
542          setsid();   // allow father process to fully exit
543              sleep (2);  // allow main to leave and release port
544
545          fprintf (stderr, "----------------------------\n");
546          fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
547          fflush  (stderr);
548
549          // if everything look OK then look forever
550          syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
551
552          // should normally never return from this loop
553          listenLoop(session);
554          syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
555
556          goto exitInitLoop;
557       }
558
559       // if fail nothing much to do
560       if (pid == -1) goto errorFork;
561
562       // fork worked and we are in father process
563       status = writePidFile (session->config, pid);
564       if (status == -1) goto errorPidFile;
565
566       // we are in father process, we don't need this one
567       exit (0);
568
569   } // end background-foreground
570
571 normalExit:
572   closeSession (session);   // try to close everything before leaving
573   if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
574   exit (0);
575
576 // ------------- Fatal ERROR display error and quit  -------------
577 errorPidFile:
578   fprintf (stderr,"\nERR:main Failled to write pid file [%s]\n\n", session->config->pidfile);
579   exit (-1);
580
581 errorFork:
582   fprintf (stderr,"\nERR:main Failled to fork son process\n\n");
583   exit (-1);
584
585 needValueForOption:
586   fprintf (stderr,"\nERR:main option [--%s] need a value i.e. --%s=xxx\n\n"
587           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
588   exit (-1);
589
590 noValueForOption:
591   fprintf (stderr,"\nERR:main option [--%s] don't take value\n\n"
592           ,gnuOptions[optionIndex].name);
593   exit (-1);
594
595 notAnInteger:
596   fprintf (stderr,"\nERR:main option [--%s] requirer an interger i.e. --%s=9\n\n"
597           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
598   exit (-1);
599
600 exitOnSignal:
601   fprintf (stderr,"\n%s INF:main pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
602                  ,configTime(), getpid());
603   exit (-1);
604
605 errConsole:
606   fprintf (stderr,"\nERR:cannot open /dev/console (use --foreground)\n\n");
607   exit (-1);
608
609 errSessiondir:
610   fprintf (stderr,"\nERR:cannot read/write session dir\n\n");
611   exit (-1);
612
613 errSoundCard:
614   fprintf (stderr,"\nERR:fail to probe sound cards\n\n");
615   exit (-1);
616
617 exitInitLoop:
618   // try to unlink pid file if any
619   if (session->background && session->config->pidfile != NULL)  unlink (session->config->pidfile);
620   exit (-1);
621
622 }; /* END main() */
623