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 "web_server/web_server.h"
25 #include "smbd/service_stream.h"
26 #include "lib/events/events.h"
27 #include "system/filesys.h"
28 #include "system/iconv.h"
29 #include "system/time.h"
30 #include "web_server/esp/esp.h"
32 /* state of the esp subsystem */
34 struct websrv_context *web;
35 struct MprVar variables[ESP_OBJ_MAX];
36 struct EspRequest *req;
39 /* destroy a esp session */
40 static int esp_destructor(void *ptr)
42 struct esp_state *esp = talloc_get_type(ptr, struct esp_state);
44 espDestroyRequest(esp->req);
52 output the http headers
54 static void http_output_headers(struct websrv_context *web)
59 const char *response_string = "Unknown Code";
62 const char *response_string;
68 { 304, "Not Modified" },
69 { 400, "Bad request" },
70 { 401, "Unauthorized" },
73 { 500, "Internal Server Error" },
74 { 501, "Not implemented" }
76 for (i=0;i<ARRAY_SIZE(codes);i++) {
77 if (codes[i].code == web->output.response_code) {
78 response_string = codes[i].response_string;
82 if (web->output.headers == NULL) return;
83 s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n",
84 web->output.response_code, response_string);
85 if (s == NULL) return;
86 for (i=0;web->output.headers[i];i++) {
87 s = talloc_asprintf_append(s, "%s\r\n", web->output.headers[i]);
89 s = talloc_asprintf_append(s, "\r\n");
90 if (s == NULL) return;
92 b = web->output.content;
93 web->output.content.data = s;
94 web->output.content.length = strlen(s);
95 data_blob_append(web, &web->output.content, b.data, b.length);
100 return the local path for a URL
102 static const char *http_local_path(struct websrv_context *web, const char *url)
107 /* check that the url is OK */
108 if (url[0] != '/') return NULL;
110 for (i=0;url[i];i++) {
111 if ((!isalnum(url[i]) && !strchr("./", url[i])) ||
112 (url[i] == '.' && strchr("/.", url[i+1]))) {
117 path = talloc_asprintf(web, "%s/%s", lp_swat_directory(), url+1);
118 if (path == NULL) return NULL;
120 if (directory_exist(path)) {
121 path = talloc_asprintf_append(path, "/index.html");
127 called when esp wants to read a file to support include() calls
129 static int http_readFile(EspHandle handle, char **buf, int *len, const char *path)
131 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
136 path = http_local_path(web, path);
137 if (path == NULL) goto failed;
139 fd = open(path, O_RDONLY);
140 if (fd == -1 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) goto failed;
142 *buf = talloc_size(handle, st.st_size+1);
143 if (*buf == NULL) goto failed;
145 if (read(fd, *buf, st.st_size) != st.st_size) goto failed;
147 (*buf)[st.st_size] = 0;
154 if (fd != -1) close(fd);
161 called when esp wants to output something
163 static int http_writeBlock(EspHandle handle, char *buf, int size)
165 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
167 status = data_blob_append(web, &web->output.content, buf, size);
168 if (!NT_STATUS_IS_OK(status)) return -1;
176 static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple)
178 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
179 char *p = strchr(value, ':');
181 if (p && !allowMultiple && web->output.headers) {
183 for (i=0;web->output.headers[i];i++) {
184 if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) {
185 web->output.headers[i] = talloc_strdup(web, value);
191 web->output.headers = str_list_add(web->output.headers, value);
195 set a http response code
197 static void http_setResponseCode(EspHandle handle, int code)
199 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
200 web->output.response_code = code;
204 redirect to another web page
206 static void http_redirect(EspHandle handle, int code, char *url)
208 struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
209 const char *host = web->input.host;
211 /* form the full url, unless it already looks like a url */
212 if (strchr(url, ':') == NULL) {
214 host = talloc_asprintf(web, "%s:%u",
215 socket_get_my_addr(web->conn->socket, web),
216 socket_get_my_port(web->conn->socket));
218 if (host == NULL) goto internal_error;
220 char *p = strrchr(web->input.url, '/');
221 if (p == web->input.url) {
222 url = talloc_asprintf(web, "http://%s/%s", host, url);
224 int dirlen = p - web->input.url;
225 url = talloc_asprintf(web, "http://%s%*.*s/%s",
227 dirlen, dirlen, web->input.url,
230 if (url == NULL) goto internal_error;
234 http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0);
236 /* make sure we give a valid redirect code */
237 if (code >= 300 && code < 400) {
238 http_setResponseCode(handle, code);
240 http_setResponseCode(handle, 302);
245 http_error(web, 500, "Internal server error");
249 /* callbacks for esp processing */
250 static const struct Esp esp_control = {
251 .maxScriptSize = 60000,
252 .writeBlock = http_writeBlock,
253 .setHeader = http_setHeader,
254 .redirect = http_redirect,
255 .setResponseCode = http_setResponseCode,
256 .readFile = http_readFile
261 setup for a raw http level error
263 void http_error(struct websrv_context *web, int code, const char *info)
266 s = talloc_asprintf(web,"<HTML><HEAD><TITLE>Error %u</TITLE></HEAD><BODY><H1>Error %u</H1>%s<p></BODY></HTML>\r\n\r\n",
269 stream_terminate_connection(web->conn, "http_error: out of memory");
272 http_writeBlock(web, s, strlen(s));
273 http_setResponseCode(web, code);
274 http_output_headers(web);
275 EVENT_FD_NOT_READABLE(web->conn->event.fde);
276 EVENT_FD_WRITEABLE(web->conn->event.fde);
280 map a unix error code to a http error
282 void http_error_unix(struct websrv_context *web, const char *info)
294 http_error(web, code, info);
299 a simple file request
301 static void http_simple_request(struct websrv_context *web)
303 const char *url = web->input.url;
307 path = http_local_path(web, url);
308 if (path == NULL) goto invalid;
311 web->output.fd = open(path, O_RDONLY);
312 if (web->output.fd == -1) {
313 http_error_unix(web, path);
317 if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) {
318 close(web->output.fd);
322 http_output_headers(web);
323 EVENT_FD_WRITEABLE(web->conn->event.fde);
327 http_error(web, 400, "Malformed URL");
331 setup the standard ESP arrays
333 static void http_setup_arrays(struct esp_state *esp)
335 struct websrv_context *web = esp->web;
336 struct EspRequest *req = esp->req;
339 espSetStringVar(req, ESP_REQUEST_OBJ, "CONTENT_LENGTH",
340 talloc_asprintf(esp, "%u", web->input.content_length));
341 if (web->input.query_string) {
342 espSetStringVar(req, ESP_REQUEST_OBJ, "QUERY_STRING",
343 web->input.query_string);
345 espSetStringVar(req, ESP_REQUEST_OBJ, "REQUEST_METHOD",
346 web->input.post_request?"POST":"GET");
347 espSetStringVar(req, ESP_REQUEST_OBJ, "REQUEST_URI", web->input.url);
348 p = strrchr(web->input.url, '/');
349 espSetStringVar(req, ESP_REQUEST_OBJ, "SCRIPT_NAME", p+1);
351 if (web->input.referer) {
352 espSetStringVar(req, ESP_HEADERS_OBJ, "HTT_REFERER", web->input.referer);
354 if (web->input.user_agent) {
355 espSetStringVar(req, ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent);
358 espSetStringVar(req, ESP_SERVER_OBJ, "SERVER_ADDR",
359 socket_get_my_addr(web->conn->socket, esp));
360 espSetStringVar(req, ESP_SERVER_OBJ, "SERVER_PORT",
361 talloc_asprintf(esp, "%u", socket_get_my_port(web->conn->socket)));
362 espSetStringVar(req, ESP_SERVER_OBJ, "SERVER_PROTOCOL", "http");
363 espSetStringVar(esp->req, ESP_REQUEST_OBJ, "SCRIPT_FILENAME", web->input.url);
371 process a esp request
373 static void esp_request(struct esp_state *esp)
375 struct websrv_context *web = esp->web;
376 const char *url = web->input.url;
379 char *emsg = NULL, *buf;
381 http_setup_arrays(esp);
383 if (http_readFile(web, &buf, &size, url) != 0) {
384 http_error_unix(web, url);
388 res = espProcessRequest(esp->req, url, buf, &emsg);
389 if (res != 0 && emsg) {
390 http_writeBlock(web, emsg, strlen(emsg));
393 http_output_headers(web);
394 EVENT_FD_WRITEABLE(web->conn->event.fde);
399 handling of + and % escapes in http variables
401 static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p)
403 char *s0 = talloc_strdup(mem_ctx, p);
405 if (s == NULL) return NULL;
409 if (*s == '+') *s = ' ';
410 if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) {
412 memmove(s+1, s+3, strlen(s+3)+1);
421 set a form or GET variable
423 static void esp_putvar(struct esp_state *esp, const char *var, const char *value)
425 espSetStringVar(esp->req, ESP_FORM_OBJ,
426 http_unescape(esp, var),
427 http_unescape(esp, value));
432 parse the variables in a POST style request
434 static NTSTATUS http_parse_post(struct esp_state *esp)
436 DATA_BLOB b = esp->web->input.partial;
442 p = memchr(b.data, '&', b.length);
446 len = p - (char *)b.data;
448 line = talloc_strndup(esp, b.data, len);
449 NT_STATUS_HAVE_NO_MEMORY(line);
451 p = strchr(line,'=');
454 esp_putvar(esp, line, p+1);
469 parse the variables in a GET style request
471 static NTSTATUS http_parse_get(struct esp_state *esp)
473 struct websrv_context *web = esp->web;
477 p = strchr(web->input.url, '?');
478 web->input.query_string = p+1;
481 s = talloc_strdup(esp, esp->web->input.query_string);
482 NT_STATUS_HAVE_NO_MEMORY(s);
484 for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) {
488 esp_putvar(esp, tok, p+1);
495 setup some standard variables
497 static void http_setup_vars(struct esp_state *esp)
501 for (i = 0; i < ESP_OBJ_MAX; i++) {
502 esp->variables[i] = mprCreateUndefinedVar();
504 esp->variables[ESP_HEADERS_OBJ] = mprCreateObjVar("headers", ESP_HASH_SIZE);
505 esp->variables[ESP_FORM_OBJ] = mprCreateObjVar("form", ESP_HASH_SIZE);
506 esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE);
507 esp->variables[ESP_COOKIES_OBJ] = mprCreateObjVar("cookies", ESP_HASH_SIZE);
508 esp->variables[ESP_FILES_OBJ] = mprCreateObjVar("files", ESP_HASH_SIZE);
509 esp->variables[ESP_REQUEST_OBJ] = mprCreateObjVar("request", ESP_HASH_SIZE);
510 esp->variables[ESP_SERVER_OBJ] = mprCreateObjVar("server", ESP_HASH_SIZE);
511 esp->variables[ESP_SESSION_OBJ] = mprCreateObjVar("session", ESP_HASH_SIZE);
515 process a complete http request
517 void http_process_input(struct websrv_context *web)
520 struct esp_state *esp;
523 const char *file_type = NULL;
525 const char *extension;
526 const char *mime_type;
528 {"gif", "image/gif"},
529 {"png", "image/png"},
530 {"jpg", "image/jpeg"},
531 {"txt", "text/plain"}
534 esp = talloc_zero(web, struct esp_state);
535 if (esp == NULL) goto internal_error;
541 talloc_set_destructor(esp, esp_destructor);
543 if (espOpen(&esp_control) != 0) goto internal_error;
545 http_setup_vars(esp);
547 esp->req = espCreateRequest(web, web->input.url, esp->variables);
548 if (esp->req == NULL) goto internal_error;
550 if (web->input.url == NULL) {
551 http_error(web, 400, "You must specify a GET or POST request");
555 if (web->input.post_request) {
556 status = http_parse_post(esp);
557 if (!NT_STATUS_IS_OK(status)) {
558 http_error(web, 400, "Malformed POST data");
561 } else if (strchr(web->input.url, '?')) {
562 status = http_parse_get(esp);
563 if (!NT_STATUS_IS_OK(status)) {
564 http_error(web, 400, "Malformed GET data");
569 /* process all html files as ESP */
570 p = strrchr(web->input.url, '.');
571 for (i=0;p && i<ARRAY_SIZE(mime_types);i++) {
572 if (strcmp(mime_types[i].extension, p+1) == 0) {
573 file_type = mime_types[i].mime_type;
576 if (file_type == NULL) {
577 file_type = "text/html";
580 /* setup basic headers */
581 http_setResponseCode(web, 200);
582 http_setHeader(web, talloc_asprintf(esp, "Date: %s",
583 http_timestring(esp, time(NULL))), 0);
584 http_setHeader(web, "Server: Samba", 0);
585 http_setHeader(web, "Connection: close", 0);
586 http_setHeader(web, talloc_asprintf(esp, "Content-Type: %s", file_type), 0);
588 if (strcmp(file_type, "text/html") == 0) {
591 http_simple_request(web);
598 http_error(web, 500, "Internal server error");
603 parse one line of header input
605 NTSTATUS http_parse_header(struct websrv_context *web, const char *line)
608 web->input.end_of_headers = True;
609 } else if (strncasecmp(line,"GET ", 4)==0) {
610 web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t"));
611 } else if (strncasecmp(line,"POST ", 5)==0) {
612 web->input.post_request = True;
613 web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t"));
614 } else if (strchr(line, ':') == NULL) {
615 http_error(web, 400, "This server only accepts GET and POST requests");
616 return NT_STATUS_INVALID_PARAMETER;
617 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
618 web->input.content_length = strtoul(&line[16], NULL, 10);
620 #define PULL_HEADER(v, s) do { \
621 if (strncmp(line, s, strlen(s)) == 0) { \
622 web->input.v = talloc_strdup(web, &line[strlen(s)]); \
623 return NT_STATUS_OK; \
626 PULL_HEADER(content_type, "Content-Type: ");
627 PULL_HEADER(user_agent, "User-Agent: ");
628 PULL_HEADER(referer, "Referer: ");
629 PULL_HEADER(host, "Host: ");
630 PULL_HEADER(accept_encoding, "Accept-Encoding: ");
633 /* ignore all other headers for now */