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