more simplification
[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 #include <stdio.h>
21 #include <string.h>
22 #include <getopt.h>
23 #include <setjmp.h>
24 #include <signal.h>
25 #include <syslog.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29
30 #include "afb-plugin.h"
31
32 #include "local-def.h"
33 #include "afb-apis.h"
34 #include "afb-hsrv.h"
35 #include "afb-hreq.h"
36 #include "session.h"
37 #include "verbose.h"
38 #include "utils-upoll.h"
39
40 #if !defined(PLUGIN_INSTALL_DIR)
41 #error "you should define PLUGIN_INSTALL_DIR"
42 #endif
43
44 #define AFB_VERSION    "0.1"
45
46 // Define command line option
47 #define SET_VERBOSE        1
48 #define SET_BACKGROUND     2
49 #define SET_FORGROUND      3
50
51 #define SET_TCP_PORT       5
52 #define SET_ROOT_DIR       6
53 #define SET_ROOT_BASE      7
54 #define SET_ROOT_API       8
55 #define SET_ALIAS          9
56
57 #define SET_CACHE_TIMEOUT  10
58 #define SET_SESSION_DIR    11
59
60 #define SET_AUTH_TOKEN     12
61 #define SET_LDPATH         13
62 #define SET_APITIMEOUT     14
63 #define SET_CNTXTIMEOUT    15
64
65 #define DISPLAY_VERSION    16
66 #define DISPLAY_HELP       17
67
68 #define SET_MODE           18
69 #define SET_READYFD        19
70
71 static struct afb_hsrv *start(AFB_config * config);
72
73 // Command line structure hold cli --command + help text
74 typedef struct {
75   int  val;        // command number within application
76   int  has_arg;    // command number within application
77   char *name;      // command as used in --xxxx cli
78   char *help;      // help text
79 } AFB_options;
80
81
82 // Supported option
83 static  AFB_options cliOptions [] = {
84   {SET_VERBOSE      ,0,"verbose"         , "Verbose Mode"},
85
86   {SET_FORGROUND    ,0,"foreground"      , "Get all in foreground mode"},
87   {SET_BACKGROUND   ,0,"daemon"          , "Get all in background mode"},
88
89   {SET_TCP_PORT     ,1,"port"            , "HTTP listening TCP port  [default 1234]"},
90   {SET_ROOT_DIR     ,1,"rootdir"         , "HTTP Root Directory [default $HOME/.AFB]"},
91   {SET_ROOT_BASE    ,1,"rootbase"        , "Angular Base Root URL [default /opa]"},
92   {SET_ROOT_API     ,1,"rootapi"         , "HTML Root API URL [default /api]"},
93   {SET_ALIAS        ,1,"alias"           , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
94   
95   {SET_APITIMEOUT   ,1,"apitimeout"      , "Plugin API timeout in seconds [default 10]"},
96   {SET_CNTXTIMEOUT  ,1,"cntxtimeout"     , "Client Session Context Timeout [default 900]"},
97   {SET_CACHE_TIMEOUT,1,"cache-eol"       , "Client cache end of live [default 3600s]"},
98   
99   {SET_SESSION_DIR  ,1,"sessiondir"      , "Sessions file path [default rootdir/sessions]"},
100
101   {SET_LDPATH       ,1,"ldpaths"         , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
102   {SET_AUTH_TOKEN   ,1,"token"           , "Initial Secret [default=no-session, --token="" for session without authentication]"},
103   
104   {DISPLAY_VERSION  ,0,"version"         , "Display version and copyright"},
105   {DISPLAY_HELP     ,0,"help"            , "Display this help"},
106
107   {SET_MODE         ,1,"mode"            , "set the mode: either local, remote or global"},
108   {SET_READYFD      ,1,"readyfd"         , "set the #fd to signal when ready"},
109   {0, 0, NULL, NULL}
110  };
111
112 static AFB_aliasdir aliasdir[MAX_ALIAS];
113 static int aliascount = 0;
114
115
116 /*----------------------------------------------------------
117  | printversion
118  |   print version and copyright
119  +--------------------------------------------------------- */
120 static void printVersion (void)
121 {
122    fprintf (stderr,"\n----------------------------------------- \n");
123    fprintf (stderr,"|  AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
124    fprintf (stderr,"----------------------------------------- \n");
125    fprintf (stderr,"|  Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
126    fprintf (stderr,"|  AFB comes with ABSOLUTELY NO WARRANTY.\n");
127    fprintf (stderr,"|  Licence Apache 2\n\n");
128    exit (0);
129 }
130
131 // load config from disk and merge with CLI option
132 static void config_set_default (AFB_config * config)
133 {
134    // default HTTP port
135    if (config->httpdPort == 0)
136         config->httpdPort = 1234;
137    
138    // default Plugin API timeout
139    if (config->apiTimeout == 0)
140         config->apiTimeout = DEFLT_API_TIMEOUT;
141    
142    // default AUTH_TOKEN
143    if (config->token == NULL)
144                 config->token = DEFLT_AUTH_TOKEN;
145
146    // cache timeout default one hour
147    if (config->cacheTimeout == 0)
148                 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
149
150    // cache timeout default one hour
151    if (config->cntxTimeout == 0)
152                 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
153
154    if (config->rootdir == NULL) {
155        config->rootdir = getenv("AFBDIR");
156        if (config->rootdir == NULL) {
157            config->rootdir = malloc (512);
158            strncpy (config->rootdir, getenv("HOME"),512);
159            strncat (config->rootdir, "/.AFB",512);
160        }
161        // if directory does not exist createit
162        mkdir (config->rootdir,  O_RDWR | S_IRWXU | S_IRGRP);
163    }
164    
165    // if no Angular/HTML5 rootbase let's try '/' as default
166    if  (config->rootbase == NULL)
167        config->rootbase = "/opa";
168    
169    if  (config->rootapi == NULL)
170        config->rootapi = "/api";
171
172    if  (config->ldpaths == NULL)
173        config->ldpaths = PLUGIN_INSTALL_DIR;
174
175    // if no session dir create a default path from rootdir
176    if  (config->sessiondir == NULL) {
177        config->sessiondir = malloc (512);
178        strncpy (config->sessiondir, config->rootdir, 512);
179        strncat (config->sessiondir, "/sessions",512);
180    }
181
182    // if no config dir create a default path from sessiondir
183    if  (config->console == NULL) {
184        config->console = malloc (512);
185        strncpy (config->console, config->sessiondir, 512);
186        strncat (config->console, "/AFB-console.out",512);
187    }
188 }
189
190
191 /*----------------------------------------------------------
192  | printHelp
193  |   print information from long option array
194  +--------------------------------------------------------- */
195
196  static void printHelp(char *name) {
197     int ind;
198     char command[20];
199
200     fprintf (stderr,"%s:\nallowed options\n", name);
201     for (ind=0; cliOptions [ind].name != NULL;ind++)
202     {
203       // display options
204       if (cliOptions [ind].has_arg == 0 )
205       {
206              fprintf (stderr,"  --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
207       } else {
208          sprintf(command,"%s=xxxx", cliOptions [ind].name);
209          fprintf (stderr,"  --%-15s %s\n", command, cliOptions[ind].help);
210       }
211     }
212     fprintf (stderr,"Example:\n  %s\\\n  --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
213 } // end printHelp
214
215 /*---------------------------------------------------------
216  | main
217  |   Parse option and launch action
218  +--------------------------------------------------------- */
219
220 static void parse_arguments(int argc, char *argv[], AFB_session *session)
221 {
222   char*          programName = argv [0];
223   int            optionIndex = 0;
224   int            optc, ind;
225   int            nbcmd;
226   struct option *gnuOptions;
227
228   // ------------- Build session handler & init config -------
229   memset(&aliasdir  ,0,sizeof(aliasdir));
230   session->config->aliasdir = aliasdir;
231
232   // ------------------ Process Command Line -----------------------
233
234   // if no argument print help and return
235   if (argc < 2) {
236        printHelp(programName);
237        exit(1);
238   }
239
240   // build GNU getopt info from cliOptions
241   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
242   gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
243   for (ind=0; ind < nbcmd;ind++) {
244     gnuOptions [ind].name    = cliOptions[ind].name;
245     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
246     gnuOptions [ind].flag    = 0;
247     gnuOptions [ind].val     = cliOptions[ind].val;
248   }
249
250   // get all options from command line
251   while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
252         != EOF)
253   {
254     switch (optc)
255     {
256      case SET_VERBOSE:
257        verbosity++;
258        break;
259
260     case SET_TCP_PORT:
261        if (optarg == 0) goto needValueForOption;
262        if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
263        break;
264        
265     case SET_APITIMEOUT:
266        if (optarg == 0) goto needValueForOption;
267        if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
268        break;
269
270     case SET_CNTXTIMEOUT:
271        if (optarg == 0) goto needValueForOption;
272        if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
273        break;
274
275     case SET_ROOT_DIR:
276        if (optarg == 0) goto needValueForOption;
277        session->config->rootdir   = optarg;
278        if (verbosity) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
279        break;       
280        
281     case SET_ROOT_BASE:
282        if (optarg == 0) goto needValueForOption;
283        session->config->rootbase   = optarg;
284        if (verbosity) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
285        break;
286
287     case SET_ROOT_API:
288        if (optarg == 0) goto needValueForOption;
289        session->config->rootapi   = optarg;
290        if (verbosity) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
291        break;
292        
293     case SET_ALIAS:
294        if (optarg == 0) goto needValueForOption;
295        if (aliascount < MAX_ALIAS) {
296             aliasdir[aliascount].url  = strsep(&optarg,":");
297             if (optarg == NULL) {
298               fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
299             } else {
300               aliasdir[aliascount].path = optarg;
301               aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
302               if (verbosity) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
303               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        session->config->token   = optarg;
313        break;
314
315     case SET_LDPATH:
316        if (optarg == 0) goto needValueForOption;
317        session->config->ldpaths = optarg;
318        break;
319
320     case SET_SESSION_DIR:
321        if (optarg == 0) goto needValueForOption;
322        session->config->sessiondir   = optarg;
323        break;
324
325     case  SET_CACHE_TIMEOUT:
326        if (optarg == 0) goto needValueForOption;
327        if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
328        break;
329
330     case SET_FORGROUND:
331        if (optarg != 0) goto noValueForOption;
332        session->background  = 0;
333        break;
334
335     case SET_BACKGROUND:
336        if (optarg != 0) goto noValueForOption;
337        session->background  = 1;
338        break;
339
340     case SET_MODE:
341        if (optarg == 0) goto needValueForOption;
342        if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
343        else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
344        else if (!strcmp(optarg, "global")) session->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", &session->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  (session->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         /* AFB_session *session = 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(AFB_session *session)
448 {
449   int            consoleFD;
450   int            pid;
451
452       // open /dev/console to redirect output messAFBes
453       consoleFD = open(session->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      printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->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  | main
492  |   Parse option and launch action
493  +--------------------------------------------------------- */
494
495 int main(int argc, char *argv[])  {
496   AFB_session    *session;
497   struct afb_hsrv *hsrv;
498
499   // open syslog if ever needed
500   openlog("afb-daemon", 0, LOG_DAEMON);
501
502   // ------------- Build session handler & init config -------
503   session = calloc (1, sizeof (AFB_session));
504   session->config = calloc (1, sizeof (AFB_config));
505
506   on_exit(closeSession, session);
507   parse_arguments(argc, argv, session);
508
509   // ------------------ sanity check ----------------------------------------
510   if (session->config->httpdPort <= 0) {
511     fprintf (stderr, "ERR: no port is defined\n");
512      exit (1);
513   }
514
515   if (session->config->ldpaths) 
516     afb_apis_add_pathset(session->config->ldpaths);
517
518   ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, afb_apis_count(), session->config->token);
519
520   install_error_handlers();
521
522   // ------------------ clean exit on CTR-C signal ------------------------
523   if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
524      fprintf (stderr, "ERR: main fail to install Signal handler\n");
525      return 1;
526   }
527
528   // let's run this program with a low priority
529   nice (20);
530
531   // ------------------ Finaly Process Commands -----------------------------
532   // let's not take the risk to run as ROOT
533   //if (getuid() == 0)  goto errorNoRoot;
534
535   if (verbosity) fprintf (stderr, "AFB: notice Init config done\n");
536
537   // --------- run -----------
538   if (session->background) {
539       // --------- in background mode -----------
540       if (verbosity) printf ("AFB: Entering background mode\n");
541       daemonize(session);
542   } else {
543       // ---- in foreground mode --------------------
544       if (verbosity) fprintf (stderr,"AFB: notice Foreground mode\n");
545
546   }
547
548    hsrv = start (session->config);
549    if (hsrv == NULL)
550         exit(1);
551
552    if (session->readyfd != 0) {
553                 static const char readystr[] = "READY=1";
554                 write(session->readyfd, readystr, sizeof(readystr) - 1);
555                 close(session->readyfd);
556   }
557
558    // infinite loop
559   for(;;)
560     upoll_wait(30000); 
561
562    if (verbosity)
563        fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
564
565   return 0;
566 }
567
568 static int init(struct afb_hsrv *hsrv, AFB_config * config)
569 {
570         int idx;
571
572         if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hreq_websocket_switch, NULL, 20))
573                 return 0;
574
575         if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hreq_rest_api, NULL, 10))
576                 return 0;
577
578         for (idx = 0; config->aliasdir[idx].url != NULL; idx++)
579                 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0))
580                         return 0;
581
582         if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10))
583                 return 0;
584
585         if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hreq_one_page_api_redirect, NULL, -20))
586                 return 0;
587
588         return 1;
589 }
590
591 static struct afb_hsrv *start(AFB_config * config)
592 {
593         int rc;
594         struct afb_hsrv *hsrv;
595
596         hsrv = afb_hsrv_create();
597         if (hsrv == NULL) {
598                 fprintf(stderr, "memory allocation failure\n");
599                 return NULL;
600         }
601
602         if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
603         || !init(hsrv, config)) {
604                 printf("Error: initialisation of httpd failed");
605                 afb_hsrv_put(hsrv);
606                 return NULL;
607         }
608
609         if (verbosity) {
610                 printf("AFB:notice Waiting port=%d rootdir=%s\n", config->httpdPort, config->rootdir);
611                 printf("AFB:notice Browser URL= http:/*localhost:%d\n", config->httpdPort);
612         }
613
614         rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
615         if (!rc) {
616                 printf("Error: starting of httpd failed");
617                 afb_hsrv_put(hsrv);
618                 return NULL;
619         }
620
621         return hsrv;
622 }
623
624