From 197870a731f18dd9759e9cc97dfd298fda773251 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 16 Sep 2008 18:05:53 +0200 Subject: Remove remaining embedded JavaScript support. --- source4/web_server/config.mk | 1 + 1 file changed, 1 insertion(+) (limited to 'source4/web_server') diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index fe78687794..02f686af0b 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,6 +4,7 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init +ENABLE = NO SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = ESP LIBTLS smbcalls process_model # End SUBSYSTEM WEB -- cgit From ef5a04485ae256f9b803da9173d6194ced82e358 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 23 May 2008 20:40:05 +0200 Subject: Rename http to esp, in preparation of adding a python backend. --- source4/web_server/config.mk | 2 +- source4/web_server/esp.c | 1030 +++++++++++++++++++++++++++++++++++++++ source4/web_server/http.c | 1030 --------------------------------------- source4/web_server/web_server.c | 4 +- 4 files changed, 1033 insertions(+), 1033 deletions(-) create mode 100644 source4/web_server/esp.c delete mode 100644 source4/web_server/http.c (limited to 'source4/web_server') diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index 02f686af0b..4094d6be07 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -10,6 +10,6 @@ PRIVATE_DEPENDENCIES = ESP LIBTLS smbcalls process_model # End SUBSYSTEM WEB ####################### -WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o http.o) +WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o esp.o) $(eval $(call proto_header_template,$(web_serversrcdir)/proto.h,$(WEB_OBJ_FILES:.o=.c))) diff --git a/source4/web_server/esp.c b/source4/web_server/esp.c new file mode 100644 index 0000000000..901a1558c4 --- /dev/null +++ b/source4/web_server/esp.c @@ -0,0 +1,1030 @@ +/* + Unix SMB/CIFS implementation. + + http handling code + + Copyright (C) Andrew Tridgell 2005 + + 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 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + 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, see . +*/ + +#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 "lib/util/dlinklist.h" +#include "lib/tls/tls.h" +#include "scripting/ejs/smbcalls.h" +#include "param/param.h" + +#define SAMBA_SESSION_KEY "SambaSessionId" +#define HTTP_PREAUTH_URI "/scripting/preauth.esp" + +/* state of the esp subsystem for a specific request */ +struct esp_state { + struct websrv_context *web; + struct EspRequest *req; + struct MprVar variables[ESP_OBJ_MAX]; + struct session_data *session; +}; + +/* + output the http headers +*/ +static void http_output_headers(struct websrv_context *web) +{ + int i; + char *s; + DATA_BLOB b; + uint32_t content_length = 0; + const char *response_string = "Unknown Code"; + const struct { + unsigned code; + const char *response_string; + } codes[] = { + { 200, "OK" }, + { 301, "Moved" }, + { 302, "Found" }, + { 303, "Method" }, + { 304, "Not Modified" }, + { 400, "Bad request" }, + { 401, "Unauthorized" }, + { 403, "Forbidden" }, + { 404, "Not Found" }, + { 500, "Internal Server Error" }, + { 501, "Not implemented" } + }; + for (i=0;ioutput.response_code) { + response_string = codes[i].response_string; + } + } + + if (web->output.headers == NULL) return; + s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n", + web->output.response_code, response_string); + if (s == NULL) return; + for (i=0;web->output.headers[i];i++) { + s = talloc_asprintf_append_buffer(s, "%s\r\n", web->output.headers[i]); + } + + /* work out the content length */ + content_length = web->output.content.length; + if (web->output.fd != -1) { + struct stat st; + fstat(web->output.fd, &st); + content_length += st.st_size; + } + s = talloc_asprintf_append_buffer(s, "Content-Length: %u\r\n\r\n", content_length); + if (s == NULL) return; + + b = web->output.content; + web->output.content = data_blob_string_const(s); + data_blob_append(web, &web->output.content, b.data, b.length); + data_blob_free(&b); +} + +/* + return the local path for a URL +*/ +static const char *http_local_path(struct websrv_context *web, + const char *url, + const char *base_dir) +{ + int i; + char *path; + + /* check that the url is OK */ + if (url[0] != '/') return NULL; + + for (i=0;url[i];i++) { + if ((!isalnum((unsigned char)url[i]) && !strchr("./_-", url[i])) || + (url[i] == '.' && strchr("/.", url[i+1]))) { + return NULL; + } + } + + path = talloc_asprintf(web, "%s/%s", base_dir, url+1); + if (path == NULL) return NULL; + + if (directory_exist(path)) { + path = talloc_asprintf_append_buffer(path, "/index.esp"); + } + return path; +} + +/* + 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, + 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, base_dir); + if (path == NULL) goto failed; + + fd = open(path, O_RDONLY); + if (fd == -1 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) goto failed; + + *buf = talloc_array(handle, char, st.st_size+1); + if (*buf == NULL) goto failed; + + if (read(fd, *buf, st.st_size) != st.st_size) goto failed; + + (*buf)[st.st_size] = 0; + + close(fd); + *len = st.st_size; + return 0; + +failed: + DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); + if (fd != -1) close(fd); + talloc_free(*buf); + *buf = NULL; + return -1; +} + +static int http_readFileFromSwatDir(EspHandle handle, char **buf, int *len, + const char *path) +{ + return http_readFile(handle, buf, len, path, + lp_swat_directory(global_loadparm)); +} + + + +/* + called when esp wants to find the real path of a file +*/ +static int http_mapToStorage(EspHandle handle, char *path, int len, const char *uri, int flags) +{ + if (uri == NULL || strlen(uri) >= len) return -1; + strncpy(path, uri, len); + return 0; +} + +/* + called when esp wants to output something +*/ +static int http_writeBlock(EspHandle handle, const char *buf, int size) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + if (!data_blob_append(web, &web->output.content, buf, size)) + return -1; + return size; +} + + +/* + set a http header +*/ +static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + char *p = strchr(value, ':'); + + if (p && !allowMultiple && web->output.headers) { + int i; + for (i=0;web->output.headers[i];i++) { + if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) { + web->output.headers[i] = talloc_strdup(web, value); + return; + } + } + } + + web->output.headers = str_list_add(web->output.headers, value); + talloc_steal(web, web->output.headers); +} + +/* + set a http response code +*/ +static void http_setResponseCode(EspHandle handle, int code) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + web->output.response_code = code; +} + +/* + redirect to another web page + */ +static void http_redirect(EspHandle handle, int code, char *url) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + const char *host = web->input.host; + + /* form the full url, unless it already looks like a url */ + if (strchr(url, ':') == NULL) { + if (host == NULL) { + struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, web); + if (socket_address == NULL) goto internal_error; + host = talloc_asprintf(web, "%s:%u", + socket_address->addr, socket_address->port); + } + if (host == NULL) goto internal_error; + if (url[0] != '/') { + char *p = strrchr(web->input.url, '/'); + if (p == web->input.url) { + url = talloc_asprintf(web, "http%s://%s/%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->conn->socket)?"s":"", + host, + dirlen, dirlen, web->input.url, + url); + } + if (url == NULL) goto internal_error; + } + } + + http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0); + + /* make sure we give a valid redirect code */ + if (code >= 300 && code < 400) { + http_setResponseCode(handle, code); + } else { + http_setResponseCode(handle, 302); + } + return; + +internal_error: + http_error(web, 500, "Internal server error"); +} + + +/* + setup a cookie +*/ +static void http_setCookie(EspHandle handle, const char *name, const char *value, + int lifetime, const char *path, bool secure) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + char *buf; + + if (lifetime > 0) { + buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; Expires=%s; %s", + name, value, path?path:"/", + http_timestring(web, time(NULL)+lifetime), + secure?"secure":""); + } else { + buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; %s", + name, value, path?path:"/", + secure?"secure":""); + } + http_setHeader(handle, "Cache-control: no-cache=\"set-cookie\"", 0); + http_setHeader(handle, buf, 0); + talloc_free(buf); +} + +/* + return the session id +*/ +static const char *http_getSessionId(EspHandle handle) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + return web->session->id; +} + +/* + setup a session +*/ +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, SAMBA_SESSION_KEY, web->session->id, + web->session->lifetime, "/", 0); + } +} + +/* + destroy a session +*/ +static void http_destroySession(EspHandle handle) +{ + struct websrv_context *web = talloc_get_type(handle, struct websrv_context); + talloc_free(web->session); + web->session = NULL; +} + + +/* + setup for a raw http level error +*/ +void http_error(struct websrv_context *web, int code, const char *info) +{ + char *s; + s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", + code, code, info); + if (s == NULL) { + stream_terminate_connection(web->conn, "http_error: out of memory"); + return; + } + http_writeBlock(web, s, strlen(s)); + http_setResponseCode(web, code); + http_output_headers(web); + EVENT_FD_NOT_READABLE(web->conn->event.fde); + EVENT_FD_WRITEABLE(web->conn->event.fde); + web->output.output_pending = true; +} + +/* + map a unix error code to a http error +*/ +void http_error_unix(struct websrv_context *web, const char *info) +{ + int code = 500; + switch (errno) { + case ENOENT: + case EISDIR: + code = 404; + break; + case EACCES: + code = 403; + break; + } + info = talloc_asprintf(web, "%s

%s

\n", info, strerror(errno)); + http_error(web, code, info); +} + + +/* + a simple file request +*/ +static void http_simple_request(struct websrv_context *web) +{ + const char *url = web->input.url; + const char *path; + struct stat st; + + path = http_local_path(web, url, lp_swat_directory(web->task->lp_ctx)); + if (path == NULL) goto invalid; + + /* looks ok */ + web->output.fd = open(path, O_RDONLY); + if (web->output.fd == -1) { + DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); + http_error_unix(web, path); + return; + } + + if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) { + close(web->output.fd); + goto invalid; + } + + return; + +invalid: + http_error(web, 400, "Malformed URL"); +} + +/* + setup the standard ESP arrays +*/ +static void http_setup_arrays(struct esp_state *esp) +{ + struct websrv_context *web = esp->web; + 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_peer_addr(web->conn->socket, esp); + char *p; + +#define SETVAR(type, name, value) do { \ + const char *v = value; \ + if (v) espSetStringVar(req, type, name, v); \ +} while (0) + + 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); + SETVAR(ESP_REQUEST_OBJ, "REMOTE_HOST", p); + SETVAR(ESP_REQUEST_OBJ, "REMOTE_USER", ""); + SETVAR(ESP_REQUEST_OBJ, "CONTENT_TYPE", web->input.content_type); + if (web->session) { + SETVAR(ESP_REQUEST_OBJ, "SESSION_ID", web->session->id); + } + SETVAR(ESP_REQUEST_OBJ, "COOKIE_SUPPORT", web->input.cookie?"true":"false"); + + 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); + SETVAR(ESP_HEADERS_OBJ, "ACCEPT_CHARSET", web->input.accept_charset); + SETVAR(ESP_HEADERS_OBJ, "COOKIE", web->input.cookie); + SETVAR(ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent); + + if (socket_address) { + SETVAR(ESP_SERVER_OBJ, "SERVER_ADDR", socket_address->addr); + SETVAR(ESP_SERVER_OBJ, "SERVER_NAME", socket_address->addr); + SETVAR(ESP_SERVER_OBJ, "SERVER_HOST", socket_address->addr); + SETVAR(ESP_SERVER_OBJ, "SERVER_PORT", + talloc_asprintf(esp, "%u", socket_address->port)); + } + + SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_swat_directory(esp->web->task->lp_ctx)); + 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"); +} + +#if HAVE_SETJMP_H +/* the esp scripting lirary generates exceptions when + it hits a major error. We need to catch these and + report a internal server error via http +*/ +static jmp_buf ejs_exception_buf; +static const char *exception_reason; + +static void web_server_ejs_exception(const char *reason) +{ + Ejs *ep = ejsPtr(0); + if (ep) { + ejsSetErrorMsg(0, "%s", reason); + exception_reason = ep->error; + } else { + exception_reason = reason; + } + DEBUG(0,("%s", exception_reason)); + longjmp(ejs_exception_buf, -1); +} +#else +static void web_server_ejs_exception(const char *reason) +{ + DEBUG(0,("%s", reason)); + smb_panic(reason); +} +#endif + +/* + process a esp request +*/ +static void esp_request(struct esp_state *esp, const char *url) +{ + struct websrv_context *web = esp->web; + int size; + int res; + char *emsg = NULL, *buf; + + if (http_readFile(web, &buf, &size, url, lp_swat_directory(esp->web->task->lp_ctx)) != 0) { + http_error_unix(web, url); + return; + } + +#if HAVE_SETJMP_H + if (setjmp(ejs_exception_buf) != 0) { + http_error(web, 500, exception_reason); + return; + } +#endif + + res = espProcessRequest(esp->req, url, buf, &emsg); + if (res != 0 && emsg) { + http_writeBlock(web, "

