session: moves initialisation to main
[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  | main
211  |   Parse option and launch action
212  +--------------------------------------------------------- */
213
214 static void parse_arguments(int argc, char *argv[], AFB_session *session)
215 {
216   char*          programName = argv [0];
217   int            optionIndex = 0;
218   int            optc, ind;
219   int            nbcmd;
220   struct option *gnuOptions;
221
222   // ------------- Build session handler & init config -------
223   memset(&aliasdir  ,0,sizeof(aliasdir));
224   session->config->aliasdir = aliasdir;
225
226   // ------------------ Process Command Line -----------------------
227
228   // if no argument print help and return
229   if (argc < 2) {
230        printHelp(programName);
231        exit(1);
232   }
233
234   // build GNU getopt info from cliOptions
235   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
236   gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
237   for (ind=0; ind < nbcmd;ind++) {
238     gnuOptions [ind].name    = cliOptions[ind].name;
239     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
240     gnuOptions [ind].flag    = 0;
241     gnuOptions [ind].val     = cliOptions[ind].val;
242   }
243
244   // get all options from command line
245   while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
246         != EOF)
247   {
248     switch (optc)
249     {
250      case SET_VERBOSE:
251        verbose = 1;
252        break;
253
254     case SET_TCP_PORT:
255        if (optarg == 0) goto needValueForOption;
256        if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
257        break;
258        
259     case SET_APITIMEOUT:
260        if (optarg == 0) goto needValueForOption;
261        if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
262        break;
263
264     case SET_CNTXTIMEOUT:
265        if (optarg == 0) goto needValueForOption;
266        if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
267        break;
268
269     case SET_ROOT_DIR:
270        if (optarg == 0) goto needValueForOption;
271        session->config->rootdir   = optarg;
272        if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
273        break;       
274        
275     case SET_ROOT_BASE:
276        if (optarg == 0) goto needValueForOption;
277        session->config->rootbase   = optarg;
278        if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
279        break;
280
281     case SET_ROOT_API:
282        if (optarg == 0) goto needValueForOption;
283        session->config->rootapi   = optarg;
284        if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
285        break;
286        
287     case SET_ALIAS:
288        if (optarg == 0) goto needValueForOption;
289        if (aliascount < MAX_ALIAS) {
290             aliasdir[aliascount].url  = strsep(&optarg,":");
291             if (optarg == NULL) {
292               fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
293             } else {
294               aliasdir[aliascount].path = optarg;
295               aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
296               if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
297               aliascount++;
298             }
299        } else {
300            fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
301        }     
302        break;
303        
304     case SET_AUTH_TOKEN:
305        if (optarg == 0) goto needValueForOption;
306        session->config->token   = optarg;
307        break;
308
309     case SET_LDPATH:
310        if (optarg == 0) goto needValueForOption;
311        session->config->ldpaths = optarg;
312        break;
313
314     case SET_SESSION_DIR:
315        if (optarg == 0) goto needValueForOption;
316        session->config->sessiondir   = optarg;
317        break;
318
319     case  SET_CACHE_TIMEOUT:
320        if (optarg == 0) goto needValueForOption;
321        if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
322        break;
323
324     case SET_FAKE_MOD:
325        if (optarg != 0) goto noValueForOption;
326        session->fakemod  = 1;
327        break;
328
329     case SET_FORGROUND:
330        if (optarg != 0) goto noValueForOption;
331        session->foreground  = 1;
332        break;
333
334     case SET_BACKGROUND:
335        if (optarg != 0) goto noValueForOption;
336        session->background  = 1;
337        break;
338
339     case SET_MODE:
340        if (optarg == 0) goto needValueForOption;
341        if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
342        else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
343        else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
344        else goto badMode;
345        break;
346
347     case SET_READYFD:
348        if (optarg == 0) goto needValueForOption;
349        if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
350        break;
351
352     case DISPLAY_VERSION:
353        if (optarg != 0) goto noValueForOption;
354        printVersion();
355        exit(0);
356
357     case DISPLAY_HELP:
358      default:
359        printHelp(programName);
360        exit(0);
361     }
362   }
363   free(gnuOptions);
364  
365   config_set_default  (session);
366   return;
367
368
369 needValueForOption:
370   fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
371           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
372   exit (1);
373
374 notAnInteger:
375   fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
376           ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
377   exit (1);
378
379 noValueForOption:
380   fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
381           ,gnuOptions[optionIndex].name);
382   exit (1);
383
384 badMode:
385   fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
386           ,gnuOptions[optionIndex].name);
387   exit (1);
388 }
389
390 /*----------------------------------------------------------
391  | closeSession
392  |   try to close everything before leaving
393  +--------------------------------------------------------- */
394 static void closeSession (int status, void *data) {
395         /* AFB_session *session = data; */
396 }
397
398 /*----------------------------------------------------------
399  | timeout signalQuit
400  |
401  +--------------------------------------------------------- */
402 void signalQuit (int signum) {
403
404   sigset_t sigset;
405
406   // unlock timeout signal to allow a new signal to come
407   sigemptyset (&sigset);
408   sigaddset   (&sigset, SIGABRT);
409   sigprocmask (SIG_UNBLOCK, &sigset, 0);
410
411   fprintf (stderr, "ERR: Received signal quit\n");
412   syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
413   exit(1);
414 }
415
416
417 /*----------------------------------------------------------
418  | listenLoop
419  |   Main listening HTTP loop
420  +--------------------------------------------------------- */
421 static void listenLoop (AFB_session *session) {
422   AFB_error  err;
423
424   // ------ Start httpd server
425
426    err = httpdStart (session);
427    if (err != AFB_SUCCESS) return;
428
429         if (session->readyfd != 0) {
430                 static const char readystr[] = "READY=1";
431                 write(session->readyfd, readystr, sizeof(readystr) - 1);
432                 close(session->readyfd);
433         }
434
435    // infinite loop
436    httpdLoop(session);
437
438    fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
439 }
440   
441 /*----------------------------------------------------------
442  | daemonize
443  |   set the process in background
444  +--------------------------------------------------------- */
445 static void daemonize(AFB_session *session)
446 {
447   int            consoleFD;
448   int            pid;
449
450       // open /dev/console to redirect output messAFBes
451       consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
452       if (consoleFD < 0) {
453                 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
454                 exit (1);
455       }
456
457       // fork process when running background mode
458       pid = fork ();
459
460       // if fail nothing much to do
461       if (pid == -1) {
462                 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
463                 exit (1);
464         }
465
466       // if in father process, just leave
467       if (pid != 0) _exit (0);
468
469       // son process get all data in standalone mode
470      printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
471
472       // redirect default I/O on console
473       close (2); dup(consoleFD);  // redirect stderr
474       close (1); dup(consoleFD);  // redirect stdout
475       close (0);           // no need for stdin
476       close (consoleFD);
477
478 #if 0
479          setsid();   // allow father process to fully exit
480      sleep (2);  // allow main to leave and release port
481 #endif
482
483          fprintf (stderr, "----------------------------\n");
484          fprintf (stderr, "INF: main background pid=%d\n", getpid());
485          fflush  (stderr);
486 }
487
488 /*---------------------------------------------------------
489  | main
490  |   Parse option and launch action
491  +--------------------------------------------------------- */
492
493 int main(int argc, char *argv[])  {
494   AFB_session    *session;
495
496   // open syslog if ever needed
497   openlog("afb-daemon", 0, LOG_DAEMON);
498
499   // ------------- Build session handler & init config -------
500   session = calloc (1, sizeof (AFB_session));
501   session->config = calloc (1, sizeof (AFB_config));
502
503   on_exit(closeSession, session);
504   parse_arguments(argc, argv, session);
505
506   // ------------------ sanity check ----------------------------------------
507   if  ((session->background) && (session->foreground)) {
508     fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
509      exit (1);
510   }
511   if (session->config->httpdPort <= 0) {
512     fprintf (stderr, "ERR: no port is defined\n");
513      exit (1);
514   }
515
516   initPlugins(session);
517   ctxStoreInit(CTX_NBCLIENTS);
518
519   // ------------------ Some useful default values -------------------------
520   if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
521
522   // ------------------ clean exit on CTR-C signal ------------------------
523   if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
524      fprintf (stderr, "ERR: main fail to install Signal handler\n");
525      return 1;
526   }
527
528
529   // let's run this program with a low priority
530   nice (20);
531
532   // ------------------ Finaly Process Commands -----------------------------
533   // let's not take the risk to run as ROOT
534   //if (getuid() == 0)  goto errorNoRoot;
535
536 #if defined(ALLOWS_SESSION_FILES)
537   // check session dir and create if it does not exist
538   if (sessionCheckdir (session) != AFB_SUCCESS) {
539         fprintf (stderr,"\nERR: AFB-daemon cannot read/write session dir\n\n");
540         exit (1);
541   }
542 #endif
543   if (verbose) fprintf (stderr, "AFB: notice Init config done\n");
544
545   // ---- run in foreground mode --------------------
546   if (session->foreground) {
547
548         if (verbose) fprintf (stderr,"AFB: notice Foreground mode\n");
549
550   } // end foreground
551
552   // --------- run in background mode -----------
553   if (session->background) {
554
555       if (verbose) printf ("AFB: Entering background mode\n");
556
557       daemonize(session);
558
559          // if everything look OK then look forever
560          syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
561
562
563   } // end background-foreground
564
565
566   listenLoop(session);
567   if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
568   exit(0);
569
570 }
571
572