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