", 5);
+		http_writeBlock(web, emsg, strlen(emsg));
+		http_writeBlock(web, "
", 6); + } + talloc_free(buf); +} + +/* + 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 +*/ +static bool http_preauth(struct esp_state *esp) +{ + const char *path = http_local_path(esp->web, + HTTP_PREAUTH_URI, + lp_swat_directory(esp->web->task->lp_ctx)); + int i; + if (path == NULL) { + http_error(esp->web, 500, "Internal server error"); + return false; + } + if (!file_exist(path)) { + /* if the preath script is not installed then allow access */ + return true; + } + esp_request(esp, HTTP_PREAUTH_URI); + for (i=0;iweb->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 */ + http_setHeader(esp->web, "Content-Type: text/html", 0); + return false; + } + } + data_blob_free(&esp->web->output.content); + return true; +} + + +/* + handling of + and % escapes in http variables +*/ +static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p) +{ + char *s0 = talloc_strdup(mem_ctx, p); + char *s = s0; + if (s == NULL) return NULL; + + while (*s) { + unsigned v; + if (*s == '+') *s = ' '; + if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) { + *s = (char)v; + memmove(s+1, s+3, strlen(s+3)+1); + } + s++; + } + + return s0; +} + +/* + set a form or GET variable +*/ +static void esp_putvar(struct esp_state *esp, const char *var, const char *value) +{ + if (strcasecmp(var, SAMBA_SESSION_KEY) == 0) { + /* special case support for browsers without cookie + support */ + esp->web->input.session_key = talloc_strdup(esp, value); + } else { + mprSetPropertyValue(&esp->variables[ESP_FORM_OBJ], + http_unescape(esp, var), + mprCreateStringVar(http_unescape(esp, value), 0)); + } +} + + +/* + parse the variables in a POST style request +*/ +static NTSTATUS http_parse_post(struct esp_state *esp) +{ + DATA_BLOB b = esp->web->input.partial; + + while (b.length) { + char *p, *line; + size_t len; + + p = memchr(b.data, '&', b.length); + if (p == NULL) { + len = b.length; + } else { + len = p - (char *)b.data; + } + line = talloc_strndup(esp, (char *)b.data, len); + NT_STATUS_HAVE_NO_MEMORY(line); + + p = strchr(line,'='); + if (p) { + *p = 0; + esp_putvar(esp, line, p+1); + } + talloc_free(line); + b.length -= len; + b.data += len; + if (b.length > 0) { + b.length--; + b.data++; + } + } + + return NT_STATUS_OK; +} + +/* + parse the variables in a GET style request +*/ +static NTSTATUS http_parse_get(struct esp_state *esp) +{ + struct websrv_context *web = esp->web; + char *p, *s, *tok; + char *pp; + + p = strchr(web->input.url, '?'); + web->input.query_string = p+1; + *p = 0; + + s = talloc_strdup(esp, esp->web->input.query_string); + NT_STATUS_HAVE_NO_MEMORY(s); + + for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) { + p = strchr(tok,'='); + if (p) { + *p = 0; + esp_putvar(esp, tok, p+1); + } + } + return NT_STATUS_OK; +} + +/* + called when a session times out +*/ +static void session_timeout(struct event_context *ev, struct timed_event *te, + struct timeval t, void *private) +{ + struct session_data *s = talloc_get_type(private, struct session_data); + talloc_free(s); +} + +/* + destroy a session + */ +static int session_destructor(struct session_data *s) +{ + DLIST_REMOVE(s->edata->sessions, s); + return 0; +} + +/* + setup the session for this request +*/ +static void http_setup_session(struct esp_state *esp) +{ + const char *session_key = SAMBA_SESSION_KEY; + char *p; + const char *cookie = esp->web->input.cookie; + const char *key = NULL; + struct esp_data *edata = talloc_get_type(esp->web->task->private, struct esp_data); + struct session_data *s; + bool generated_key = false; + + /* look for our session key */ + if (cookie && (p = strstr(cookie, session_key)) && + p[strlen(session_key)] == '=') { + p += strlen(session_key)+1; + key = talloc_strndup(esp, p, strcspn(p, ";")); + } + + if (key == NULL && esp->web->input.session_key) { + key = esp->web->input.session_key; + } else if (key == NULL) { + key = generate_random_str_list(esp, 16, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + generated_key = true; + } + + /* try to find this session in the existing session list */ + for (s=edata->sessions;s;s=s->next) { + if (strcmp(key, s->id) == 0) { + break; + } + } + + if (s == NULL) { + /* create a new session */ + s = talloc_zero(edata, struct session_data); + s->id = talloc_steal(s, key); + s->data = NULL; + s->te = NULL; + s->edata = edata; + s->lifetime = lp_parm_int(esp->web->task->lp_ctx, NULL, "web", "sessiontimeout", 900); + DLIST_ADD(edata->sessions, s); + talloc_set_destructor(s, session_destructor); + if (!generated_key) { + mprSetPropertyValue(&esp->variables[ESP_REQUEST_OBJ], + "SESSION_EXPIRED", mprCreateStringVar("true", 0)); + } + } + + http_setCookie(esp->web, session_key, key, s->lifetime, "/", 0); + + if (s->data) { + mprCopyVar(&esp->variables[ESP_SESSION_OBJ], s->data, MPR_DEEP_COPY); + } + + esp->web->session = s; +} + + +/* callbacks for esp processing */ +static const struct Esp esp_control = { + .maxScriptSize = 60000, + .writeBlock = http_writeBlock, + .setHeader = http_setHeader, + .redirect = http_redirect, + .setResponseCode = http_setResponseCode, + .readFile = http_readFileFromSwatDir, + .mapToStorage = http_mapToStorage, + .setCookie = http_setCookie, + .createSession = http_createSession, + .destroySession = http_destroySession, + .getSessionId = http_getSessionId +}; + +/* + process a complete http request +*/ +void http_process_input(struct websrv_context *web) +{ + NTSTATUS status; + 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; + enum page_type { + page_type_simple, + page_type_esp + }; + enum page_type page_type; + const struct { + const char *extension; + const char *mime_type; + enum page_type page_type; + } mime_types[] = { + {"gif", "image/gif"}, + {"png", "image/png"}, + {"jpg", "image/jpeg"}, + {"txt", "text/plain"}, + {"ico", "image/x-icon"}, + {"css", "text/css"}, + {"esp", "text/html", true} + }; + + /* + * 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; + + mprSetCtx(esp); + + if (espOpen(&esp_control) != 0) goto internal_error; + + for (i=0;ivariables);i++) { + esp->variables[i] = mprCreateUndefinedVar(); + } + esp->variables[ESP_HEADERS_OBJ] = mprCreateObjVar("headers", ESP_HASH_SIZE); + esp->variables[ESP_FORM_OBJ] = mprCreateObjVar("form", ESP_HASH_SIZE); + esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE); + esp->variables[ESP_COOKIES_OBJ] = mprCreateObjVar("cookies", ESP_HASH_SIZE); + esp->variables[ESP_FILES_OBJ] = mprCreateObjVar("files", ESP_HASH_SIZE); + esp->variables[ESP_REQUEST_OBJ] = mprCreateObjVar("request", ESP_HASH_SIZE); + esp->variables[ESP_SERVER_OBJ] = mprCreateObjVar("server", ESP_HASH_SIZE); + esp->variables[ESP_SESSION_OBJ] = mprCreateObjVar("session", ESP_HASH_SIZE); + + if (edata->application_data) { + mprCopyVar(&esp->variables[ESP_APPLICATION_OBJ], + edata->application_data, MPR_DEEP_COPY); + } + + 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"); + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); + return; + } + + /* parse any form or get variables */ + if (web->input.post_request) { + status = http_parse_post(esp); + if (!NT_STATUS_IS_OK(status)) { + http_error(web, 400, "Malformed POST data"); + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); + return; + } + } + if (strchr(web->input.url, '?')) { + status = http_parse_get(esp); + if (!NT_STATUS_IS_OK(status)) { + http_error(web, 400, "Malformed GET data"); + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); + return; + } + } + + http_setup_session(esp); + + esp->req = espCreateRequest(web, web->input.url, esp->variables); + if (esp->req == NULL) goto internal_error; + + p = strrchr(web->input.url, '.'); + if (p == NULL) { + page_type = page_type_esp; + file_type = "text/html"; + } + for (i=0;p && iinput.url); + } + break; + } + + if (web->conn == NULL) { + /* the connection has been terminated above us, probably + via a timeout */ + goto internal_error; + } + + if (!web->output.output_pending) { + http_output_headers(web); + EVENT_FD_WRITEABLE(web->conn->event.fde); + web->output.output_pending = true; + } + + /* copy any application data to long term storage in edata */ + talloc_free(edata->application_data); + edata->application_data = talloc_zero(edata, struct MprVar); + mprSetCtx(edata->application_data); + mprCopyVar(edata->application_data, &esp->variables[ESP_APPLICATION_OBJ], + MPR_DEEP_COPY); + mprSetCtx(esp); + + /* copy any session data */ + if (web->session) { + talloc_free(web->session->data); + web->session->data = talloc_zero(web->session, struct MprVar); + if (esp->variables[ESP_SESSION_OBJ].properties == NULL || + esp->variables[ESP_SESSION_OBJ].properties[0].numItems == 0) { + talloc_free(web->session); + web->session = NULL; + } else { + mprSetCtx(web->session->data); + mprCopyVar(web->session->data, &esp->variables[ESP_SESSION_OBJ], + MPR_DEEP_COPY); + /* setup the timeout for the session data */ + mprSetCtx(esp); + talloc_free(web->session->te); + web->session->te = event_add_timed(web->conn->event.ctx, web->session, + timeval_current_ofs(web->session->lifetime, 0), + session_timeout, web->session); + } + } + + talloc_free(esp); + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); + return; + +internal_error: + mprSetCtx(esp); + talloc_free(esp); + if (web->conn != NULL) { + http_error(web, 500, "Internal server error"); + } + mprSetCtx(save_mpr_ctx); + ejs_restore_state(ejs_save); +} + + +/* + parse one line of header input +*/ +NTSTATUS http_parse_header(struct websrv_context *web, const char *line) +{ + if (line[0] == 0) { + web->input.end_of_headers = true; + } else if (strncasecmp(line,"GET ", 4)==0) { + web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t")); + } else if (strncasecmp(line,"POST ", 5)==0) { + web->input.post_request = true; + web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); + } else if (strchr(line, ':') == NULL) { + http_error(web, 400, "This server only accepts GET and POST requests"); + return NT_STATUS_INVALID_PARAMETER; + } else if (strncasecmp(line,"Content-Length: ", 16)==0) { + web->input.content_length = strtoul(&line[16], NULL, 10); + } else { +#define PULL_HEADER(v, s) do { \ + if (strncmp(line, s, strlen(s)) == 0) { \ + web->input.v = talloc_strdup(web, &line[strlen(s)]); \ + return NT_STATUS_OK; \ + } \ +} while (0) + PULL_HEADER(content_type, "Content-Type: "); + PULL_HEADER(user_agent, "User-Agent: "); + PULL_HEADER(referer, "Referer: "); + PULL_HEADER(host, "Host: "); + PULL_HEADER(accept_encoding, "Accept-Encoding: "); + PULL_HEADER(accept_language, "Accept-Language: "); + PULL_HEADER(accept_charset, "Accept-Charset: "); + PULL_HEADER(cookie, "Cookie: "); + } + + /* ignore all other headers for now */ + return NT_STATUS_OK; +} + + +/* + setup the esp processor - called at task initialisation +*/ +struct esp_data *http_setup_esp(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx) +{ + struct esp_data *edata; + + edata = talloc_zero(mem_ctx, struct esp_data); + if (edata == NULL) + return NULL; + + edata->tls_params = tls_initialise(edata, lp_ctx); + if (edata->tls_params == NULL) + return NULL; + + return edata; +} diff --git a/source4/web_server/http.c b/source4/web_server/http.c deleted file mode 100644 index bd6efa9262..0000000000 --- a/source4/web_server/http.c +++ /dev/null @@ -1,1030 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - http handling code - - Copyright (C) Andrew Tridgell 2005 - - 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 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - 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, see . -*/ - -#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 "lib/util/dlinklist.h" -#include "lib/tls/tls.h" -#include "scripting/ejs/smbcalls.h" -#include "param/param.h" - -#define SAMBA_SESSION_KEY "SambaSessionId" -#define HTTP_PREAUTH_URI "/scripting/preauth.esp" - -/* state of the esp subsystem for a specific request */ -struct esp_state { - struct websrv_context *web; - struct EspRequest *req; - struct MprVar variables[ESP_OBJ_MAX]; - struct session_data *session; -}; - -/* - output the http headers -*/ -static void http_output_headers(struct websrv_context *web) -{ - int i; - char *s; - DATA_BLOB b; - uint32_t content_length = 0; - const char *response_string = "Unknown Code"; - const struct { - unsigned code; - const char *response_string; - } codes[] = { - { 200, "OK" }, - { 301, "Moved" }, - { 302, "Found" }, - { 303, "Method" }, - { 304, "Not Modified" }, - { 400, "Bad request" }, - { 401, "Unauthorized" }, - { 403, "Forbidden" }, - { 404, "Not Found" }, - { 500, "Internal Server Error" }, - { 501, "Not implemented" } - }; - for (i=0;ioutput.response_code) { - response_string = codes[i].response_string; - } - } - - if (web->output.headers == NULL) return; - s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n", - web->output.response_code, response_string); - if (s == NULL) return; - for (i=0;web->output.headers[i];i++) { - s = talloc_asprintf_append_buffer(s, "%s\r\n", web->output.headers[i]); - } - - /* work out the content length */ - content_length = web->output.content.length; - if (web->output.fd != -1) { - struct stat st; - fstat(web->output.fd, &st); - content_length += st.st_size; - } - s = talloc_asprintf_append_buffer(s, "Content-Length: %u\r\n\r\n", content_length); - if (s == NULL) return; - - b = web->output.content; - web->output.content = data_blob_string_const(s); - data_blob_append(web, &web->output.content, b.data, b.length); - data_blob_free(&b); -} - -/* - return the local path for a URL -*/ -static const char *http_local_path(struct websrv_context *web, - const char *url, - const char *base_dir) -{ - int i; - char *path; - - /* check that the url is OK */ - if (url[0] != '/') return NULL; - - for (i=0;url[i];i++) { - if ((!isalnum((unsigned char)url[i]) && !strchr("./_-", url[i])) || - (url[i] == '.' && strchr("/.", url[i+1]))) { - return NULL; - } - } - - path = talloc_asprintf(web, "%s/%s", base_dir, url+1); - if (path == NULL) return NULL; - - if (directory_exist(path)) { - path = talloc_asprintf_append_buffer(path, "/index.esp"); - } - return path; -} - -/* - 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, - 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, base_dir); - if (path == NULL) goto failed; - - fd = open(path, O_RDONLY); - if (fd == -1 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) goto failed; - - *buf = talloc_array(handle, char, st.st_size+1); - if (*buf == NULL) goto failed; - - if (read(fd, *buf, st.st_size) != st.st_size) goto failed; - - (*buf)[st.st_size] = 0; - - close(fd); - *len = st.st_size; - return 0; - -failed: - DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); - if (fd != -1) close(fd); - talloc_free(*buf); - *buf = NULL; - return -1; -} - -static int http_readFileFromSwatDir(EspHandle handle, char **buf, int *len, - const char *path) -{ - return http_readFile(handle, buf, len, path, - lp_swat_directory(global_loadparm)); -} - - - -/* - called when esp wants to find the real path of a file -*/ -static int http_mapToStorage(EspHandle handle, char *path, int len, const char *uri, int flags) -{ - if (uri == NULL || strlen(uri) >= len) return -1; - strncpy(path, uri, len); - return 0; -} - -/* - called when esp wants to output something -*/ -static int http_writeBlock(EspHandle handle, const char *buf, int size) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - if (!data_blob_append(web, &web->output.content, buf, size)) - return -1; - return size; -} - - -/* - set a http header -*/ -static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - char *p = strchr(value, ':'); - - if (p && !allowMultiple && web->output.headers) { - int i; - for (i=0;web->output.headers[i];i++) { - if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) { - web->output.headers[i] = talloc_strdup(web, value); - return; - } - } - } - - web->output.headers = str_list_add(web->output.headers, value); - talloc_steal(web, web->output.headers); -} - -/* - set a http response code -*/ -static void http_setResponseCode(EspHandle handle, int code) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - web->output.response_code = code; -} - -/* - redirect to another web page - */ -static void http_redirect(EspHandle handle, int code, char *url) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - const char *host = web->input.host; - - /* form the full url, unless it already looks like a url */ - if (strchr(url, ':') == NULL) { - if (host == NULL) { - struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, web); - if (socket_address == NULL) goto internal_error; - host = talloc_asprintf(web, "%s:%u", - socket_address->addr, socket_address->port); - } - if (host == NULL) goto internal_error; - if (url[0] != '/') { - char *p = strrchr(web->input.url, '/'); - if (p == web->input.url) { - url = talloc_asprintf(web, "http%s://%s/%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->conn->socket)?"s":"", - host, - dirlen, dirlen, web->input.url, - url); - } - if (url == NULL) goto internal_error; - } - } - - http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0); - - /* make sure we give a valid redirect code */ - if (code >= 300 && code < 400) { - http_setResponseCode(handle, code); - } else { - http_setResponseCode(handle, 302); - } - return; - -internal_error: - http_error(web, 500, "Internal server error"); -} - - -/* - setup a cookie -*/ -static void http_setCookie(EspHandle handle, const char *name, const char *value, - int lifetime, const char *path, bool secure) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - char *buf; - - if (lifetime > 0) { - buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; Expires=%s; %s", - name, value, path?path:"/", - http_timestring(web, time(NULL)+lifetime), - secure?"secure":""); - } else { - buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; %s", - name, value, path?path:"/", - secure?"secure":""); - } - http_setHeader(handle, "Cache-control: no-cache=\"set-cookie\"", 0); - http_setHeader(handle, buf, 0); - talloc_free(buf); -} - -/* - return the session id -*/ -static const char *http_getSessionId(EspHandle handle) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - return web->session->id; -} - -/* - setup a session -*/ -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, SAMBA_SESSION_KEY, web->session->id, - web->session->lifetime, "/", 0); - } -} - -/* - destroy a session -*/ -static void http_destroySession(EspHandle handle) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - talloc_free(web->session); - web->session = NULL; -} - - -/* - setup for a raw http level error -*/ -void http_error(struct websrv_context *web, int code, const char *info) -{ - char *s; - s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", - code, code, info); - if (s == NULL) { - stream_terminate_connection(web->conn, "http_error: out of memory"); - return; - } - http_writeBlock(web, s, strlen(s)); - http_setResponseCode(web, code); - http_output_headers(web); - EVENT_FD_NOT_READABLE(web->conn->event.fde); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; -} - -/* - map a unix error code to a http error -*/ -void http_error_unix(struct websrv_context *web, const char *info) -{ - int code = 500; - switch (errno) { - case ENOENT: - case EISDIR: - code = 404; - break; - case EACCES: - code = 403; - break; - } - info = talloc_asprintf(web, "%s

%s

\n", info, strerror(errno)); - http_error(web, code, info); -} - - -/* - a simple file request -*/ -static void http_simple_request(struct websrv_context *web) -{ - const char *url = web->input.url; - const char *path; - struct stat st; - - path = http_local_path(web, url, lp_swat_directory(web->task->lp_ctx)); - if (path == NULL) goto invalid; - - /* looks ok */ - web->output.fd = open(path, O_RDONLY); - if (web->output.fd == -1) { - DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); - http_error_unix(web, path); - return; - } - - if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) { - close(web->output.fd); - goto invalid; - } - - return; - -invalid: - http_error(web, 400, "Malformed URL"); -} - -/* - setup the standard ESP arrays -*/ -static void http_setup_arrays(struct esp_state *esp) -{ - struct websrv_context *web = esp->web; - 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_peer_addr(web->conn->socket, esp); - char *p; - -#define SETVAR(type, name, value) do { \ - const char *v = value; \ - if (v) espSetStringVar(req, type, name, v); \ -} while (0) - - 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); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_HOST", p); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_USER", ""); - SETVAR(ESP_REQUEST_OBJ, "CONTENT_TYPE", web->input.content_type); - if (web->session) { - SETVAR(ESP_REQUEST_OBJ, "SESSION_ID", web->session->id); - } - SETVAR(ESP_REQUEST_OBJ, "COOKIE_SUPPORT", web->input.cookie?"true":"false"); - - 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); - SETVAR(ESP_HEADERS_OBJ, "ACCEPT_CHARSET", web->input.accept_charset); - SETVAR(ESP_HEADERS_OBJ, "COOKIE", web->input.cookie); - SETVAR(ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent); - - if (socket_address) { - SETVAR(ESP_SERVER_OBJ, "SERVER_ADDR", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_NAME", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_HOST", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_PORT", - talloc_asprintf(esp, "%u", socket_address->port)); - } - - SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_swat_directory(esp->web->task->lp_ctx)); - 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"); -} - -#if HAVE_SETJMP_H -/* the esp scripting lirary generates exceptions when - it hits a major error. We need to catch these and - report a internal server error via http -*/ -static jmp_buf ejs_exception_buf; -static const char *exception_reason; - -static void web_server_ejs_exception(const char *reason) -{ - Ejs *ep = ejsPtr(0); - if (ep) { - ejsSetErrorMsg(0, "%s", reason); - exception_reason = ep->error; - } else { - exception_reason = reason; - } - DEBUG(0,("%s", exception_reason)); - longjmp(ejs_exception_buf, -1); -} -#else -static void web_server_ejs_exception(const char *reason) -{ - DEBUG(0,("%s", reason)); - smb_panic(reason); -} -#endif - -/* - process a esp request -*/ -static void esp_request(struct esp_state *esp, const char *url) -{ - struct websrv_context *web = esp->web; - int size; - int res; - char *emsg = NULL, *buf; - - if (http_readFile(web, &buf, &size, url, lp_swat_directory(esp->web->task->lp_ctx)) != 0) { - http_error_unix(web, url); - return; - } - -#if HAVE_SETJMP_H - if (setjmp(ejs_exception_buf) != 0) { - http_error(web, 500, exception_reason); - return; - } -#endif - - res = espProcessRequest(esp->req, url, buf, &emsg); - if (res != 0 && emsg) { - http_writeBlock(web, "

