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