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