", 5);
-		http_writeBlock(web, emsg, strlen(emsg));
-		http_writeBlock(web, "
", 6); - } - talloc_free(buf); -} - -/* - 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 -*/ -static bool http_preauth(struct esp_state *esp) -{ - const char *path = http_local_path(esp->web, - HTTP_PREAUTH_URI, - lp_swat_directory(esp->web->task->lp_ctx)); - int i; - if (path == NULL) { - http_error(esp->web, 500, "Internal server error"); - return false; - } - if (!file_exist(path)) { - /* if the preath script is not installed then allow access */ - return true; - } - esp_request(esp, HTTP_PREAUTH_URI); - for (i=0;iweb->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 */ - http_setHeader(esp->web, "Content-Type: text/html", 0); - return false; - } - } - data_blob_free(&esp->web->output.content); - return true; -} - - -/* - handling of + and % escapes in http variables -*/ -static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p) -{ - char *s0 = talloc_strdup(mem_ctx, p); - char *s = s0; - if (s == NULL) return NULL; - - while (*s) { - unsigned v; - if (*s == '+') *s = ' '; - if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) { - *s = (char)v; - memmove(s+1, s+3, strlen(s+3)+1); - } - s++; - } - - return s0; -} - -/* - set a form or GET variable -*/ -static void esp_putvar(struct esp_state *esp, const char *var, const char *value) -{ - if (strcasecmp(var, SAMBA_SESSION_KEY) == 0) { - /* special case support for browsers without cookie - support */ - esp->web->input.session_key = talloc_strdup(esp, value); - } else { - mprSetPropertyValue(&esp->variables[ESP_FORM_OBJ], - http_unescape(esp, var), - mprCreateStringVar(http_unescape(esp, value), 0)); - } -} - - -/* - parse the variables in a POST style request -*/ -static NTSTATUS http_parse_post(struct esp_state *esp) -{ - DATA_BLOB b = esp->web->input.partial; - - while (b.length) { - char *p, *line; - size_t len; - - p = memchr(b.data, '&', b.length); - if (p == NULL) { - len = b.length; - } else { - len = p - (char *)b.data; - } - line = talloc_strndup(esp, (char *)b.data, len); - NT_STATUS_HAVE_NO_MEMORY(line); - - p = strchr(line,'='); - if (p) { - *p = 0; - esp_putvar(esp, line, p+1); - } - talloc_free(line); - b.length -= len; - b.data += len; - if (b.length > 0) { - b.length--; - b.data++; - } - } - - return NT_STATUS_OK; -} - -/* - parse the variables in a GET style request -*/ -static NTSTATUS http_parse_get(struct esp_state *esp) -{ - struct websrv_context *web = esp->web; - char *p, *s, *tok; - char *pp; - - p = strchr(web->input.url, '?'); - web->input.query_string = p+1; - *p = 0; - - s = talloc_strdup(esp, esp->web->input.query_string); - NT_STATUS_HAVE_NO_MEMORY(s); - - for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) { - p = strchr(tok,'='); - if (p) { - *p = 0; - esp_putvar(esp, tok, p+1); - } - } - return NT_STATUS_OK; -} - -/* - called when a session times out -*/ -static void session_timeout(struct event_context *ev, struct timed_event *te, - struct timeval t, void *private) -{ - struct session_data *s = talloc_get_type(private, struct session_data); - talloc_free(s); -} - -/* - destroy a session - */ -static int session_destructor(struct session_data *s) -{ - DLIST_REMOVE(s->edata->sessions, s); - return 0; -} - -/* - setup the session for this request -*/ -static void http_setup_session(struct esp_state *esp) -{ - const char *session_key = SAMBA_SESSION_KEY; - char *p; - const char *cookie = esp->web->input.cookie; - const char *key = NULL; - struct esp_data *edata = talloc_get_type(esp->web->task->private, struct esp_data); - struct session_data *s; - bool generated_key = false; - - /* look for our session key */ - if (cookie && (p = strstr(cookie, session_key)) && - p[strlen(session_key)] == '=') { - p += strlen(session_key)+1; - key = talloc_strndup(esp, p, strcspn(p, ";")); - } - - if (key == NULL && esp->web->input.session_key) { - key = esp->web->input.session_key; - } else if (key == NULL) { - key = generate_random_str_list(esp, 16, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - generated_key = true; - } - - /* try to find this session in the existing session list */ - for (s=edata->sessions;s;s=s->next) { - if (strcmp(key, s->id) == 0) { - break; - } - } - - if (s == NULL) { - /* create a new session */ - s = talloc_zero(edata, struct session_data); - s->id = talloc_steal(s, key); - s->data = NULL; - s->te = NULL; - s->edata = edata; - s->lifetime = lp_parm_int(esp->web->task->lp_ctx, NULL, "web", "sessiontimeout", 900); - DLIST_ADD(edata->sessions, s); - talloc_set_destructor(s, session_destructor); - if (!generated_key) { - mprSetPropertyValue(&esp->variables[ESP_REQUEST_OBJ], - "SESSION_EXPIRED", mprCreateStringVar("true", 0)); - } - } - - http_setCookie(esp->web, session_key, key, s->lifetime, "/", 0); - - if (s->data) { - mprCopyVar(&esp->variables[ESP_SESSION_OBJ], s->data, MPR_DEEP_COPY); - } - - esp->web->session = s; -} - - -/* callbacks for esp processing */ -static const struct Esp esp_control = { - .maxScriptSize = 60000, - .writeBlock = http_writeBlock, - .setHeader = http_setHeader, - .redirect = http_redirect, - .setResponseCode = http_setResponseCode, - .readFile = http_readFileFromSwatDir, - .mapToStorage = http_mapToStorage, - .setCookie = http_setCookie, - .createSession = http_createSession, - .destroySession = http_destroySession, - .getSessionId = http_getSessionId -}; - -/* - process a complete http request -*/ -void http_process_input(struct websrv_context *web) -{ - NTSTATUS status; - 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; - enum page_type { - page_type_simple, - page_type_esp - }; - enum page_type page_type; - const struct { - const char *extension; - const char *mime_type; - enum page_type page_type; - } mime_types[] = { - {"gif", "image/gif"}, - {"png", "image/png"}, - {"jpg", "image/jpeg"}, - {"txt", "text/plain"}, - {"ico", "image/x-icon"}, - {"css", "text/css"}, - {"esp", "text/html", true} - }; - - /* - * 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; - - mprSetCtx(esp); - - if (espOpen(&esp_control) != 0) goto internal_error; - - for (i=0;ivariables);i++) { - esp->variables[i] = mprCreateUndefinedVar(); - } - esp->variables[ESP_HEADERS_OBJ] = mprCreateObjVar("headers", ESP_HASH_SIZE); - esp->variables[ESP_FORM_OBJ] = mprCreateObjVar("form", ESP_HASH_SIZE); - esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE); - esp->variables[ESP_COOKIES_OBJ] = mprCreateObjVar("cookies", ESP_HASH_SIZE); - esp->variables[ESP_FILES_OBJ] = mprCreateObjVar("files", ESP_HASH_SIZE); - esp->variables[ESP_REQUEST_OBJ] = mprCreateObjVar("request", ESP_HASH_SIZE); - esp->variables[ESP_SERVER_OBJ] = mprCreateObjVar("server", ESP_HASH_SIZE); - esp->variables[ESP_SESSION_OBJ] = mprCreateObjVar("session", ESP_HASH_SIZE); - - if (edata->application_data) { - mprCopyVar(&esp->variables[ESP_APPLICATION_OBJ], - edata->application_data, MPR_DEEP_COPY); - } - - 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"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - - /* parse any form or get variables */ - if (web->input.post_request) { - status = http_parse_post(esp); - if (!NT_STATUS_IS_OK(status)) { - http_error(web, 400, "Malformed POST data"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - } - if (strchr(web->input.url, '?')) { - status = http_parse_get(esp); - if (!NT_STATUS_IS_OK(status)) { - http_error(web, 400, "Malformed GET data"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - } - - http_setup_session(esp); - - esp->req = espCreateRequest(web, web->input.url, esp->variables); - if (esp->req == NULL) goto internal_error; - - p = strrchr(web->input.url, '.'); - if (p == NULL) { - page_type = page_type_esp; - file_type = "text/html"; - } - for (i=0;p && iinput.url); - } - break; - } - - if (web->conn == NULL) { - /* the connection has been terminated above us, probably - via a timeout */ - goto internal_error; - } - - if (!web->output.output_pending) { - http_output_headers(web); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; - } - - /* copy any application data to long term storage in edata */ - talloc_free(edata->application_data); - edata->application_data = talloc_zero(edata, struct MprVar); - mprSetCtx(edata->application_data); - mprCopyVar(edata->application_data, &esp->variables[ESP_APPLICATION_OBJ], - MPR_DEEP_COPY); - mprSetCtx(esp); - - /* copy any session data */ - if (web->session) { - talloc_free(web->session->data); - web->session->data = talloc_zero(web->session, struct MprVar); - if (esp->variables[ESP_SESSION_OBJ].properties == NULL || - esp->variables[ESP_SESSION_OBJ].properties[0].numItems == 0) { - talloc_free(web->session); - web->session = NULL; - } else { - mprSetCtx(web->session->data); - mprCopyVar(web->session->data, &esp->variables[ESP_SESSION_OBJ], - MPR_DEEP_COPY); - /* setup the timeout for the session data */ - mprSetCtx(esp); - talloc_free(web->session->te); - web->session->te = event_add_timed(web->conn->event.ctx, web->session, - timeval_current_ofs(web->session->lifetime, 0), - session_timeout, web->session); - } - } - - talloc_free(esp); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - -internal_error: - mprSetCtx(esp); - talloc_free(esp); - if (web->conn != NULL) { - http_error(web, 500, "Internal server error"); - } - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); -} - - -/* - parse one line of header input -*/ -NTSTATUS http_parse_header(struct websrv_context *web, const char *line) -{ - if (line[0] == 0) { - web->input.end_of_headers = true; - } else if (strncasecmp(line,"GET ", 4)==0) { - web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t")); - } else if (strncasecmp(line,"POST ", 5)==0) { - web->input.post_request = true; - web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); - } else if (strchr(line, ':') == NULL) { - http_error(web, 400, "This server only accepts GET and POST requests"); - return NT_STATUS_INVALID_PARAMETER; - } else if (strncasecmp(line,"Content-Length: ", 16)==0) { - web->input.content_length = strtoul(&line[16], NULL, 10); - } else { -#define PULL_HEADER(v, s) do { \ - if (strncmp(line, s, strlen(s)) == 0) { \ - web->input.v = talloc_strdup(web, &line[strlen(s)]); \ - return NT_STATUS_OK; \ - } \ -} while (0) - PULL_HEADER(content_type, "Content-Type: "); - PULL_HEADER(user_agent, "User-Agent: "); - PULL_HEADER(referer, "Referer: "); - PULL_HEADER(host, "Host: "); - PULL_HEADER(accept_encoding, "Accept-Encoding: "); - PULL_HEADER(accept_language, "Accept-Language: "); - PULL_HEADER(accept_charset, "Accept-Charset: "); - PULL_HEADER(cookie, "Cookie: "); - } - - /* ignore all other headers for now */ - return NT_STATUS_OK; -} - - -/* - setup the esp processor - called at task initialisation -*/ -NTSTATUS http_setup_esp(struct task_server *task) -{ - struct esp_data *edata; - - edata = talloc_zero(task, struct esp_data); - NT_STATUS_HAVE_NO_MEMORY(edata); - - task->private = edata; - - edata->tls_params = tls_initialise(edata, task->lp_ctx); - NT_STATUS_HAVE_NO_MEMORY(edata->tls_params); - - return NT_STATUS_OK; -} diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index ac83a3384d..bfbd254d9e 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -280,8 +280,8 @@ static void websrv_task_init(struct task_server *task) /* startup the esp processor - unfortunately we can't do this per connection as that wouldn't allow for session variables */ - status = http_setup_esp(task); - if (!NT_STATUS_IS_OK(status)) goto failed; + task->private = http_setup_esp(task, task->lp_ctx); + if (task->private == NULL) goto failed; return; -- cgit From 4bb17b60ef608b10284ccd2146c9344cc43b8637 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 23 May 2008 21:21:07 +0200 Subject: Add initial work on WSGI support in the web server. --- source4/web_server/config.mk | 2 +- source4/web_server/wsgi.c | 69 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 source4/web_server/wsgi.c (limited to 'source4/web_server') diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index 4094d6be07..810cc7f430 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -10,6 +10,6 @@ PRIVATE_DEPENDENCIES = ESP LIBTLS smbcalls process_model # End SUBSYSTEM WEB ####################### -WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o esp.o) +WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o esp.o wsgi.o) $(eval $(call proto_header_template,$(web_serversrcdir)/proto.h,$(WEB_OBJ_FILES:.o=.c))) diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c new file mode 100644 index 0000000000..50f8599869 --- /dev/null +++ b/source4/web_server/wsgi.c @@ -0,0 +1,69 @@ +/* + Unix SMB/CIFS implementation. + Samba utility functions + Copyright © Jelmer Vernooij 2008 + + Implementation of the WSGI interface described in PEP0333 + (http://www.python.org/dev/peps/pep-0333) + + 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 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + 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, see . +*/ + +#include "includes.h" +#include + +static PyObject *start_response(PyObject *args, PyObject *kwargs) +{ + PyObject *response_header, *exc_info; + char *status; + const char *kwnames[] = { + "status", "response_header", "exc_info", NULL + }; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"sOO:start_response", (char **)kwnames, &status, &response_header, &exc_info)) { + return NULL; + } + + /* FIXME: response_header, exc_info */ + + /* FIXME: Wrap stdout */ + return NULL; +} + +static PyObject *create_environ(void) +{ + PyObject *env, *osmodule, *osenviron; + + osmodule = PyImport_ImportModule("os"); + if (osmodule == NULL) + return NULL; + + osenviron = PyObject_CallMethod(osmodule, "environ", NULL); + + env = PyDict_Copy(osenviron); + + PyDict_SetItemString(env, "wsgi.input", NULL); /* FIXME */ + PyDict_SetItemString(env, "wsgi.errors", NULL); /* FIXME */ + PyDict_SetItemString(env, "wsgi.version", Py_BuildValue("(i,i)", 1, 0)); + PyDict_SetItemString(env, "wsgi.multithread", Py_False); + PyDict_SetItemString(env, "wsgi.multiprocess", Py_True); + PyDict_SetItemString(env, "wsgi.run_once", Py_False); + + /* FIXME: + PyDict_SetItemString(env, "wsgi.url_scheme", "http"); + PyDict_SetItemString(env, "wsgi.url_scheme", "https"); + */ + + return env; +} -- cgit From a4e8ff7429db8620a4d91e901295413560be6c91 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sat, 24 May 2008 03:54:47 +0200 Subject: Add more parts of the WSGI implementation. --- source4/web_server/wsgi.c | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) (limited to 'source4/web_server') diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 50f8599869..3253873de2 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -41,9 +41,32 @@ static PyObject *start_response(PyObject *args, PyObject *kwargs) return NULL; } +/* + * read(size) input 1 + * readline() input 1,2 + * readlines(hint) input 1,3 + * __iter__() input + * flush() errors 4 + * write(str) errors + * writelines(seq) errors + */ + +static PyObject *Py_InputHttpStream(void *foo) +{ + /* FIXME */ + return NULL; +} + +static PyObject *Py_ErrorHttpStream(void) +{ + /* FIXME */ + return NULL; +} + static PyObject *create_environ(void) { PyObject *env, *osmodule, *osenviron; + PyObject *inputstream, *errorstream; osmodule = PyImport_ImportModule("os"); if (osmodule == NULL) @@ -53,8 +76,23 @@ static PyObject *create_environ(void) env = PyDict_Copy(osenviron); - PyDict_SetItemString(env, "wsgi.input", NULL); /* FIXME */ - PyDict_SetItemString(env, "wsgi.errors", NULL); /* FIXME */ + Py_DECREF(env); + + inputstream = Py_InputHttpStream(NULL); /* FIXME */ + if (inputstream == NULL) { + Py_DECREF(env); + return NULL; + } + + errorstream = Py_ErrorHttpStream(); + if (errorstream == NULL) { + Py_DECREF(env); + Py_DECREF(inputstream); + return NULL; + } + + PyDict_SetItemString(env, "wsgi.input", inputstream); + PyDict_SetItemString(env, "wsgi.errors", errorstream); PyDict_SetItemString(env, "wsgi.version", Py_BuildValue("(i,i)", 1, 0)); PyDict_SetItemString(env, "wsgi.multithread", Py_False); PyDict_SetItemString(env, "wsgi.multiprocess", Py_True); -- cgit From 2df040d8995b3198be8d3e1099eeb89860a3222d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sat, 24 May 2008 15:43:37 +0200 Subject: Add input / error stream objects in WSGI implementation. --- source4/web_server/wsgi.c | 113 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 100 insertions(+), 13 deletions(-) (limited to 'source4/web_server') diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 3253873de2..54adeb0943 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -41,28 +41,115 @@ static PyObject *start_response(PyObject *args, PyObject *kwargs) return NULL; } -/* - * read(size) input 1 - * readline() input 1,2 - * readlines(hint) input 1,3 - * __iter__() input - * flush() errors 4 - * write(str) errors - * writelines(seq) errors - */ +typedef struct { + PyObject_HEAD +} error_Stream_Object; -static PyObject *Py_InputHttpStream(void *foo) +static PyObject *py_error_flush(PyObject *self, PyObject *args, PyObject *kwargs) +{ + /* Nothing to do here */ + return Py_None; +} + +static PyObject *py_error_write(PyObject *self, PyObject *args, PyObject *kwargs) +{ + const char *kwnames[] = { "str", NULL }; + char *str = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"s:write", (char **)kwnames, &str)) { + return NULL; + } + + DEBUG(0, ("WSGI App: %s", str)); + + return Py_None; +} + +static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *kwargs) +{ + const char *kwnames[] = { "seq", NULL }; + PyObject *seq = NULL, *item; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"O:writelines", (char **)kwnames, &seq)) { + return NULL; + } + + while ((item = PyIter_Next(seq))) { + char *str = PyString_AsString(item); + + DEBUG(0, ("WSGI App: %s", str)); + } + + return Py_None; +} + +static PyMethodDef error_Stream_methods[] = { + { "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL }, + { "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL }, + { "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL }, + { NULL, NULL, 0, NULL } +}; + +PyTypeObject error_Stream_Type = { + PyObject_HEAD_INIT(NULL) 0, + .tp_name = "wsgi.ErrorStream", + .tp_basicsize = sizeof(error_Stream_Object), + .tp_methods = error_Stream_methods, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, +}; + +typedef struct { + PyObject_HEAD +} input_Stream_Object; + +static PyObject *py_input_read(PyObject *self, PyObject *args, PyObject *kwargs) { - /* FIXME */ return NULL; } -static PyObject *Py_ErrorHttpStream(void) +static PyObject *py_input_readline(PyObject *self, PyObject *args, PyObject *kwargs) +{ + return NULL; +} + +static PyObject *py_input_readlines(PyObject *self, PyObject *args, PyObject *kwargs) +{ + return NULL; +} + +static PyObject *py_input___iter__(PyObject *self, PyObject *args, PyObject *kwargs) { - /* FIXME */ return NULL; } +static PyMethodDef input_Stream_methods[] = { + { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readline", (PyCFunction)py_input_readline, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL }, + { "__iter__", (PyCFunction)py_input___iter__, METH_VARARGS|METH_KEYWORDS, NULL }, + { NULL, NULL, 0, NULL } +}; + +PyTypeObject input_Stream_Type = { + PyObject_HEAD_INIT(NULL) 0, + .tp_name = "wsgi.InputStream", + .tp_basicsize = sizeof(input_Stream_Object), + .tp_methods = input_Stream_methods, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, +}; + +static PyObject *Py_InputHttpStream(void *foo) +{ + PyObject *ret = PyObject_New(input_Stream_Object, &input_Stream_Type); + return ret; +} + +static PyObject *Py_ErrorHttpStream(void) +{ + PyObject *ret = PyObject_New(error_Stream_Object, &error_Stream_Type); + return ret; +} + static PyObject *create_environ(void) { PyObject *env, *osmodule, *osenviron; -- cgit From fda85985e91179f8e03538581335326f54456f4f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sat, 24 May 2008 18:13:30 +0200 Subject: Remove some dependencies of the web server on esp. --- source4/web_server/esp.c | 38 +++++++++++++++++++++++++------------- source4/web_server/web_server.c | 20 +++++++++++++++----- source4/web_server/web_server.h | 23 ++++++----------------- source4/web_server/wsgi.c | 24 +++++++++++++++--------- 4 files changed, 61 insertions(+), 44 deletions(-) (limited to 'source4/web_server') diff --git a/source4/web_server/esp.c b/source4/web_server/esp.c index 901a1558c4..29bda2a965 100644 --- a/source4/web_server/esp.c +++ b/source4/web_server/esp.c @@ -37,6 +37,24 @@ #define SAMBA_SESSION_KEY "SambaSessionId" #define HTTP_PREAUTH_URI "/scripting/preauth.esp" +/* + context for long term storage in the web server, to support session[] + and application[] data. Stored in task->private. +*/ +struct esp_data { + struct session_data { + struct session_data *next, *prev; + struct esp_data *edata; + const char *id; + struct MprVar *data; + struct timed_event *te; + int lifetime; + } *sessions; + struct MprVar *application_data; +}; + + + /* state of the esp subsystem for a specific request */ struct esp_state { struct websrv_context *web; @@ -413,10 +431,9 @@ invalid: /* setup the standard ESP arrays */ -static void http_setup_arrays(struct esp_state *esp) +static void http_setup_arrays(struct web_server_data *wdata, struct esp_state *esp) { struct websrv_context *web = esp->web; - 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_peer_addr(web->conn->socket, esp); @@ -474,7 +491,7 @@ static void http_setup_arrays(struct esp_state *esp) 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"); + SETVAR(ESP_SERVER_OBJ, "TLS_SUPPORT", tls_support(wdata->tls_params)?"true":"false"); } #if HAVE_SETJMP_H @@ -696,13 +713,12 @@ static int session_destructor(struct session_data *s) /* setup the session for this request */ -static void http_setup_session(struct esp_state *esp) +static void http_setup_session(struct esp_data *edata, struct esp_state *esp) { const char *session_key = SAMBA_SESSION_KEY; char *p; const char *cookie = esp->web->input.cookie; const char *key = NULL; - struct esp_data *edata = talloc_get_type(esp->web->task->private, struct esp_data); struct session_data *s; bool generated_key = false; @@ -771,11 +787,11 @@ static const struct Esp esp_control = { /* process a complete http request */ -void http_process_input(struct websrv_context *web) +void esp_process_http_input(struct web_server_data *wdata, struct websrv_context *web) { NTSTATUS status; struct esp_state *esp = NULL; - struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data); + struct esp_data *edata = talloc_get_type(wdata->private, struct esp_data); struct smbcalls_context *smbcalls_ctx; char *p; void *save_mpr_ctx = mprMemCtx(); @@ -865,7 +881,7 @@ void http_process_input(struct websrv_context *web) } } - http_setup_session(esp); + http_setup_session(edata, esp); esp->req = espCreateRequest(web, web->input.url, esp->variables); if (esp->req == NULL) goto internal_error; @@ -894,7 +910,7 @@ void http_process_input(struct websrv_context *web) http_setHeader(web, "Connection: close", 0); http_setHeader(web, talloc_asprintf(esp, "Content-Type: %s", file_type), 0); - http_setup_arrays(esp); + http_setup_arrays(wdata, esp); /* * Do pre-authentication. If pre-authentication succeeds, do @@ -1022,9 +1038,5 @@ struct esp_data *http_setup_esp(TALLOC_CTX *mem_ctx, struct loadparm_context *lp if (edata == NULL) return NULL; - edata->tls_params = tls_initialise(edata, lp_ctx); - if (edata->tls_params == NULL) - return NULL; - return edata; } diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index bfbd254d9e..6d8b2a2758 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -123,7 +123,7 @@ static void websrv_recv(struct stream_connection *conn, uint16_t flags) destroy the stack variables being used by that rendering process when we handle the timeout. */ if (!talloc_reference(web->task, web)) goto failed; - http_process_input(web); + web->http_process_input(web); talloc_unlink(web->task, web); } return; @@ -192,13 +192,14 @@ static void websrv_send(struct stream_connection *conn, uint16_t flags) static void websrv_accept(struct stream_connection *conn) { struct task_server *task = talloc_get_type(conn->private, struct task_server); - struct esp_data *edata = talloc_get_type(task->private, struct esp_data); + struct web_server_data *wdata = talloc_get_type(task->private, struct web_server_data); struct websrv_context *web; struct socket_context *tls_socket; web = talloc_zero(conn, struct websrv_context); if (web == NULL) goto failed; + web->http_process_input = esp_process_http_input; web->task = task; web->conn = conn; conn->private = web; @@ -210,7 +211,7 @@ static void websrv_accept(struct stream_connection *conn) websrv_timeout, web); /* Overwrite the socket with a (possibly) TLS socket */ - tls_socket = tls_init_server(edata->tls_params, conn->socket, + tls_socket = tls_init_server(wdata->tls_params, conn->socket, conn->event.fde, "GPHO"); /* We might not have TLS, or it might not have initilised */ if (tls_socket) { @@ -243,6 +244,7 @@ static void websrv_task_init(struct task_server *task) NTSTATUS status; uint16_t port = lp_web_port(task->lp_ctx); const struct model_ops *model_ops; + struct web_server_data *wdata; task_server_set_title(task, "task[websrv]"); @@ -280,8 +282,16 @@ static void websrv_task_init(struct task_server *task) /* startup the esp processor - unfortunately we can't do this per connection as that wouldn't allow for session variables */ - task->private = http_setup_esp(task, task->lp_ctx); - if (task->private == NULL) goto failed; + wdata = talloc_zero(task, struct web_server_data); + if (wdata == NULL)goto failed; + + task->private = wdata; + + wdata->tls_params = tls_initialise(wdata, task->lp_ctx); + if (wdata->tls_params == NULL) goto failed; + + wdata->private = http_setup_esp(task, task->lp_ctx); + if (wdata->private == NULL) goto failed; return; diff --git a/source4/web_server/web_server.h b/source4/web_server/web_server.h index 52aff05dcc..0ce68bdd17 100644 --- a/source4/web_server/web_server.h +++ b/source4/web_server/web_server.h @@ -19,12 +19,18 @@ #include "smbd/process_model.h" +struct web_server_data { + struct tls_params *tls_params; + void *private; +}; + /* context of one open web connection */ struct websrv_context { struct task_server *task; struct stream_connection *conn; + void (*http_process_input)(struct websrv_context *web); struct { bool tls_detect; bool tls_first_char; @@ -57,22 +63,5 @@ struct websrv_context { }; -/* - context for long term storage in the web server, to support session[] - and application[] data. Stored in task->private. -*/ -struct esp_data { - struct session_data { - struct session_data *next, *prev; - struct esp_data *edata; - const char *id; - struct MprVar *data; - struct timed_event *te; - int lifetime; - } *sessions; - struct MprVar *application_data; - struct tls_params *tls_params; -}; - #include "web_server/proto.h" diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 54adeb0943..32b1f0dbc2 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -21,9 +21,10 @@ */ #include "includes.h" +#include "web_server/web_server.h" #include -static PyObject *start_response(PyObject *args, PyObject *kwargs) +static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs) { PyObject *response_header, *exc_info; char *status; @@ -84,9 +85,9 @@ static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *k } static PyMethodDef error_Stream_methods[] = { - { "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL }, - { "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL }, - { "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL }, + { "flush", (PyCFunction)py_error_flush, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "write", (PyCFunction)py_error_write, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "writelines", (PyCFunction)py_error_writelines, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, { NULL, NULL, 0, NULL } }; @@ -123,10 +124,10 @@ static PyObject *py_input___iter__(PyObject *self, PyObject *args, PyObject *kwa } static PyMethodDef input_Stream_methods[] = { - { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL }, - { "readline", (PyCFunction)py_input_readline, METH_VARARGS|METH_KEYWORDS, NULL }, - { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL }, - { "__iter__", (PyCFunction)py_input___iter__, METH_VARARGS|METH_KEYWORDS, NULL }, + { "read", (PyCFunction)py_input_read, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "readline", (PyCFunction)py_input_readline, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "readlines", (PyCFunction)py_input_readlines, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "__iter__", (PyCFunction)py_input___iter__, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, { NULL, NULL, 0, NULL } }; @@ -165,7 +166,7 @@ static PyObject *create_environ(void) Py_DECREF(env); - inputstream = Py_InputHttpStream(NULL); /* FIXME */ + inputstream = Py_InputHttpStream(NULL); if (inputstream == NULL) { Py_DECREF(env); return NULL; @@ -192,3 +193,8 @@ static PyObject *create_environ(void) return env; } + +void wsgi_process_http_input(struct websrv_context *web) +{ + +} -- cgit From 1271066234fed0e5f0e28a1e75420482abd20887 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 16:53:29 +0200 Subject: Remove support for ESP in the web server. --- source4/web_server/config.mk | 5 +- source4/web_server/esp.c | 1042 --------------------------------------- source4/web_server/web_server.c | 63 ++- source4/web_server/web_server.h | 18 +- source4/web_server/wsgi.c | 14 +- 5 files changed, 76 insertions(+), 1066 deletions(-) delete mode 100644 source4/web_server/esp.c (limited to 'source4/web_server') diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index 810cc7f430..af3ac5f544 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,12 +4,11 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init -ENABLE = NO SUBSYSTEM = smbd -PRIVATE_DEPENDENCIES = ESP LIBTLS smbcalls process_model +PRIVATE_DEPENDENCIES = LIBTLS smbcalls process_model LIBPYTHON # End SUBSYSTEM WEB ####################### -WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o esp.o wsgi.o) +WEB_OBJ_FILES = $(addprefix $(web_serversrcdir)/, web_server.o wsgi.o) $(eval $(call proto_header_template,$(web_serversrcdir)/proto.h,$(WEB_OBJ_FILES:.o=.c))) diff --git a/source4/web_server/esp.c b/source4/web_server/esp.c deleted file mode 100644 index 29bda2a965..0000000000 --- a/source4/web_server/esp.c +++ /dev/null @@ -1,1042 +0,0 @@ -/* - Unix SMB/CIFS implementation. - - http handling code - - Copyright (C) Andrew Tridgell 2005 - - 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 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - 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, see . -*/ - -#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 "lib/util/dlinklist.h" -#include "lib/tls/tls.h" -#include "scripting/ejs/smbcalls.h" -#include "param/param.h" - -#define SAMBA_SESSION_KEY "SambaSessionId" -#define HTTP_PREAUTH_URI "/scripting/preauth.esp" - -/* - context for long term storage in the web server, to support session[] - and application[] data. Stored in task->private. -*/ -struct esp_data { - struct session_data { - struct session_data *next, *prev; - struct esp_data *edata; - const char *id; - struct MprVar *data; - struct timed_event *te; - int lifetime; - } *sessions; - struct MprVar *application_data; -}; - - - -/* state of the esp subsystem for a specific request */ -struct esp_state { - struct websrv_context *web; - struct EspRequest *req; - struct MprVar variables[ESP_OBJ_MAX]; - struct session_data *session; -}; - -/* - output the http headers -*/ -static void http_output_headers(struct websrv_context *web) -{ - int i; - char *s; - DATA_BLOB b; - uint32_t content_length = 0; - const char *response_string = "Unknown Code"; - const struct { - unsigned code; - const char *response_string; - } codes[] = { - { 200, "OK" }, - { 301, "Moved" }, - { 302, "Found" }, - { 303, "Method" }, - { 304, "Not Modified" }, - { 400, "Bad request" }, - { 401, "Unauthorized" }, - { 403, "Forbidden" }, - { 404, "Not Found" }, - { 500, "Internal Server Error" }, - { 501, "Not implemented" } - }; - for (i=0;ioutput.response_code) { - response_string = codes[i].response_string; - } - } - - if (web->output.headers == NULL) return; - s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n", - web->output.response_code, response_string); - if (s == NULL) return; - for (i=0;web->output.headers[i];i++) { - s = talloc_asprintf_append_buffer(s, "%s\r\n", web->output.headers[i]); - } - - /* work out the content length */ - content_length = web->output.content.length; - if (web->output.fd != -1) { - struct stat st; - fstat(web->output.fd, &st); - content_length += st.st_size; - } - s = talloc_asprintf_append_buffer(s, "Content-Length: %u\r\n\r\n", content_length); - if (s == NULL) return; - - b = web->output.content; - web->output.content = data_blob_string_const(s); - data_blob_append(web, &web->output.content, b.data, b.length); - data_blob_free(&b); -} - -/* - return the local path for a URL -*/ -static const char *http_local_path(struct websrv_context *web, - const char *url, - const char *base_dir) -{ - int i; - char *path; - - /* check that the url is OK */ - if (url[0] != '/') return NULL; - - for (i=0;url[i];i++) { - if ((!isalnum((unsigned char)url[i]) && !strchr("./_-", url[i])) || - (url[i] == '.' && strchr("/.", url[i+1]))) { - return NULL; - } - } - - path = talloc_asprintf(web, "%s/%s", base_dir, url+1); - if (path == NULL) return NULL; - - if (directory_exist(path)) { - path = talloc_asprintf_append_buffer(path, "/index.esp"); - } - return path; -} - -/* - 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, - 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, base_dir); - if (path == NULL) goto failed; - - fd = open(path, O_RDONLY); - if (fd == -1 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) goto failed; - - *buf = talloc_array(handle, char, st.st_size+1); - if (*buf == NULL) goto failed; - - if (read(fd, *buf, st.st_size) != st.st_size) goto failed; - - (*buf)[st.st_size] = 0; - - close(fd); - *len = st.st_size; - return 0; - -failed: - DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); - if (fd != -1) close(fd); - talloc_free(*buf); - *buf = NULL; - return -1; -} - -static int http_readFileFromSwatDir(EspHandle handle, char **buf, int *len, - const char *path) -{ - return http_readFile(handle, buf, len, path, - lp_swat_directory(global_loadparm)); -} - - - -/* - called when esp wants to find the real path of a file -*/ -static int http_mapToStorage(EspHandle handle, char *path, int len, const char *uri, int flags) -{ - if (uri == NULL || strlen(uri) >= len) return -1; - strncpy(path, uri, len); - return 0; -} - -/* - called when esp wants to output something -*/ -static int http_writeBlock(EspHandle handle, const char *buf, int size) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - if (!data_blob_append(web, &web->output.content, buf, size)) - return -1; - return size; -} - - -/* - set a http header -*/ -static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - char *p = strchr(value, ':'); - - if (p && !allowMultiple && web->output.headers) { - int i; - for (i=0;web->output.headers[i];i++) { - if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) { - web->output.headers[i] = talloc_strdup(web, value); - return; - } - } - } - - web->output.headers = str_list_add(web->output.headers, value); - talloc_steal(web, web->output.headers); -} - -/* - set a http response code -*/ -static void http_setResponseCode(EspHandle handle, int code) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - web->output.response_code = code; -} - -/* - redirect to another web page - */ -static void http_redirect(EspHandle handle, int code, char *url) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - const char *host = web->input.host; - - /* form the full url, unless it already looks like a url */ - if (strchr(url, ':') == NULL) { - if (host == NULL) { - struct socket_address *socket_address = socket_get_my_addr(web->conn->socket, web); - if (socket_address == NULL) goto internal_error; - host = talloc_asprintf(web, "%s:%u", - socket_address->addr, socket_address->port); - } - if (host == NULL) goto internal_error; - if (url[0] != '/') { - char *p = strrchr(web->input.url, '/'); - if (p == web->input.url) { - url = talloc_asprintf(web, "http%s://%s/%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->conn->socket)?"s":"", - host, - dirlen, dirlen, web->input.url, - url); - } - if (url == NULL) goto internal_error; - } - } - - http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0); - - /* make sure we give a valid redirect code */ - if (code >= 300 && code < 400) { - http_setResponseCode(handle, code); - } else { - http_setResponseCode(handle, 302); - } - return; - -internal_error: - http_error(web, 500, "Internal server error"); -} - - -/* - setup a cookie -*/ -static void http_setCookie(EspHandle handle, const char *name, const char *value, - int lifetime, const char *path, bool secure) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - char *buf; - - if (lifetime > 0) { - buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; Expires=%s; %s", - name, value, path?path:"/", - http_timestring(web, time(NULL)+lifetime), - secure?"secure":""); - } else { - buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; %s", - name, value, path?path:"/", - secure?"secure":""); - } - http_setHeader(handle, "Cache-control: no-cache=\"set-cookie\"", 0); - http_setHeader(handle, buf, 0); - talloc_free(buf); -} - -/* - return the session id -*/ -static const char *http_getSessionId(EspHandle handle) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - return web->session->id; -} - -/* - setup a session -*/ -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, SAMBA_SESSION_KEY, web->session->id, - web->session->lifetime, "/", 0); - } -} - -/* - destroy a session -*/ -static void http_destroySession(EspHandle handle) -{ - struct websrv_context *web = talloc_get_type(handle, struct websrv_context); - talloc_free(web->session); - web->session = NULL; -} - - -/* - setup for a raw http level error -*/ -void http_error(struct websrv_context *web, int code, const char *info) -{ - char *s; - s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", - code, code, info); - if (s == NULL) { - stream_terminate_connection(web->conn, "http_error: out of memory"); - return; - } - http_writeBlock(web, s, strlen(s)); - http_setResponseCode(web, code); - http_output_headers(web); - EVENT_FD_NOT_READABLE(web->conn->event.fde); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; -} - -/* - map a unix error code to a http error -*/ -void http_error_unix(struct websrv_context *web, const char *info) -{ - int code = 500; - switch (errno) { - case ENOENT: - case EISDIR: - code = 404; - break; - case EACCES: - code = 403; - break; - } - info = talloc_asprintf(web, "%s

%s

\n", info, strerror(errno)); - http_error(web, code, info); -} - - -/* - a simple file request -*/ -static void http_simple_request(struct websrv_context *web) -{ - const char *url = web->input.url; - const char *path; - struct stat st; - - path = http_local_path(web, url, lp_swat_directory(web->task->lp_ctx)); - if (path == NULL) goto invalid; - - /* looks ok */ - web->output.fd = open(path, O_RDONLY); - if (web->output.fd == -1) { - DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno))); - http_error_unix(web, path); - return; - } - - if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) { - close(web->output.fd); - goto invalid; - } - - return; - -invalid: - http_error(web, 400, "Malformed URL"); -} - -/* - setup the standard ESP arrays -*/ -static void http_setup_arrays(struct web_server_data *wdata, struct esp_state *esp) -{ - struct websrv_context *web = esp->web; - 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_peer_addr(web->conn->socket, esp); - char *p; - -#define SETVAR(type, name, value) do { \ - const char *v = value; \ - if (v) espSetStringVar(req, type, name, v); \ -} while (0) - - 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); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_HOST", p); - SETVAR(ESP_REQUEST_OBJ, "REMOTE_USER", ""); - SETVAR(ESP_REQUEST_OBJ, "CONTENT_TYPE", web->input.content_type); - if (web->session) { - SETVAR(ESP_REQUEST_OBJ, "SESSION_ID", web->session->id); - } - SETVAR(ESP_REQUEST_OBJ, "COOKIE_SUPPORT", web->input.cookie?"true":"false"); - - 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); - SETVAR(ESP_HEADERS_OBJ, "ACCEPT_CHARSET", web->input.accept_charset); - SETVAR(ESP_HEADERS_OBJ, "COOKIE", web->input.cookie); - SETVAR(ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent); - - if (socket_address) { - SETVAR(ESP_SERVER_OBJ, "SERVER_ADDR", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_NAME", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_HOST", socket_address->addr); - SETVAR(ESP_SERVER_OBJ, "SERVER_PORT", - talloc_asprintf(esp, "%u", socket_address->port)); - } - - SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_swat_directory(esp->web->task->lp_ctx)); - 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(wdata->tls_params)?"true":"false"); -} - -#if HAVE_SETJMP_H -/* the esp scripting lirary generates exceptions when - it hits a major error. We need to catch these and - report a internal server error via http -*/ -static jmp_buf ejs_exception_buf; -static const char *exception_reason; - -static void web_server_ejs_exception(const char *reason) -{ - Ejs *ep = ejsPtr(0); - if (ep) { - ejsSetErrorMsg(0, "%s", reason); - exception_reason = ep->error; - } else { - exception_reason = reason; - } - DEBUG(0,("%s", exception_reason)); - longjmp(ejs_exception_buf, -1); -} -#else -static void web_server_ejs_exception(const char *reason) -{ - DEBUG(0,("%s", reason)); - smb_panic(reason); -} -#endif - -/* - process a esp request -*/ -static void esp_request(struct esp_state *esp, const char *url) -{ - struct websrv_context *web = esp->web; - int size; - int res; - char *emsg = NULL, *buf; - - if (http_readFile(web, &buf, &size, url, lp_swat_directory(esp->web->task->lp_ctx)) != 0) { - http_error_unix(web, url); - return; - } - -#if HAVE_SETJMP_H - if (setjmp(ejs_exception_buf) != 0) { - http_error(web, 500, exception_reason); - return; - } -#endif - - res = espProcessRequest(esp->req, url, buf, &emsg); - if (res != 0 && emsg) { - http_writeBlock(web, "

