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