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