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