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