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