r9409: fix a problem that volker noticed with web page timeouts causing smbd
[kai/samba.git] / source4 / web_server / http.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    http handling code
5
6    Copyright (C) Andrew Tridgell 2005
7    
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.
12    
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.
17    
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.
21 */
22
23 #include "includes.h"
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 "lib/appweb/esp/esp.h"
32 #include "dlinklist.h"
33 #include "lib/tls/tls.h"
34
35 #define SWAT_SESSION_KEY "SwatSessionId"
36 #define HTTP_PREAUTH_URI "/scripting/preauth.esp"
37
38 /* state of the esp subsystem for a specific request */
39 struct esp_state {
40         struct websrv_context *web;
41         struct EspRequest *req;
42         struct MprVar variables[ESP_OBJ_MAX];
43         struct session_data *session;
44 };
45
46 /* destroy a esp session */
47 static int esp_destructor(void *ptr)
48 {
49         struct esp_state *esp = talloc_get_type(ptr, struct esp_state);
50
51         if (esp->req) {
52                 espDestroyRequest(esp->req);
53         }
54         return 0;
55 }
56
57 /*
58   output the http headers
59 */
60 static void http_output_headers(struct websrv_context *web)
61 {
62         int i;
63         char *s;
64         DATA_BLOB b;
65         uint32_t content_length = 0;
66         const char *response_string = "Unknown Code";
67         const struct {
68                 unsigned code;
69                 const char *response_string;
70         } codes[] = {
71                 { 200, "OK" },
72                 { 301, "Moved" },
73                 { 302, "Found" },
74                 { 303, "Method" },
75                 { 304, "Not Modified" },
76                 { 400, "Bad request" },
77                 { 401, "Unauthorized" },
78                 { 403, "Forbidden" },
79                 { 404, "Not Found" },
80                 { 500, "Internal Server Error" },
81                 { 501, "Not implemented" }
82         };
83         for (i=0;i<ARRAY_SIZE(codes);i++) {
84                 if (codes[i].code == web->output.response_code) {
85                         response_string = codes[i].response_string;
86                 }
87         }
88
89         if (web->output.headers == NULL) return;
90         s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n", 
91                             web->output.response_code, response_string);
92         if (s == NULL) return;
93         for (i=0;web->output.headers[i];i++) {
94                 s = talloc_asprintf_append(s, "%s\r\n", web->output.headers[i]);
95         }
96
97         /* work out the content length */
98         content_length = web->output.content.length;
99         if (web->output.fd != -1) {
100                 struct stat st;
101                 fstat(web->output.fd, &st);
102                 content_length += st.st_size;
103         }
104         s = talloc_asprintf_append(s, "Content-Length: %u\r\n\r\n", content_length);
105         if (s == NULL) return;
106
107         b = web->output.content;
108         web->output.content = data_blob_string_const(s);
109         data_blob_append(web, &web->output.content, b.data, b.length);
110         data_blob_free(&b);
111 }
112
113 /*
114   return the local path for a URL
115 */
116 static const char *http_local_path(struct websrv_context *web, const char *url)
117 {
118         int i;
119         char *path;
120
121         /* check that the url is OK */
122         if (url[0] != '/') return NULL;
123
124         for (i=0;url[i];i++) {
125                 if ((!isalnum((unsigned char)url[i]) && !strchr("./_", url[i])) ||
126                     (url[i] == '.' && strchr("/.", url[i+1]))) {
127                         return NULL;
128                 }
129         }
130
131         path = talloc_asprintf(web, "%s/%s", lp_swat_directory(), url+1);
132         if (path == NULL) return NULL;
133
134         if (directory_exist(path)) {
135                 path = talloc_asprintf_append(path, "/index.esp");
136         }
137         return path;
138 }
139
140 /*
141   called when esp wants to read a file to support include() calls
142 */
143 static int http_readFile(EspHandle handle, char **buf, int *len, const char *path)
144 {
145         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
146         int fd = -1;
147         struct stat st;
148         *buf = NULL;
149
150         path = http_local_path(web, path);
151         if (path == NULL) goto failed;
152
153         fd = open(path, O_RDONLY);
154         if (fd == -1 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) goto failed;
155
156         *buf = talloc_size(handle, st.st_size+1);
157         if (*buf == NULL) goto failed;
158
159         if (read(fd, *buf, st.st_size) != st.st_size) goto failed;
160
161         (*buf)[st.st_size] = 0;
162
163         close(fd);
164         *len = st.st_size;
165         return 0;
166
167 failed:
168         DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno)));
169         if (fd != -1) close(fd);
170         talloc_free(*buf);
171         *buf = NULL;
172         return -1;
173 }
174
175 /*
176   called when esp wants to find the real path of a file
177 */
178 static int http_mapToStorage(EspHandle handle, char *path, int len, const char *uri, int flags)
179 {
180         if (uri == NULL || strlen(uri) >= len) return -1;
181         strncpy(path, uri, len);
182         return 0;
183 }
184
185 /*
186   called when esp wants to output something
187 */
188 static int http_writeBlock(EspHandle handle, const char *buf, int size)
189 {
190         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
191         NTSTATUS status;
192         status = data_blob_append(web, &web->output.content, buf, size);
193         if (!NT_STATUS_IS_OK(status)) return -1;
194         return size;
195 }
196
197
198 /*
199   set a http header
200 */
201 static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple)
202 {
203         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
204         char *p = strchr(value, ':');
205
206         if (p && !allowMultiple && web->output.headers) {
207                 int i;
208                 for (i=0;web->output.headers[i];i++) {
209                         if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) {
210                                 web->output.headers[i] = talloc_strdup(web, value);
211                                 return;
212                         }
213                 }
214         }
215
216         web->output.headers = str_list_add(web->output.headers, value);
217         talloc_steal(web, web->output.headers);
218 }
219
220 /*
221   set a http response code
222 */
223 static void http_setResponseCode(EspHandle handle, int code)
224 {
225         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
226         web->output.response_code = code;
227 }
228
229 /*
230   redirect to another web page
231  */
232 static void http_redirect(EspHandle handle, int code, char *url)
233 {
234         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
235         const char *host = web->input.host;
236         
237         /* form the full url, unless it already looks like a url */
238         if (strchr(url, ':') == NULL) {
239                 if (host == NULL) {
240                         host = talloc_asprintf(web, "%s:%u",
241                                                socket_get_my_addr(web->conn->socket, web),
242                                                socket_get_my_port(web->conn->socket));
243                 }
244                 if (host == NULL) goto internal_error;
245                 if (url[0] != '/') {
246                         char *p = strrchr(web->input.url, '/');
247                         if (p == web->input.url) {
248                                 url = talloc_asprintf(web, "http%s://%s/%s", 
249                                                       tls_enabled(web->tls)?"s":"",
250                                                       host, url);
251                         } else {
252                                 int dirlen = p - web->input.url;
253                                 url = talloc_asprintf(web, "http%s://%s%*.*s/%s",
254                                                       tls_enabled(web->tls)?"s":"",
255                                                       host, 
256                                                       dirlen, dirlen, web->input.url,
257                                                       url);
258                         }
259                         if (url == NULL) goto internal_error;
260                 }
261         }
262
263         http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0);
264
265         /* make sure we give a valid redirect code */
266         if (code >= 300 && code < 400) {
267                 http_setResponseCode(handle, code);
268         } else {
269                 http_setResponseCode(handle, 302);
270         }
271         return;
272
273 internal_error:
274         http_error(web, 500, "Internal server error");
275 }
276
277
278 /*
279   setup a cookie
280 */
281 static void http_setCookie(EspHandle handle, const char *name, const char *value, 
282                            int lifetime, const char *path, bool secure)
283 {
284         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
285         char *buf;
286         
287         if (lifetime > 0) {
288                 buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; Expires=%s; %s",
289                                       name, value, path?path:"/", 
290                                       http_timestring(web, time(NULL)+lifetime),
291                                       secure?"secure":"");
292         } else {
293                 buf = talloc_asprintf(web, "Set-Cookie: %s=%s; path=%s; %s",
294                                       name, value, path?path:"/", 
295                                       secure?"secure":"");
296         }
297         http_setHeader(handle, "Cache-control: no-cache=\"set-cookie\"", 0);
298         http_setHeader(handle, buf, 0);
299         talloc_free(buf);
300 }
301
302 /*
303   return the session id
304 */
305 static const char *http_getSessionId(EspHandle handle)
306 {
307         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
308         return web->session->id;
309 }
310
311 /*
312   setup a session
313 */
314 static void http_createSession(EspHandle handle, int timeout)
315 {
316         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
317         if (web->session) {
318                 web->session->lifetime = timeout;
319                 http_setCookie(web, SWAT_SESSION_KEY, web->session->id, 
320                                web->session->lifetime, "/", 0);
321         }
322 }
323
324 /*
325   destroy a session
326 */
327 static void http_destroySession(EspHandle handle)
328 {
329         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
330         talloc_free(web->session);
331         web->session = NULL;
332 }
333
334
335 /*
336   setup for a raw http level error
337 */
338 void http_error(struct websrv_context *web, int code, const char *info)
339 {
340         char *s;
341         s = talloc_asprintf(web,"<HTML><HEAD><TITLE>Error %u</TITLE></HEAD><BODY><H1>Error %u</H1>%s<p></BODY></HTML>\r\n\r\n", 
342                             code, code, info);
343         if (s == NULL) {
344                 stream_terminate_connection(web->conn, "http_error: out of memory");
345                 return;
346         }
347         http_writeBlock(web, s, strlen(s));
348         http_setResponseCode(web, code);
349         http_output_headers(web);
350         EVENT_FD_NOT_READABLE(web->conn->event.fde);
351         EVENT_FD_WRITEABLE(web->conn->event.fde);
352         web->output.output_pending = True;
353 }
354
355 /*
356   map a unix error code to a http error
357 */
358 void http_error_unix(struct websrv_context *web, const char *info)
359 {
360         int code = 500;
361         switch (errno) {
362         case ENOENT:
363         case EISDIR:
364                 code = 404;
365                 break;
366         case EACCES:
367                 code = 403;
368                 break;
369         }
370         info = talloc_asprintf(web, "%s<p>%s<p>\n", info, strerror(errno));
371         http_error(web, code, info);
372 }
373
374
375 /*
376   a simple file request
377 */
378 static void http_simple_request(struct websrv_context *web)
379 {
380         const char *url = web->input.url;
381         const char *path;
382         struct stat st;
383
384         path = http_local_path(web, url);
385         if (path == NULL) goto invalid;
386
387         /* looks ok */
388         web->output.fd = open(path, O_RDONLY);
389         if (web->output.fd == -1) {
390                 DEBUG(0,("Failed to read file %s - %s\n", path, strerror(errno)));
391                 http_error_unix(web, path);
392                 return;
393         }
394
395         if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) {
396                 close(web->output.fd);
397                 goto invalid;
398         }
399
400         return;
401
402 invalid:
403         http_error(web, 400, "Malformed URL");
404 }
405
406 /*
407   setup the standard ESP arrays
408 */
409 static void http_setup_arrays(struct esp_state *esp)
410 {
411         struct websrv_context *web = esp->web;
412         struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data);
413         struct EspRequest *req = esp->req;
414         char *p;
415
416 #define SETVAR(type, name, value) do { \
417                 const char *v = value; \
418                 if (v) espSetStringVar(req, type, name, v); \
419 } while (0)
420
421         SETVAR(ESP_REQUEST_OBJ, "CONTENT_LENGTH", 
422                talloc_asprintf(esp, "%u", web->input.content_length));
423         SETVAR(ESP_REQUEST_OBJ, "QUERY_STRING", web->input.query_string);
424         SETVAR(ESP_REQUEST_OBJ, "REQUEST_METHOD", web->input.post_request?"POST":"GET");
425         SETVAR(ESP_REQUEST_OBJ, "REQUEST_URI", web->input.url);
426         p = strrchr(web->input.url, '/');
427         SETVAR(ESP_REQUEST_OBJ, "SCRIPT_NAME", p+1);
428         SETVAR(ESP_REQUEST_OBJ, "SCRIPT_FILENAME", web->input.url);
429         p = socket_get_peer_addr(web->conn->socket, esp);
430         SETVAR(ESP_REQUEST_OBJ, "REMOTE_ADDR", p);
431         p = socket_get_peer_name(web->conn->socket, esp);
432         SETVAR(ESP_REQUEST_OBJ, "REMOTE_HOST", p);
433         SETVAR(ESP_REQUEST_OBJ, "REMOTE_USER", "");
434         SETVAR(ESP_REQUEST_OBJ, "CONTENT_TYPE", web->input.content_type);
435         if (web->session) {
436                 SETVAR(ESP_REQUEST_OBJ, "SESSION_ID", web->session->id);
437         }
438         SETVAR(ESP_REQUEST_OBJ, "COOKIE_SUPPORT", web->input.cookie?"True":"False");
439
440         SETVAR(ESP_HEADERS_OBJ, "HTT_REFERER", web->input.referer);
441         SETVAR(ESP_HEADERS_OBJ, "HOST", web->input.host);
442         SETVAR(ESP_HEADERS_OBJ, "ACCEPT_ENCODING", web->input.accept_encoding);
443         SETVAR(ESP_HEADERS_OBJ, "ACCEPT_LANGUAGE", web->input.accept_language);
444         SETVAR(ESP_HEADERS_OBJ, "ACCEPT_CHARSET", web->input.accept_charset);
445         SETVAR(ESP_HEADERS_OBJ, "COOKIE", web->input.cookie);
446         SETVAR(ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent);
447
448         SETVAR(ESP_SERVER_OBJ, "SERVER_ADDR", socket_get_my_addr(web->conn->socket, esp));
449         SETVAR(ESP_SERVER_OBJ, "SERVER_NAME", socket_get_my_addr(web->conn->socket, esp));
450         SETVAR(ESP_SERVER_OBJ, "SERVER_HOST", socket_get_my_addr(web->conn->socket, esp));
451         SETVAR(ESP_SERVER_OBJ, "DOCUMENT_ROOT", lp_swat_directory());
452         SETVAR(ESP_SERVER_OBJ, "SERVER_PORT", 
453                talloc_asprintf(esp, "%u", socket_get_my_port(web->conn->socket)));
454         SETVAR(ESP_SERVER_OBJ, "SERVER_PROTOCOL", tls_enabled(web->tls)?"https":"http");
455         SETVAR(ESP_SERVER_OBJ, "SERVER_SOFTWARE", "SWAT");
456         SETVAR(ESP_SERVER_OBJ, "GATEWAY_INTERFACE", "CGI/1.1");
457         SETVAR(ESP_SERVER_OBJ, "TLS_SUPPORT", tls_support(edata->tls_params)?"True":"False");
458 }
459
460 #if HAVE_SETJMP_H
461 /* the esp scripting lirary generates exceptions when
462    it hits a major error. We need to catch these and
463    report a internal server error via http
464 */
465 #include <setjmp.h>
466 static jmp_buf ejs_exception_buf;
467 static const char *exception_reason;
468
469 void ejs_exception(const char *reason)
470 {
471         exception_reason = reason;
472         DEBUG(0,("%s", reason));
473         longjmp(ejs_exception_buf, -1);
474 }
475 #else
476 void ejs_exception(const char *reason)
477 {
478         DEBUG(0,("%s", reason));
479         smb_panic(reason);
480 }
481 #endif
482
483 /*
484   process a esp request
485 */
486 static void esp_request(struct esp_state *esp, const char *url)
487 {
488         struct websrv_context *web = esp->web;
489         int size;
490         int res;
491         char *emsg = NULL, *buf;
492
493         if (http_readFile(web, &buf, &size, url) != 0) {
494                 http_error_unix(web, url);
495                 return;
496         }
497
498 #if HAVE_SETJMP_H
499         if (setjmp(ejs_exception_buf) != 0) {
500                 http_error(web, 500, exception_reason);
501                 return;
502         }
503 #endif
504
505         res = espProcessRequest(esp->req, url, buf, &emsg);
506         if (res != 0 && emsg) {
507                 http_writeBlock(web, "<pre>", 5);
508                 http_writeBlock(web, emsg, strlen(emsg));
509                 http_writeBlock(web, "</pre>", 6);
510         }
511         talloc_free(buf);
512 }
513
514
515 /*
516   perform pre-authentication on every page is /scripting/preauth.esp
517   exists.  If this script generates any non-whitepace output at all,
518   then we don't run the requested URL.
519
520   note that the preauth is run even for static pages such as images.
521 */
522 static BOOL http_preauth(struct esp_state *esp)
523 {
524         const char *path = http_local_path(esp->web, HTTP_PREAUTH_URI);
525         int i;
526         if (path == NULL) {
527                 http_error(esp->web, 500, "Internal server error");
528                 return False;
529         }
530         if (!file_exist(path)) {
531                 /* if the preath script is not installed then allow access */
532                 return True;
533         }
534         esp_request(esp, HTTP_PREAUTH_URI);
535         for (i=0;i<esp->web->output.content.length;i++) {
536                 if (!isspace(esp->web->output.content.data[i])) {
537                         /* if the preauth has generated content, then force it to be
538                            html, so that we can show the login page for failed
539                            access to images */
540                         http_setHeader(esp->web, "Content-Type: text/html", 0);
541                         return False;
542                 }
543         }
544         data_blob_free(&esp->web->output.content);
545         return True;
546 }
547
548
549 /* 
550    handling of + and % escapes in http variables 
551 */
552 static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p)
553 {
554         char *s0 = talloc_strdup(mem_ctx, p);
555         char *s = s0;
556         if (s == NULL) return NULL;
557
558         while (*s) {
559                 unsigned v;
560                 if (*s == '+') *s = ' ';
561                 if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) {
562                         *s = (char)v;
563                         memmove(s+1, s+3, strlen(s+3)+1);
564                 }
565                 s++;
566         }
567
568         return s0;
569 }
570
571 /*
572   set a form or GET variable
573 */
574 static void esp_putvar(struct esp_state *esp, const char *var, const char *value)
575 {
576         if (strcasecmp(var, SWAT_SESSION_KEY) == 0) {
577                 /* special case support for browsers without cookie
578                  support */
579                 esp->web->input.session_key = talloc_strdup(esp, value);
580         } else {
581                 mprSetPropertyValue(&esp->variables[ESP_FORM_OBJ], 
582                                     http_unescape(esp, var),
583                                     mprCreateStringVar(http_unescape(esp, value), 0));
584         }
585 }
586
587
588 /*
589   parse the variables in a POST style request
590 */
591 static NTSTATUS http_parse_post(struct esp_state *esp)
592 {
593         DATA_BLOB b = esp->web->input.partial;
594
595         while (b.length) {
596                 char *p, *line;
597                 size_t len;
598
599                 p = memchr(b.data, '&', b.length);
600                 if (p == NULL) {
601                         len = b.length;
602                 } else {
603                         len = p - (char *)b.data;
604                 }
605                 line = talloc_strndup(esp, (char *)b.data, len);
606                 NT_STATUS_HAVE_NO_MEMORY(line);
607                                      
608                 p = strchr(line,'=');
609                 if (p) {
610                         *p = 0;
611                         esp_putvar(esp, line, p+1);
612                 }
613                 talloc_free(line);
614                 b.length -= len;
615                 b.data += len;
616                 if (b.length > 0) {
617                         b.length--;
618                         b.data++;
619                 }
620         }
621
622         return NT_STATUS_OK;
623 }
624
625 /*
626   parse the variables in a GET style request
627 */
628 static NTSTATUS http_parse_get(struct esp_state *esp)
629 {
630         struct websrv_context *web = esp->web;
631         char *p, *s, *tok;
632         char *pp;
633
634         p = strchr(web->input.url, '?');
635         web->input.query_string = p+1;
636         *p = 0;
637
638         s = talloc_strdup(esp, esp->web->input.query_string);
639         NT_STATUS_HAVE_NO_MEMORY(s);
640
641         for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) {
642                 p = strchr(tok,'=');
643                 if (p) {
644                         *p = 0;
645                         esp_putvar(esp, tok, p+1);
646                 }
647         }
648         return NT_STATUS_OK;
649 }
650
651 /*
652   called when a session times out
653 */
654 static void session_timeout(struct event_context *ev, struct timed_event *te, 
655                             struct timeval t, void *private)
656 {
657         struct session_data *s = talloc_get_type(private, struct session_data);
658         talloc_free(s);
659 }
660
661 /*
662   destroy a session
663  */
664 static int session_destructor(void *ptr)
665 {
666         struct session_data *s = talloc_get_type(ptr, struct session_data);
667         DLIST_REMOVE(s->edata->sessions, s);
668         return 0;
669 }
670
671 /*
672   setup the session for this request
673 */
674 static void http_setup_session(struct esp_state *esp)
675 {
676         const char *session_key = SWAT_SESSION_KEY;
677         char *p;
678         const char *cookie = esp->web->input.cookie;
679         const char *key = NULL;
680         struct esp_data *edata = talloc_get_type(esp->web->task->private, struct esp_data);
681         struct session_data *s;
682         BOOL generated_key = False;
683
684         /* look for our session key */
685         if (cookie && (p = strstr(cookie, session_key)) && 
686             p[strlen(session_key)] == '=') {
687                 p += strlen(session_key)+1;
688                 key = talloc_strndup(esp, p, strcspn(p, ";"));
689         }
690
691         if (key == NULL && esp->web->input.session_key) {
692                 key = esp->web->input.session_key;
693         } else if (key == NULL) {
694                 key = generate_random_str_list(esp, 16, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
695                 generated_key = True;
696         }
697
698         /* try to find this session in the existing session list */
699         for (s=edata->sessions;s;s=s->next) {
700                 if (strcmp(key, s->id) == 0) {
701                         break;
702                 }
703         }
704
705         if (s == NULL) {
706                 /* create a new session */
707                 s = talloc_zero(edata, struct session_data);
708                 s->id = talloc_steal(s, key);
709                 s->data = NULL;
710                 s->te = NULL;
711                 s->edata = edata;
712                 s->lifetime = lp_parm_int(-1, "web", "sessiontimeout", 900);
713                 DLIST_ADD(edata->sessions, s);
714                 talloc_set_destructor(s, session_destructor);
715                 if (!generated_key) {
716                         mprSetPropertyValue(&esp->variables[ESP_REQUEST_OBJ], 
717                                             "SESSION_EXPIRED", mprCreateStringVar("True", 0));
718                 }
719         }
720
721         http_setCookie(esp->web, session_key, key, s->lifetime, "/", 0);
722
723         if (s->data) {
724                 mprCopyVar(&esp->variables[ESP_SESSION_OBJ], s->data, MPR_DEEP_COPY);
725         }
726
727         esp->web->session = s;
728 }
729
730
731 /* callbacks for esp processing */
732 static const struct Esp esp_control = {
733         .maxScriptSize   = 60000,
734         .writeBlock      = http_writeBlock,
735         .setHeader       = http_setHeader,
736         .redirect        = http_redirect,
737         .setResponseCode = http_setResponseCode,
738         .readFile        = http_readFile,
739         .mapToStorage    = http_mapToStorage,
740         .setCookie       = http_setCookie,
741         .createSession   = http_createSession,
742         .destroySession  = http_destroySession,
743         .getSessionId    = http_getSessionId
744 };
745
746 /*
747   process a complete http request
748 */
749 void http_process_input(struct websrv_context *web)
750 {
751         NTSTATUS status;
752         struct esp_state *esp;
753         struct esp_data *edata = talloc_get_type(web->task->private, struct esp_data);
754         char *p;
755         void *save_mpr_ctx = mprMemCtx();
756         void *ejs_save = ejs_save_state();
757         int i;
758         const char *file_type = NULL;
759         BOOL esp_enable = False;
760         const struct {
761                 const char *extension;
762                 const char *mime_type;
763                 BOOL esp_enable;
764         } mime_types[] = {
765                 {"gif",  "image/gif"},
766                 {"png",  "image/png"},
767                 {"jpg",  "image/jpeg"},
768                 {"txt",  "text/plain"},
769                 {"ico",  "image/x-icon"},
770                 {"css",  "text/css"},
771                 {"esp",  "text/html", True}
772         };
773
774         esp = talloc_zero(web, struct esp_state);
775         if (esp == NULL) goto internal_error;
776
777         esp->web = web;
778
779         mprSetCtx(esp);
780
781         if (espOpen(&esp_control) != 0) goto internal_error;
782
783         for (i=0;i<ARRAY_SIZE(esp->variables);i++) {
784                 esp->variables[i] = mprCreateUndefinedVar();
785         }
786         esp->variables[ESP_HEADERS_OBJ]     = mprCreateObjVar("headers", ESP_HASH_SIZE);
787         esp->variables[ESP_FORM_OBJ]        = mprCreateObjVar("form", ESP_HASH_SIZE);
788         esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE);
789         esp->variables[ESP_COOKIES_OBJ]     = mprCreateObjVar("cookies", ESP_HASH_SIZE);
790         esp->variables[ESP_FILES_OBJ]       = mprCreateObjVar("files", ESP_HASH_SIZE);
791         esp->variables[ESP_REQUEST_OBJ]     = mprCreateObjVar("request", ESP_HASH_SIZE);
792         esp->variables[ESP_SERVER_OBJ]      = mprCreateObjVar("server", ESP_HASH_SIZE);
793         esp->variables[ESP_SESSION_OBJ]     = mprCreateObjVar("session", ESP_HASH_SIZE);
794
795         if (edata->application_data) {
796                 mprCopyVar(&esp->variables[ESP_APPLICATION_OBJ], 
797                            edata->application_data, MPR_DEEP_COPY);
798         }
799
800         talloc_set_destructor(esp, esp_destructor);
801
802         smb_setup_ejs_functions();
803
804         if (web->input.url == NULL) {
805                 http_error(web, 400, "You must specify a GET or POST request");
806                 mprSetCtx(save_mpr_ctx);
807                 ejs_restore_state(ejs_save);
808                 return;
809         }
810         
811         /* parse any form or get variables */
812         if (web->input.post_request) {
813                 status = http_parse_post(esp);
814                 if (!NT_STATUS_IS_OK(status)) {
815                         http_error(web, 400, "Malformed POST data");
816                         mprSetCtx(save_mpr_ctx);
817                         ejs_restore_state(ejs_save);
818                         return;
819                 }
820         } 
821         if (strchr(web->input.url, '?')) {
822                 status = http_parse_get(esp);
823                 if (!NT_STATUS_IS_OK(status)) {
824                         http_error(web, 400, "Malformed GET data");
825                         mprSetCtx(save_mpr_ctx);
826                         ejs_restore_state(ejs_save);
827                         return;
828                 }
829         }
830
831         http_setup_session(esp);
832
833         esp->req = espCreateRequest(web, web->input.url, esp->variables);
834         if (esp->req == NULL) goto internal_error;
835
836         /* work out the mime type */
837         p = strrchr(web->input.url, '.');
838         if (p == NULL) {
839                 esp_enable = True;
840         }
841         for (i=0;p && i<ARRAY_SIZE(mime_types);i++) {
842                 if (strcmp(mime_types[i].extension, p+1) == 0) {
843                         file_type = mime_types[i].mime_type;
844                         esp_enable = mime_types[i].esp_enable;
845                 }
846         }
847         if (file_type == NULL) {
848                 file_type = "text/html";
849         }
850
851         /* setup basic headers */
852         http_setResponseCode(web, 200);
853         http_setHeader(web, talloc_asprintf(esp, "Date: %s", 
854                                             http_timestring(esp, time(NULL))), 0);
855         http_setHeader(web, "Server: Samba", 0);
856         http_setHeader(web, "Connection: close", 0);
857         http_setHeader(web, talloc_asprintf(esp, "Content-Type: %s", file_type), 0);
858
859         http_setup_arrays(esp);
860
861         /* possibly do pre-authentication */
862         if (http_preauth(esp)) {
863                 if (esp_enable) {
864                         esp_request(esp, web->input.url);
865                 } else {
866                         http_simple_request(web);
867                 }
868         }
869
870         if (web->conn == NULL) {
871                 /* the connection has been terminated above us, probably
872                    via a timeout */
873                 goto internal_error;
874         }
875
876         if (!web->output.output_pending) {
877                 http_output_headers(web);
878                 EVENT_FD_WRITEABLE(web->conn->event.fde);
879                 web->output.output_pending = True;
880         }
881
882         /* copy any application data to long term storage in edata */
883         talloc_free(edata->application_data);
884         edata->application_data = talloc_zero(edata, struct MprVar);
885         mprSetCtx(edata->application_data);
886         mprCopyVar(edata->application_data, &esp->variables[ESP_APPLICATION_OBJ], 
887                    MPR_DEEP_COPY);
888         mprSetCtx(esp);
889
890         /* copy any session data */
891         if (web->session) {
892                 talloc_free(web->session->data);
893                 web->session->data = talloc_zero(web->session, struct MprVar);
894                 if (esp->variables[ESP_SESSION_OBJ].properties == NULL ||
895                     esp->variables[ESP_SESSION_OBJ].properties[0].numItems == 0) {
896                         talloc_free(web->session);
897                         web->session = NULL;
898                 } else {
899                         mprSetCtx(web->session->data);
900                         mprCopyVar(web->session->data, &esp->variables[ESP_SESSION_OBJ], 
901                                    MPR_DEEP_COPY);
902                         /* setup the timeout for the session data */
903                         mprSetCtx(esp);
904                         talloc_free(web->session->te);
905                         web->session->te = event_add_timed(web->conn->event.ctx, web->session, 
906                                                            timeval_current_ofs(web->session->lifetime, 0), 
907                                                            session_timeout, web->session);
908                 }
909         }
910
911         talloc_free(esp);
912         mprSetCtx(save_mpr_ctx);
913         ejs_restore_state(ejs_save);
914         return;
915         
916 internal_error:
917         mprSetCtx(esp);
918         talloc_free(esp);
919         if (web->conn != NULL) {
920                 http_error(web, 500, "Internal server error");
921         }
922         mprSetCtx(save_mpr_ctx);
923         ejs_restore_state(ejs_save);
924 }
925
926
927 /*
928   parse one line of header input
929 */
930 NTSTATUS http_parse_header(struct websrv_context *web, const char *line)
931 {
932         if (line[0] == 0) {
933                 web->input.end_of_headers = True;
934         } else if (strncasecmp(line,"GET ", 4)==0) {
935                 web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t"));
936         } else if (strncasecmp(line,"POST ", 5)==0) {
937                 web->input.post_request = True;
938                 web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t"));
939         } else if (strchr(line, ':') == NULL) {
940                 http_error(web, 400, "This server only accepts GET and POST requests");
941                 return NT_STATUS_INVALID_PARAMETER;
942         } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
943                 web->input.content_length = strtoul(&line[16], NULL, 10);
944         } else {
945 #define PULL_HEADER(v, s) do { \
946         if (strncmp(line, s, strlen(s)) == 0) { \
947                 web->input.v = talloc_strdup(web, &line[strlen(s)]); \
948                 return NT_STATUS_OK; \
949         } \
950 } while (0)
951                 PULL_HEADER(content_type, "Content-Type: ");
952                 PULL_HEADER(user_agent, "User-Agent: ");
953                 PULL_HEADER(referer, "Referer: ");
954                 PULL_HEADER(host, "Host: ");
955                 PULL_HEADER(accept_encoding, "Accept-Encoding: ");
956                 PULL_HEADER(accept_language, "Accept-Language: ");
957                 PULL_HEADER(accept_charset, "Accept-Charset: ");
958                 PULL_HEADER(cookie, "Cookie: ");
959         }
960
961         /* ignore all other headers for now */
962         return NT_STATUS_OK;
963 }
964
965
966 /*
967   setup the esp processor - called at task initialisation
968 */
969 NTSTATUS http_setup_esp(struct task_server *task)
970 {
971         struct esp_data *edata;
972
973         edata = talloc_zero(task, struct esp_data);
974         NT_STATUS_HAVE_NO_MEMORY(edata);
975
976         task->private = edata;
977
978         edata->tls_params = tls_initialise(edata);
979         NT_STATUS_HAVE_NO_MEMORY(edata->tls_params);
980
981         return NT_STATUS_OK;
982 }