r24780: More work allowing libutil to be used by external users.
[kai/samba.git] / source4 / web_server / http.c
index 8779007f86994f7035e2f5d2efc4124ee8c9ad18..502d5de2d0646480290950e6a0155fd9317134b4 100644 (file)
@@ -7,7 +7,7 @@
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
+   the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "includes.h"
 #include "smbd/service_task.h"
 #include "web_server/web_server.h"
 #include "smbd/service_stream.h"
+#include "smbd/service.h"
 #include "lib/events/events.h"
 #include "system/time.h"
+#include "system/wait.h"
 #include "lib/appweb/esp/esp.h"
 #include "lib/appweb/ejs/ejsInternal.h"
-#include "dlinklist.h"
+#include "lib/util/dlinklist.h"
 #include "lib/tls/tls.h"
+#include "scripting/ejs/smbcalls.h"
 
-#define SWAT_SESSION_KEY "SwatSessionId"
-#define HTTP_PREAUTH_URI "/scripting/preauth.esp"
+#define SAMBA_SESSION_KEY "SambaSessionId"
+#define HTTP_PREAUTH_URI  "/scripting/preauth.esp"
+#define JSONRPC_REQUEST   "/services"
+#define JSONRPC_SERVER    "/request.esp"
 
 /* state of the esp subsystem for a specific request */
 struct esp_state {
@@ -101,7 +105,9 @@ static void http_output_headers(struct websrv_context *web)
 /*
   return the local path for a URL
 */
-static const char *http_local_path(struct websrv_context *web, const char *url)
+static const char *http_local_path(struct websrv_context *web,
+                                   const char *url,
+                                   const char *base_dir)
 {
        int i;
        char *path;
@@ -110,13 +116,13 @@ static const char *http_local_path(struct websrv_context *web, const char *url)
        if (url[0] != '/') return NULL;
 
        for (i=0;url[i];i++) {
-               if ((!isalnum((unsigned char)url[i]) && !strchr("./_", url[i])) ||
+               if ((!isalnum((unsigned char)url[i]) && !strchr("./_-", url[i])) ||
                    (url[i] == '.' && strchr("/.", url[i+1]))) {
                        return NULL;
                }
        }
 
-       path = talloc_asprintf(web, "%s/%s", lp_swat_directory(), url+1);
+       path = talloc_asprintf(web, "%s/%s", base_dir, url+1);
        if (path == NULL) return NULL;
 
        if (directory_exist(path)) {
@@ -128,14 +134,18 @@ static const char *http_local_path(struct websrv_context *web, const char *url)
 /*
   called when esp wants to read a file to support include() calls
 */
-static int http_readFile(EspHandle handle, char **buf, int *len, const char *path)
+static int http_readFile(EspHandle handle,
+                         char **buf,
+                         int *len,
+                         const char *path,
+                         const char *base_dir)
 {
        struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
        int fd = -1;
        struct stat st;
        *buf = NULL;
 
-       path = http_local_path(web, path);
+       path = http_local_path(web, path, base_dir);
        if (path == NULL) goto failed;
 
        fd = open(path, O_RDONLY);
@@ -160,6 +170,16 @@ failed:
        return -1;
 }
 
+static int http_readFileFromWebappsDir(EspHandle handle,
+                                       char **buf,
+                                       int *len,
+                                       const char *path)
+{
+    return http_readFile(handle, buf, len, path, lp_webapps_directory());
+}
+
+
+
 /*
   called when esp wants to find the real path of a file
 */
@@ -176,9 +196,8 @@ static int http_mapToStorage(EspHandle handle, char *path, int len, const char *
 static int http_writeBlock(EspHandle handle, const char *buf, int size)
 {
        struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
-       NTSTATUS status;
-       status = data_blob_append(web, &web->output.content, buf, size);
-       if (!NT_STATUS_IS_OK(status)) return -1;
+       if (!data_blob_append(web, &web->output.content, buf, size))
+               return -1;
        return size;
 }
 
@@ -235,12 +254,12 @@ static void http_redirect(EspHandle handle, int code, char *url)
                        char *p = strrchr(web->input.url, '/');
                        if (p == web->input.url) {
                                url = talloc_asprintf(web, "http%s://%s/%s", 
-                                                     tls_enabled(web->tls)?"s":"",
+                                                     tls_enabled(web->conn->socket)?"s":"",
                                                      host, url);
                        } else {
                                int dirlen = p - web->input.url;
                                url = talloc_asprintf(web, "http%s://%s%*.*s/%s",
-                                                     tls_enabled(web->tls)?"s":"",
+                                                     tls_enabled(web->conn->socket)?"s":"",
                                                      host, 
                                                      dirlen, dirlen, web->input.url,
                                                      url);
@@ -305,7 +324,7 @@ static void http_createSession(EspHandle handle, int timeout)
        struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
        if (web->session) {
                web->session->lifetime = timeout;
-               http_setCookie(web, SWAT_SESSION_KEY, web->session->id, 
+               http_setCookie(web, SAMBA_SESSION_KEY, web->session->id, 
                               web->session->lifetime, "/", 0);
        }
 }
@@ -370,7 +389,7 @@ static void http_simple_request(struct websrv_context *web)
        const char *path;
        struct stat st;
 
-       path = http_local_path(web, url);
+       path = http_local_path(web, url, lp_webapps_directory());
        if (path == NULL) goto invalid;
 
        /* looks ok */
@@ -401,7 +420,7 @@ static void http_setup_arrays(struct esp_state *esp)
        struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data);
        struct EspRequest *req = esp->req;
        struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, esp);
-       struct socket_address *peer_address = socket_get_my_addr(web->conn->socket, esp);
+       struct socket_address *peer_address = socket_get_peer_addr(web->conn->socket, esp);
        char *p;
 
 #define SETVAR(type, name, value) do { \
@@ -412,12 +431,19 @@ static void http_setup_arrays(struct esp_state *esp)
        SETVAR(ESP_REQUEST_OBJ, "CONTENT_LENGTH", 
               talloc_asprintf(esp, "%u", web->input.content_length));
        SETVAR(ESP_REQUEST_OBJ, "QUERY_STRING", web->input.query_string);
+       SETVAR(ESP_REQUEST_OBJ, "POST_DATA",
+               talloc_strndup(esp,
+                              web->input.partial.data,
+                              web->input.partial.length));
        SETVAR(ESP_REQUEST_OBJ, "REQUEST_METHOD", web->input.post_request?"POST":"GET");
        SETVAR(ESP_REQUEST_OBJ, "REQUEST_URI", web->input.url);
        p = strrchr(web->input.url, '/');
        SETVAR(ESP_REQUEST_OBJ, "SCRIPT_NAME", p+1);
        SETVAR(ESP_REQUEST_OBJ, "SCRIPT_FILENAME", web->input.url);
        if (peer_address) {
+               struct MprVar mpv = mprObject("socket_address");
+               mprSetPtrChild(&mpv, "socket_address", peer_address);
+               espSetVar(req, ESP_REQUEST_OBJ, "REMOTE_SOCKET_ADDRESS", mpv);
                SETVAR(ESP_REQUEST_OBJ, "REMOTE_ADDR", peer_address->addr);
        }
        p = socket_get_peer_name(web->conn->socket, esp);
@@ -429,7 +455,7 @@ static void http_setup_arrays(struct esp_state *esp)
        }
        SETVAR(ESP_REQUEST_OBJ, "COOKIE_SUPPORT", web->input.cookie?"True":"False");
 
-       SETVAR(ESP_HEADERS_OBJ, "HTT_REFERER", web->input.referer);
+       SETVAR(ESP_HEADERS_OBJ, "HTTP_REFERER", web->input.referer);
        SETVAR(ESP_HEADERS_OBJ, "HOST", web->input.host);
        SETVAR(ESP_HEADERS_OBJ, "ACCEPT_ENCODING", web->input.accept_encoding);
        SETVAR(ESP_HEADERS_OBJ, "ACCEPT_LANGUAGE", web->input.accept_language);
@@ -445,9 +471,9 @@ static void http_setup_arrays(struct esp_state *esp)
                       talloc_asprintf(esp, "%u", socket_address->port));
        }
 
-       SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_swat_directory());
-       SETVAR(ESP_SERVER_OBJ, "SERVER_PROTOCOL", tls_enabled(web->tls)?"https":"http");
-       SETVAR(ESP_SERVER_OBJ, "SERVER_SOFTWARE", "SWAT");
+       SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_webapps_directory());
+       SETVAR(ESP_SERVER_OBJ, "SERVER_PROTOCOL", tls_enabled(web->conn->socket)?"https":"http");
+       SETVAR(ESP_SERVER_OBJ, "SERVER_SOFTWARE", "SAMBA");
        SETVAR(ESP_SERVER_OBJ, "GATEWAY_INTERFACE", "CGI/1.1");
        SETVAR(ESP_SERVER_OBJ, "TLS_SUPPORT", tls_support(edata->tls_params)?"True":"False");
 }
