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