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