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