afb-hreq: creation of hreq classe
[src/app-framework-binder.git] / src / main.c
index b681bd0..40f28c1 100644 (file)
 #include <setjmp.h>
 #include <signal.h>
 #include <getopt.h>
+#include <pwd.h>
 
-static sigjmp_buf exitpoint; // context save for set/longjmp
-static sigjmp_buf restartpoint; // context save for set/longjmp
+#define AFB_VERSION    "0.1"
+
+static sigjmp_buf exitPoint; // context save for set/longjmp
 
 /*----------------------------------------------------------
  | printversion
@@ -40,7 +42,7 @@ static sigjmp_buf restartpoint; // context save for set/longjmp
  static void printVersion (void) {
 
    fprintf (stderr,"\n----------------------------------------- \n");
-   fprintf (stderr,"|  AFB [Application Framework Binder] version=%s |\n", AJQ_VERSION);
+   fprintf (stderr,"|  AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
    fprintf (stderr,"----------------------------------------- \n");
    fprintf (stderr,"|  Copyright(C) 2015 Fulup Ar Foll /IoT.bzh [fulup -at- iot.bzh]\n");
    fprintf (stderr,"|  AFB comes with ABSOLUTELY NO WARRANTY.\n");
@@ -50,33 +52,45 @@ static sigjmp_buf restartpoint; // context save for set/longjmp
 
 
 // Define command line option
- #define SET_VERBOSE        101
- #define SET_BACKGROUND     105
- #define SET_FORGROUND      106
- #define KILL_PREV_EXIT     107
- #define KILL_PREV_REST     108
- #define SET_FAKE_MOD       109
-
- #define SET_TCP_PORT       120
- #define SET_ROOT_DIR       121
- #define SET_ROOT_BASE      122
- #define SET_ROOT_API       123
- #define SET_ROOT_ALIAS     124
-
- #define SET_CACHE_TO       130
- #define SET_cardid         131
- #define SET_PID_FILE       132
- #define SET_SESSION_DIR    133
- #define SET_CONFIG_FILE    134
- #define SET_CONFIG_SAVE    135
- #define SET_CONFIG_EXIT    138
-
- #define SET_SMACK          140
- #define SET_PLUGINS        141
- #define SET_APITIMEOUT     142
-
- #define DISPLAY_VERSION    150
- #define DISPLAY_HELP       151
+#define SET_VERBOSE        101
+#define SET_BACKGROUND     105
+#define SET_FORGROUND      106
+#define KILL_PREV_EXIT     107
+#define KILL_PREV_REST     108
+#define SET_FAKE_MOD       109
+
+#define SET_TCP_PORT       120
+#define SET_ROOT_DIR       121
+#define SET_ROOT_BASE      122
+#define SET_ROOT_API       123
+#define SET_ROOT_ALIAS     124
+
+#define SET_CACHE_TO       130
+#define SET_USERID         131
+#define SET_PID_FILE       132
+#define SET_SESSION_DIR    133
+#define SET_CONFIG_FILE    134
+#define SET_CONFIG_SAVE    135
+#define SET_CONFIG_EXIT    138
+
+#define SET_AUTH_TOKEN     141
+#define SET_LDPATH         142
+#define SET_APITIMEOUT     143
+#define SET_CNTXTIMEOUT    144
+
+#define DISPLAY_VERSION    150
+#define DISPLAY_HELP       151
+
+#define SET_MODE           160
+#define SET_READYFD        161
+
+// Command line structure hold cli --command + help text
+typedef struct {
+  int  val;        // command number within application
+  int  has_arg;    // command number within application
+  char *name;      // command as used in --xxxx cli
+  char *help;      // help text
+} AFB_options;
 
 
 // Supported option
@@ -89,47 +103,41 @@ static  AFB_options cliOptions [] = {
   {KILL_PREV_REST   ,0,"restart"         , "Kill active process if any and restart"},
 
   {SET_TCP_PORT     ,1,"port"            , "HTTP listening TCP port  [default 1234]"},
-  {SET_ROOT_DIR     ,1,"rootdir"         , "HTTP Root Directory [default $HOME/.AFB"},
-  {SET_ROOT_BASE    ,1,"rootbase"        , "Angular Base Root URL [default /opa"},
-  {SET_ROOT_API     ,1,"rootapi"         , "HTML Root API URL [default /api"},
+  {SET_ROOT_DIR     ,1,"rootdir"         , "HTTP Root Directory [default $HOME/.AFB]"},
+  {SET_ROOT_BASE    ,1,"rootbase"        , "Angular Base Root URL [default /opa]"},
+  {SET_ROOT_API     ,1,"rootapi"         , "HTML Root API URL [default /api]"},
   {SET_ROOT_ALIAS   ,1,"alias"           , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
+  
   {SET_APITIMEOUT   ,1,"apitimeout"      , "Plugin API timeout in seconds [default 10]"},
-
+  {SET_CNTXTIMEOUT  ,1,"cntxtimeout"     , "Client Session Context Timeout [default 900]"},
   {SET_CACHE_TO     ,1,"cache-eol"       , "Client cache end of live [default 3600s]"},
-  {SET_cardid       ,1,"setuid"          , "Change user id [default don't change]"},
+  
+  {SET_USERID       ,1,"setuid"          , "Change user id [default don't change]"},
   {SET_PID_FILE     ,1,"pidfile"         , "PID file path [default none]"},
   {SET_SESSION_DIR  ,1,"sessiondir"      , "Sessions file path [default rootdir/sessions]"},
   {SET_CONFIG_FILE  ,1,"config"          , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
   {SET_CONFIG_SAVE  ,0,"save"            , "Save config on disk [default no]"},
   {SET_CONFIG_EXIT  ,0,"saveonly"        , "Save config on disk and then exit"},
 
-  {SET_SMACK        ,1,"smack"           , "Set Smack Label [default=demo"},
-  {SET_PLUGINS      ,1,"mods"            , "Enable module [default=all"},
+  {SET_LDPATH       ,1,"ldpaths"         , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
+  {SET_AUTH_TOKEN   ,1,"token"           , "Initial Secret [default=no-session, --token="" for session without authentication]"},
   
   {DISPLAY_VERSION  ,0,"version"         , "Display version and copyright"},
   {DISPLAY_HELP     ,0,"help"            , "Display this help"},
-  {0, 0, 0}
+
+  {SET_MODE         ,1,"mode"            , "set the mode: either local, remote or global"},
+  {SET_READYFD      ,1,"readyfd"         , "set the #fd to signal when ready"},
+  {0, 0, NULL, NULL}
  };
 
 static AFB_aliasdir aliasdir[MAX_ALIAS];
 static int aliascount=0;
 
-/*----------------------------------------------------------
- | signalQuit
- |  return to intitial exitpoint on order to close backend
- |  before exiting.
- +--------------------------------------------------------- */
-void signalQuit (int signum)
-{
-  if (verbose) printf ("INF:signalQuit received signal to quit\n");
-  longjmp (exitpoint, signum);
-}
-
 /*----------------------------------------------------------
  | timeout signalQuit
  |
  +--------------------------------------------------------- */
