r6981: first version of the builtin web server for Samba4
[samba.git] / source / web_server / http.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    http handling code
5
6    Copyright (C) Andrew Tridgell 2005
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "web_server/web_server.h"
25 #include "smbd/service_stream.h"
26 #include "lib/events/events.h"
27 #include "system/filesys.h"
28 #include "system/iconv.h"
29 #include "system/time.h"
30 #include "web_server/esp/esp.h"
31
32 /* state of the esp subsystem */
33 struct esp_state {
34         struct websrv_context *web;
35         struct MprVar variables[ESP_OBJ_MAX];
36         struct EspRequest *req;
37 };
38
39 /* destroy a esp session */
40 static int esp_destructor(void *ptr)
41 {
42         struct esp_state *esp = talloc_get_type(ptr, struct esp_state);
43         if (esp->req) {
44                 espDestroyRequest(esp->req);
45         }
46         espClose();
47         mprFreeAll();
48         return 0;
49 }
50
51 /*
52   output the http headers
53 */
54 static void http_output_headers(struct websrv_context *web)
55 {
56         int i;
57         char *s;
58         DATA_BLOB b;
59         const char *response_string = "Unknown Code";
60         const struct {
61                 unsigned code;
62                 const char *response_string;
63         } codes[] = {
64                 { 200, "OK" },
65                 { 301, "Moved" },
66                 { 302, "Found" },
67                 { 303, "Method" },
68                 { 304, "Not Modified" },
69                 { 400, "Bad request" },
70                 { 401, "Unauthorized" },
71                 { 403, "Forbidden" },
72                 { 404, "Not Found" },
73                 { 500, "Internal Server Error" },
74                 { 501, "Not implemented" }
75         };
76         for (i=0;i<ARRAY_SIZE(codes);i++) {
77                 if (codes[i].code == web->output.response_code) {
78                         response_string = codes[i].response_string;
79                 }
80         }
81
82         if (web->output.headers == NULL) return;
83         s = talloc_asprintf(web, "HTTP/1.0 %u %s\r\n", 
84                             web->output.response_code, response_string);
85         if (s == NULL) return;
86         for (i=0;web->output.headers[i];i++) {
87                 s = talloc_asprintf_append(s, "%s\r\n", web->output.headers[i]);
88         }
89         s = talloc_asprintf_append(s, "\r\n");
90         if (s == NULL) return;
91
92         b = web->output.content;
93         web->output.content.data = s;
94         web->output.content.length = strlen(s);
95         data_blob_append(web, &web->output.content, b.data, b.length);
96         data_blob_free(&b);
97 }
98
99 /*
100   called when esp wants to output something
101 */
102 static int http_writeBlock(EspHandle handle, char *buf, int size)
103 {
104         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
105         NTSTATUS status;
106         status = data_blob_append(web, &web->output.content, buf, size);
107         if (!NT_STATUS_IS_OK(status)) return -1;
108         return size;
109 }
110
111
112 /*
113   set a http header
114 */
115 static void http_setHeader(EspHandle handle, const char *value, bool allowMultiple)
116 {
117         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
118         char *p = strchr(value, ':');
119
120         if (p && !allowMultiple && web->output.headers) {
121                 int i;
122                 for (i=0;web->output.headers[i];i++) {
123                         if (strncmp(web->output.headers[i], value, (p+1)-value) == 0) {
124                                 web->output.headers[i] = talloc_strdup(web, value);
125                                 return;
126                         }
127                 }
128         }
129
130         web->output.headers = str_list_add(web->output.headers, value);
131 }
132
133 /*
134   set a http response code
135 */
136 static void http_setResponseCode(EspHandle handle, int code)
137 {
138         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
139         web->output.response_code = code;
140 }
141
142 /*
143   redirect to another web page
144  */
145 static void http_redirect(EspHandle handle, int code, char *url)
146 {
147         struct websrv_context *web = talloc_get_type(handle, struct websrv_context);
148         const char *host = web->input.host;
149         
150         /* form the full url, unless it already looks like a url */
151         if (strchr(url, ':') == NULL) {
152                 if (host == NULL) {
153                         host = talloc_asprintf(web, "%s:%u",
154                                                socket_get_my_addr(web->conn->socket, web),
155                                                socket_get_my_port(web->conn->socket));
156                 }
157                 if (host == NULL) goto internal_error;
158                 if (url[0] != '/') {
159                         char *p = strrchr(web->input.url, '/');
160                         if (p == web->input.url) {
161                                 url = talloc_asprintf(web, "http://%s/%s", host, url);
162                         } else {
163                                 int dirlen = p - web->input.url;
164                                 url = talloc_asprintf(web, "http://%s%*.*s/%s",
165                                                       host, 
166                                                       dirlen, dirlen, web->input.url,
167                                                       url);
168                         }
169                         if (url == NULL) goto internal_error;
170                 }
171         }
172
173         http_setHeader(handle, talloc_asprintf(web, "Location: %s", url), 0);
174
175         /* make sure we give a valid redirect code */
176         if (code >= 300 && code < 400) {
177                 http_setResponseCode(handle, code);
178         } else {
179                 http_setResponseCode(handle, 302);
180         }
181         return;
182
183 internal_error:
184         http_error(web, 500, "Internal server error");
185 }
186
187
188 /* callbacks for esp processing */
189 static const struct Esp esp_control = {
190         .maxScriptSize   = 60000,
191         .writeBlock      = http_writeBlock,
192         .setHeader       = http_setHeader,
193         .redirect        = http_redirect,
194         .setResponseCode = http_setResponseCode
195 };
196
197
198 /*
199   setup for a raw http level error
200 */
201 void http_error(struct websrv_context *web, int code, const char *info)
202 {
203         char *s;
204         s = talloc_asprintf(web,"<HTML><HEAD><TITLE>Error %u</TITLE></HEAD><BODY><H1>Error %u</H1>%s<p></BODY></HTML>\r\n\r\n", 
205                             code, code, info);
206         if (s == NULL) {
207                 stream_terminate_connection(web->conn, "http_error: out of memory");
208                 return;
209         }
210         http_writeBlock(web, s, strlen(s));
211         http_setResponseCode(web, code);
212         http_output_headers(web);
213         EVENT_FD_NOT_READABLE(web->conn->event.fde);
214         EVENT_FD_WRITEABLE(web->conn->event.fde);
215 }
216
217 /*
218   map a unix error code to a http error
219 */
220 void http_error_unix(struct websrv_context *web, const char *info)
221 {
222         int code = 500;
223         switch (errno) {
224         case ENOENT:
225         case EISDIR:
226                 code = 404;
227                 break;
228         case EACCES:
229                 code = 403;
230                 break;
231         }
232         http_error(web, code, info);
233 }
234
235 /*
236   return the local path for a URL
237 */
238 static const char *http_local_path(struct websrv_context *web, const char *url)
239 {
240         int i;
241         char *path;
242
243         /* check that the url is OK */
244         if (url[0] != '/') return NULL;
245
246         for (i=0;url[i];i++) {
247                 if ((!isalnum(url[i]) && !strchr("./", url[i])) ||
248                     (url[i] == '.' && strchr("/.", url[i+1]))) {
249                         return NULL;
250                 }
251         }
252
253         path = talloc_asprintf(web, "%s/%s", lp_swat_directory(), url+1);
254         if (path == NULL) return NULL;
255
256         if (directory_exist(path)) {
257                 path = talloc_asprintf_append(path, "/index.html");
258         }
259         return path;
260 }
261
262
263 /*
264   a simple file request
265 */
266 static void http_simple_request(struct websrv_context *web)
267 {
268         const char *url = web->input.url;
269         const char *path;
270         struct stat st;
271
272         path = http_local_path(web, url);
273         if (path == NULL) goto invalid;
274
275         /* looks ok */
276         web->output.fd = open(path, O_RDONLY);
277         if (web->output.fd == -1) {
278                 http_error_unix(web, url);
279                 return;
280         }
281
282         if (fstat(web->output.fd, &st) != 0 || !S_ISREG(st.st_mode)) {
283                 close(web->output.fd);
284                 goto invalid;
285         }
286
287         http_output_headers(web);
288         EVENT_FD_WRITEABLE(web->conn->event.fde);
289         return;
290
291 invalid:
292         http_error(web, 400, "Malformed URL");
293 }
294
295 /*
296   setup the standard ESP arrays
297 */
298 static void http_setup_arrays(struct esp_state *esp)
299 {
300         struct websrv_context *web = esp->web;
301         struct EspRequest *req = esp->req;
302         char *p;
303
304         espSetStringVar(req, ESP_REQUEST_OBJ, "CONTENT_LENGTH", 
305                         talloc_asprintf(esp, "%u", web->input.content_length));
306         if (web->input.query_string) {
307                 espSetStringVar(req, ESP_REQUEST_OBJ, "QUERY_STRING", 
308                                 web->input.query_string);
309         }
310         espSetStringVar(req, ESP_REQUEST_OBJ, "REQUEST_METHOD", 
311                         web->input.post_request?"POST":"GET");
312         espSetStringVar(req, ESP_REQUEST_OBJ, "REQUEST_URI", web->input.url);
313         p = strrchr(web->input.url, '/');
314         espSetStringVar(req, ESP_REQUEST_OBJ, "SCRIPT_NAME", p+1);
315
316         if (web->input.referer) {
317                 espSetStringVar(req, ESP_HEADERS_OBJ, "HTT_REFERER", web->input.referer);
318         }
319         if (web->input.user_agent) {
320                 espSetStringVar(req, ESP_HEADERS_OBJ, "USER_AGENT", web->input.user_agent);
321         }
322
323         espSetStringVar(req, ESP_SERVER_OBJ, "SERVER_ADDR", 
324                         socket_get_my_addr(web->conn->socket, esp));
325         espSetStringVar(req, ESP_SERVER_OBJ, "SERVER_PORT", 
326                         talloc_asprintf(esp, "%u", socket_get_my_port(web->conn->socket)));
327         espSetStringVar(req, ESP_SERVER_OBJ, "SERVER_PROTOCOL", "http");
328 }
329
330
331
332
333
334 /*
335   process a esp request
336 */
337 static void esp_request(struct esp_state *esp)
338 {
339         struct websrv_context *web = esp->web;
340         const char *url = web->input.url;
341         char *buf;
342         const char *path;
343         struct stat st;
344         int fd, res;
345         char *emsg = NULL;
346
347         http_setup_arrays(esp);
348
349         path = http_local_path(web, url);
350         if (path == NULL) goto invalid;
351
352         espSetStringVar(esp->req, ESP_REQUEST_OBJ, "SCRIPT_FILENAME", path);
353
354         /* looks ok */
355         fd = open(path, O_RDONLY);
356         if (fd == -1) {
357                 http_error_unix(web, url);
358                 return;
359         }
360
361         if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
362                 close(fd);
363                 goto invalid;
364         }
365
366         buf = talloc_size(esp, st.st_size+1);
367         if (buf == NULL) goto invalid;
368
369         if (read(fd, buf, st.st_size) != st.st_size) {
370                 goto invalid;
371         }
372         buf[st.st_size] = 0;
373         close(fd);
374
375         res = espProcessRequest(esp->req, path, buf, &emsg);
376         if (res != 0 && emsg) {
377                 http_writeBlock(esp, emsg, strlen(emsg));
378         }
379         http_output_headers(web);
380         EVENT_FD_WRITEABLE(web->conn->event.fde);
381         return;
382
383 invalid:
384         http_error(web, 400, "Malformed URL");
385 }
386
387
388 /* 
389    handling of + and % escapes in http variables 
390 */
391 static const char *http_unescape(TALLOC_CTX *mem_ctx, const char *p)
392 {
393         char *s0 = talloc_strdup(mem_ctx, p);
394         char *s = s0;
395         if (s == NULL) return NULL;
396
397         while (*s) {
398                 unsigned v;
399                 if (*s == '+') *s = ' ';
400                 if (*s == '%' && sscanf(s+1, "%02x", &v) == 1) {
401                         *s = (char)v;
402                         memmove(s+1, s+3, strlen(s+3)+1);
403                 }
404                 s++;
405         }
406
407         return s0;
408 }
409
410 /*
411   set a form or GET variable
412 */
413 static void esp_putvar(struct esp_state *esp, const char *var, const char *value)
414 {
415         espSetStringVar(esp->req, ESP_FORM_OBJ, 
416                         http_unescape(esp, var),
417                         http_unescape(esp, value));
418 }
419
420
421 /*
422   parse the variables in a POST style request
423 */
424 static NTSTATUS http_parse_post(struct esp_state *esp)
425 {
426         DATA_BLOB b = esp->web->input.partial;
427
428         while (b.length) {
429                 char *p, *line;
430                 size_t len;
431
432                 p = memchr(b.data, '&', b.length);
433                 if (p == NULL) {
434                         len = b.length;
435                 } else {
436                         len = p - (char *)b.data;
437                 }
438                 line = talloc_strndup(esp, b.data, len);
439                 NT_STATUS_HAVE_NO_MEMORY(line);
440                                      
441                 p = strchr(line,'=');
442                 if (p) {
443                         *p = 0;
444                         esp_putvar(esp, line, p+1);
445                 }
446                 talloc_free(line);
447                 b.length -= len;
448                 b.data += len;
449                 if (b.length > 0) {
450                         b.length--;
451                         b.data++;
452                 }
453         }
454
455         return NT_STATUS_OK;
456 }
457
458 /*
459   parse the variables in a GET style request
460 */
461 static NTSTATUS http_parse_get(struct esp_state *esp)
462 {
463         struct websrv_context *web = esp->web;
464         char *p, *s, *tok;
465         char *pp;
466
467         p = strchr(web->input.url, '?');
468         web->input.query_string = p+1;
469         *p = 0;
470
471         s = talloc_strdup(esp, esp->web->input.query_string);
472         NT_STATUS_HAVE_NO_MEMORY(s);
473
474         for (tok=strtok_r(s,"&;", &pp);tok;tok=strtok_r(NULL,"&;", &pp)) {
475                 p = strchr(tok,'=');
476                 if (p) {
477                         *p = 0;
478                         esp_putvar(esp, tok, p+1);
479                 }
480         }
481         return NT_STATUS_OK;
482 }
483
484 /*
485   setup some standard variables
486 */
487 static void http_setup_vars(struct esp_state *esp)
488 {
489         int i;
490
491         for (i = 0; i < ESP_OBJ_MAX; i++) {
492                 esp->variables[i] = mprCreateUndefinedVar();
493         }
494         esp->variables[ESP_HEADERS_OBJ]     = mprCreateObjVar("headers", ESP_HASH_SIZE);
495         esp->variables[ESP_FORM_OBJ]        = mprCreateObjVar("form", ESP_HASH_SIZE);
496         esp->variables[ESP_APPLICATION_OBJ] = mprCreateObjVar("application", ESP_HASH_SIZE);
497         esp->variables[ESP_COOKIES_OBJ]     = mprCreateObjVar("cookies", ESP_HASH_SIZE);
498         esp->variables[ESP_FILES_OBJ]       = mprCreateObjVar("files", ESP_HASH_SIZE);
499         esp->variables[ESP_REQUEST_OBJ]     = mprCreateObjVar("request", ESP_HASH_SIZE);
500         esp->variables[ESP_SERVER_OBJ]      = mprCreateObjVar("server", ESP_HASH_SIZE);
501         esp->variables[ESP_SESSION_OBJ]     = mprCreateObjVar("session", ESP_HASH_SIZE);
502 }
503
504 /*
505   process a complete http request
506 */
507 void http_process_input(struct websrv_context *web)
508 {
509         NTSTATUS status;
510         struct esp_state *esp;
511         char *p;
512         int i;
513         const char *file_type = NULL;
514         const struct {
515                 const char *extension;
516                 const char *mime_type;
517         } mime_types[] = {
518                 {"gif",  "image/gif"},
519                 {"png",  "image/png"},
520                 {"jpg",  "image/jpeg"},
521                 {"txt",  "text/plain"}
522         };
523
524         esp = talloc_zero(web, struct esp_state);
525         if (esp == NULL) goto internal_error;
526
527         esp->web = web;
528
529         mprSetCtx(esp);
530
531         talloc_set_destructor(esp, esp_destructor);
532
533         if (espOpen(&esp_control) != 0) goto internal_error;
534
535         http_setup_vars(esp);
536         
537         esp->req = espCreateRequest(web, web->input.url, esp->variables);
538         if (esp->req == NULL) goto internal_error;
539
540         if (web->input.url == NULL) {
541                 http_error(web, 400, "You must specify a GET or POST request");
542                 return;
543         }
544
545         if (web->input.post_request) {
546                 status = http_parse_post(esp);
547                 if (!NT_STATUS_IS_OK(status)) {
548                         http_error(web, 400, "Malformed POST data");
549                         return;
550                 }
551         } else if (strchr(web->input.url, '?')) {
552                 status = http_parse_get(esp);
553                 if (!NT_STATUS_IS_OK(status)) {
554                         http_error(web, 400, "Malformed GET data");
555                         return;
556                 }
557         }
558
559         /* process all html files as ESP */
560         p = strrchr(web->input.url, '.');
561         for (i=0;p && i<ARRAY_SIZE(mime_types);i++) {
562                 if (strcmp(mime_types[i].extension, p+1) == 0) {
563                         file_type = mime_types[i].mime_type;
564                 }
565         }
566         if (file_type == NULL) {
567                 file_type = "text/html";
568         }
569
570         /* setup basic headers */
571         http_setResponseCode(web, 200);
572         http_setHeader(web, talloc_asprintf(esp, "Date: %s", 
573                                             http_timestring(esp, time(NULL))), 0);
574         http_setHeader(web, "Server: Samba", 0);
575         http_setHeader(web, "Connection: close", 0);
576         http_setHeader(web, talloc_asprintf(esp, "Content-Type: %s", file_type), 0);
577
578         if (strcmp(file_type, "text/html") == 0) {
579                 esp_request(esp);
580         } else {
581                 http_simple_request(web);
582         }
583         talloc_free(esp);
584         return;
585         
586 internal_error:
587         talloc_free(esp);
588         http_error(web, 500, "Internal server error");
589 }
590
591
592 /*
593   parse one line of header input
594 */
595 NTSTATUS http_parse_header(struct websrv_context *web, const char *line)
596 {
597         if (line[0] == 0) {
598                 web->input.end_of_headers = True;
599         } else if (strncasecmp(line,"GET ", 4)==0) {
600                 web->input.url = talloc_strndup(web, &line[4], strcspn(&line[4], " \t"));
601         } else if (strncasecmp(line,"POST ", 5)==0) {
602                 web->input.post_request = True;
603                 web->input.url = talloc_strndup(web, &line[5], strcspn(&line[5], " \t"));
604         } else if (strchr(line, ':') == NULL) {
605                 http_error(web, 400, "This server only accepts GET and POST requests");
606                 return NT_STATUS_INVALID_PARAMETER;
607         } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
608                 web->input.content_length = strtoul(&line[16], NULL, 10);
609         } else {
610 #define PULL_HEADER(v, s) do { \
611         if (strncmp(line, s, strlen(s)) == 0) { \
612                 web->input.v = talloc_strdup(web, &line[strlen(s)]); \
613                 return NT_STATUS_OK; \
614         } \
615 } while (0)
616                 PULL_HEADER(content_type, "Content-Type: ");
617                 PULL_HEADER(user_agent, "User-Agent: ");
618                 PULL_HEADER(referer, "Referer: ");
619                 PULL_HEADER(host, "Host: ");
620                 PULL_HEADER(accept_encoding, "Accept-Encoding: ");
621         }
622
623         /* ignore all other headers for now */
624         return NT_STATUS_OK;
625 }
626
627