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