@@ -457,11 +483,10 @@ static void http_setup_arrays(struct esp_state *esp)
    it hits a major error. We need to catch these and
    report a internal server error via http
 */
-#include <setjmp.h>
 static jmp_buf ejs_exception_buf;
 static const char *exception_reason;
 
-void ejs_exception(const char *reason)
+static void web_server_ejs_exception(const char *reason)
 {
        Ejs *ep = ejsPtr(0);
        if (ep) {
@@ -474,7 +499,7 @@ void ejs_exception(const char *reason)
        longjmp(ejs_exception_buf, -1);
 }
 #else
-void ejs_exception(const char *reason)
+static void web_server_ejs_exception(const char *reason)
 {
        DEBUG(0,("%s", reason));
        smb_panic(reason);
@@ -491,7 +516,7 @@ static void esp_request(struct esp_state *esp, const char *url)
        int res;
        char *emsg = NULL, *buf;
 
-       if (http_readFile(web, &buf, &size, url) != 0) {
+       if (http_readFile(web, &buf, &size, url, lp_webapps_directory()) != 0) {
                http_error_unix(web, url);
                return;
        }
@@ -512,17 +537,90 @@ static void esp_request(struct esp_state *esp, const char *url)
        talloc_free(buf);
 }
 
+/*
+  process a JSON RPC request
+*/
+static void jsonrpc_request(struct esp_state *esp)
+{
+       struct websrv_context *web = esp->web;
+       const char *path = http_local_path(web,
+                                           JSONRPC_SERVER,
+                                           lp_jsonrpc_services_dir());
+        MprVar *global;
+        MprVar v;
+        MprVar temp;
+       int size;
+       int res;
+       char *emsg = NULL;
+       char *emsg2 = NULL;
+        char *buf;
+        char *error_script =
+                "error.setOrigin(jsonrpc.Constant.ErrorOrigin.Server); "
+                "error.setError(jsonrpc.Constant.ErrorCode.UnexpectedOutput, "
+                "               global.errorString);"
+                "error.Send();";
+
+        /* Ensure we got a valid path. */
+       if (path == NULL) {
+                /* should never occur */
+               http_error(esp->web, 500, "Internal server error");
+               return;
+       }
+
+        /* Ensure that the JSON-RPC server request script exists */
+       if (!file_exist(path)) {
+               http_error_unix(esp->web, path);
+               return;
+       }
+
+        /* Call the server request script */
+       if (http_readFile(web, &buf, &size,
+                          JSONRPC_SERVER, lp_jsonrpc_services_dir()) != 0) {
+               http_error_unix(web, JSONRPC_SERVER);
+               return;
+       }
+
+#if HAVE_SETJMP_H
+       if (setjmp(ejs_exception_buf) != 0) {
+               http_error(web, 500, exception_reason);
+               return;
+       }
+#endif
+
+       res = espProcessRequest(esp->req, JSONRPC_SERVER, buf, &emsg);
+       if (res != 0 && emsg) {
+                /* Save the error in a string accessible from javascript */
+                global = ejsGetGlobalObject(0);
+                v = mprString(emsg);
+                mprCreateProperty(global, "errorString", &v);
+
+                /* Create and send a JsonRpcError object */
+                if (ejsEvalScript(0,
+                                  error_script,
+                                  &temp,
+                                  &emsg2) != 0) {
+                        http_writeBlock(web, "<pre>", 5);
+                        http_writeBlock(web, emsg, strlen(emsg));
+                        http_writeBlock(web, "</pre>", 6);
+                }
+       }
+       talloc_free(buf);
+}
 
 /*
-  perform pre-authentication on every page is /scripting/preauth.esp
+  perform pre-authentication on every page if /scripting/preauth.esp
   exists.  If this script generates any non-whitepace output at all,
   then we don't run the requested URL.
 
-  note that the preauth is run even for static pages such as images.
+  note that the preauth is run even for static pages such as images, but not
+  for JSON-RPC service requests which do their own authentication via the
+  JSON-RPC server.
 */
 static BOOL http_preauth(struct esp_state *esp)
 {
-       const char *path = http_local_path(esp->web, HTTP_PREAUTH_URI);
+       const char *path = http_local_path(esp->web,
+                                           HTTP_PREAUTH_URI,
+                                           lp_webapps_directory());
        int i;
        if (path == NULL) {
                http_error(esp->web, 500, "Internal server error");
@@ -535,9 +633,9 @@ static BOOL http_preauth(struct esp_state *esp)
        esp_request(esp, HTTP_PREAUTH_URI);
        for (i=0;i<esp->web->output.content.length;i++) {
                if (!isspace(esp->web->output.content.data[i])) {
-                       /* if the preauth has generated content, then force it to be
-                          html, so that we can show the login page for failed
-                          access to images */
+                       /* if the preauth has generated content, then force it
+                          to be html, so that we can show the login page for
+                          failed access to images */
                        http_setHeader(esp->web, "Content-Type: text/html", 0);
                        return False;
                }
@@ -574,7 +672,7 @@ static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p)
 */
 static void esp_putvar(struct esp_state *esp, const char *var, const char *value)
 {
-       if (strcasecmp(var, SWAT_SESSION_KEY) == 0) {
+       if (strcasecmp(var, SAMBA_SESSION_KEY) == 0) {
                /* special case support for browsers without cookie
                 support */
                esp->web->input.session_key = talloc_strdup(esp, value);
@@ -662,9 +760,8 @@ static void session_timeout(struct event_context *ev, struct timed_event *te,
 /*
   destroy a session
  */
-static int session_destructor(void *ptr)
+static int session_destructor(struct session_data *s)
 {
-       struct session_data *s = talloc_get_type(ptr, struct session_data);
        DLIST_REMOVE(s->edata->sessions, s);
        return 0;
 }
@@ -674,7 +771,7 @@ static int session_destructor(void *ptr)
 */
 static void http_setup_session(struct esp_state *esp)
 {
-       const char *session_key = SWAT_SESSION_KEY;
+       const char *session_key = SAMBA_SESSION_KEY;
        char *p;
        const char *cookie = esp->web->input.cookie;
        const char *key = NULL;
@@ -736,7 +833,7 @@ static const struct Esp esp_control = {
        .setHeader       = http_setHeader,
        .redirect        = http_redirect,
        .setResponseCode = http_setResponseCode,
-       .readFile        = http_readFile,
+       .readFile        = http_readFileFromWebappsDir,
        .mapToStorage    = http_mapToStorage,
        .setCookie       = http_setCookie,
        .createSession   = http_createSession,
@@ -750,18 +847,24 @@ static const struct Esp esp_control = {
 void http_process_input(struct websrv_context *web)
 {
        NTSTATUS status;
-       struct esp_state *esp;
+       struct esp_state *esp = NULL;
        struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data);
+       struct smbcalls_context *smbcalls_ctx;
        char *p;
        void *save_mpr_ctx = mprMemCtx();
        void *ejs_save = ejs_save_state();
        int i;
        const char *file_type = NULL;
-       BOOL esp_enable = False;
+        enum page_type {
+                page_type_simple,
+                page_type_esp,
+                page_type_jsonrpc
+        };
+        enum page_type page_type;
        const struct {
                const char *extension;
                const char *mime_type;
-               BOOL esp_enable;
+                enum page_type page_type;
        } mime_types[] = {
                {"gif",  "image/gif"},
                {"png",  "image/png"},
@@ -772,7 +875,16 @@ void http_process_input(struct websrv_context *web)
                {"esp",  "text/html", True}
        };
 
-       esp = talloc_zero(web, struct esp_state);
+       /*
+        * give the smbcalls a chance to find the event context
+        * and messaging context 
+        */
+       smbcalls_ctx = talloc(web, struct smbcalls_context);
+       if (smbcalls_ctx == NULL) goto internal_error;
+       smbcalls_ctx->event_ctx = web->conn->event.ctx;
+       smbcalls_ctx->msg_ctx = web->conn->msg_ctx;
+
+       esp = talloc_zero(smbcalls_ctx, struct esp_state);
        if (esp == NULL) goto internal_error;
 
        esp->web = web;
@@ -798,7 +910,7 @@ void http_process_input(struct websrv_context *web)
                           edata->application_data, MPR_DEEP_COPY);
        }
 
-       smb_setup_ejs_functions();
+       smb_setup_ejs_functions(web_server_ejs_exception);
 
        if (web->input.url == NULL) {
                http_error(web, 400, "You must specify a GET or POST request");
@@ -832,20 +944,35 @@ void http_process_input(struct websrv_context *web)
        esp->req = espCreateRequest(web, web->input.url, esp->variables);
        if (esp->req == NULL) goto internal_error;
 
-       /* work out the mime type */
-       p = strrchr(web->input.url, '.');
-       if (p == NULL) {
-               esp_enable = True;
-       }
-       for (i=0;p && i<ARRAY_SIZE(mime_types);i++) {
+       /*
+         * Work out the mime type.  First, we see if the request is a JSON-RPC
+         * service request.  If not, we look at the extension.
+         */
+        if (strncmp(web->input.url,
+                    JSONRPC_REQUEST,
+                    sizeof(JSONRPC_REQUEST) - 1) == 0 &&
+            (web->input.url[sizeof(JSONRPC_REQUEST) - 1] == '\0' ||
+             web->input.url[sizeof(JSONRPC_REQUEST) - 1] == '/')) {
+            page_type = page_type_jsonrpc;
+            file_type = "text/json";
+            
+        } else {
+            p = strrchr(web->input.url, '.');
+            if (p == NULL) {
+                    page_type = page_type_esp;
+                   file_type = "text/html";
+            }
+            for (i=0;p && i<ARRAY_SIZE(mime_types);i++) {
                if (strcmp(mime_types[i].extension, p+1) == 0) {
-                       file_type = mime_types[i].mime_type;
-                       esp_enable = mime_types[i].esp_enable;
+                    page_type = mime_types[i].page_type;
+                    file_type = mime_types[i].mime_type;
                }
-       }
-       if (file_type == NULL) {
+            }
+            if (file_type == NULL) {
+                page_type = page_type_simple;
                file_type = "text/html";
-       }
+            }
+        }
 
        /* setup basic headers */
        http_setResponseCode(web, 200);
@@ -857,14 +984,28 @@ void http_process_input(struct websrv_context *web)
 
        http_setup_arrays(esp);
 
-       /* possibly do pre-authentication */
-       if (http_preauth(esp)) {
-               if (esp_enable) {
-                       esp_request(esp, web->input.url);
-               } else {
-                       http_simple_request(web);
-               }
-       }
+       /*
+         * Do pre-authentication.  If pre-authentication succeeds, do
+         * page-type-specific processing.
+         */
+        switch(page_type)
+        {
+        case page_type_simple:
+                if (http_preauth(esp)) {
+                        http_simple_request(web);
+                }
+                break;
+
+        case page_type_esp:
+                if (http_preauth(esp)) {
+                        esp_request(esp, web->input.url);
+                }
+                break;
+
+        case page_type_jsonrpc:
+                jsonrpc_request(esp);
+                break;
+        }
 
        if (web->conn == NULL) {
                /* the connection has been terminated above us, probably