Merged revisions 279726 via svnmerge from
[asterisk/asterisk.git] / main / http.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \brief http server for AMI access
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * This program implements a tiny http server
26  * and was inspired by micro-httpd by Jef Poskanzer
27  *
28  * \extref GMime http://spruce.sourceforge.net/gmime/
29  *
30  * \ref AstHTTP - AMI over the http protocol
31  */
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <time.h>
38 #include <sys/time.h>
39 #include <sys/stat.h>
40 #include <sys/signal.h>
41 #include <fcntl.h>
42
43 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
44 #include "asterisk/network.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/tcptls.h"
47 #include "asterisk/http.h"
48 #include "asterisk/utils.h"
49 #include "asterisk/strings.h"
50 #include "asterisk/config.h"
51 #include "asterisk/stringfields.h"
52 #include "asterisk/ast_version.h"
53 #include "asterisk/manager.h"
54 #include "asterisk/_private.h"
55 #include "asterisk/astobj2.h"
56
57 #define MAX_PREFIX 80
58
59 /* See http.h for more information about the SSL implementation */
60 #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
61 #define DO_SSL  /* comment in/out if you want to support ssl */
62 #endif
63
64 static struct ast_tls_config http_tls_cfg;
65
66 static void *httpd_helper_thread(void *arg);
67
68 /*!
69  * we have up to two accepting threads, one for http, one for https
70  */
71 static struct ast_tcptls_session_args http_desc = {
72         .accept_fd = -1,
73         .master = AST_PTHREADT_NULL,
74         .tls_cfg = NULL,
75         .poll_timeout = -1,
76         .name = "http server",
77         .accept_fn = ast_tcptls_server_root,
78         .worker_fn = httpd_helper_thread,
79 };
80
81 static struct ast_tcptls_session_args https_desc = {
82         .accept_fd = -1,
83         .master = AST_PTHREADT_NULL,
84         .tls_cfg = &http_tls_cfg,
85         .poll_timeout = -1,
86         .name = "https server",
87         .accept_fn = ast_tcptls_server_root,
88         .worker_fn = httpd_helper_thread,
89 };
90
91 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri);      /*!< list of supported handlers */
92
93 /* all valid URIs must be prepended by the string in prefix. */
94 static char prefix[MAX_PREFIX];
95 static int enablestatic;
96
97 /*! \brief Limit the kinds of files we're willing to serve up */
98 static struct {
99         const char *ext;
100         const char *mtype;
101 } mimetypes[] = {
102         { "png", "image/png" },
103         { "xml", "text/xml" },
104         { "jpg", "image/jpeg" },
105         { "js", "application/x-javascript" },
106         { "wav", "audio/x-wav" },
107         { "mp3", "audio/mpeg" },
108         { "svg", "image/svg+xml" },
109         { "svgz", "image/svg+xml" },
110         { "gif", "image/gif" },
111 };
112
113 struct http_uri_redirect {
114         AST_LIST_ENTRY(http_uri_redirect) entry;
115         char *dest;
116         char target[0];
117 };
118
119 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
120
121 static const struct ast_cfhttp_methods_text {
122         enum ast_http_method method;
123         const char text[];
124 } ast_http_methods_text[] = {
125         { AST_HTTP_UNKNOWN,     "UNKNOWN" },
126         { AST_HTTP_GET,         "GET" },
127         { AST_HTTP_POST,        "POST" },
128         { AST_HTTP_HEAD,        "HEAD" },
129         { AST_HTTP_PUT,         "PUT" },
130 };
131
132 const char *ast_get_http_method(enum ast_http_method method)
133 {
134         return ast_http_methods_text[method].text;
135 }
136
137 const char *ast_http_ftype2mtype(const char *ftype)
138 {
139         int x;
140
141         if (ftype) {
142                 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
143                         if (!strcasecmp(ftype, mimetypes[x].ext)) {
144                                 return mimetypes[x].mtype;
145                         }
146                 }
147         }
148         return NULL;
149 }
150
151 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
152 {
153         uint32_t mngid = 0;
154         struct ast_variable *v, *cookies;
155
156         cookies = ast_http_get_cookies(headers);
157         for (v = cookies; v; v = v->next) {
158                 if (!strcasecmp(v->name, "mansession_id")) {
159                         sscanf(v->value, "%30x", &mngid);
160                         break;
161                 }
162         }
163         if (cookies) {
164                 ast_variables_destroy(cookies);
165         }
166         return mngid;
167 }
168
169 void ast_http_prefix(char *buf, int len)
170 {
171         if (buf) {
172                 ast_copy_string(buf, prefix, len);
173         }
174 }
175
176 static int static_callback(struct ast_tcptls_session_instance *ser,
177         const struct ast_http_uri *urih, const char *uri,
178         enum ast_http_method method, struct ast_variable *get_vars,
179         struct ast_variable *headers)
180 {
181         char *path;
182         const char *ftype;
183         const char *mtype;
184         char wkspace[80];
185         struct stat st;
186         int len;
187         int fd;
188         struct ast_str *http_header;
189         struct timeval tv;
190         struct ast_tm tm;
191         char timebuf[80], etag[23];
192         struct ast_variable *v;
193         int not_modified = 0;
194
195         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
196                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
197                 return -1;
198         }
199
200         /* Yuck.  I'm not really sold on this, but if you don't deliver static content it makes your configuration
201            substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
202         if (!enablestatic || ast_strlen_zero(uri)) {
203                 goto out403;
204         }
205
206         /* Disallow any funny filenames at all */
207         if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
208                 goto out403;
209         }
210
211         if (strstr(uri, "/..")) {
212                 goto out403;
213         }
214
215         if ((ftype = strrchr(uri, '.'))) {
216                 ftype++;
217         }
218
219         if (!(mtype = ast_http_ftype2mtype(ftype))) {
220                 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
221         }
222
223         /* Cap maximum length */
224         if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
225                 goto out403;
226         }
227
228         path = alloca(len);
229         sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
230         if (stat(path, &st)) {
231                 goto out404;
232         }
233
234         if (S_ISDIR(st.st_mode)) {
235                 goto out404;
236         }
237
238         fd = open(path, O_RDONLY);
239         if (fd < 0) {
240                 goto out403;
241         }
242
243         if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
244                 goto out403;
245         }
246
247         /* make "Etag:" http header value */
248         snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
249
250         /* make "Last-Modified:" http header value */
251         tv.tv_sec = st.st_mtime;
252         tv.tv_usec = 0;
253         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
254
255         /* check received "If-None-Match" request header and Etag value for file */
256         for (v = headers; v; v = v->next) {
257                 if (!strcasecmp(v->name, "If-None-Match")) {
258                         if (!strcasecmp(v->value, etag)) {
259                                 not_modified = 1;
260                         }
261                         break;
262                 }
263         }
264
265         if ( (http_header = ast_str_create(255)) == NULL) {
266                 return -1;
267         }
268
269         ast_str_set(&http_header, 0, "Content-type: %s\r\n"
270                 "ETag: %s\r\n"
271                 "Last-Modified: %s",
272                 mtype,
273                 etag,
274                 timebuf);
275
276         /* ast_http_send() frees http_header, so we don't need to do it before returning */
277         if (not_modified) {
278                 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
279         } else {
280                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
281         }
282         close(fd);
283         return 0;
284
285 out404:
286         ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
287         return -1;
288
289 out403:
290         ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
291         return -1;
292 }
293
294 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
295         const struct ast_http_uri *urih, const char *uri,
296         enum ast_http_method method, struct ast_variable *get_vars,
297         struct ast_variable *headers)
298 {
299         struct ast_str *out;
300         struct ast_variable *v, *cookies = NULL;
301
302         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
303                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
304                 return -1;
305         }
306
307         if ( (out = ast_str_create(512)) == NULL) {
308                 return -1;
309         }
310
311         ast_str_append(&out, 0,
312                 "<title>Asterisk HTTP Status</title>\r\n"
313                 "<body bgcolor=\"#ffffff\">\r\n"
314                 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
315                 "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
316
317         ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
318         ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
319                        ast_sockaddr_stringify_addr(&http_desc.old_address));
320         ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
321                        ast_sockaddr_stringify_port(&http_desc.old_address));
322         if (http_tls_cfg.enabled) {
323                 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
324                                ast_sockaddr_stringify_port(&https_desc.old_address));
325         }
326         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
327         for (v = get_vars; v; v = v->next) {
328                 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
329         }
330         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
331
332         cookies = ast_http_get_cookies(headers);
333         for (v = cookies; v; v = v->next) {
334                 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
335         }
336         ast_variables_destroy(cookies);
337
338         ast_str_append(&out, 0, "</table><center><font size=\"-1\"><i>Asterisk and Digium are registered trademarks of Digium, Inc.</i></font></center></body>\r\n");
339         ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
340         return 0;
341 }
342
343 static struct ast_http_uri statusuri = {
344         .callback = httpstatus_callback,
345         .description = "Asterisk HTTP General Status",
346         .uri = "httpstatus",
347         .has_subtree = 0,
348         .data = NULL,
349         .key = __FILE__,
350 };
351
352 static struct ast_http_uri staticuri = {
353         .callback = static_callback,
354         .description = "Asterisk HTTP Static Delivery",
355         .uri = "static",
356         .has_subtree = 1,
357         .data = NULL,
358         .key= __FILE__,
359 };
360
361
362 /* send http/1.1 responce */
363 /* free content variable and close socket*/
364 void ast_http_send(struct ast_tcptls_session_instance *ser,
365         enum ast_http_method method, int status_code, const char *status_title,
366         struct ast_str *http_header, struct ast_str *out, const int fd,
367         unsigned int static_content)
368 {
369         struct timeval now = ast_tvnow();
370         struct ast_tm tm;
371         char timebuf[80];
372         int content_length = 0;
373
374         if (!ser || 0 == ser->f) {
375                 return;
376         }
377
378         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
379
380         /* calc conetnt length */
381         if (out) {
382                 content_length += strlen(ast_str_buffer(out));
383         }
384
385         if (fd) {
386                 content_length += lseek(fd, 0, SEEK_END);
387                 lseek(fd, 0, SEEK_SET);
388         }
389
390         /* send http header */
391         fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
392                 "Server: Asterisk/%s\r\n"
393                 "Date: %s\r\n"
394                 "Connection: close\r\n"
395                 "%s"
396                 "Content-Length: %d\r\n"
397                 "%s\r\n\r\n",
398                 status_code, status_title ? status_title : "OK",
399                 ast_get_version(),
400                 timebuf,
401                 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
402                 content_length,
403                 http_header ? ast_str_buffer(http_header) : ""
404                 );
405
406         /* send content */
407         if (method != AST_HTTP_HEAD || status_code >= 400) {
408                 if (out) {
409                         fprintf(ser->f, "%s", ast_str_buffer(out));
410                 }
411
412                 if (fd) {
413                         char buf[256];
414                         int len;
415                         while ((len = read(fd, buf, sizeof(buf))) > 0) {
416                                 if (fwrite(buf, len, 1, ser->f) != 1) {
417                                         ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
418                                         break;
419                                 }
420                         }
421                 }
422         }
423
424         if (http_header) {
425                 ast_free(http_header);
426         }
427         if (out) {
428                 ast_free(out);
429         }
430
431         fclose(ser->f);
432         ser->f = 0;
433         return;
434 }
435
436 /* Send http "401 Unauthorized" responce and close socket*/
437 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
438         const unsigned long nonce, const unsigned long opaque, int stale,
439         const char *text)
440 {
441         struct ast_str *http_headers = ast_str_create(128);
442         struct ast_str *out = ast_str_create(512);
443
444         if (!http_headers || !out) {
445                 ast_free(http_headers);
446                 ast_free(out);
447                 return;
448         }
449
450         ast_str_set(&http_headers, 0,
451                 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
452                 "Content-type: text/html",
453                 realm ? realm : "Asterisk",
454                 nonce,
455                 opaque,
456                 stale ? ", stale=true" : "");
457
458         ast_str_set(&out, 0,
459                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
460                 "<html><head>\r\n"
461                 "<title>401 Unauthorized</title>\r\n"
462                 "</head><body>\r\n"
463                 "<h1>401 Unauthorized</h1>\r\n"
464                 "<p>%s</p>\r\n"
465                 "<hr />\r\n"
466                 "<address>Asterisk Server</address>\r\n"
467                 "</body></html>\r\n",
468                 text ? text : "");
469
470         ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
471         return;
472 }
473
474 /* send http error responce and close socket*/
475 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
476 {
477         struct ast_str *http_headers = ast_str_create(40);
478         struct ast_str *out = ast_str_create(256);
479
480         if (!http_headers || !out) {
481                 ast_free(http_headers);
482                 ast_free(out);
483                 return;
484         }
485
486         ast_str_set(&http_headers, 0, "Content-type: text/html");
487
488         ast_str_set(&out, 0,
489                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
490                 "<html><head>\r\n"
491                 "<title>%d %s</title>\r\n"
492                 "</head><body>\r\n"
493                 "<h1>%s</h1>\r\n"
494                 "<p>%s</p>\r\n"
495                 "<hr />\r\n"
496                 "<address>Asterisk Server</address>\r\n"
497                 "</body></html>\r\n",
498                         status_code, status_title, status_title, text);
499
500         ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
501         return;
502 }
503
504 /*! \brief
505  * Link the new uri into the list.
506  *
507  * They are sorted by length of
508  * the string, not alphabetically. Duplicate entries are not replaced,
509  * but the insertion order (using <= and not just <) makes sure that
510  * more recent insertions hide older ones.
511  * On a lookup, we just scan the list and stop at the first matching entry.
512  */
513 int ast_http_uri_link(struct ast_http_uri *urih)
514 {
515         struct ast_http_uri *uri;
516         int len = strlen(urih->uri);
517
518         AST_RWLIST_WRLOCK(&uris);
519
520         if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
521                 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
522                 AST_RWLIST_UNLOCK(&uris);
523                 return 0;
524         }
525
526         AST_RWLIST_TRAVERSE(&uris, uri, entry) {
527                 if (AST_RWLIST_NEXT(uri, entry) &&
528                         strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
529                         AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
530                         AST_RWLIST_UNLOCK(&uris);
531
532                         return 0;
533                 }
534         }
535
536         AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
537
538         AST_RWLIST_UNLOCK(&uris);
539
540         return 0;
541 }
542
543 void ast_http_uri_unlink(struct ast_http_uri *urih)
544 {
545         AST_RWLIST_WRLOCK(&uris);
546         AST_RWLIST_REMOVE(&uris, urih, entry);
547         AST_RWLIST_UNLOCK(&uris);
548 }
549
550 void ast_http_uri_unlink_all_with_key(const char *key)
551 {
552         struct ast_http_uri *urih;
553         AST_RWLIST_WRLOCK(&uris);
554         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
555                 if (!strcmp(urih->key, key)) {
556                         AST_RWLIST_REMOVE_CURRENT(entry);
557                 }
558                 if (urih->dmallocd) {
559                         ast_free(urih->data);
560                 }
561                 if (urih->mallocd) {
562                         ast_free(urih);
563                 }
564         }
565         AST_RWLIST_TRAVERSE_SAFE_END;
566         AST_RWLIST_UNLOCK(&uris);
567 }
568
569 /*
570  * Decode special characters in http uri.
571  * We have ast_uri_decode to handle %XX sequences, but spaces
572  * are encoded as a '+' so we need to replace them beforehand.
573  */
574 static void http_decode(char *s)
575 {
576         char *t;
577
578         for (t = s; *t; t++) {
579                 if (*t == '+') {
580                         *t = ' ';
581                 }
582         }
583
584         ast_uri_decode(s);
585 }
586
587 /*
588  * get post variables from client Request Entity-Body, if content type is
589  * application/x-www-form-urlencoded
590  */
591 struct ast_variable *ast_http_get_post_vars(
592         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
593 {
594         int content_length = 0;
595         struct ast_variable *v, *post_vars=NULL, *prev = NULL;
596         char *buf, *var, *val;
597
598         for (v = headers; v; v = v->next) {
599                 if (!strcasecmp(v->name, "Content-Type")) {
600                         if (strcasecmp(v->value, "application/x-www-form-urlencoded")) {
601                                 return NULL;
602                         }
603                         break;
604                 }
605         }
606
607         for (v = headers; v; v = v->next) {
608                 if (!strcasecmp(v->name, "Content-Length")) {
609                         content_length = atoi(v->value) + 1;
610                         break;
611                 }
612         }
613
614         if (!content_length) {
615                 return NULL;
616         }
617
618         if (!(buf = alloca(content_length))) {
619                 return NULL;
620         }
621         if (!fgets(buf, content_length, ser->f)) {
622                 return NULL;
623         }
624
625         while ((val = strsep(&buf, "&"))) {
626                 var = strsep(&val, "=");
627                 if (val) {
628                         http_decode(val);
629                 } else  {
630                         val = "";
631                 }
632                 http_decode(var);
633                 if ((v = ast_variable_new(var, val, ""))) {
634                         if (post_vars) {
635                                 prev->next = v;
636                         } else {
637                                 post_vars = v;
638                         }
639                         prev = v;
640                 }
641         }
642         return post_vars;
643 }
644
645 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
646         enum ast_http_method method, struct ast_variable *headers)
647 {
648         char *c;
649         int res = -1;
650         char *params = uri;
651         struct ast_http_uri *urih = NULL;
652         int l;
653         struct ast_variable *get_vars = NULL, *v, *prev = NULL;
654         struct http_uri_redirect *redirect;
655
656         strsep(&params, "?");
657         /* Extract arguments from the request and store them in variables. */
658         if (params) {
659                 char *var, *val;
660
661                 while ((val = strsep(&params, "&"))) {
662                         var = strsep(&val, "=");
663                         if (val) {
664                                 http_decode(val);
665                         } else  {
666                                 val = "";
667                         }
668                         http_decode(var);
669                         if ((v = ast_variable_new(var, val, ""))) {
670                                 if (get_vars) {
671                                         prev->next = v;
672                                 } else {
673                                         get_vars = v;
674                                 }
675                                 prev = v;
676                         }
677                 }
678         }
679         http_decode(uri);
680
681         AST_RWLIST_RDLOCK(&uri_redirects);
682         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
683                 if (!strcasecmp(uri, redirect->target)) {
684                         struct ast_str *http_header = ast_str_create(128);
685                         ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
686                         ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
687
688                         break;
689                 }
690         }
691         AST_RWLIST_UNLOCK(&uri_redirects);
692         if (redirect) {
693                 goto cleanup;
694         }
695
696         /* We want requests to start with the (optional) prefix and '/' */
697         l = strlen(prefix);
698         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
699                 uri += l + 1;
700                 /* scan registered uris to see if we match one. */
701                 AST_RWLIST_RDLOCK(&uris);
702                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
703                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
704                         l = strlen(urih->uri);
705                         c = uri + l;    /* candidate */
706                         if (strncasecmp(urih->uri, uri, l) /* no match */
707                             || (*c && *c != '/')) { /* substring */
708                                 continue;
709                         }
710                         if (*c == '/') {
711                                 c++;
712                         }
713                         if (!*c || urih->has_subtree) {
714                                 uri = c;
715                                 break;
716                         }
717                 }
718                 AST_RWLIST_UNLOCK(&uris);
719         }
720         if (urih) {
721                 res = urih->callback(ser, urih, uri, method, get_vars, headers);
722         } else {
723                 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
724         }
725
726 cleanup:
727         ast_variables_destroy(get_vars);
728         return res;
729 }
730
731 #ifdef DO_SSL
732 #if defined(HAVE_FUNOPEN)
733 #define HOOK_T int
734 #define LEN_T int
735 #else
736 #define HOOK_T ssize_t
737 #define LEN_T size_t
738 #endif
739
740 /*!
741  * replacement read/write functions for SSL support.
742  * We use wrappers rather than SSL_read/SSL_write directly so
743  * we can put in some debugging.
744  */
745 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
746 {
747         int i = SSL_read(cookie, buf, len-1);
748 #if 0
749         if (i >= 0)
750                 buf[i] = '\0';
751         ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
752 #endif
753         return i;
754 }
755
756 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
757 {
758 #if 0
759         char *s = alloca(len+1);
760         strncpy(s, buf, len);
761         s[len] = '\0';
762         ast_verbose("ssl write size %d <%s>\n", (int)len, s);
763 #endif
764         return SSL_write(cookie, buf, len);
765 }
766
767 static int ssl_close(void *cookie)
768 {
769         close(SSL_get_fd(cookie));
770         SSL_shutdown(cookie);
771         SSL_free(cookie);
772         return 0;
773 }*/
774 #endif  /* DO_SSL */
775
776 static struct ast_variable *parse_cookies(char *cookies)
777 {
778         char *cur;
779         struct ast_variable *vars = NULL, *var;
780
781         while ((cur = strsep(&cookies, ";"))) {
782                 char *name, *val;
783
784                 name = val = cur;
785                 strsep(&val, "=");
786
787                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
788                         continue;
789                 }
790
791                 name = ast_strip(name);
792                 val = ast_strip_quoted(val, "\"", "\"");
793
794                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
795                         continue;
796                 }
797
798                 if (option_debug) {
799                         ast_log(LOG_DEBUG, "mmm ... cookie!  Name: '%s'  Value: '%s'\n", name, val);
800                 }
801
802                 var = ast_variable_new(name, val, __FILE__);
803                 var->next = vars;
804                 vars = var;
805         }
806
807         return vars;
808 }
809
810 /* get cookie from Request headers */
811 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
812 {
813         struct ast_variable *v, *cookies=NULL;
814
815         for (v = headers; v; v = v->next) {
816                 if (!strncasecmp(v->name, "Cookie", 6)) {
817                         char *tmp = ast_strdupa(v->value);
818                         if (cookies) {
819                                 ast_variables_destroy(cookies);
820                         }
821
822                         cookies = parse_cookies(tmp);
823                 }
824         }
825         return cookies;
826 }
827
828
829 static void *httpd_helper_thread(void *data)
830 {
831         char buf[4096];
832         char header_line[4096];
833         struct ast_tcptls_session_instance *ser = data;
834         struct ast_variable *headers = NULL;
835         struct ast_variable *tail = headers;
836         char *uri, *method;
837         enum ast_http_method http_method = AST_HTTP_UNKNOWN;
838
839         if (!fgets(buf, sizeof(buf), ser->f)) {
840                 goto done;
841         }
842
843         /* Get method */
844         method = ast_skip_blanks(buf);
845         uri = ast_skip_nonblanks(method);
846         if (*uri) {
847                 *uri++ = '\0';
848         }
849
850         if (!strcasecmp(method,"GET")) {
851                 http_method = AST_HTTP_GET;
852         } else if (!strcasecmp(method,"POST")) {
853                 http_method = AST_HTTP_POST;
854         } else if (!strcasecmp(method,"HEAD")) {
855                 http_method = AST_HTTP_HEAD;
856         } else if (!strcasecmp(method,"PUT")) {
857                 http_method = AST_HTTP_PUT;
858         }
859
860         uri = ast_skip_blanks(uri);     /* Skip white space */
861
862         if (*uri) {                     /* terminate at the first blank */
863                 char *c = ast_skip_nonblanks(uri);
864
865                 if (*c) {
866                         *c = '\0';
867                 }
868         }
869
870         /* process "Request Headers" lines */
871         while (fgets(header_line, sizeof(header_line), ser->f)) {
872                 char *name, *value;
873
874                 /* Trim trailing characters */
875                 ast_trim_blanks(header_line);
876                 if (ast_strlen_zero(header_line)) {
877                         break;
878                 }
879
880                 value = header_line;
881                 name = strsep(&value, ":");
882                 if (!value) {
883                         continue;
884                 }
885
886                 value = ast_skip_blanks(value);
887                 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
888                         continue;
889                 }
890
891                 ast_trim_blanks(name);
892
893                 if (!headers) {
894                         headers = ast_variable_new(name, value, __FILE__);
895                         tail = headers;
896                 } else {
897                         tail->next = ast_variable_new(name, value, __FILE__);
898                         tail = tail->next;
899                 }
900         }
901
902         if (!*uri) {
903                 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
904                 return NULL;
905         }
906
907         handle_uri(ser, uri, http_method, headers);
908
909         /* Clean up all the header information pulled as well */
910         if (headers) {
911                 ast_variables_destroy(headers);
912         }
913
914 done:
915         if (ser->f) {
916                 fclose(ser->f);
917         }
918         ao2_ref(ser, -1);
919         ser = NULL;
920         return NULL;
921 }
922
923 /*!
924  * \brief Add a new URI redirect
925  * The entries in the redirect list are sorted by length, just like the list
926  * of URI handlers.
927  */
928 static void add_redirect(const char *value)
929 {
930         char *target, *dest;
931         struct http_uri_redirect *redirect, *cur;
932         unsigned int target_len;
933         unsigned int total_len;
934
935         dest = ast_strdupa(value);
936         dest = ast_skip_blanks(dest);
937         target = strsep(&dest, " ");
938         target = ast_skip_blanks(target);
939         target = strsep(&target, " "); /* trim trailing whitespace */
940
941         if (!dest) {
942                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
943                 return;
944         }
945
946         target_len = strlen(target) + 1;
947         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
948
949         if (!(redirect = ast_calloc(1, total_len))) {
950                 return;
951         }
952         redirect->dest = redirect->target + target_len;
953         strcpy(redirect->target, target);
954         strcpy(redirect->dest, dest);
955
956         AST_RWLIST_WRLOCK(&uri_redirects);
957
958         target_len--; /* So we can compare directly with strlen() */
959         if (AST_RWLIST_EMPTY(&uri_redirects)
960                 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
961                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
962                 AST_RWLIST_UNLOCK(&uri_redirects);
963
964                 return;
965         }
966
967         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
968                 if (AST_RWLIST_NEXT(cur, entry)
969                         && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
970                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
971                         AST_RWLIST_UNLOCK(&uri_redirects);
972                         return;
973                 }
974         }
975
976         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
977
978         AST_RWLIST_UNLOCK(&uri_redirects);
979 }
980
981 static int __ast_http_load(int reload)
982 {
983         struct ast_config *cfg;
984         struct ast_variable *v;
985         int enabled=0;
986         int newenablestatic=0;
987         struct hostent *hp;
988         struct ast_hostent ahp;
989         char newprefix[MAX_PREFIX] = "";
990         struct http_uri_redirect *redirect;
991         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
992         struct sockaddr_in tmp = {0,};
993         struct sockaddr_in tmp2 = {0,};
994
995         cfg = ast_config_load2("http.conf", "http", config_flags);
996         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
997                 return 0;
998         }
999
1000         /* default values */
1001         tmp.sin_family = AF_INET;
1002         tmp.sin_port = htons(8088);
1003         ast_sockaddr_from_sin(&http_desc.local_address, &tmp);
1004
1005         tmp2.sin_family = AF_INET;
1006         tmp2.sin_port = htons(8089);
1007         ast_sockaddr_from_sin(&https_desc.local_address, &tmp2);
1008
1009         http_tls_cfg.enabled = 0;
1010         if (http_tls_cfg.certfile) {
1011                 ast_free(http_tls_cfg.certfile);
1012         }
1013         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1014
1015         if (http_tls_cfg.pvtfile) {
1016                 ast_free(http_tls_cfg.pvtfile);
1017         }
1018         http_tls_cfg.pvtfile = ast_strdup("");
1019
1020         if (http_tls_cfg.cipher) {
1021                 ast_free(http_tls_cfg.cipher);
1022         }
1023         http_tls_cfg.cipher = ast_strdup("");
1024
1025         AST_RWLIST_WRLOCK(&uri_redirects);
1026         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1027                 ast_free(redirect);
1028         }
1029         AST_RWLIST_UNLOCK(&uri_redirects);
1030
1031         if (cfg) {
1032                 v = ast_variable_browse(cfg, "general");
1033                 for (; v; v = v->next) {
1034
1035                         /* handle tls conf */
1036                         if (!ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1037                                 continue;
1038                         }
1039
1040                         if (!strcasecmp(v->name, "enabled")) {
1041                                 enabled = ast_true(v->value);
1042                         } else if (!strcasecmp(v->name, "enablestatic")) {
1043                                 newenablestatic = ast_true(v->value);
1044                         } else if (!strcasecmp(v->name, "bindport")) {
1045                                 ast_sockaddr_set_port(&http_desc.local_address,
1046                                                       atoi(v->value));
1047                         } else if (!strcasecmp(v->name, "bindaddr")) {
1048                                 if ((hp = ast_gethostbyname(v->value, &ahp))) {
1049                                         ast_sockaddr_to_sin(&http_desc.local_address,
1050                                                             &tmp);
1051                                         memcpy(&tmp.sin_addr, hp->h_addr, sizeof(tmp.sin_addr));
1052                                         ast_sockaddr_from_sin(&http_desc.local_address,
1053                                                               &tmp);
1054                                 } else {
1055                                         ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
1056                                 }
1057                         } else if (!strcasecmp(v->name, "prefix")) {
1058                                 if (!ast_strlen_zero(v->value)) {
1059                                         newprefix[0] = '/';
1060                                         ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1061                                 } else {
1062                                         newprefix[0] = '\0';
1063                                 }
1064                         } else if (!strcasecmp(v->name, "redirect")) {
1065                                 add_redirect(v->value);
1066                         } else {
1067                                 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1068                         }
1069                 }
1070
1071                 ast_config_destroy(cfg);
1072         }
1073         /* if the https addres has not been set, default is the same as non secure http */
1074         ast_sockaddr_to_sin(&http_desc.local_address, &tmp);
1075         ast_sockaddr_to_sin(&https_desc.local_address, &tmp2);
1076         if (!tmp2.sin_addr.s_addr) {
1077                 tmp2.sin_addr = tmp.sin_addr;
1078                 ast_sockaddr_from_sin(&https_desc.local_address, &tmp2);
1079         }
1080         if (!enabled) {
1081                 ast_sockaddr_setnull(&http_desc.local_address);
1082                 ast_sockaddr_setnull(&https_desc.local_address);
1083         }
1084         if (strcmp(prefix, newprefix)) {
1085                 ast_copy_string(prefix, newprefix, sizeof(prefix));
1086         }
1087         enablestatic = newenablestatic;
1088         ast_tcptls_server_start(&http_desc);
1089         if (ast_ssl_setup(https_desc.tls_cfg)) {
1090                 ast_tcptls_server_start(&https_desc);
1091         }
1092
1093         return 0;
1094 }
1095
1096 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1097 {
1098         struct ast_http_uri *urih;
1099         struct http_uri_redirect *redirect;
1100         struct sockaddr_in tmp;
1101
1102         switch (cmd) {
1103         case CLI_INIT:
1104                 e->command = "http show status";
1105                 e->usage =
1106                         "Usage: http show status\n"
1107                         "       Lists status of internal HTTP engine\n";
1108                 return NULL;
1109         case CLI_GENERATE:
1110                 return NULL;
1111         }
1112
1113         if (a->argc != 3) {
1114                 return CLI_SHOWUSAGE;
1115         }
1116         ast_cli(a->fd, "HTTP Server Status:\n");
1117         ast_cli(a->fd, "Prefix: %s\n", prefix);
1118         ast_sockaddr_to_sin(&http_desc.old_address, &tmp);
1119         if (!tmp.sin_family) {
1120                 ast_cli(a->fd, "Server Disabled\n\n");
1121         } else {
1122                 ast_cli(a->fd, "Server Enabled and Bound to %s:%d\n\n",
1123                         ast_inet_ntoa(tmp.sin_addr), ntohs(tmp.sin_port));
1124                 if (http_tls_cfg.enabled) {
1125                         ast_sockaddr_to_sin(&https_desc.old_address, &tmp);
1126                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s:%d\n\n",
1127                                 ast_inet_ntoa(tmp.sin_addr),
1128                                 ntohs(tmp.sin_port));
1129                 }
1130         }
1131
1132         ast_cli(a->fd, "Enabled URI's:\n");
1133         AST_RWLIST_RDLOCK(&uris);
1134         if (AST_RWLIST_EMPTY(&uris)) {
1135                 ast_cli(a->fd, "None.\n");
1136         } else {
1137                 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1138                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1139         }
1140         AST_RWLIST_UNLOCK(&uris);
1141
1142         ast_cli(a->fd, "\nEnabled Redirects:\n");
1143         AST_RWLIST_RDLOCK(&uri_redirects);
1144         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1145                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
1146         if (AST_RWLIST_EMPTY(&uri_redirects)) {
1147                 ast_cli(a->fd, "  None.\n");
1148         }
1149         AST_RWLIST_UNLOCK(&uri_redirects);
1150
1151         return CLI_SUCCESS;
1152 }
1153
1154 int ast_http_reload(void)
1155 {
1156         return __ast_http_load(1);
1157 }
1158
1159 static struct ast_cli_entry cli_http[] = {
1160         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1161 };
1162
1163 int ast_http_init(void)
1164 {
1165         ast_http_uri_link(&statusuri);
1166         ast_http_uri_link(&staticuri);
1167         ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1168
1169         return __ast_http_load(0);
1170 }