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