several improvements
[src/app-framework-binder.git] / src / main.c
1 /* 
2  * Copyright (C) 2015 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  * Author José Bollo <jose.bollo@iot.bzh>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #include <syslog.h>
20 #include <setjmp.h>
21 #include <signal.h>
22 #include <getopt.h>
23 #include <pwd.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26
27 #include "local-def.h"
28
29 #if !defined(PLUGIN_INSTALL_DIR)
30 #error "you should define PLUGIN_INSTALL_DIR"
31 #endif
32
33 #define AFB_VERSION    "0.1"
34
35 // Define command line option
36 #define SET_VERBOSE        1
37 #define SET_BACKGROUND     2
38 #define SET_FORGROUND      3
39 #define SET_FAKE_MOD       4
40
41 #define SET_TCP_PORT       5
42 #define SET_ROOT_DIR       6
43 #define SET_ROOT_BASE      7
44 #define SET_ROOT_API       8
45 #define SET_ALIAS          9
46
47 #define SET_CACHE_TIMEOUT  10
48 #define SET_SESSION_DIR    11
49
50 #define SET_AUTH_TOKEN     12
51 #define SET_LDPATH         13
52 #define SET_APITIMEOUT     14
53 #define SET_CNTXTIMEOUT    15
54
55 #define DISPLAY_VERSION    16
56 #define DISPLAY_HELP       17
57
58 #define SET_MODE           18
59 #define SET_READYFD        19
60
61 // Command line structure hold cli --command + help text
62 typedef struct {
63   int  val;        // command number within application
64   int  has_arg;    // command number within application
65   char *name;      // command as used in --xxxx cli
66   char *help;      // help text
67 } AFB_options;
68
69
70 // Supported option
71 static  AFB_options cliOptions [] = {
72   {SET_VERBOSE      ,0,"verbose"         , "Verbose Mode"},
73
74   {SET_FORGROUND    ,0,"foreground"      , "Get all in foreground mode"},
75   {SET_BACKGROUND   ,0,"daemon"          , "Get all in background mode"},
76
77   {SET_TCP_PORT     ,1,"port"            , "HTTP listening TCP port  [default 1234]"},
78   {SET_ROOT_DIR     ,1,"rootdir"         , "HTTP Root Directory [default $HOME/.AFB]"},
79   {SET_ROOT_BASE    ,1,"rootbase"        , "Angular Base Root URL [default /opa]"},
80   {SET_ROOT_API     ,1,"rootapi"         , "HTML Root API URL [default /api]"},
81   {SET_ALIAS        ,1,"alias"           , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
82   
83   {SET_APITIMEOUT   ,1,"apitimeout"      , "Plugin API timeout in seconds [default 10]"},
84   {SET_CNTXTIMEOUT  ,1,"cntxtimeout"     , "Client Session Context Timeout [default 900]"},
85   {SET_CACHE_TIMEOUT,1,"cache-eol"       , "Client cache end of live [default 3600s]"},
86   
87   {SET_SESSION_DIR  ,1,"sessiondir"      , "Sessions file path [default rootdir/sessions]"},
88
89   {SET_LDPATH       ,1,"ldpaths"         , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
90   {SET_AUTH_TOKEN   ,1,"token"           , "Initial Secret [default=no-session, --token="" for session without authentication]"},
91   
92   {DISPLAY_VERSION  ,0,"version"         , "Display version and copyright"},
93   {DISPLAY_HELP     ,0,"help"            , "Display this help"},
94
95   {SET_MODE         ,1,"mode"            , "set the mode: either local, remote or global"},
96   {SET_READYFD      ,1,"readyfd"         , "set the #fd to signal when ready"},
97   {0, 0, NULL, NULL}
98  };
99
100 static AFB_aliasdir aliasdir[MAX_ALIAS];
101 static int aliascount = 0;
102
103
104 /*----------------------------------------------------------
105  | printversion
106  |   print version and copyright
107  +--------------------------------------------------------- */
108 static void printVersion (void)
109 {
110    fprintf (stderr,"\n----------------------------------------- \n");
111    fprintf (stderr,"|  AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
112    fprintf (stderr,"----------------------------------------- \n");
113    fprintf (stderr,"|  Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
114    fprintf (stderr,"|  AFB comes with ABSOLUTELY NO WARRANTY.\n");
115    fprintf (stderr,"|  Licence Apache 2\n\n");
116    exit (0);
117 }
118
119 // load config from disk and merge with CLI option
120 static AFB_error config_set_default (AFB_session * session)
121 {
122    static char cacheTimeout [10];
123    
124    // default HTTP port
125    if (session->config->httpdPort == 0) session->config->httpdPort=1234;
126    
127    // default Plugin API timeout
128    if (session->config->apiTimeout == 0) session->config->apiTimeout=DEFLT_API_TIMEOUT;
129    
130    // default AUTH_TOKEN
131    if (session->config->token == NULL) session->config->token= DEFLT_AUTH_TOKEN;
132
133    // cache timeout default one hour
134    if (session->config->cacheTimeout == 0) session->config->cacheTimeout=DEFLT_CACHE_TIMEOUT;
135
136    // cache timeout default one hour
137    if (session->config->cntxTimeout == 0) session->config->cntxTimeout=DEFLT_CNTX_TIMEOUT;
138
139    if (session->config->rootdir == NULL) {
140        session->config->rootdir = getenv("AFBDIR");
141        if (session->config->rootdir == NULL) {
142            session->config->rootdir = malloc (512);
143            strncpy  (session->config->rootdir, getenv("HOME"),512);
144            strncat (session->config->rootdir, "/.AFB",512);
145        }
146        // if directory does not exist createit
147        mkdir (session->config->rootdir,  O_RDWR | S_IRWXU | S_IRGRP);
148    }
149    
150    // if no Angular/HTML5 rootbase let's try '/' as default
151    if  (session->config->rootbase == NULL) {
152        session->config->rootbase = "/opa";
153    }
154    
155    if  (session->config->rootapi == NULL) {
156        session->config->rootapi = "/api";
157    }
158
159    if  (session->config->ldpaths == NULL) {
160        session->config->ldpaths = PLUGIN_INSTALL_DIR;
161    }
162
163    // if no session dir create a default path from rootdir
164    if  (session->config->sessiondir == NULL) {
165        session->config->sessiondir = malloc (512);
166        strncpy (session->config->sessiondir, session->config->rootdir, 512);
167        strncat (session->config->sessiondir, "/sessions",512);
168    }
169
170    // if no config dir create a default path from sessiondir
171    if  (session->config->console == NULL) {
172        session->config->console = malloc (512);
173        strncpy (session->config->console, session->config->sessiondir, 512);
174        strncat (session->config->console, "/AFB-console.out",512);
175    }
176
177    // cacheTimeout is an integer but HTTPd wants it as a string
178    snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
179    session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
180
181    return AFB_SUCCESS;
182 }
183
184
185 /*----------------------------------------------------------
186  | printHelp
187  |   print information from long option array
188  +--------------------------------------------------------- */
189
190  static void printHelp(char *name) {
191     int ind;
192     char command[20];
193
194     fprintf (stderr,"%s:\nallowed options\n", name);
195     for (ind=0; cliOptions [ind].name != NULL;ind++)
196     {
197       // display options
198       if (cliOptions [ind].has_arg == 0 )
199       {
200              fprintf (stderr,"  --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
201       } else {
202          sprintf(command,"%s=xxxx", cliOptions [ind].name);
203          fprintf (stderr,"  --%-15s %s\n", command, cliOptions[ind].help);
204       }
205     }
206     fprintf (stderr,"Example:\n  %s\\\n  --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
207 } // end printHelp
208
209 /*----------------------------------------------------------
210  | closeSession
211  |   try to close everything before leaving
212  +--------------------------------------------------------- */
213 static void closeSession (int status, void *data) {
214 //      AFB_session *session = data;
215 }
216
217 /*----------------------------------------------------------
218  | timeout signalQuit
219  |
220  +--------------------------------------------------------- */
221 void signalQuit (int signum) {
222
223   sigset_t sigset;
224
225   // unlock timeout signal to allow a new signal to come
226   sigemptyset (&sigset);
227   sigaddset   (&sigset, SIGABRT);
228   sigprocmask (SIG_UNBLOCK, &sigset, 0);
229
230   fprintf (stderr, "ERR: Received signal quit\n");
231   syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
232   exit(1);
233 }
234
235
236 /*----------------------------------------------------------
237  | listenLoop
238  |   Main listening HTTP loop
239  +--------------------------------------------------------- */
240 static void listenLoop (AFB_session *session) {
241   AFB_error  err;
242
243   // ------ Start httpd server
244
245    err = httpdStart (session);
246    if (err != AFB_SUCCESS) return;
247
248         if (session->readyfd != 0) {
249                 static const char readystr[] = "READY=1";
250                 write(session->readyfd, readystr, sizeof(readystr) - 1);
251                 close(session->readyfd);
252         }
253
254    // infinite loop
255    httpdLoop(session);
256
257    fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
258 }
259   
260 /*---------------------------------------------------------
261  | main
262  |   Parse option and launch action
263  +--------------------------------------------------------- */
264
265 static void parse_arguments(int argc, char *argv[], AFB_session *session)
266 {
267   char*          programName = argv [0];
268   int            optionIndex = 0;
269   int            optc, ind;
270   int            nbcmd;
271   struct option *gnuOptions;
272
273   // ------------- Build session handler & init config -------
274   memset(&aliasdir  ,0,sizeof(aliasdir));
275   session->config->aliasdir = aliasdir;
276
277   // ------------------ Process Command Line -----------------------
278
279   // if no argument print help and return
280   if (argc < 2) {
281        printHelp(programName);
282        exit(1);
283   }
284
285   // build GNU getopt info from cliOptions
286   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
287   gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
288   for (ind=0; ind < nbcmd;ind++) {
289     gnuOptions [ind].name    = cliOptions[ind].name;
290     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
291     gnuOptions [ind].flag    = 0;
292     gnuOptions [ind].val     = cliOptions[ind].val;
293   }
294
295   // get all options from command line
296   while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
297         != EOF)
298   {
299     switch (optc)
300     {
301      case SET_VERBOSE:
302        verbose = 1;
303        break;
304
305     case SET_TCP_PORT:
306        if (optarg == 0) goto needValueForOption;
307        if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
308        break;
309        
310     case SET_APITIMEOUT:
311        if (optarg == 0) goto needValueForOption;
312        if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
313        break;
314
315     case SET_CNTXTIMEOUT:
316        if (optarg == 0) goto needValueForOption;
317        if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
318        break;
319
320     case SET_ROOT_DIR:
321        if (optarg == 0) goto needValueForOption;
322        session->config->rootdir   = optarg;
323        if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
324        break;       
325        
326     case SET_ROOT_BASE:
327        if (optarg == 0) goto needValueForOption;
328        session->config->rootbase   = optarg;
329        if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
330        break;
331
332     case SET_ROOT_API:
333        if (optarg == 0) goto needValueForOption;
334        session->config->rootapi   = optarg;
335        if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
336        break;
337        
338     case SET_ALIAS:
339        if (optarg == 0) goto needValueForOption;
340        if (aliascount < MAX_ALIAS) {
341             aliasdir[aliascount].url  = strsep(&optarg,":");
342             if (optarg == NULL) {
343               fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
344             } else {
345               aliasdir[aliascount].path = optarg;
346               aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
347               if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
348               aliascount++;
349             }
350        } else {
351            fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
352        }     
353        break;
354        
355     case SET_AUTH_TOKEN:
356        if (optarg == 0) goto needValueForOption;
357        session->config->token   = optarg;
358        break;
359
360     case SET_LDPATH:
361        if (optarg == 0) goto needValueForOption;
362        session->config->ldpaths = optarg;
363        break;
364
365     case SET_SESSION_DIR:
366        if (optarg == 0) goto needValueForOption;
367        session->config->sessiondir   = optarg;
368        break;
369
370     case  SET_CACHE_TIMEOUT:
371        if (optarg == 0) goto needValueForOption;
372        if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) 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 SET_MODE:
391        if (optarg == 0) goto needValueForOption;
392        if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
393        else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
394        else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
395        else goto badMode;
396        break;
397
398     case SET_READYFD:
399        if (optarg == 0) goto needValueForOption;
400        if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
401        break;
402
403     case DISPLAY_VERSION:
404        if (optarg != 0) goto noValueForOption;
405        printVersion();
406        exit(0);
407
408     case DISPLAY_HELP:
409      default:
410        printHelp(programName);
411        exit(0);
412     }
413   }
414   free(gnuOptions);
415  
416   config_set_default  (session);
417   return;
418
419
420 needValueForOption:
421   fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
422           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
423   exit (1);
424
425 notAnInteger:
426   fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
427           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
428   exit (1);
429
430 noValueForOption:
431   fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
432           ,gnuOptions[optionIndex].name);
433   exit (1);
434
435 badMode:
436   fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
437           ,gnuOptions[optionIndex].name);
438   exit (1);
439 }
440
441 /*---------------------------------------------------------
442  | main
443  |   Parse option and launch action
444  +--------------------------------------------------------- */
445
446 int main(int argc, char *argv[])  {
447   AFB_session    *session;
448   int            consoleFD;
449   int            pid;
450
451   // open syslog if ever needed
452   openlog("afb-daemon", 0, LOG_DAEMON);
453
454   // ------------- Build session handler & init config -------
455   session = calloc (1, sizeof (AFB_session));
456   session->config = calloc (1, sizeof (AFB_config));
457
458   on_exit(closeSession, session);
459   parse_arguments(argc, argv, session);
460
461   initPlugins(session);
462
463   // ------------------ sanity check ----------------------------------------
464   if  ((session->background) && (session->foreground)) {
465     fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
466      exit (1);
467   }
468   if (session->config->httpdPort <= 0) {
469     fprintf (stderr, "ERR: no port is defined\n");
470      exit (1);
471   }
472
473   // ------------------ Some useful default values -------------------------
474   if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
475
476   // ------------------ clean exit on CTR-C signal ------------------------
477   if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
478      fprintf (stderr, "ERR: main fail to install Signal handler\n");
479      return 1;
480   }
481
482
483   // let's run this program with a low priority
484   nice (20);
485
486   // ------------------ Finaly Process Commands -----------------------------
487   // let's not take the risk to run as ROOT
488   //if (getuid() == 0)  goto errorNoRoot;
489
490   // check session dir and create if it does not exist
491   if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
492   if (verbose) fprintf (stderr, "AFB: notice Init config done\n");
493
494   // ---- run in foreground mode --------------------
495   if (session->foreground) {
496
497         if (verbose) fprintf (stderr,"AFB: notice Foreground mode\n");
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
523          // redirect default I/O on console
524          close (2); dup(consoleFD);  // redirect stderr
525          close (1); dup(consoleFD);  // redirect stdout
526          close (0);           // no need for stdin
527          close (consoleFD);
528
529          setsid();   // allow father process to fully exit
530              sleep (2);  // allow main to leave and release port
531
532          fprintf (stderr, "----------------------------\n");
533          fprintf (stderr, "INF: main background pid=%d\n", getpid());
534          fflush  (stderr);
535
536          // if everything look OK then look forever
537          syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
538
539          // should normally never return from this loop
540          listenLoop(session);
541          syslog (LOG_ERR, "AFB: FAIL background infinite loop exited check [%s]\n", session->config->console);
542
543          goto exitInitLoop;
544       }
545
546       // if fail nothing much to do
547       if (pid == -1) goto errorFork;
548
549       // we are in father process, we don't need this one
550       _exit (0);
551
552   } // end background-foreground
553
554   if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
555   exit(0);
556
557 // ------------- Fatal ERROR display error and quit  -------------
558 errorFork:
559   fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
560   exit (1);
561
562 errConsole:
563   fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
564   exit (1);
565
566 errSessiondir:
567   fprintf (stderr,"\nERR: AFB-daemon cannot read/write session dir\n\n");
568   exit (1);
569
570 exitInitLoop:
571   exit (1);
572 }
573
574