", 5);
-		http_writeBlock(web, emsg, strlen(emsg));
-		http_writeBlock(web, "
", 6); - } - talloc_free(buf); -} - -/* - 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 -*/ -static bool http_preauth(struct esp_state *esp) -{ - const char *path = http_local_path(esp->web, - HTTP_PREAUTH_URI, - lp_swat_directory(esp->web->task->lp_ctx)); - int i; - if (path == NULL) { - http_error(esp->web, 500, "Internal server error"); - return false; - } - if (!file_exist(path)) { - /* if the preath script is not installed then allow access */ - return true; - } - esp_request(esp, HTTP_PREAUTH_URI); - for (i=0;iweb->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 */ - http_setHeader(esp->web, "Content-Type: text/html", 0); - return false; - } - } - data_blob_free(&esp->web->output.content); - return true; -} - - -/* - handling of + and % escapes in http variables -*/ -static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p) -{ - char *s0 = talloc_strdup(mem_ctx, p); - char *s = s0; - if (s == NULL) return NULL; - - while (*s) { - unsigned v; - if (*s == '+') *s = ' '; - if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) { - *s = (char)v; - memmove(s+1, s+3, strlen(s+3)+1); - } - s++; - } - - return s0; -} - -/* - set a form or GET variable -*/ -static void esp_putvar(struct esp_state *esp, const char *var, const char *value) -{ - if (strcasecmp(var, SAMBA_SESSION_KEY) == 0) { - /* special case support for browsers without cookie - support */ - esp->web->input.session_key = talloc_strdup(esp, value); - } else { - mprSetPropertyValue(&esp->variables[ESP_FORM_OBJ], - http_unescape(esp, var), - mprCreateStringVar(http_unescape(esp, value), 0)); - } -} - - -/* - parse the variables in a POST style request -*/ -static NTSTATUS http_parse_post(struct esp_state *esp) -{ - DATA_BLOB b = esp->web->input.partial; - - while (b.length) { - char *p, *line; - size_t len; - - p = memchr(b.data, '&', b.length); - if (p == NULL) { - len = b.length; - } else { - len = p - (char *)b.data; - } - line = talloc_strndup(esp, (char *)b.data, len); - NT_STATUS_HAVE_NO_MEMORY(line); - - p = strchr(line,'='); - if (p) { - *p = 0; - esp_putvar(esp, line, p+1); - } - talloc_free(line); - b.length -= len; - b.data += len; - if (b.length > 0) { - b.length--; - b.data++; - } - } - - return NT_STATUS_OK; -} - -/* - parse the variables in a GET style request -*/ -static NTSTATUS http_parse_get(struct esp_state *esp) -{ - struct websrv_context *web = esp->web; - char *p, *s, *tok; - char *pp; - - p = strchr(web->input.url, '?'); - web->input.query_string = p+1; - *p = 0; - - s = talloc_strdup(esp, esp->web->input.query_string); - NT_STATUS_HAVE_NO_MEMORY(s); - - for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) { - p = strchr(tok,'='); - if (p) { - *p = 0; - esp_putvar(esp, tok, p+1); - } - } - return NT_STATUS_OK; -} - -/* - called when a session times out -*/ -static void session_timeout(struct event_context *ev, struct timed_event *te, - struct timeval t, void *private) -{ - struct session_data *s = talloc_get_type(private, struct session_data); - talloc_free(s); -} - -/* - destroy a session - */ -static int session_destructor(struct session_data *s) -{ - DLIST_REMOVE(s->edata->sessions, s); - return 0; -} - -/* - setup the session for this request -*/ -static void http_setup_session(struct esp_data *edata, struct esp_state *esp) -{ - const char *session_key = SAMBA_SESSION_KEY; - char *p; - const char *cookie = esp->web->input.cookie; - const char *key = NULL; - struct session_data *s; - bool generated_key = false; - - /* look for our session key */ - if (cookie && (p = strstr(cookie, session_key)) && - p[strlen(session_key)] == '=') { - p += strlen(session_key)+1; - key = talloc_strndup(esp, p, strcspn(p, ";")); - } - - if (key == NULL && esp->web->input.session_key) { - key = esp->web->input.session_key; - } else if (key == NULL) { - key = generate_random_str_list(esp, 16, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - generated_key = true; - } - - /* try to find this session in the existing session list */ - for (s=edata->sessions;s;s=s->next) { - if (strcmp(key, s->id) == 0) { - break; - } - } - - if (s == NULL) { - /* create a new session */ - s = talloc_zero(edata, struct session_data); - s->id = talloc_steal(s, key); - s->data = NULL; - s->te = NULL; - s->edata = edata; - s->lifetime = lp_parm_int(esp->web->task->lp_ctx, NULL, "web", "sessiontimeout", 900); - DLIST_ADD(edata->sessions, s); - talloc_set_destructor(s, session_destructor); - if (!generated_key) { - mprSetPropertyValue(&esp->variables[ESP_REQUEST_OBJ], - "SESSION_EXPIRED", mprCreateStringVar("true", 0)); - } - } - - http_setCookie(esp->web, session_key, key, s->lifetime, "/", 0); - - if (s->data) { - mprCopyVar(&esp->variables[ESP_SESSION_OBJ], s->data, MPR_DEEP_COPY); - } - - esp->web->session = s; -} - - -/* callbacks for esp processing */ -static const struct Esp esp_control = { - .maxScriptSize = 60000, - .writeBlock = http_writeBlock, - .setHeader = http_setHeader, - .redirect = http_redirect, - .setResponseCode = http_setResponseCode, - .readFile = http_readFileFromSwatDir, - .mapToStorage = http_mapToStorage, - .setCookie = http_setCookie, - .createSession = http_createSession, - .destroySession = http_destroySession, - .getSessionId = http_getSessionId -}; - -/* - process a complete http request -*/ -void esp_process_http_input(struct web_server_data *wdata, struct websrv_context *web) -{ - NTSTATUS status; - struct esp_state *esp = NULL; - struct esp_data *edata = talloc_get_type(wdata->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; - enum page_type { - page_type_simple, - page_type_esp - }; - enum page_type page_type; - const struct { - const char *extension; - const char *mime_type; - enum page_type page_type; - } mime_types[] = { - {"gif", "image/gif"}, - {"png", "image/png"}, - {"jpg", "image/jpeg"}, - {"txt", "text/plain"}, - {"ico", "image/x-icon"}, - {"css", "text/css"}, - {"esp", "text/html", true} - }; - - /* - * 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; - - mprSetCtx(esp); - - if (espOpen(&esp_control) != 0) goto internal_error; - - for (i=0;ivariables);i++) { - esp->variables[i] = mprCreateUndefinedVar(); - } - esp->variables[ESP_HEADERS_OBJ] = mprCreateObjVar("headers", ESP_HASH_SIZE); - esp->variables[ESP_FORM_OBJ] = mprCreateObjVar("form", ESP_HASH_SIZE); - esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE); - esp->variables[ESP_COOKIES_OBJ] = mprCreateObjVar("cookies", ESP_HASH_SIZE); - esp->variables[ESP_FILES_OBJ] = mprCreateObjVar("files", ESP_HASH_SIZE); - esp->variables[ESP_REQUEST_OBJ] = mprCreateObjVar("request", ESP_HASH_SIZE); - esp->variables[ESP_SERVER_OBJ] = mprCreateObjVar("server", ESP_HASH_SIZE); - esp->variables[ESP_SESSION_OBJ] = mprCreateObjVar("session", ESP_HASH_SIZE); - - if (edata->application_data) { - mprCopyVar(&esp->variables[ESP_APPLICATION_OBJ], - edata->application_data, MPR_DEEP_COPY); - } - - 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"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - - /* parse any form or get variables */ - if (web->input.post_request) { - status = http_parse_post(esp); - if (!NT_STATUS_IS_OK(status)) { - http_error(web, 400, "Malformed POST data"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - } - if (strchr(web->input.url, '?')) { - status = http_parse_get(esp); - if (!NT_STATUS_IS_OK(status)) { - http_error(web, 400, "Malformed GET data"); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - } - } - - http_setup_session(edata, esp); - - esp->req = espCreateRequest(web, web->input.url, esp->variables); - if (esp->req == NULL) goto internal_error; - - p = strrchr(web->input.url, '.'); - if (p == NULL) { - page_type = page_type_esp; - file_type = "text/html"; - } - for (i=0;p && iinput.url); - } - break; - } - - if (web->conn == NULL) { - /* the connection has been terminated above us, probably - via a timeout */ - goto internal_error; - } - - if (!web->output.output_pending) { - http_output_headers(web); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; - } - - /* copy any application data to long term storage in edata */ - talloc_free(edata->application_data); - edata->application_data = talloc_zero(edata, struct MprVar); - mprSetCtx(edata->application_data); - mprCopyVar(edata->application_data, &esp->variables[ESP_APPLICATION_OBJ], - MPR_DEEP_COPY); - mprSetCtx(esp); - - /* copy any session data */ - if (web->session) { - talloc_free(web->session->data); - web->session->data = talloc_zero(web->session, struct MprVar); - if (esp->variables[ESP_SESSION_OBJ].properties == NULL || - esp->variables[ESP_SESSION_OBJ].properties[0].numItems == 0) { - talloc_free(web->session); - web->session = NULL; - } else { - mprSetCtx(web->session->data); - mprCopyVar(web->session->data, &esp->variables[ESP_SESSION_OBJ], - MPR_DEEP_COPY); - /* setup the timeout for the session data */ - mprSetCtx(esp); - talloc_free(web->session->te); - web->session->te = event_add_timed(web->conn->event.ctx, web->session, - timeval_current_ofs(web->session->lifetime, 0), - session_timeout, web->session); - } - } - - talloc_free(esp); - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); - return; - -internal_error: - mprSetCtx(esp); - talloc_free(esp); - if (web->conn != NULL) { - http_error(web, 500, "Internal server error"); - } - mprSetCtx(save_mpr_ctx); - ejs_restore_state(ejs_save); -} - - -/* - parse one line of header input -*/ -NTSTATUS http_parse_header(struct websrv_context *web, const char *line) -{ - if (line[0] == 0) { - web->input.end_of_headers = true; - } else if (strncasecmp(line,"GET ", 4)==0) { - web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t")); - } else if (strncasecmp(line,"POST ", 5)==0) { - web->input.post_request = true; - web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); - } else if (strchr(line, ':') == NULL) { - http_error(web, 400, "This server only accepts GET and POST requests"); - return NT_STATUS_INVALID_PARAMETER; - } else if (strncasecmp(line,"Content-Length: ", 16)==0) { - web->input.content_length = strtoul(&line[16], NULL, 10); - } else { -#define PULL_HEADER(v, s) do { \ - if (strncmp(line, s, strlen(s)) == 0) { \ - web->input.v = talloc_strdup(web, &line[strlen(s)]); \ - return NT_STATUS_OK; \ - } \ -} while (0) - PULL_HEADER(content_type, "Content-Type: "); - PULL_HEADER(user_agent, "User-Agent: "); - PULL_HEADER(referer, "Referer: "); - PULL_HEADER(host, "Host: "); - PULL_HEADER(accept_encoding, "Accept-Encoding: "); - PULL_HEADER(accept_language, "Accept-Language: "); - PULL_HEADER(accept_charset, "Accept-Charset: "); - PULL_HEADER(cookie, "Cookie: "); - } - - /* ignore all other headers for now */ - return NT_STATUS_OK; -} - - -/* - setup the esp processor - called at task initialisation -*/ -struct esp_data *http_setup_esp(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx) -{ - struct esp_data *edata; - - edata = talloc_zero(mem_ctx, struct esp_data); - if (edata == NULL) - return NULL; - - return edata; -} diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index 6d8b2a2758..20924ff0dc 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -4,6 +4,7 @@ web server startup Copyright (C) Andrew Tridgell 2005 + Copyright (C) Jelmer Vernooij 2008 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 @@ -29,6 +30,7 @@ #include "system/network.h" #include "lib/socket/netif.h" #include "lib/tls/tls.h" +#include "lib/util/dlinklist.h" #include "param/param.h" /* don't allow connections to hang around forever */ @@ -61,6 +63,62 @@ static void websrv_timeout(struct event_context *event_context, stream_terminate_connection(conn, "websrv_timeout: timed out"); } +/* + setup for a raw http level error +*/ +void http_error(struct websrv_context *web, int code, const char *info) +{ + char *s; + s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", + code, code, info); + if (s == NULL) { + stream_terminate_connection(web->conn, "http_error: out of memory"); + return; + } + /* FIXME: + http_writeBlock(web, s, strlen(s)); + http_setResponseCode(web, code); + http_output_headers(web); */ + EVENT_FD_NOT_READABLE(web->conn->event.fde); + EVENT_FD_WRITEABLE(web->conn->event.fde); + web->output.output_pending = true; +} + + +/* + parse one line of header input +*/ +NTSTATUS http_parse_header(struct websrv_context *web, const char *line) +{ + if (line[0] == 0) { + web->input.end_of_headers = true; + } else if (strncasecmp(line,"GET ", 4)==0) { + web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t")); + } else if (strncasecmp(line,"POST ", 5)==0) { + web->input.post_request = true; + web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); + } else if (strchr(line, ':') == NULL) { + http_error(web, 400, "This server only accepts GET and POST requests"); + return NT_STATUS_INVALID_PARAMETER; + } else if (strncasecmp(line, "Content-Length: ", 16)==0) { + web->input.content_length = strtoul(&line[16], NULL, 10); + } else { + struct http_header *hdr = talloc_zero(web, struct http_header); + char *colon = strchr(line, ':'); + if (colon == NULL) { + http_error(web, 500, "invalidly formatted header"); + return NT_STATUS_INVALID_PARAMETER; + } + + hdr->name = talloc_strndup(hdr, line, colon-line); + hdr->value = talloc_strdup(hdr, colon+1); + DLIST_ADD(web->input.headers, hdr); + } + + /* ignore all other headers for now */ + return NT_STATUS_OK; +} + /* called when a web connection becomes readable */ @@ -199,7 +257,7 @@ static void websrv_accept(struct stream_connection *conn) web = talloc_zero(conn, struct websrv_context); if (web == NULL) goto failed; - web->http_process_input = esp_process_http_input; + web->http_process_input = wsgi_process_http_input; web->task = task; web->conn = conn; conn->private = web; @@ -290,9 +348,6 @@ static void websrv_task_init(struct task_server *task) wdata->tls_params = tls_initialise(wdata, task->lp_ctx); if (wdata->tls_params == NULL) goto failed; - wdata->private = http_setup_esp(task, task->lp_ctx); - if (wdata->private == NULL) goto failed; - return; failed: diff --git a/source4/web_server/web_server.h b/source4/web_server/web_server.h index 0ce68bdd17..7375a2e9ca 100644 --- a/source4/web_server/web_server.h +++ b/source4/web_server/web_server.h @@ -24,6 +24,12 @@ struct web_server_data { void *private; }; +struct http_header { + char *name; + char *value; + struct http_header *prev, *next; +}; + /* context of one open web connection */ @@ -40,16 +46,8 @@ struct websrv_context { char *url; unsigned content_length; bool post_request; + struct http_header *headers; const char *content_type; - const char *query_string; - const char *user_agent; - const char *referer; - const char *host; - const char *accept_encoding; - const char *accept_language; - const char *accept_charset; - const char *cookie; - const char *session_key; } input; struct { bool output_pending; @@ -57,7 +55,7 @@ struct websrv_context { int fd; unsigned nsent; int response_code; - const char **headers; + struct http_header *headers; } output; struct session_data *session; }; diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 32b1f0dbc2..3391065dae 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -32,7 +32,7 @@ static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs "status", "response_header", "exc_info", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"sOO:start_response", (char **)kwnames, &status, &response_header, &exc_info)) { + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sOO:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) { return NULL; } @@ -57,7 +57,7 @@ static PyObject *py_error_write(PyObject *self, PyObject *args, PyObject *kwargs const char *kwnames[] = { "str", NULL }; char *str = NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"s:write", (char **)kwnames, &str)) { + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s:write", discard_const_p(char *, kwnames), &str)) { return NULL; } @@ -71,7 +71,7 @@ static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *k const char *kwnames[] = { "seq", NULL }; PyObject *seq = NULL, *item; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *)"O:writelines", (char **)kwnames, &seq)) { + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:writelines", discard_const_p(char *, kwnames), &seq)) { return NULL; } @@ -141,14 +141,14 @@ PyTypeObject input_Stream_Type = { static PyObject *Py_InputHttpStream(void *foo) { - PyObject *ret = PyObject_New(input_Stream_Object, &input_Stream_Type); - return ret; + input_Stream_Object *ret = PyObject_New(input_Stream_Object, &input_Stream_Type); + return (PyObject *)ret; } static PyObject *Py_ErrorHttpStream(void) { - PyObject *ret = PyObject_New(error_Stream_Object, &error_Stream_Type); - return ret; + error_Stream_Object *ret = PyObject_New(error_Stream_Object, &error_Stream_Type); + return (PyObject *)ret; } static PyObject *create_environ(void) -- cgit From 4141e70da97d924969b48fcd198e5996d615e75d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 18:45:09 +0200 Subject: Properly call WSGI request handler when requests come in. --- source4/web_server/swat/__init__.py | 3 +- source4/web_server/web_server.c | 42 +++----- source4/web_server/web_server.h | 13 +-- source4/web_server/wsgi.c | 204 +++++++++++++++++++++++++++++++----- 4 files changed, 198 insertions(+), 64 deletions(-) (limited to 'source4/web_server') diff --git a/source4/web_server/swat/__init__.py b/source4/web_server/swat/__init__.py index e0d85dbe2c..580097186c 100644 --- a/source4/web_server/swat/__init__.py +++ b/source4/web_server/swat/__init__.py @@ -1,4 +1,5 @@ #!/usr/bin/python +# -*- coding: utf-8 -*- # Unix SMB/CIFS implementation. # Copyright © Jelmer Vernooij 2008 @@ -19,7 +20,7 @@ # along with this program. If not, see . # -def SWAT(environ, start_response): +def __call__(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index 20924ff0dc..1a3c48a03d 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -41,9 +41,6 @@ */ static int websrv_destructor(struct websrv_context *web) { - if (web->output.fd != -1) { - close(web->output.fd); - } return 0; } @@ -84,6 +81,11 @@ void http_error(struct websrv_context *web, int code, const char *info) web->output.output_pending = true; } +void websrv_output_headers(struct websrv_context *web, const char *status, struct http_header *headers) +{ + /* FIXME */ +} + /* parse one line of header input @@ -124,6 +126,7 @@ NTSTATUS http_parse_header(struct websrv_context *web, const char *line) */ static void websrv_recv(struct stream_connection *conn, uint16_t flags) { + struct web_server_data *wdata; struct websrv_context *web = talloc_get_type(conn->private, struct websrv_context); NTSTATUS status; @@ -181,7 +184,9 @@ static void websrv_recv(struct stream_connection *conn, uint16_t flags) destroy the stack variables being used by that rendering process when we handle the timeout. */ if (!talloc_reference(web->task, web)) goto failed; - web->http_process_input(web); + wdata = talloc_get_type(web->task->private, struct web_server_data); + if (wdata == NULL) goto failed; + wdata->http_process_input(wdata, web); talloc_unlink(web->task, web); } return; @@ -191,6 +196,7 @@ failed: } + /* called when a web connection becomes writable */ @@ -217,29 +223,7 @@ static void websrv_send(struct stream_connection *conn, uint16_t flags) web->output.nsent += nsent; - /* possibly read some more raw data from a file */ - if (web->output.content.length == web->output.nsent && - web->output.fd != -1) { - uint8_t buf[2048]; - ssize_t nread; - - data_blob_free(&web->output.content); - web->output.nsent = 0; - - nread = read(web->output.fd, buf, sizeof(buf)); - if (nread == -1 && errno == EINTR) { - return; - } - if (nread <= 0) { - close(web->output.fd); - web->output.fd = -1; - nread = 0; - } - web->output.content = data_blob_talloc(web, buf, nread); - } - - if (web->output.content.length == web->output.nsent && - web->output.fd == -1) { + if (web->output.content.length == web->output.nsent) { stream_terminate_connection(web->conn, "websrv_send: finished sending"); } } @@ -257,11 +241,9 @@ static void websrv_accept(struct stream_connection *conn) web = talloc_zero(conn, struct websrv_context); if (web == NULL) goto failed; - web->http_process_input = wsgi_process_http_input; web->task = task; web->conn = conn; conn->private = web; - web->output.fd = -1; talloc_set_destructor(web, websrv_destructor); event_add_timed(conn->event.ctx, web, @@ -348,6 +330,8 @@ static void websrv_task_init(struct task_server *task) wdata->tls_params = tls_initialise(wdata, task->lp_ctx); if (wdata->tls_params == NULL) goto failed; + if (!wsgi_initialize(wdata)) goto failed; + return; failed: diff --git a/source4/web_server/web_server.h b/source4/web_server/web_server.h index 7375a2e9ca..0cc299f332 100644 --- a/source4/web_server/web_server.h +++ b/source4/web_server/web_server.h @@ -19,8 +19,12 @@ #include "smbd/process_model.h" +struct websrv_context; + struct web_server_data { struct tls_params *tls_params; + void (*http_process_input)(struct web_server_data *wdata, + struct websrv_context *web); void *private; }; @@ -36,8 +40,7 @@ struct http_header { struct websrv_context { struct task_server *task; struct stream_connection *conn; - void (*http_process_input)(struct websrv_context *web); - struct { + struct websrv_request_input { bool tls_detect; bool tls_first_char; uint8_t first_byte; @@ -49,13 +52,11 @@ struct websrv_context { struct http_header *headers; const char *content_type; } input; - struct { + struct websrv_request_output { bool output_pending; DATA_BLOB content; - int fd; + bool headers_sent; unsigned nsent; - int response_code; - struct http_header *headers; } output; struct session_data *session; }; diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 3391065dae..0709e0ba39 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -22,26 +22,90 @@ #include "includes.h" #include "web_server/web_server.h" +#include "lib/util/dlinklist.h" +#include "lib/util/data_blob.h" #include +typedef struct { + PyObject_HEAD + struct websrv_context *web; +} web_request_Object; + static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs) { - PyObject *response_header, *exc_info; + PyObject *response_header, *exc_info = NULL; char *status; + int i; const char *kwnames[] = { "status", "response_header", "exc_info", NULL }; + web_request_Object *py_web = (web_request_Object *)self; + struct websrv_context *web = py_web->web; + struct http_header *headers = NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sOO:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) { + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|O:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) { return NULL; } - /* FIXME: response_header, exc_info */ + /* FIXME: exc_info */ - /* FIXME: Wrap stdout */ - return NULL; + if (!PyList_Check(response_header)) { + PyErr_SetString(PyExc_TypeError, "response_header should be list"); + return NULL; + } + + for (i = 0; i < PyList_Size(response_header); i++) { + struct http_header *hdr = talloc_zero(web, struct http_header); + PyObject *item = PyList_GetItem(response_header, i); + PyObject *py_name, *py_value; + + if (!PyTuple_Check(item)) { + PyErr_SetString(PyExc_TypeError, "Expected tuple"); + return NULL; + } + + if (PyTuple_Size(item) != 2) { + PyErr_SetString(PyExc_TypeError, "header tuple has invalid size, expected 2"); + return NULL; + } + + py_name = PyTuple_GetItem(item, 0); + + if (!PyString_Check(py_name)) { + PyErr_SetString(PyExc_TypeError, "header name should be string"); + return NULL; + } + + py_value = PyTuple_GetItem(item, 1); + if (!PyString_Check(py_value)) { + PyErr_SetString(PyExc_TypeError, "header value should be string"); + return NULL; + } + + hdr->name = talloc_strdup(hdr, PyString_AsString(py_name)); + hdr->value = talloc_strdup(hdr, PyString_AsString(py_value)); + DLIST_ADD(headers, hdr); + } + + websrv_output_headers(web, status, headers); + + return Py_None; } +static PyMethodDef web_request_methods[] = { + { "start_response", (PyCFunction)start_response, METH_VARARGS|METH_KEYWORDS, NULL }, + { NULL } +}; + + +PyTypeObject web_request_Type = { + PyObject_HEAD_INIT(NULL) 0, + .tp_name = "wsgi.Request", + .tp_methods = web_request_methods, + .tp_basicsize = sizeof(web_request_Object), + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, +}; + typedef struct { PyObject_HEAD } error_Stream_Object; @@ -85,9 +149,9 @@ static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *k } static PyMethodDef error_Stream_methods[] = { - { "flush", (PyCFunction)py_error_flush, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "write", (PyCFunction)py_error_write, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "writelines", (PyCFunction)py_error_writelines, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL }, + { "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL }, + { "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL }, { NULL, NULL, 0, NULL } }; @@ -105,29 +169,33 @@ typedef struct { static PyObject *py_input_read(PyObject *self, PyObject *args, PyObject *kwargs) { + /* FIXME */ return NULL; } static PyObject *py_input_readline(PyObject *self, PyObject *args, PyObject *kwargs) { + /* FIXME */ return NULL; } static PyObject *py_input_readlines(PyObject *self, PyObject *args, PyObject *kwargs) { + /* FIXME */ return NULL; } static PyObject *py_input___iter__(PyObject *self, PyObject *args, PyObject *kwargs) { + /* FIXME */ return NULL; } static PyMethodDef input_Stream_methods[] = { - { "read", (PyCFunction)py_input_read, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "readline", (PyCFunction)py_input_readline, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "readlines", (PyCFunction)py_input_readlines, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, - { "__iter__", (PyCFunction)py_input___iter__, METH_O|METH_VARARGS|METH_KEYWORDS, NULL }, + { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readline", (PyCFunction)py_input_readline, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL }, + { "__iter__", (PyCFunction)py_input___iter__, METH_VARARGS|METH_KEYWORDS, NULL }, { NULL, NULL, 0, NULL } }; @@ -151,20 +219,17 @@ static PyObject *Py_ErrorHttpStream(void) return (PyObject *)ret; } -static PyObject *create_environ(void) +static PyObject *create_environ(bool tls, int content_length, const char *content_type, struct http_header *headers, const char *request_method) { - PyObject *env, *osmodule, *osenviron; + PyObject *env; PyObject *inputstream, *errorstream; - - osmodule = PyImport_ImportModule("os"); - if (osmodule == NULL) + PyObject *py_scheme; + struct http_header *hdr; + + env = PyDict_New(); + if (env == NULL) { return NULL; - - osenviron = PyObject_CallMethod(osmodule, "environ", NULL); - - env = PyDict_Copy(osenviron); - - Py_DECREF(env); + } inputstream = Py_InputHttpStream(NULL); if (inputstream == NULL) { @@ -185,16 +250,99 @@ static PyObject *create_environ(void) PyDict_SetItemString(env, "wsgi.multithread", Py_False); PyDict_SetItemString(env, "wsgi.multiprocess", Py_True); PyDict_SetItemString(env, "wsgi.run_once", Py_False); + PyDict_SetItemString(env, "SERVER_PROTOCOL", PyString_FromString("HTTP/1.0")); + if (content_type != NULL) { + PyDict_SetItemString(env, "CONTENT_TYPE", PyString_FromString(content_type)); + } + if (content_length > 0) { + PyDict_SetItemString(env, "CONTENT_LENGTH", PyLong_FromLong(content_length)); + } + PyDict_SetItemString(env, "REQUEST_METHOD", PyString_FromString(request_method)); + + /* FIXME: SCRIPT_NAME */ + /* FIXME: PATH_INFO */ + /* FIXME: QUERY_STRING */ + /* FIXME: SERVER_NAME, SERVER_PORT */ + + for (hdr = headers; hdr; hdr = hdr->next) { + char *name; + asprintf(&name, "HTTP_%s", hdr->name); + PyDict_SetItemString(env, name, PyString_FromString(hdr->value)); + free(name); + } - /* FIXME: - PyDict_SetItemString(env, "wsgi.url_scheme", "http"); - PyDict_SetItemString(env, "wsgi.url_scheme", "https"); - */ + if (tls) { + py_scheme = PyString_FromString("https"); + } else { + py_scheme = PyString_FromString("http"); + } + PyDict_SetItemString(env, "wsgi.url_scheme", py_scheme); return env; } -void wsgi_process_http_input(struct websrv_context *web) +static void wsgi_process_http_input(struct web_server_data *wdata, + struct websrv_context *web) +{ + PyObject *py_environ, *result, *item, *iter; + PyObject *request_handler = wdata->private; + + web_request_Object *py_web = PyObject_New(web_request_Object, &web_request_Type); + py_web->web = web; + + py_environ = create_environ(false /* FIXME: Figure out whether we're using tls */, + web->input.content_length, + web->input.content_type, + web->input.headers, + web->input.post_request?"POST":"GET"); + if (py_environ == NULL) { + DEBUG(0, ("Unable to create WSGI environment object\n")); + return; + } + + result = PyObject_CallMethod(request_handler, discard_const_p(char, "__call__"), discard_const_p(char, "OO"), + py_environ, PyObject_GetAttrString((PyObject *)py_web, "start_response")); + + if (result == NULL) { + DEBUG(0, ("error while running WSGI code\n")); + return; + } + + iter = PyObject_GetIter(result); + Py_DECREF(result); + + /* Now, iter over all the data returned */ + + while ((item = PyIter_Next(iter))) { + data_blob_append(web, &web->output.content, + PyString_AsString(item), PyString_Size(item)); + Py_DECREF(item); + } + + Py_DECREF(iter); +} + +bool wsgi_initialize(struct web_server_data *wdata) { + PyObject *py_swat; + Py_Initialize(); + + if (PyType_Ready(&web_request_Type) < 0) + return false; + + if (PyType_Ready(&input_Stream_Type) < 0) + return false; + + if (PyType_Ready(&error_Stream_Type) < 0) + return false; + + wdata->http_process_input = wsgi_process_http_input; + py_swat = PyImport_Import(PyString_FromString("swat")); + if (py_swat == NULL) { + DEBUG(0, ("Unable to find SWAT\n")); + return false; + } + wdata->private = py_swat; + return true; } -- cgit From 1ed040d8e22a63079c72126bbc896fa3c32c7f0f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 19:03:12 +0200 Subject: First GET request works. SWAT now displays a Hello world message. --- source4/web_server/web_server.c | 44 +++++++++++++++++++++++++++++------------ source4/web_server/wsgi.c | 3 +-- 2 files changed, 32 insertions(+), 15 deletions(-) (limited to 'source4/web_server') diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index 1a3c48a03d..1ed37f657b 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -63,27 +63,45 @@ static void websrv_timeout(struct event_context *event_context, /* setup for a raw http level error */ -void http_error(struct websrv_context *web, int code, const char *info) +void http_error(struct websrv_context *web, const char *status, const char *info) { char *s; - s = talloc_asprintf(web,"Error %u

Error %u

%s

\r\n\r\n", - code, code, info); + s = talloc_asprintf(web,"Error %s

Error %s

%s

\r\n\r\n", + status, status, info); if (s == NULL) { stream_terminate_connection(web->conn, "http_error: out of memory"); return; } - /* FIXME: - http_writeBlock(web, s, strlen(s)); - http_setResponseCode(web, code); - http_output_headers(web); */ - EVENT_FD_NOT_READABLE(web->conn->event.fde); - EVENT_FD_WRITEABLE(web->conn->event.fde); - web->output.output_pending = true; + websrv_output_headers(web, status, NULL); + websrv_output(web, s, strlen(s)); } void websrv_output_headers(struct websrv_context *web, const char *status, struct http_header *headers) { - /* FIXME */ + char *s; + DATA_BLOB b; + struct http_header *hdr; + + s = talloc_asprintf(web, "HTTP/1.0 %s\r\n", status); + if (s == NULL) return; + for (hdr = headers; hdr; hdr = hdr->next) { + s = talloc_asprintf_append_buffer(s, "%s: %s\r\n", hdr->name, hdr->value); + } + + s = talloc_asprintf_append_buffer(s, "\r\n"); + + b = web->output.content; + web->output.content = data_blob_string_const(s); + websrv_output(web, b.data, b.length); + data_blob_free(&b); +} + +void websrv_output(struct websrv_context *web, void *data, size_t length) +{ + data_blob_append(web, &web->output.content, data, length); + EVENT_FD_NOT_READABLE(web->conn->event.fde); + EVENT_FD_WRITEABLE(web->conn->event.fde); + web->output.output_pending = true; } @@ -100,7 +118,7 @@ NTSTATUS http_parse_header(struct websrv_context *web, const char *line) web->input.post_request = true; web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t")); } else if (strchr(line, ':') == NULL) { - http_error(web, 400, "This server only accepts GET and POST requests"); + http_error(web, "400 Bad request", "This server only accepts GET and POST requests"); return NT_STATUS_INVALID_PARAMETER; } else if (strncasecmp(line, "Content-Length: ", 16)==0) { web->input.content_length = strtoul(&line[16], NULL, 10); @@ -108,7 +126,7 @@ NTSTATUS http_parse_header(struct websrv_context *web, const char *line) struct http_header *hdr = talloc_zero(web, struct http_header); char *colon = strchr(line, ':'); if (colon == NULL) { - http_error(web, 500, "invalidly formatted header"); + http_error(web, "500 Internal Server Error", "invalidly formatted header"); return NT_STATUS_INVALID_PARAMETER; } diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 0709e0ba39..3d5d0b4bf0 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -314,8 +314,7 @@ static void wsgi_process_http_input(struct web_server_data *wdata, /* Now, iter over all the data returned */ while ((item = PyIter_Next(iter))) { - data_blob_append(web, &web->output.content, - PyString_AsString(item), PyString_Size(item)); + websrv_output(web, PyString_AsString(item), PyString_Size(item)); Py_DECREF(item); } -- cgit From ef8d9f8a756936578dc770a0ec275e57aa3ee51b Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 20:00:44 +0200 Subject: Make standard SWAT script print received headers. --- source4/web_server/swat/__init__.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'source4/web_server') diff --git a/source4/web_server/swat/__init__.py b/source4/web_server/swat/__init__.py index 580097186c..8229d15a3c 100644 --- a/source4/web_server/swat/__init__.py +++ b/source4/web_server/swat/__init__.py @@ -22,7 +22,13 @@ def __call__(environ, start_response): status = '200 OK' - response_headers = [('Content-type','text/plain')] + response_headers = [('Content-type','text/html')] start_response(status, response_headers) - return ['Hello world!\n'] + yield '\n' + + for key, value in environ.items(): + if isinstance(value, str): + yield '\t\n' % (key, value) + + yield '
%s%s
\n' -- cgit From f3d513b378fcc094255264de0c73f96fac461b68 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 20:01:00 +0200 Subject: Support POST requests again, provide more variables in environment. --- source4/web_server/web_server.h | 1 - source4/web_server/wsgi.c | 106 ++++++++++++++++++++++++++++------------ 2 files changed, 75 insertions(+), 32 deletions(-) (limited to 'source4/web_server') diff --git a/source4/web_server/web_server.h b/source4/web_server/web_server.h index 0cc299f332..f91c766494 100644 --- a/source4/web_server/web_server.h +++ b/source4/web_server/web_server.h @@ -50,7 +50,6 @@ struct websrv_context { unsigned content_length; bool post_request; struct http_header *headers; - const char *content_type; } input; struct websrv_request_output { bool output_pending; diff --git a/source4/web_server/wsgi.c b/source4/web_server/wsgi.c index 3d5d0b4bf0..66697868e0 100644 --- a/source4/web_server/wsgi.c +++ b/source4/web_server/wsgi.c @@ -24,6 +24,7 @@ #include "web_server/web_server.h" #include "lib/util/dlinklist.h" #include "lib/util/data_blob.h" +#include "lib/tls/tls.h" #include typedef struct { @@ -165,37 +166,71 @@ PyTypeObject error_Stream_Type = { typedef struct { PyObject_HEAD + struct websrv_context *web; + size_t offset; } input_Stream_Object; -static PyObject *py_input_read(PyObject *self, PyObject *args, PyObject *kwargs) +static PyObject *py_input_read(PyObject *_self, PyObject *args, PyObject *kwargs) { - /* FIXME */ - return NULL; + const char *kwnames[] = { "size", NULL }; + PyObject *ret; + input_Stream_Object *self = (input_Stream_Object *)_self; + int size = -1; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &size)) + return NULL; + + /* Don't read beyond buffer boundaries */ + if (size == -1) + size = self->web->input.partial.length-self->offset; + else + size = MIN(size, self->web->input.partial.length-self->offset); + + ret = PyString_FromStringAndSize((char *)self->web->input.partial.data+self->offset, size); + self->offset += size; + + return ret; } -static PyObject *py_input_readline(PyObject *self, PyObject *args, PyObject *kwargs) +static PyObject *py_input_readline(PyObject *_self) { + input_Stream_Object *self = (input_Stream_Object *)_self; /* FIXME */ + PyErr_SetString(PyExc_NotImplementedError, + "readline() not yet implemented"); return NULL; } -static PyObject *py_input_readlines(PyObject *self, PyObject *args, PyObject *kwargs) +static PyObject *py_input_readlines(PyObject *_self, PyObject *args, PyObject *kwargs) { + const char *kwnames[] = { "hint", NULL }; + PyObject *ret; + int hint; + input_Stream_Object *self = (input_Stream_Object *)_self; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &hint)) + return NULL; + /* FIXME */ + PyErr_SetString(PyExc_NotImplementedError, + "readlines() not yet implemented"); return NULL; } -static PyObject *py_input___iter__(PyObject *self, PyObject *args, PyObject *kwargs) +static PyObject *py_input___iter__(PyObject *_self) { + input_Stream_Object *self = (input_Stream_Object *)_self; /* FIXME */ + PyErr_SetString(PyExc_NotImplementedError, + "__iter__() not yet implemented"); return NULL; } static PyMethodDef input_Stream_methods[] = { { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL }, - { "readline", (PyCFunction)py_input_readline, METH_VARARGS|METH_KEYWORDS, NULL }, + { "readline", (PyCFunction)py_input_readline, METH_NOARGS, NULL }, { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL }, - { "__iter__", (PyCFunction)py_input___iter__, METH_VARARGS|METH_KEYWORDS, NULL }, + { "__iter__", (PyCFunction)py_input___iter__, METH_NOARGS, NULL }, { NULL, NULL, 0, NULL } }; @@ -207,9 +242,11 @@ PyTypeObject input_Stream_Type = { .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, }; -static PyObject *Py_InputHttpStream(void *foo) +static PyObject *Py_InputHttpStream(struct websrv_context *web) { input_Stream_Object *ret = PyObject_New(input_Stream_Object, &input_Stream_Type); + ret->web = web; + ret->offset = 0; return (PyObject *)ret; } @@ -219,24 +256,19 @@ static PyObject *Py_ErrorHttpStream(void) return (PyObject *)ret; } -static PyObject *create_environ(bool tls, int content_length, const char *content_type, struct http_header *headers, const char *request_method) +static PyObject *create_environ(bool tls, int content_length, struct http_header *headers, const char *request_method, const char *servername, int serverport, PyObject *inputstream, const char *request_string) { PyObject *env; - PyObject *inputstream, *errorstream; + PyObject *errorstream; PyObject *py_scheme; struct http_header *hdr; + char *questionmark; env = PyDict_New(); if (env == NULL) { return NULL; } - inputstream = Py_InputHttpStream(NULL); - if (inputstream == NULL) { - Py_DECREF(env); - return NULL; - } - errorstream = Py_ErrorHttpStream(); if (errorstream == NULL) { Py_DECREF(env); @@ -251,24 +283,30 @@ static PyObject *create_environ(bool tls, int content_length, const char *conten PyDict_SetItemString(env, "wsgi.multiprocess", Py_True); PyDict_SetItemString(env, "wsgi.run_once", Py_False); PyDict_SetItemString(env, "SERVER_PROTOCOL", PyString_FromString("HTTP/1.0")); - if (content_type != NULL) { - PyDict_SetItemString(env, "CONTENT_TYPE", PyString_FromString(content_type)); - } if (content_length > 0) { PyDict_SetItemString(env, "CONTENT_LENGTH", PyLong_FromLong(content_length)); } PyDict_SetItemString(env, "REQUEST_METHOD", PyString_FromString(request_method)); - /* FIXME: SCRIPT_NAME */ - /* FIXME: PATH_INFO */ - /* FIXME: QUERY_STRING */ - /* FIXME: SERVER_NAME, SERVER_PORT */ - + questionmark = strchr(request_string, '?'); + if (questionmark == NULL) { + PyDict_SetItemString(env, "SCRIPT_NAME", PyString_FromString(request_string)); + } else { + PyDict_SetItemString(env, "QUERY_STRING", PyString_FromString(questionmark+1)); + PyDict_SetItemString(env, "SCRIPT_NAME", PyString_FromStringAndSize(request_string, questionmark-request_string)); + } + + PyDict_SetItemString(env, "SERVER_NAME", PyString_FromString(servername)); + PyDict_SetItemString(env, "SERVER_PORT", PyInt_FromLong(serverport)); for (hdr = headers; hdr; hdr = hdr->next) { char *name; - asprintf(&name, "HTTP_%s", hdr->name); - PyDict_SetItemString(env, name, PyString_FromString(hdr->value)); - free(name); + if (!strcasecmp(hdr->name, "Content-Type")) { + PyDict_SetItemString(env, "CONTENT_TYPE", PyString_FromString(hdr->value)); + } else { + asprintf(&name, "HTTP_%s", hdr->name); + PyDict_SetItemString(env, name, PyString_FromString(hdr->value)); + free(name); + } } if (tls) { @@ -286,15 +324,21 @@ static void wsgi_process_http_input(struct web_server_data *wdata, { PyObject *py_environ, *result, *item, *iter; PyObject *request_handler = wdata->private; + struct socket_address *socket_address; web_request_Object *py_web = PyObject_New(web_request_Object, &web_request_Type); py_web->web = web; - py_environ = create_environ(false /* FIXME: Figure out whether we're using tls */, + socket_address = socket_get_my_addr(web->conn->socket, web); + py_environ = create_environ(tls_enabled(web->conn->socket), web->input.content_length, - web->input.content_type, web->input.headers, - web->input.post_request?"POST":"GET"); + web->input.post_request?"POST":"GET", + socket_address->addr, + socket_address->port, + Py_InputHttpStream(web), + web->input.url + ); if (py_environ == NULL) { DEBUG(0, ("Unable to create WSGI environment object\n")); return; -- cgit From bbfce1b43d183cdccbe6f9a189098091f9d4a251 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 20:06:18 +0200 Subject: Allow SWAT to be run outside of smbd. --- source4/web_server/swat/__init__.py | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'source4/web_server') diff --git a/source4/web_server/swat/__init__.py b/source4/web_server/swat/__init__.py index 8229d15a3c..d434bb260b 100644 --- a/source4/web_server/swat/__init__.py +++ b/source4/web_server/swat/__init__.py @@ -32,3 +32,8 @@ def __call__(environ, start_response): yield '\n' +if __name__ == '__main__': + from wsgiref import simple_server + httpd = simple_server.make_server('localhost', 8090, __call__) + print "Serving HTTP on port 8090..." + httpd.serve_forever() -- cgit From 0e9008be35a5b334bd65e6417193d4b8f27bdc36 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 21:26:40 +0200 Subject: Rename smbd -> samba. --- source4/web_server/config.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'source4/web_server') diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index af3ac5f544..e034590111 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = LIBTLS smbcalls process_model LIBPYTHON # End SUBSYSTEM WEB ####################### -- cgit From 05ea5e23cf4e70de0bd658b1c5c0ead133967091 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Sun, 21 Sep 2008 21:32:40 +0200 Subject: Revert "Rename smbd -> samba." This reverts commit 0e9008be35a5b334bd65e6417193d4b8f27bdc36. --- source4/web_server/config.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'source4/web_server') diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index e034590111..af3ac5f544 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init -SUBSYSTEM = samba +SUBSYSTEM = smbd PRIVATE_DEPENDENCIES = LIBTLS smbcalls process_model LIBPYTHON # End SUBSYSTEM WEB ####################### -- cgit From 1d92b2211cc507dd62526f564ec7f75a07110e00 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Mon, 22 Sep 2008 18:15:24 +0200 Subject: s4: allways initialize the process model before it's used metze --- source4/web_server/web_server.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'source4/web_server') diff --git a/source4/web_server/web_server.c b/source4/web_server/web_server.c index 1ed37f657b..d741992770 100644 --- a/source4/web_server/web_server.c +++ b/source4/web_server/web_server.c @@ -307,7 +307,7 @@ static void websrv_task_init(struct task_server *task) task_server_set_title(task, "task[websrv]"); /* run the web server as a single process */ - model_ops = process_model_byname("single"); + model_ops = process_model_startup(task->event_ctx, "single"); if (!model_ops) goto failed; if (lp_interfaces(task->lp_ctx) && lp_bind_interfaces_only(task->lp_ctx)) { -- cgit From 6a689c23e83fef71a562a9009b92983d750f63cc Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 24 Sep 2008 03:16:15 +0200 Subject: Rename smbd -> samba. This reverts commit 05ea5e23cf4e70de0bd658b1c5c0ead133967091. Conflicts: source4/smbd/server.c --- source4/web_server/config.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'source4/web_server') diff --git a/source4/web_server/config.mk b/source4/web_server/config.mk index af3ac5f544..e034590111 100644 --- a/source4/web_server/config.mk +++ b/source4/web_server/config.mk @@ -4,7 +4,7 @@ # Start SUBSYSTEM WEB [MODULE::WEB] INIT_FUNCTION = server_service_web_init -SUBSYSTEM = smbd +SUBSYSTEM = samba PRIVATE_DEPENDENCIES = LIBTLS smbcalls process_model LIBPYTHON # End SUBSYSTEM WEB ####################### -- cgit