-void signalFail (int signum) {
+void signalQuit (int signum) {
 
   sigset_t sigset;
 
@@ -138,9 +146,9 @@ void signalFail (int signum) {
   sigaddset   (&sigset, SIGABRT);
   sigprocmask (SIG_UNBLOCK, &sigset, 0);
 
-  fprintf (stderr, "%s ERR:getAllBlock acquisition timeout\n",configTime());
-  syslog (LOG_ERR, "Daemon fail and restart [please report bug]");
-  longjmp (restartpoint, signum);
+  fprintf (stderr, "%s ERR:Received signal quit\n",configTime());
+  syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
+  longjmp (exitPoint, signum);
 }
 
 
@@ -165,7 +173,7 @@ void signalFail (int signum) {
          fprintf (stderr,"  --%-15s %s\n", command, cliOptions[ind].help);
       }
     }
-    fprintf (stderr,"Example:\n  %s\\\n  --verbose --port=1234 --smack=xxxx --mods=alsa:dbus\n", name);
+    fprintf (stderr,"Example:\n  %s\\\n  --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
 } // end printHelp
 
 /*----------------------------------------------------------
@@ -228,7 +236,6 @@ static void closeSession (AFB_session *session) {
 
 }
 
-
 /*----------------------------------------------------------
  | listenLoop
  |   Main listening HTTP loop
@@ -236,7 +243,7 @@ static void closeSession (AFB_session *session) {
 static void listenLoop (AFB_session *session) {
   AFB_error  err;
 
-  if (signal (SIGABRT, signalFail) == SIG_ERR) {
+  if (signal (SIGABRT, signalQuit) == SIG_ERR) {
         fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
         return;
   }
@@ -247,48 +254,49 @@ static void listenLoop (AFB_session *session) {
         err = httpdStart (session);
         if (err != AFB_SUCCESS) return;
 
+       if (session->readyfd != 0) {
+               static const char readystr[] = "READY=1";
+               write(session->readyfd, readystr, sizeof(readystr) - 1);
+               close(session->readyfd);
+       }
+
         // infinite loop
         httpdLoop(session);
 
         fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
   }
 }
-
-
+  
 /*---------------------------------------------------------
  | main
  |   Parse option and launch action
  +--------------------------------------------------------- */
 
-int main(int argc, char *argv[])  {
-  AFB_session    *session;
+static void parse_arguments(int argc, char *argv[], AFB_session *session)
+{
   char*          programName = argv [0];
   int            optionIndex = 0;
-  int            optc, ind, consoleFD;
-  int            pid, nbcmd, status;
+  int            optc, ind;
+  int            nbcmd;
+  struct option *gnuOptions;
   AFB_config     cliconfig; // temp structure to store CLI option before file config upload
 
   // ------------- Build session handler & init config -------
-  session =  configInit ();
   memset(&cliconfig,0,sizeof(cliconfig));
   memset(&aliasdir  ,0,sizeof(aliasdir));
   cliconfig.aliasdir = aliasdir;
 
-  // GNU CLI getopts nterface.
-  struct option ggcOption;
-  struct option *gnuOptions;
-
   // ------------------ Process Command Line -----------------------
 
   // if no argument print help and return
   if (argc < 2) {
        printHelp(programName);
-       return (-1);
+       exit(1);
   }
 
   // build GNU getopt info from cliOptions
   nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
-  gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
+  gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
   for (ind=0; ind < nbcmd;ind++) {
     gnuOptions [ind].name    = cliOptions[ind].name;
     gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
@@ -316,6 +324,11 @@ int main(int argc, char *argv[])  {
        if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
        break;
 
+    case SET_CNTXTIMEOUT:
+       if (optarg == 0) goto needValueForOption;
+       if (!sscanf (optarg, "%d", &cliconfig.cntxTimeout)) goto notAnInteger;
+       break;
+
     case SET_ROOT_DIR:
        if (optarg == 0) goto needValueForOption;
        cliconfig.rootdir   = optarg;
@@ -338,27 +351,27 @@ int main(int argc, char *argv[])  {
        if (optarg == 0) goto needValueForOption;
        if (aliascount < MAX_ALIAS) {
             aliasdir[aliascount].url  = strsep(&optarg,":");
-            aliasdir[aliascount].path = strsep(&optarg,":");
-            aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
-            if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
-            aliascount++;
+            if (optarg == NULL) {
+              fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
+            } else {
+              aliasdir[aliascount].path = optarg;
+              aliasdir[aliascount].len  = strlen(aliasdir[aliascount].url);
+              if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
+              aliascount++;
+            }
        } else {
-           fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
-       }
-       
-      
+           fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
+       }     
        break;
        
-    case SET_SMACK:
+    case SET_AUTH_TOKEN:
        if (optarg == 0) goto needValueForOption;
-       fprintf (stderr, "Not Implemented yet\n");
-       cliconfig.smack   = optarg;
+       cliconfig.token   = optarg;
        break;
 
-    case SET_PLUGINS:
+    case SET_LDPATH:
        if (optarg == 0) goto needValueForOption;
-       fprintf (stderr, "Not Implemented yet\n");
-       cliconfig.plugins = optarg;
+       cliconfig.ldpaths = optarg;
        break;
 
     case SET_PID_FILE:
@@ -392,9 +405,9 @@ int main(int argc, char *argv[])  {
        session->configsave  = 1;
        break;
 
-    case SET_cardid:
+    case SET_USERID:
        if (optarg == 0) goto needValueForOption;
-       if (!sscanf (optarg, "%d", &cliconfig.setuid)) goto notAnInteger;
+       cliconfig.setuid = optarg;
        break;
 
     case SET_FAKE_MOD:
@@ -422,37 +435,87 @@ int main(int argc, char *argv[])  {
        session->killPrevious  = 2;
        break;
 
+    case SET_MODE:
+       if (optarg == 0) goto needValueForOption;
+       if (!strcmp(optarg, "local")) cliconfig.mode = AFB_MODE_LOCAL;
+       else if (!strcmp(optarg, "remote")) cliconfig.mode = AFB_MODE_REMOTE;
+       else if (!strcmp(optarg, "global")) cliconfig.mode = AFB_MODE_GLOBAL;
+       else goto badMode;
+       break;
+
+    case SET_READYFD:
+       if (optarg == 0) goto needValueForOption;
+       if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
+       break;
+
     case DISPLAY_VERSION:
        if (optarg != 0) goto noValueForOption;
        printVersion();
-       goto normalExit;
+       exit(0);
 
     case DISPLAY_HELP:
      default:
        printHelp(programName);
-       goto normalExit;
-
-  }
+       exit(0);
+    }
   }
-  // Create session config
-  configInit (/* session & config are initialized globally */);
-
+  free(gnuOptions);
   // if exist merge config file with CLI arguments
   configLoadFile  (session, &cliconfig);
+  return;
+
+
+needValueForOption:
+  fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
+          ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
+  exit (1);
+
+notAnInteger:
+  fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
+          ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
+  exit (1);
+
+noValueForOption:
+  fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
+          ,gnuOptions[optionIndex].name);
+  exit (1);
+
+badMode:
+  fprintf (stderr,"\nERR:AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
+          ,gnuOptions[optionIndex].name);
+  exit (1);
+}
+
+/*---------------------------------------------------------
+ | main
+ |   Parse option and launch action
+ +--------------------------------------------------------- */
+
+int main(int argc, char *argv[])  {
+  AFB_session    *session;
+  char*          programName = argv [0];
+  int            consoleFD;
+  int            pid, status;
+
+  // ------------- Build session handler & init config -------
+  session = configInit ();
+  parse_arguments(argc, argv, session);
+  initPlugins(session);
 
   // ------------------ sanity check ----------------------------------------
   if  ((session->background) && (session->foreground)) {
     fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
-     exit (-1);
+     exit (1);
   }
 
   // ------------------ Some useful default values -------------------------
   if  ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
 
   // open syslog if ever needed
-  openlog("AGB-log", 0, LOG_DAEMON);
+  openlog("AFB-log", 0, LOG_DAEMON);
 
-  // -------------- Try to kill any previsou process if asked ---------------------
+  // -------------- Try to kill any previous process if asked ---------------------
   if (session->killPrevious) {
     pid = readPidFile (session->config);  // enforce commandline option
     switch (pid) {
@@ -480,11 +543,11 @@ int main(int argc, char *argv[])  {
   // ------------------ clean exit on CTR-C signal ------------------------
   if (signal (SIGINT, signalQuit) == SIG_ERR) {
     fprintf (stderr, "%s Quit Signal received.",configTime());
-    return (-1);
+    return 1;
   }
 
-  // save exitpoint context when returning from longjmp closeSession and exit
-  status = setjmp (exitpoint); // return !+ when coming from longjmp
+  // save exitPoint context when returning from longjmp closeSession and exit
+  status = setjmp (exitPoint); // return !+ when coming from longjmp
   if (status != 0) {
     if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
     closeSession (session);
@@ -494,24 +557,24 @@ int main(int argc, char *argv[])  {
   // let's run this program with a low priority
   status=nice (20);
 
-
   // ------------------ Finaly Process Commands -----------------------------
-
-
-
    // if --save then store config on disk upfront
    if (session->configsave) configStoreFile (session);
    if (session->forceexit)  exit (0);
 
     if (session->config->setuid) {
         int err;
-
-        err = setuid(session->config->setuid);
-        if (err) fprintf (stderr, "Fail to change program cardid error=%s", strerror(err));
+        struct passwd *passwd;
+        passwd=getpwnam(session->config->setuid);
+        
+        if (passwd == NULL) goto errorSetuid;
+        
+        err = setuid(passwd->pw_uid);
+        if (err) goto errorSetuid;
     }
 
     // let's not take the risk to run as ROOT
-    if (getuid() == 0)  status=setuid(65534);  // run as nobody
+    //if (getuid() == 0)  goto errorNoRoot;
 
     // check session dir and create if it does not exist
     if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
@@ -584,60 +647,50 @@ int main(int argc, char *argv[])  {
       if (status == -1) goto errorPidFile;
 
       // we are in father process, we don't need this one
-      exit (0);
+      _exit (0);
 
   } // end background-foreground
 
 normalExit:
   closeSession (session);   // try to close everything before leaving
   if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
-  exit (0);
+  exit(0);
 
 // ------------- Fatal ERROR display error and quit  -------------
+errorSetuid:
+  fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
+  exit (1);
+  
+//errorNoRoot:
+//  fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
+//  exit (1);
+
 errorPidFile:
-  fprintf (stderr,"\nERR:main Failled to write pid file [%s]\n\n", session->config->pidfile);
-  exit (-1);
+  fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
+  exit (1);
 
 errorFork:
-  fprintf (stderr,"\nERR:main Failled to fork son process\n\n");
-  exit (-1);
-
-needValueForOption:
-  fprintf (stderr,"\nERR:main option [--%s] need a value i.e. --%s=xxx\n\n"
-          ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
-  exit (-1);
-
-noValueForOption:
-  fprintf (stderr,"\nERR:main option [--%s] don't take value\n\n"
-          ,gnuOptions[optionIndex].name);
-  exit (-1);
-
-notAnInteger:
-  fprintf (stderr,"\nERR:main option [--%s] requirer an interger i.e. --%s=9\n\n"
-          ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
-  exit (-1);
+  fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
+  exit (1);
 
 exitOnSignal:
-  fprintf (stderr,"\n%s INF:main pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
+  fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
                  ,configTime(), getpid());
-  exit (-1);
+  exit (1);
 
 errConsole:
-  fprintf (stderr,"\nERR:cannot open /dev/console (use --foreground)\n\n");
-  exit (-1);
+  fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
+  exit (1);
 
 errSessiondir:
-  fprintf (stderr,"\nERR:cannot read/write session dir\n\n");
-  exit (-1);
-
-errSoundCard:
-  fprintf (stderr,"\nERR:fail to probe sound cards\n\n");
-  exit (-1);
+  fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
+  exit (1);
 
 exitInitLoop:
   // try to unlink pid file if any
   if (session->background && session->config->pidfile != NULL)  unlink (session->config->pidfile);
-  exit (-1);
+  exit (1);
+
+}
 
-}; /* END main() */