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