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