Fixed Client Session Context by Plugin
[src/app-framework-binder.git] / src / rest-api.c
index 0a31e20..e19e1f2 100644 (file)
@@ -50,9 +50,11 @@ PUBLIC void endPostRequest(AFB_PostHandle *postHandle) {
 }
 
 // Check of apiurl is declare in this plugin and call it
-STATIC AFB_error callPluginApi(AFB_plugin *plugin, AFB_request *request, void *context) {
+STATIC AFB_error callPluginApi(AFB_request *request, int plugidx, void *context) {
     json_object *jresp, *jcall;
     int idx, status, sig;
+    AFB_clientCtx *clientCtx;
+    AFB_plugin *plugin = request->plugins[plugidx];
     int signals[]= {SIGALRM, SIGSEGV, SIGFPE, 0};
     
     /*---------------------------------------------------------------
@@ -60,8 +62,8 @@ STATIC AFB_error callPluginApi(AFB_plugin *plugin, AFB_request *request, void *c
     +---------------------------------------------------------------- */
     void pluginError (int signum) {
       sigset_t sigset;
-      AFB_clientCtx *context;
-              
+   
+      
       // unlock signal to allow a new signal to come
       sigemptyset (&sigset);
       sigaddset   (&sigset, signum);
@@ -116,7 +118,8 @@ STATIC AFB_error callPluginApi(AFB_plugin *plugin, AFB_request *request, void *c
                 if (AFB_SESSION_NONE != plugin->apis[idx].session) {
                     
                     // add client context to request
-                    if (ctxClientGet(request, plugin) != AFB_SUCCESS) {
+                    clientCtx = ctxClientGet(request, plugidx);
+                    if (clientCtx == NULL) {
                         request->errcode=MHD_HTTP_INSUFFICIENT_STORAGE;
                         json_object_object_add(jcall, "status", json_object_new_string ("fail"));
                         json_object_object_add(jcall, "info", json_object_new_string ("Client Session Context Full !!!"));
@@ -125,12 +128,12 @@ STATIC AFB_error callPluginApi(AFB_plugin *plugin, AFB_request *request, void *c
                     };
                     
                     if (verbose) fprintf(stderr, "Plugin=[%s] Api=[%s] Middleware=[%d] Client=[0x%x] Uuid=[%s] Token=[%s]\n"
-                           , request->plugin, request->api, plugin->apis[idx].session, request->client, request->client->uuid, request->client->token);                        
+                           , request->prefix, request->api, plugin->apis[idx].session, clientCtx, clientCtx->uuid, clientCtx->token);                        
                     
                     switch(plugin->apis[idx].session) {
 
                         case AFB_SESSION_CREATE:
-                            if (request->client->token[0] != '\0') {
+                            if (clientCtx->token[0] != '\0') {
                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
                                 json_object_object_add(jcall, "status", json_object_new_string ("exist"));
                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CREATE Session already exist"));
@@ -138,50 +141,50 @@ STATIC AFB_error callPluginApi(AFB_plugin *plugin, AFB_request *request, void *c
                                 return (AFB_DONE);                              
                             }
                         
-                            if (AFB_SUCCESS != ctxTokenCreate (request)) {
+                            if (AFB_SUCCESS != ctxTokenCreate (clientCtx, request)) {
                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
                                 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CREATE Invalid Initial Token"));
                                 json_object_object_add(request->jresp, "request", jcall);
                                 return (AFB_DONE);
                             } else {
-                                json_object_object_add(jcall, "uuid", json_object_new_string (request->client->uuid));                                
-                                json_object_object_add(jcall, "token", json_object_new_string (request->client->token));                                
+                                json_object_object_add(jcall, "uuid", json_object_new_string (clientCtx->uuid));                                
+                                json_object_object_add(jcall, "token", json_object_new_string (clientCtx->token));                                
                                 json_object_object_add(jcall, "timeout", json_object_new_int (request->config->cntxTimeout));                                
                             }
                             break;
 
 
                         case AFB_SESSION_RENEW:
-                            if (AFB_SUCCESS != ctxTokenRefresh (request)) {
+                            if (AFB_SUCCESS != ctxTokenRefresh (clientCtx, request)) {
                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
                                 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_REFRESH Broken Exchange Token Chain"));
                                 json_object_object_add(request->jresp, "request", jcall);
                                 return (AFB_DONE);
                             } else {
-                                json_object_object_add(jcall, "uuid", json_object_new_string (request->client->uuid));                                
-                                json_object_object_add(jcall, "token", json_object_new_string (request->client->token));                                
+                                json_object_object_add(jcall, "uuid", json_object_new_string (clientCtx->uuid));                                
+                                json_object_object_add(jcall, "token", json_object_new_string (clientCtx->token));                                
                                 json_object_object_add(jcall, "timeout", json_object_new_int (request->config->cntxTimeout));                                
                             }
                             break;
 
                         case AFB_SESSION_CLOSE:
-                            if (AFB_SUCCESS != ctxTokenCheck (request)) {
+                            if (AFB_SUCCESS != ctxTokenCheck (clientCtx, request)) {
                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
                                 json_object_object_add(jcall, "status", json_object_new_string ("empty"));
                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CLOSE Not a Valid Access Token"));
                                 json_object_object_add(request->jresp, "request", jcall);
                                 return (AFB_DONE);
                             } else {
-                                json_object_object_add(jcall, "uuid", json_object_new_string (request->client->uuid));                                
+                                json_object_object_add(jcall, "uuid", json_object_new_string (clientCtx->uuid));                                
                             }
                             break;
                         
                         case AFB_SESSION_CHECK:
                         default: 
                             // default action is check
-                            if (AFB_SUCCESS != ctxTokenCheck (request)) {
+                            if (AFB_SUCCESS != ctxTokenCheck (clientCtx, request)) {
                                 request->errcode=MHD_HTTP_UNAUTHORIZED;
                                 json_object_object_add(jcall, "status", json_object_new_string ("fail"));
                                 json_object_object_add(jcall, "info", json_object_new_string ("AFB_SESSION_CHECK Invalid Active Token"));
@@ -192,14 +195,17 @@ STATIC AFB_error callPluginApi(AFB_plugin *plugin, AFB_request *request, void *c
                     }
                 }
                 
-                // Effectively call the API with a subset of the context
+                // Effectively CALL PLUGIN API with a subset of the context
                 jresp = plugin->apis[idx].callback(request, context);
                 
-                // handle intemediatry Post Iterates out of band
+                // Store context in case it was updated by plugins
+                clientCtx->contexts[plugidx] = request->context;               
+                
+                // handle intermediary Post Iterates out of band
                 if ((jresp == NULL) && (request->errcode == MHD_HTTP_OK)) return (AFB_SUCCESS);
 
                 // Session close is done after the API call so API can still use session in closing API
-                if (AFB_SESSION_CLOSE == plugin->apis[idx].session) ctxTokenReset (request);                    
+                if (AFB_SESSION_CLOSE == plugin->apis[idx].session) ctxTokenReset (clientCtx, request);                    
                 
                 // API should return NULL of a valid Json Object
                 if (jresp == NULL) {
@@ -230,23 +236,24 @@ STATIC AFB_error findAndCallApi (AFB_request *request, void *context) {
     int idx;
     AFB_error status;
     
+    if (!request->api || !request->prefix) return (AFB_FAIL);
    
     // Search for a plugin with this urlpath
     for (idx = 0; request->plugins[idx] != NULL; idx++) {
-        if (!strcmp(request->plugins[idx]->prefix, request->plugin)) {
-            status =callPluginApi(request->plugins[idx], request, context);
+        if (!strcmp(request->plugins[idx]->prefix, request->prefix)) {
+            status =callPluginApi(request, idx, context);
             break;
         }
     }
     // No plugin was found
     if (request->plugins[idx] == NULL) {
-        request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s]", request->plugin);
+        request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->prefix, request->url);
         goto ExitOnError;
     }  
     
     // plugin callback did not return a valid Json Object
     if (status == AFB_FAIL) {
-        request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s]", request->api, request->plugin);
+        request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->prefix, request->url);
         goto ExitOnError;
     }
     
@@ -302,7 +309,7 @@ doPostIterate (void *cls, enum MHD_ValueKind kind, const char *key,
 
 STATIC void freeRequest (AFB_request *request) {
 
- free (request->plugin);    
+ free (request->prefix);    
  free (request->api);    
  free (request);    
 }
@@ -310,7 +317,8 @@ STATIC void freeRequest (AFB_request *request) {
 STATIC AFB_request *createRequest (struct MHD_Connection *connection, AFB_session *session, const char* url) {
     
     AFB_request *request;
-    
+    int idx;
+
     // Start with a clean request
     request = calloc (1, sizeof (AFB_request));
     char *urlcpy1, *urlcpy2;
@@ -321,22 +329,28 @@ STATIC AFB_request *createRequest (struct MHD_Connection *connection, AFB_sessio
     baseurl = strsep(&urlcpy2, "/");
     if (baseurl == NULL) {
         request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
+        request->errcode = MHD_HTTP_BAD_REQUEST;
+        goto Done;
     }
 
     // let's compute URL and call API
     baseapi = strsep(&urlcpy2, "/");
     if (baseapi == NULL) {
-        request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
+        request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
+        request->errcode = MHD_HTTP_BAD_REQUEST;
+        goto Done;
     }
     
     // build request structure
     request->connection = connection;
     request->config = session->config;
     request->url    = url;
-    request->plugin = strdup (baseurl);
+    request->prefix = strdup (baseurl);
     request->api    = strdup (baseapi);
     request->plugins= session->plugins;
-    
+    // note request->handle is fed with request->context in ctxClientGet
+
+Done:    
     free(urlcpy1);
     return (request);
 }
@@ -367,6 +381,7 @@ PUBLIC int doRestApi(struct MHD_Connection *connection, AFB_session *session, co
             // allocate application POST processor handle to zero
             postHandle = calloc(1, sizeof (AFB_PostHandle));
             postHandle->uid = postcount++; // build a UID for DEBUG
+            *con_cls = postHandle;  // update context with posthandle
             
             // Let make sure we have the right encoding and a valid length
             encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
@@ -382,15 +397,12 @@ PUBLIC int doRestApi(struct MHD_Connection *connection, AFB_session *session, co
                 if (verbose) fprintf(stderr, "Create PostForm[uid=%d]\n", postHandle->uid);
 
                 request = createRequest (connection, session, url);
-                if (request->jresp != NULL) {
-                    errMessage = request->jresp;
-                    goto ExitOnError;
-                }
+                if (request->jresp != NULL) goto ProcessApiCall;
+
                 postHandle = malloc(sizeof (AFB_PostHandle)); // allocate application POST processor handle
                 postHandle->type   = AFB_POST_FORM;
                 postHandle->pp     = MHD_create_post_processor (connection, MAX_POST_SIZE, doPostIterate, postHandle);
                 postHandle->private= (void*)request;
-                *con_cls = postHandle;  // update context with posthandle
                 
                 if (NULL == postHandle->pp) {
                     fprintf(stderr,"OOPS: Internal error fail to allocate MHD_create_post_processor\n");
@@ -496,9 +508,9 @@ ProcessApiCall:
     webResponse = MHD_create_response_from_buffer(strlen(serialized), (void*) serialized, MHD_RESPMEM_MUST_COPY);
     
     // client did not pass token on URI let's use cookies 
-    if ((!request->restfull) && (request->client != NULL)) {
+    if ((!request->restfull) && (request->context != NULL)) {
        char cookie[64]; 
-       snprintf (cookie, sizeof (cookie), "%s=%s", COOKIE_NAME,  request->client->uuid); 
+       snprintf (cookie, sizeof (cookie), "%s=%s", COOKIE_NAME,  request->uuid); 
        MHD_add_response_header (webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
     }
     
@@ -563,48 +575,105 @@ STATIC AFB_plugin ** RegisterJsonPlugins(AFB_plugin **plugins) {
     return (plugins);
 }
 
-void initPlugins(AFB_session *session) {
-    static AFB_plugin **plugins;
-    AFB_plugin* (*pluginRegisterFct)(void);
-    void *plugin;
-    char *pluginPath;
-    struct dirent *pluginDir;
+STATIC void scanDirectory(char *dirpath, int dirfd, AFB_plugin **plugins, int *count) {
     DIR *dir;
-    afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
-    int i = 0;
-
-    if ((dir = opendir(session->config->plugins)) == NULL) {
-        fprintf(stderr, "Could not open plugin directory=%s\n", session->config->plugins);
-        return;
+    void *libso;
+    struct dirent *pluginDir;  
+    AFB_plugin* (*pluginRegisterFct)(void);
+    char pluginPath[255];   
+    
+    // Open Directory to scan over it
+    dir = fdopendir (dirfd);
+    if (dir == NULL) {
+        fprintf(stderr, "ERROR in scanning directory\n");
+        return; 
     }
+    if (verbose) fprintf (stderr, "Scanning dir=[%s] for plugins\n", dirpath);
 
     while ((pluginDir = readdir(dir)) != NULL) {
+        
+        // Loop on any contained directory
+        if ((pluginDir->d_type == DT_DIR) && (pluginDir->d_name[0] != '.')) {
+           int fd = openat (dirfd, pluginDir->d_name, O_DIRECTORY);
+           char newpath[255];
+           strncpy (newpath, dirpath, sizeof(newpath));
+           strncat (newpath, "/", sizeof(newpath));
+           strncat (newpath, pluginDir->d_name, sizeof(newpath));
+           
+           scanDirectory (newpath, fd, plugins, count);
+           close (fd);
+           
+        } else {
+            
+            // This is a file but not a plugin let's move to next directory element
+            if (!strstr (pluginDir->d_name, ".so")) continue;
 
-        if (!strstr (pluginDir->d_name, ".so"))
-            continue;
+            // This is a loadable library let's check if it's a plugin
+            snprintf (pluginPath, sizeof(pluginPath), "%s/%s", dirpath, pluginDir->d_name);
+            libso = dlopen (pluginPath, RTLD_NOW | RTLD_LOCAL);
 
-        asprintf (&pluginPath, "%s/%s", session->config->plugins, pluginDir->d_name);
-        plugin = dlopen (pluginPath, RTLD_NOW | RTLD_LOCAL);
-        pluginRegisterFct = dlsym (plugin, "pluginRegister");
-        free (pluginPath);
-        if (!plugin) {
-            if (verbose) fprintf(stderr, "[%s] is not a binary plugin, continuing...\n", pluginDir->d_name);
-            continue;
-        } else if (!pluginRegisterFct) {
-            if (verbose) fprintf(stderr, "[%s] is not an AFB plugin, continuing...\n", pluginDir->d_name);
-            continue;
+            // Load fail we ignore this .so file            
+            if (!libso) {
+                fprintf(stderr, "[%s] is not loadable, continuing...\n", pluginDir->d_name);
+                continue;
+            }
+            
+            pluginRegisterFct = dlsym (libso, "pluginRegister");
+            free (libso);
+            
+            if (!pluginRegisterFct) {
+                fprintf(stderr, "[%s] is not an AFB plugin, continuing...\n", pluginDir->d_name);
+                continue;
+            }
+
+            // if max plugin is reached let's stop searching
+            if (*count == AFB_MAX_PLUGINS) {
+                fprintf(stderr, "[%s] is not loaded [Max Count=%d reached]\n", *count);
+                continue;
+            }
+
+            if (verbose) fprintf(stderr, "[%s] is a valid AFB plugin, loading pos[%d]\n", pluginDir->d_name, *count);
+            plugins[*count] = (AFB_plugin *) malloc (sizeof(AFB_plugin));
+            plugins[*count] = (**pluginRegisterFct)();
+            *count = *count +1;
+            
         }
+    }
+    closedir (dir);
+}
+
+void initPlugins(AFB_session *session) {
+    static AFB_plugin **plugins;
+    
+    afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
+    int count = 0;
+    char *dirpath;
+    int dirfd;
 
-        if (verbose) fprintf(stderr, "[%s] is a valid AFB plugin, loading it\n", pluginDir->d_name);
-        plugins = (AFB_plugin **) realloc (plugins, (i+1)*sizeof(AFB_plugin));
-        plugins[i] = (AFB_plugin *) malloc (sizeof(AFB_plugin));
-        plugins[i] = (**pluginRegisterFct)();
-        i++;
+    /* pre-allocate for AFB_MAX_PLUGINS plugins, we will downsize later */
+    plugins = (AFB_plugin **) malloc (AFB_MAX_PLUGINS *sizeof(AFB_plugin));
+    
+    // Loop on every directory passed in --plugins=xxx
+    while (dirpath = strsep(&session->config->ldpaths, ":")) {
+            // Ignore any directory we fail to open
+        if ((dirfd = open(dirpath, O_DIRECTORY)) <= 0) {
+            fprintf(stderr, "Invalid directory path=[%s]\n", dirpath);
+            continue;
+        }
+        scanDirectory (dirpath, dirfd, plugins, &count);
+        close (dirfd);
     }
-    plugins[i++] = NULL;
 
-    closedir (dir);
+    if (count == 0) {
+        fprintf(stderr, "No plugins found, afb-daemon is unlikely to work in this configuration, exiting...\n");
+        exit (-1);
+    }
     
+    // downsize structure to effective number of loaded plugins
+    plugins = (AFB_plugin **)realloc (plugins, (count+1)*sizeof(AFB_plugin));
+    plugins[count] = NULL;
+
     // complete plugins and save them within current sessions    
     session->plugins = RegisterJsonPlugins(plugins);
+    session->config->pluginCount = count;
 }