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