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