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