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