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