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