2 Unix SMB/CIFS implementation.
6 Copyright (C) Andrew Tridgell 2005
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #include "smbd/service_task.h"
25 #include "web_server/web_server.h"
26 #include "smbd/service_stream.h"
27 #include "lib/events/events.h"
28 #include "system/filesys.h"
29 #include "system/iconv.h"
30 #include "system/time.h"
31 #include "web_server/esp/esp.h"
32 #include "dlinklist.h"
34 #define SWAT_SESSION_KEY "_swat_session_"
37 context for long term storage in the web server, to support session[]
38 and application[] data. Stored in task->private.
42 struct session_data *next, *prev;
43 struct esp_data *edata;
46 struct timed_event *te;
49 struct MprVar *application_data;
52 /* state of the esp subsystem for a specific request */
54 struct websrv_context *web;
55 struct EspRequest *req;
56 struct MprVar variables[ESP_OBJ_MAX];
57 struct session_data *session;
60 /* destroy a esp session */
61 static int esp_destructor(void *ptr)
63 struct esp_state *esp = talloc_get_type(ptr, struct esp_state);
66 espDestroyRequest(esp->req);
72 output the http headers
74 static void http_output_headers(struct websrv_context *web)
79 const char *response_string = "Unknown Code";
82 const char *response_string;
88 { 304, "Not Modified" },
89 { 400, "Bad request" },
90 { 401, "Unauthorized" },
93 { 500, "Internal Server Error" },
94 { 501, "Not implemented" }
96 for (i=0;i<ARRAY_SIZE(codes);i++) {
97 if (codes[i].code == web->output.response_code) {
98 response_string = codes[i].response_string;
102 if (web->output.headers == NULL) return;
103 s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n",
104 web->output.response_code, response_string);
105 if (s == NULL) return;
106 for (i=0;web->output.headers[i];i++) {
107 s = talloc_asprintf_append(s, "%s\r\n", web->output.headers[i]);
109 s = talloc_asprintf_append(s, "\r\n");
110 if (s == NULL) return;
112 b = web->output.content;
113 web->output.content.data = s;
114 web->output.content.length = strlen(s);
115 data_blob_append(web, &web->output.content, b.data, b.length);
120 return the local path for a URL
122 static const char *http_local_path(struct websrv_context *web, const char *url)
127 /* check that the url is OK */
128 if (url[0] != '/') return NULL;
130 for (i=0;url[i];i++) {
131 if ((!isalnum(url[i]) && !strchr("./", url[i])) ||
132 (url[i] == '.' && strchr("/.", url[i+1]))) {
137 path = talloc_asprintf(web, "%s/%s", lp_swat_directory(), url+1);
138 if (path == NULL) return NULL;
140 if (directory_exist(path)) {
141 path = talloc_asprintf_append(path, "/index.esp");
147 called when esp wants to read a file to support include() calls
149 static int http_readFile(EspHandle handle, char **buf, int *len, const char *path)
151 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
156 path = http_local_path(web, path);
157 if (path == NULL) goto failed;
159 fd = open(path, O_RDONLY);
160 if (fd == -1 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) goto failed;
162 *buf = talloc_size(handle, st.st_size+1);
163 if (*buf == NULL) goto failed;
165 if (read(fd, *buf, st.st_size) != st.st_size) goto failed;
167 (*buf)[st.st_size] = 0;
174 if (fd != -1) close(fd);
181 called when esp wants to find the real path of a file
183 static int http_mapToStorage(EspHandle handle, char *path, int len, const char *uri, int flags)
185 if (uri == NULL || strlen(uri) >= len) return -1;
186 strncpy(path, uri, len);
191 called when esp wants to output something
193 static int http_writeBlock(EspHandle handle, char *buf, int size)
195 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
197 status = data_blob_append(web, &web->output.content, buf, size);
198 if (!NT_STATUS_IS_OK(status)) return -1;
206 static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple)
208 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
209 char *p = strchr(value, ':');
211 if (p && !allowMultiple && web->output.headers) {
213 for (i=0;web->output.headers[i];i++) {
214 if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) {
215 web->output.headers[i] = talloc_strdup(web, value);
221 web->output.headers = str_list_add(web->output.headers, value);
222 talloc_steal(web, web->output.headers);
226 set a http response code
228 static void http_setResponseCode(EspHandle handle, int code)
230 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
231 web->output.response_code = code;
235 redirect to another web page
237 static void http_redirect(EspHandle handle, int code, char *url)
239 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
240 const char *host = web->input.host;
242 /* form the full url, unless it already looks like a url */
243 if (strchr(url, ':') == NULL) {
245 host = talloc_asprintf(web, "%s:%u",
246 socket_get_my_addr(web->conn->socket, web),
247 socket_get_my_port(web->conn->socket));
249 if (host == NULL) goto internal_error;
251 char *p = strrchr(web->input.url, '/');
252 if (p == web->input.url) {
253 url = talloc_asprintf(web, "http://%s/%s", host, url);
255 int dirlen = p - web->input.url;
256 url = talloc_asprintf(web, "http://%s%*.*s/%s",
258 dirlen, dirlen, web->input.url,
261 if (url == NULL) goto internal_error;
265 http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0);
267 /* make sure we give a valid redirect code */
268 if (code >= 300 && code < 400) {
269 http_setResponseCode(handle, code);
271 http_setResponseCode(handle, 302);
276 http_error(web, 500, "Internal server error");
283 static void http_setCookie(EspHandle handle, const char *name, const char *value,
284 int lifetime, const char *path, bool secure)
286 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
290 buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; Expires=%s; %s",
291 name, value, path?path:"/",
292 http_timestring(web, time(NULL)+lifetime),
295 buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; %s",
296 name, value, path?path:"/",
299 http_setHeader(handle, "Cache-control: no-cache=\"set-cookie\"", 0);
300 http_setHeader(handle, buf, 0);
305 return the session id
307 static const char *http_getSessionId(EspHandle handle)
309 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
310 return web->session->id;
316 static void http_createSession(EspHandle handle, int timeout)
318 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
320 web->session->lifetime = timeout;
321 http_setCookie(web, SWAT_SESSION_KEY, web->session->id,
322 web->session->lifetime, "/", 0);
329 static void http_destroySession(EspHandle handle)
331 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
332 talloc_free(web->session);
338 setup for a raw http level error
340 void http_error(struct websrv_context *web, int code, const char *info)
343 s = talloc_asprintf(web,"<HTML><HEAD><TITLE>Error %u</TITLE></HEAD><BODY><H1>Error %u</H1>%s<p></BODY></HTML>\r\n\r\n",
346 stream_terminate_connection(web->conn, "http_error: out of memory");
349 http_writeBlock(web, s, strlen(s));
350 http_setResponseCode(web, code);
351 http_output_headers(web);
352 EVENT_FD_NOT_READABLE(web->conn->event.fde);
353 EVENT_FD_WRITEABLE(web->conn->event.fde);
357 map a unix error code to a http error
359 void http_error_unix(struct websrv_context *web, const char *info)
371 info = talloc_asprintf(web, "%s<p>%s<p>\n", info, strerror(errno));
372 http_error(web, code, info);
377 a simple file request
379 static void http_simple_request(struct websrv_context *web)
381 const char *url = web->input.url;
385 path = http_local_path(web, url);
386 if (path == NULL) goto invalid;
389 web->output.fd = open(path, O_RDONLY);
390 if (web->output.fd == -1) {
391 http_error_unix(web, path);
395 if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) {
396 close(web->output.fd);
400 http_output_headers(web);
401 EVENT_FD_WRITEABLE(web->conn->event.fde);
405 http_error(web, 400, "Malformed URL");
409 setup the standard ESP arrays
411 static void http_setup_arrays(struct esp_state *esp)
413 struct websrv_context *web = esp->web;
414 struct EspRequest *req = esp->req;
417 #define SETVAR(type, name, value) do { \
418 const char *v = value; \
419 if (v) espSetStringVar(req, type, name, v); \
422 SETVAR(ESP_REQUEST_OBJ, "CONTENT_LENGTH",
423 talloc_asprintf(esp, "%u", web->input.content_length));
424 SETVAR(ESP_REQUEST_OBJ, "QUERY_STRING", web->input.query_string);
425 SETVAR(ESP_REQUEST_OBJ, "REQUEST_METHOD", web->input.post_request?"POST":"GET");
426 SETVAR(ESP_REQUEST_OBJ, "REQUEST_URI", web->input.url);
427 p = strrchr(web->input.url, '/');
428 SETVAR(ESP_REQUEST_OBJ, "SCRIPT_NAME", p+1);
429 p = socket_get_peer_name(web->conn->socket, esp);
430 SETVAR(ESP_REQUEST_OBJ, "REMOTE_HOST", p);
431 SETVAR(ESP_REQUEST_OBJ, "REMOTE_ADDR", p);
432 SETVAR(ESP_REQUEST_OBJ, "REMOTE_USER", "");
433 SETVAR(ESP_REQUEST_OBJ, "CONTENT_TYPE", web->input.content_type);
435 SETVAR(ESP_REQUEST_OBJ, "SESSION_ID", web->session->id);
438 SETVAR(ESP_HEADERS_OBJ, "HTT_REFERER", web->input.referer);
439 SETVAR(ESP_HEADERS_OBJ, "HOST", web->input.host);
440 SETVAR(ESP_HEADERS_OBJ, "ACCEPT_ENCODING", web->input.accept_encoding);
441 SETVAR(ESP_HEADERS_OBJ, "ACCEPT_LANGUAGE", web->input.accept_language);
442 SETVAR(ESP_HEADERS_OBJ, "ACCEPT_CHARSET", web->input.accept_charset);
443 SETVAR(ESP_HEADERS_OBJ, "COOKIE", web->input.cookie);
444 SETVAR(ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent);
446 SETVAR(ESP_SERVER_OBJ, "SERVER_ADDR", socket_get_my_addr(web->conn->socket, esp));
447 SETVAR(ESP_SERVER_OBJ, "SERVER_NAME", socket_get_my_addr(web->conn->socket, esp));
448 SETVAR(ESP_SERVER_OBJ, "SERVER_HOST", socket_get_my_addr(web->conn->socket, esp));
449 SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_swat_directory());
450 SETVAR(ESP_SERVER_OBJ, "SERVER_PORT",
451 talloc_asprintf(esp, "%u", socket_get_my_port(web->conn->socket)));
452 SETVAR(ESP_SERVER_OBJ, "SERVER_PROTOCOL", "http");
453 SETVAR(ESP_SERVER_OBJ, "SERVER_SOFTWARE", "SWAT");
454 SETVAR(ESP_SERVER_OBJ, "GATEWAY_INTERFACE", "CGI/1.1");
455 SETVAR(ESP_REQUEST_OBJ, "SCRIPT_FILENAME", web->input.url);
460 process a esp request
462 static void esp_request(struct esp_state *esp)
464 struct websrv_context *web = esp->web;
465 const char *url = web->input.url;
468 char *emsg = NULL, *buf;
470 http_setup_arrays(esp);
472 if (http_readFile(web, &buf, &size, url) != 0) {
473 http_error_unix(web, url);
477 res = espProcessRequest(esp->req, url, buf, &emsg);
478 if (res != 0 && emsg) {
479 http_writeBlock(web, emsg, strlen(emsg));
482 http_output_headers(web);
483 EVENT_FD_WRITEABLE(web->conn->event.fde);
488 handling of + and % escapes in http variables
490 static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p)
492 char *s0 = talloc_strdup(mem_ctx, p);
494 if (s == NULL) return NULL;
498 if (*s == '+') *s = ' ';
499 if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) {
501 memmove(s+1, s+3, strlen(s+3)+1);
510 set a form or GET variable
512 static void esp_putvar(struct esp_state *esp, const char *var, const char *value)
514 espSetStringVar(esp->req, ESP_FORM_OBJ,
515 http_unescape(esp, var),
516 http_unescape(esp, value));
521 parse the variables in a POST style request
523 static NTSTATUS http_parse_post(struct esp_state *esp)
525 DATA_BLOB b = esp->web->input.partial;
531 p = memchr(b.data, '&', b.length);
535 len = p - (char *)b.data;
537 line = talloc_strndup(esp, b.data, len);
538 NT_STATUS_HAVE_NO_MEMORY(line);
540 p = strchr(line,'=');
543 esp_putvar(esp, line, p+1);
558 parse the variables in a GET style request
560 static NTSTATUS http_parse_get(struct esp_state *esp)
562 struct websrv_context *web = esp->web;
566 p = strchr(web->input.url, '?');
567 web->input.query_string = p+1;
570 s = talloc_strdup(esp, esp->web->input.query_string);
571 NT_STATUS_HAVE_NO_MEMORY(s);
573 for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) {
577 esp_putvar(esp, tok, p+1);
584 called when a session times out
586 static void session_timeout(struct event_context *ev, struct timed_event *te,
587 struct timeval t, void *private)
589 struct session_data *s = talloc_get_type(private, struct session_data);
596 static int session_destructor(void *ptr)
598 struct session_data *s = talloc_get_type(ptr, struct session_data);
599 DLIST_REMOVE(s->edata->sessions, s);
604 setup the session for this request
606 static void http_setup_session(struct esp_state *esp)
608 const char *session_key = SWAT_SESSION_KEY;
610 const char *cookie = esp->web->input.cookie;
611 const char *key = NULL;
612 struct esp_data *edata = talloc_get_type(esp->web->task->private, struct esp_data);
613 struct session_data *s;
615 /* look for our session key */
616 if (cookie && (p = strstr(cookie, session_key)) &&
617 p[strlen(session_key)] == '=') {
618 p += strlen(session_key)+1;
619 key = talloc_strndup(esp, p, strcspn(p, ";"));
623 key = generate_random_str_list(esp, 64, "0123456789");
626 /* try to find this session in the existing session list */
627 for (s=edata->sessions;s;s=s->next) {
628 if (strcmp(key, s->id) == 0) break;
632 /* create a new session */
633 s = talloc_zero(edata, struct session_data);
634 s->id = talloc_steal(s, key);
638 s->lifetime = lp_parm_int(-1, "http", "sessiontimeout", 300);
639 DLIST_ADD(edata->sessions, s);
640 talloc_set_destructor(s, session_destructor);
643 http_setCookie(esp->web, session_key, key, s->lifetime, "/", 0);
646 mprCopyVar(&esp->variables[ESP_SESSION_OBJ], s->data, MPR_DEEP_COPY);
649 esp->web->session = s;
653 /* callbacks for esp processing */
654 static const struct Esp esp_control = {
655 .maxScriptSize = 60000,
656 .writeBlock = http_writeBlock,
657 .setHeader = http_setHeader,
658 .redirect = http_redirect,
659 .setResponseCode = http_setResponseCode,
660 .readFile = http_readFile,
661 .mapToStorage = http_mapToStorage,
662 .setCookie = http_setCookie,
663 .createSession = http_createSession,
664 .destroySession = http_destroySession,
665 .getSessionId = http_getSessionId
669 process a complete http request
671 void http_process_input(struct websrv_context *web)
674 struct esp_state *esp;
675 struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data);
678 const char *file_type = NULL;
679 BOOL esp_enable = False;
681 const char *extension;
682 const char *mime_type;
685 {"gif", "image/gif"},
686 {"png", "image/png"},
687 {"jpg", "image/jpeg"},
688 {"txt", "text/plain"},
689 {"ico", "image/x-icon"},
690 {"esp", "text/html", True}
693 esp = talloc_zero(web, struct esp_state);
694 if (esp == NULL) goto internal_error;
700 if (espOpen(&esp_control) != 0) goto internal_error;
702 for (i=0;i<ARRAY_SIZE(esp->variables);i++) {
703 esp->variables[i] = mprCreateUndefinedVar();
705 esp->variables[ESP_HEADERS_OBJ] = mprCreateObjVar("headers", ESP_HASH_SIZE);
706 esp->variables[ESP_FORM_OBJ] = mprCreateObjVar("form", ESP_HASH_SIZE);
707 esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE);
708 esp->variables[ESP_COOKIES_OBJ] = mprCreateObjVar("cookies", ESP_HASH_SIZE);
709 esp->variables[ESP_FILES_OBJ] = mprCreateObjVar("files", ESP_HASH_SIZE);
710 esp->variables[ESP_REQUEST_OBJ] = mprCreateObjVar("request", ESP_HASH_SIZE);
711 esp->variables[ESP_SERVER_OBJ] = mprCreateObjVar("server", ESP_HASH_SIZE);
712 esp->variables[ESP_SESSION_OBJ] = mprCreateObjVar("session", ESP_HASH_SIZE);
714 if (edata->application_data) {
715 mprCopyVar(&esp->variables[ESP_APPLICATION_OBJ],
716 edata->application_data, MPR_DEEP_COPY);
719 http_setup_session(esp);
721 talloc_set_destructor(esp, esp_destructor);
723 http_setup_ejs_functions();
725 esp->req = espCreateRequest(web, web->input.url, esp->variables);
726 if (esp->req == NULL) goto internal_error;
728 if (web->input.url == NULL) {
729 http_error(web, 400, "You must specify a GET or POST request");
733 /* parse any form or get variables */
734 if (web->input.post_request) {
735 status = http_parse_post(esp);
736 if (!NT_STATUS_IS_OK(status)) {
737 http_error(web, 400, "Malformed POST data");
740 } else if (strchr(web->input.url, '?')) {
741 status = http_parse_get(esp);
742 if (!NT_STATUS_IS_OK(status)) {
743 http_error(web, 400, "Malformed GET data");
748 /* work out the mime type */
749 p = strrchr(web->input.url, '.');
750 for (i=0;p && i<ARRAY_SIZE(mime_types);i++) {
751 if (strcmp(mime_types[i].extension, p+1) == 0) {
752 file_type = mime_types[i].mime_type;
753 esp_enable = mime_types[i].esp_enable;
756 if (file_type == NULL) {
757 file_type = "text/html";
760 /* setup basic headers */
761 http_setResponseCode(web, 200);
762 http_setHeader(web, talloc_asprintf(esp, "Date: %s",
763 http_timestring(esp, time(NULL))), 0);
764 http_setHeader(web, "Server: Samba", 0);
765 http_setHeader(web, "Connection: close", 0);
766 http_setHeader(web, talloc_asprintf(esp, "Content-Type: %s", file_type), 0);
771 http_simple_request(web);
774 /* copy any application data to long term storage in edata */
775 talloc_free(edata->application_data);
776 edata->application_data = talloc_zero(edata, struct MprVar);
777 mprSetCtx(edata->application_data);
778 mprCopyVar(edata->application_data, &esp->variables[ESP_APPLICATION_OBJ], MPR_DEEP_COPY);
780 /* copy any session data */
782 talloc_free(web->session->data);
783 web->session->data = talloc_zero(web->session, struct MprVar);
784 mprSetCtx(web->session->data);
785 if (esp->variables[ESP_SESSION_OBJ].properties == NULL ||
786 esp->variables[ESP_SESSION_OBJ].properties[0].numItems == 0) {
787 talloc_free(web->session);
790 mprCopyVar(web->session->data, &esp->variables[ESP_SESSION_OBJ],
792 /* setup the timeout for the session data */
793 talloc_free(web->session->te);
794 web->session->te = event_add_timed(web->conn->event.ctx, web->session,
795 timeval_current_ofs(web->session->lifetime, 0),
796 session_timeout, web->session);
805 http_error(web, 500, "Internal server error");
810 parse one line of header input
812 NTSTATUS http_parse_header(struct websrv_context *web, const char *line)
815 web->input.end_of_headers = True;
816 } else if (strncasecmp(line,"GET ", 4)==0) {
817 web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t"));
818 } else if (strncasecmp(line,"POST ", 5)==0) {
819 web->input.post_request = True;
820 web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t"));
821 } else if (strchr(line, ':') == NULL) {
822 http_error(web, 400, "This server only accepts GET and POST requests");
823 return NT_STATUS_INVALID_PARAMETER;
824 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
825 web->input.content_length = strtoul(&line[16], NULL, 10);
827 #define PULL_HEADER(v, s) do { \
828 if (strncmp(line, s, strlen(s)) == 0) { \
829 web->input.v = talloc_strdup(web, &line[strlen(s)]); \
830 return NT_STATUS_OK; \
833 PULL_HEADER(content_type, "Content-Type: ");
834 PULL_HEADER(user_agent, "User-Agent: ");
835 PULL_HEADER(referer, "Referer: ");
836 PULL_HEADER(host, "Host: ");
837 PULL_HEADER(accept_encoding, "Accept-Encoding: ");
838 PULL_HEADER(accept_language, "Accept-Language: ");
839 PULL_HEADER(accept_charset, "Accept-Charset: ");
840 PULL_HEADER(cookie, "Cookie: ");
843 /* ignore all other headers for now */
849 setup the esp processor - called at task initialisation
851 NTSTATUS http_setup_esp(struct task_server *task)
853 struct esp_data *edata;
855 edata = talloc(task, struct esp_data);
856 NT_STATUS_HAVE_NO_MEMORY(edata);
858 task->private = edata;
859 edata->sessions = NULL;
860 edata->application_data = NULL;