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