work in progress
[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 /*
31 #include <pwd.h>
32 #include <pthread.h>
33 */
34
35 #include "local-def.h"
36 #include "afb-apis.h"
37 #include "session.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 AFB_error config_set_default (AFB_session * session)
131 {
132    static char cacheTimeout [10];
133    
134    // default HTTP port
135    if (session->config->httpdPort == 0) session->config->httpdPort=1234;
136    
137    // default Plugin API timeout
138    if (session->config->apiTimeout == 0) session->config->apiTimeout=DEFLT_API_TIMEOUT;
139    
140    // default AUTH_TOKEN
141    if (session->config->token == NULL) session->config->token= DEFLT_AUTH_TOKEN;
142
143    // cache timeout default one hour
144    if (session->config->cacheTimeout == 0) session->config->cacheTimeout=DEFLT_CACHE_TIMEOUT;
145
146    // cache timeout default one hour
147    if (session->config->cntxTimeout == 0) session->config->cntxTimeout=DEFLT_CNTX_TIMEOUT;
148
149    if (session->config->rootdir == NULL) {
150        session->config->rootdir = getenv("AFBDIR");
151        if (session->config->rootdir == NULL) {
152            session->config->rootdir = malloc (512);
153            strncpy  (session->config->rootdir, getenv("HOME"),512);
154            strncat (session->config->rootdir, "/.AFB",512);
155        }
156        // if directory does not exist createit
157        mkdir (session->config->rootdir,  O_RDWR | S_IRWXU | S_IRGRP);
158    }
159    
160    // if no Angular/HTML5 rootbase let's try '/' as default
161    if  (session->config->rootbase == NULL) {
162        session->config->rootbase = "/opa";
163    }
164    
165    if  (session->config->rootapi == NULL) {
166        session->config->rootapi = "/api";
167    }
168
169    if  (session->config->ldpaths == NULL) {
170        session->config->ldpaths = PLUGIN_INSTALL_DIR;
171    }
172
173    // if no session dir create a default path from rootdir
174    if  (session->config->sessiondir == NULL) {
175        session->config->sessiondir = malloc (512);
176        strncpy (session->config->sessiondir, session->config->rootdir, 512);
177        strncat (session->config->sessiondir, "/sessions",512);
178    }
179
180    // if no config dir create a default path from sessiondir
181    if  (session->config->console == NULL) {
182        session->config->console = malloc (512);
183        strncpy (session->config->console, session->config->sessiondir, 512);
184        strncat (session->config->console, "/AFB-console.out",512);
185    }
186
187    // cacheTimeout is an integer but HTTPd wants it as a string
188    snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
189    session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
190
191    return AFB_SUCCESS;
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        verbose = 1;
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 (verbose) 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 (verbose) 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 (verbose) 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 (verbose) 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  +--------------------------------------------------------- */
412 void signalQuit (int signum) {
413
414   sigset_t sigset;
415
416   // unlock timeout signal to allow a new signal to come
417   sigemptyset (&sigset);
418   sigaddset   (&sigset, SIGABRT);
419   sigprocmask (SIG_UNBLOCK, &sigset, 0);
420
421   fprintf (stderr, "ERR: Received signal quit\n");
422   syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
423   exit(1);
424 }
425
426
427 /*----------------------------------------------------------
428  | Error signals
429  |
430  +--------------------------------------------------------- */
431 __thread sigjmp_buf *error_handler;
432 static void signalError(int signum)
433 {
434         sigset_t sigset;
435
436         // unlock signal to allow a new signal to come
437         if (error_handler != NULL) {
438                 sigemptyset(&sigset);
439                 sigaddset(&sigset, signum);
440                 sigprocmask(SIG_UNBLOCK, &sigset, 0);
441                 longjmp(*error_handler, signum);
442         }
443 }
444
445 static void install_error_handlers()
446 {
447         int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
448
449         for (i = 0; signals[i] != 0; i++) {
450                 if (signal(signals[i], signalError) == SIG_ERR) {
451                         fprintf(stderr, "Signal handler error\n");
452                         exit(1);
453                 }
454         }
455 }
456
457 /*----------------------------------------------------------
458  | listenLoop
459  |   Main listening HTTP loop
460  +--------------------------------------------------------- */
461 static void listenLoop (AFB_session *session) {
462   AFB_error  err;
463
464   // ------ Start httpd server
465
466    err = httpdStart (session);
467    if (err != AFB_SUCCESS) return;
468
469         if (session->readyfd != 0) {
470                 static const char readystr[] = "READY=1";
471                 write(session->readyfd, readystr, sizeof(readystr) - 1);
472                 close(session->readyfd);
473         }
474
475    // infinite loop
476    httpdLoop(session);
477
478    fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
479 }
480   
481 /*----------------------------------------------------------
482  | daemonize
483  |   set the process in background
484  +--------------------------------------------------------- */
485 static void daemonize(AFB_session *session)
486 {
487   int            consoleFD;
488   int            pid;
489
490       // open /dev/console to redirect output messAFBes
491       consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
492       if (consoleFD < 0) {
493                 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
494                 exit (1);
495       }
496
497       // fork process when running background mode
498       pid = fork ();
499
500       // if fail nothing much to do
501       if (pid == -1) {
502                 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
503                 exit (1);
504         }
505
506       // if in father process, just leave
507       if (pid != 0) _exit (0);
508
509       // son process get all data in standalone mode
510      printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
511
512       // redirect default I/O on console
513       close (2); dup(consoleFD);  // redirect stderr
514       close (1); dup(consoleFD);  // redirect stdout
515       close (0);           // no need for stdin
516       close (consoleFD);
517
518 #if 0
519          setsid();   // allow father process to fully exit
520      sleep (2);  // allow main to leave and release port
521 #endif
522
523          fprintf (stderr, "----------------------------\n");
524          fprintf (stderr, "INF: main background pid=%d\n", getpid());
525          fflush  (stderr);
526 }
527
528 /*---------------------------------------------------------
529  | main
530  |   Parse option and launch action
531  +--------------------------------------------------------- */
532
533 int main(int argc, char *argv[])  {
534   AFB_session    *session;
535
536   // open syslog if ever needed
537   openlog("afb-daemon", 0, LOG_DAEMON);
538
539   // ------------- Build session handler & init config -------
540   session = calloc (1, sizeof (AFB_session));
541   session->config = calloc (1, sizeof (AFB_config));
542
543   on_exit(closeSession, session);
544   parse_arguments(argc, argv, session);
545
546   // ------------------ sanity check ----------------------------------------
547   if  ((session->background) && (session->foreground)) {
548     fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
549      exit (1);
550   }
551   if (session->config->httpdPort <= 0) {
552     fprintf (stderr, "ERR: no port is defined\n");
553      exit (1);
554   }
555
556   if (session->config->ldpaths) 
557     afb_apis_add_pathset(session->config->ldpaths);
558
559   ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, afb_apis_count(), session->config->token);
560
561   install_error_handlers();
562
563   // ------------------ Some useful default values -------------------------
564   if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
565
566   // ------------------ clean exit on CTR-C signal ------------------------
567   if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
568      fprintf (stderr, "ERR: main fail to install Signal handler\n");
569      return 1;
570   }
571
572
573   // let's run this program with a low priority
574   nice (20);
575
576   // ------------------ Finaly Process Commands -----------------------------
577   // let's not take the risk to run as ROOT
578   //if (getuid() == 0)  goto errorNoRoot;
579
580 #if defined(ALLOWS_SESSION_FILES)
581   // check session dir and create if it does not exist
582   if (sessionCheckdir (session) != AFB_SUCCESS) {
583         fprintf (stderr,"\nERR: AFB-daemon cannot read/write session dir\n\n");
584         exit (1);
585   }
586 #endif
587   if (verbose) fprintf (stderr, "AFB: notice Init config done\n");
588
589   // ---- run in foreground mode --------------------
590   if (session->foreground) {
591
592         if (verbose) fprintf (stderr,"AFB: notice Foreground mode\n");
593
594   } // end foreground
595
596   // --------- run in background mode -----------
597   if (session->background) {
598
599       if (verbose) printf ("AFB: Entering background mode\n");
600
601       daemonize(session);
602
603          // if everything look OK then look forever
604          syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
605
606
607   } // end background-foreground
608
609
610   listenLoop(session);
611   if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
612   exit(0);
613
614 }
615
616