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