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