e2982a73b5e0e94ffaeb82ddaf00511f09913acf
[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  * GMime http://spruce.sourceforge.net/gmime/
29  *
30  * \ref AstHTTP - AMI over the http protocol
31  */
32
33 /*! \li \ref http.c uses the configuration file \ref http.conf
34  * \addtogroup configuration_file
35  */
36
37 /*! \page http.conf http.conf
38  * \verbinclude http.conf.sample
39  */
40
41 /*** MODULEINFO
42         <support_level>core</support_level>
43  ***/
44
45 #include "asterisk.h"
46
47 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
48
49 #include <time.h>
50 #include <sys/time.h>
51 #include <sys/stat.h>
52 #include <sys/signal.h>
53 #include <fcntl.h>
54
55 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
56 #include "asterisk/cli.h"
57 #include "asterisk/tcptls.h"
58 #include "asterisk/http.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/strings.h"
61 #include "asterisk/config.h"
62 #include "asterisk/stringfields.h"
63 #include "asterisk/ast_version.h"
64 #include "asterisk/manager.h"
65 #include "asterisk/_private.h"
66 #include "asterisk/astobj2.h"
67 #include "asterisk/netsock2.h"
68 #include "asterisk/json.h"
69
70 #define MAX_PREFIX 80
71 #define DEFAULT_PORT 8088
72 #define DEFAULT_TLS_PORT 8089
73 #define DEFAULT_SESSION_LIMIT 100
74
75 /* See http.h for more information about the SSL implementation */
76 #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
77 #define DO_SSL  /* comment in/out if you want to support ssl */
78 #endif
79
80 static int session_limit = DEFAULT_SESSION_LIMIT;
81 static int session_count = 0;
82
83 static struct ast_tls_config http_tls_cfg;
84
85 static void *httpd_helper_thread(void *arg);
86
87 /*!
88  * we have up to two accepting threads, one for http, one for https
89  */
90 static struct ast_tcptls_session_args http_desc = {
91         .accept_fd = -1,
92         .master = AST_PTHREADT_NULL,
93         .tls_cfg = NULL,
94         .poll_timeout = -1,
95         .name = "http server",
96         .accept_fn = ast_tcptls_server_root,
97         .worker_fn = httpd_helper_thread,
98 };
99
100 static struct ast_tcptls_session_args https_desc = {
101         .accept_fd = -1,
102         .master = AST_PTHREADT_NULL,
103         .tls_cfg = &http_tls_cfg,
104         .poll_timeout = -1,
105         .name = "https server",
106         .accept_fn = ast_tcptls_server_root,
107         .worker_fn = httpd_helper_thread,
108 };
109
110 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri);      /*!< list of supported handlers */
111
112 /* all valid URIs must be prepended by the string in prefix. */
113 static char prefix[MAX_PREFIX];
114 static int enablestatic;
115
116 /*! \brief Limit the kinds of files we're willing to serve up */
117 static struct {
118         const char *ext;
119         const char *mtype;
120 } mimetypes[] = {
121         { "png", "image/png" },
122         { "xml", "text/xml" },
123         { "jpg", "image/jpeg" },
124         { "js", "application/x-javascript" },
125         { "wav", "audio/x-wav" },
126         { "mp3", "audio/mpeg" },
127         { "svg", "image/svg+xml" },
128         { "svgz", "image/svg+xml" },
129         { "gif", "image/gif" },
130         { "html", "text/html" },
131         { "htm", "text/html" },
132         { "css", "text/css" },
133         { "cnf", "text/plain" },
134         { "cfg", "text/plain" },
135         { "bin", "application/octet-stream" },
136         { "sbn", "application/octet-stream" },
137         { "ld", "application/octet-stream" },
138 };
139
140 struct http_uri_redirect {
141         AST_LIST_ENTRY(http_uri_redirect) entry;
142         char *dest;
143         char target[0];
144 };
145
146 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
147
148 static const struct ast_cfhttp_methods_text {
149         enum ast_http_method method;
150         const char *text;
151 } ast_http_methods_text[] = {
152         { AST_HTTP_UNKNOWN,     "UNKNOWN" },
153         { AST_HTTP_GET,         "GET" },
154         { AST_HTTP_POST,        "POST" },
155         { AST_HTTP_HEAD,        "HEAD" },
156         { AST_HTTP_PUT,         "PUT" },
157         { AST_HTTP_DELETE,      "DELETE" },
158         { AST_HTTP_OPTIONS,     "OPTIONS" },
159 };
160
161 const char *ast_get_http_method(enum ast_http_method method)
162 {
163         int x;
164
165         for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
166                 if (ast_http_methods_text[x].method == method) {
167                         return ast_http_methods_text[x].text;
168                 }
169         }
170
171         return NULL;
172 }
173
174 const char *ast_http_ftype2mtype(const char *ftype)
175 {
176         int x;
177
178         if (ftype) {
179                 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
180                         if (!strcasecmp(ftype, mimetypes[x].ext)) {
181                                 return mimetypes[x].mtype;
182                         }
183                 }
184         }
185         return NULL;
186 }
187
188 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
189 {
190         uint32_t mngid = 0;
191         struct ast_variable *v, *cookies;
192
193         cookies = ast_http_get_cookies(headers);
194         for (v = cookies; v; v = v->next) {
195                 if (!strcasecmp(v->name, "mansession_id")) {
196                         sscanf(v->value, "%30x", &mngid);
197                         break;
198                 }
199         }
200         ast_variables_destroy(cookies);
201         return mngid;
202 }
203
204 void ast_http_prefix(char *buf, int len)
205 {
206         if (buf) {
207                 ast_copy_string(buf, prefix, len);
208         }
209 }
210
211 static int static_callback(struct ast_tcptls_session_instance *ser,
212         const struct ast_http_uri *urih, const char *uri,
213         enum ast_http_method method, struct ast_variable *get_vars,
214         struct ast_variable *headers)
215 {
216         char *path;
217         const char *ftype;
218         const char *mtype;
219         char wkspace[80];
220         struct stat st;
221         int len;
222         int fd;
223         struct ast_str *http_header;
224         struct timeval tv;
225         struct ast_tm tm;
226         char timebuf[80], etag[23];
227         struct ast_variable *v;
228         int not_modified = 0;
229
230         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
231                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
232                 return -1;
233         }
234
235         /* Yuck.  I'm not really sold on this, but if you don't deliver static content it makes your configuration
236            substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
237         if (!enablestatic || ast_strlen_zero(uri)) {
238                 goto out403;
239         }
240
241         /* Disallow any funny filenames at all (checking first character only??) */
242         if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
243                 goto out403;
244         }
245
246         if (strstr(uri, "/..")) {
247                 goto out403;
248         }
249
250         if ((ftype = strrchr(uri, '.'))) {
251                 ftype++;
252         }
253
254         if (!(mtype = ast_http_ftype2mtype(ftype))) {
255                 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
256                 mtype = wkspace;
257         }
258
259         /* Cap maximum length */
260         if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
261                 goto out403;
262         }
263
264         path = ast_alloca(len);
265         sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
266         if (stat(path, &st)) {
267                 goto out404;
268         }
269
270         if (S_ISDIR(st.st_mode)) {
271                 goto out404;
272         }
273
274         if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
275                 goto out403;
276         }
277
278         fd = open(path, O_RDONLY);
279         if (fd < 0) {
280                 goto out403;
281         }
282
283         /* make "Etag:" http header value */
284         snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
285
286         /* make "Last-Modified:" http header value */
287         tv.tv_sec = st.st_mtime;
288         tv.tv_usec = 0;
289         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
290
291         /* check received "If-None-Match" request header and Etag value for file */
292         for (v = headers; v; v = v->next) {
293                 if (!strcasecmp(v->name, "If-None-Match")) {
294                         if (!strcasecmp(v->value, etag)) {
295                                 not_modified = 1;
296                         }
297                         break;
298                 }
299         }
300
301         if ( (http_header = ast_str_create(255)) == NULL) {
302                 close(fd);
303                 return -1;
304         }
305
306         ast_str_set(&http_header, 0, "Content-type: %s\r\n"
307                 "ETag: %s\r\n"
308                 "Last-Modified: %s\r\n",
309                 mtype,
310                 etag,
311                 timebuf);
312
313         /* ast_http_send() frees http_header, so we don't need to do it before returning */
314         if (not_modified) {
315                 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
316         } else {
317                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
318         }
319         close(fd);
320         return 0;
321
322 out404:
323         ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
324         return -1;
325
326 out403:
327         ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
328         return -1;
329 }
330
331 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
332         const struct ast_http_uri *urih, const char *uri,
333         enum ast_http_method method, struct ast_variable *get_vars,
334         struct ast_variable *headers)
335 {
336         struct ast_str *out;
337         struct ast_variable *v, *cookies = NULL;
338
339         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
340                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
341                 return -1;
342         }
343
344         if ( (out = ast_str_create(512)) == NULL) {
345                 return -1;
346         }
347
348         ast_str_append(&out, 0,
349                 "<title>Asterisk HTTP Status</title>\r\n"
350                 "<body bgcolor=\"#ffffff\">\r\n"
351                 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
352                 "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
353
354         ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
355         ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
356                        ast_sockaddr_stringify_addr(&http_desc.old_address));
357         ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
358                        ast_sockaddr_stringify_port(&http_desc.old_address));
359         if (http_tls_cfg.enabled) {
360                 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
361                                ast_sockaddr_stringify_port(&https_desc.old_address));
362         }
363         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
364         for (v = get_vars; v; v = v->next) {
365                 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
366         }
367         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
368
369         cookies = ast_http_get_cookies(headers);
370         for (v = cookies; v; v = v->next) {
371                 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
372         }
373         ast_variables_destroy(cookies);
374
375         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");
376         ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
377         return 0;
378 }
379
380 static struct ast_http_uri statusuri = {
381         .callback = httpstatus_callback,
382         .description = "Asterisk HTTP General Status",
383         .uri = "httpstatus",
384         .has_subtree = 0,
385         .data = NULL,
386         .key = __FILE__,
387 };
388
389 static struct ast_http_uri staticuri = {
390         .callback = static_callback,
391         .description = "Asterisk HTTP Static Delivery",
392         .uri = "static",
393         .has_subtree = 1,
394         .data = NULL,
395         .key= __FILE__,
396 };
397
398
399 /* send http/1.1 response */
400 /* free content variable and close socket*/
401 void ast_http_send(struct ast_tcptls_session_instance *ser,
402         enum ast_http_method method, int status_code, const char *status_title,
403         struct ast_str *http_header, struct ast_str *out, const int fd,
404         unsigned int static_content)
405 {
406         struct timeval now = ast_tvnow();
407         struct ast_tm tm;
408         char timebuf[80];
409         int content_length = 0;
410
411         if (!ser || 0 == ser->f) {
412                 return;
413         }
414
415         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
416
417         /* calc content length */
418         if (out) {
419                 content_length += strlen(ast_str_buffer(out));
420         }
421
422         if (fd) {
423                 content_length += lseek(fd, 0, SEEK_END);
424                 lseek(fd, 0, SEEK_SET);
425         }
426
427         /* send http header */
428         fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
429                 "Server: Asterisk/%s\r\n"
430                 "Date: %s\r\n"
431                 "Connection: close\r\n"
432                 "%s"
433                 "Content-Length: %d\r\n"
434                 "%s"
435                 "\r\n",
436                 status_code, status_title ? status_title : "OK",
437                 ast_get_version(),
438                 timebuf,
439                 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
440                 content_length,
441                 http_header ? ast_str_buffer(http_header) : ""
442                 );
443
444         /* send content */
445         if (method != AST_HTTP_HEAD || status_code >= 400) {
446                 if (out) {
447                         fprintf(ser->f, "%s", ast_str_buffer(out));
448                 }
449
450                 if (fd) {
451                         char buf[256];
452                         int len;
453                         while ((len = read(fd, buf, sizeof(buf))) > 0) {
454                                 if (fwrite(buf, len, 1, ser->f) != 1) {
455                                         ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
456                                         break;
457                                 }
458                         }
459                 }
460         }
461
462         if (http_header) {
463                 ast_free(http_header);
464         }
465         if (out) {
466                 ast_free(out);
467         }
468
469         fclose(ser->f);
470         ser->f = 0;
471         return;
472 }
473
474 /* Send http "401 Unauthorized" responce and close socket*/
475 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
476         const unsigned long nonce, const unsigned long opaque, int stale,
477         const char *text)
478 {
479         struct ast_str *http_headers = ast_str_create(128);
480         struct ast_str *out = ast_str_create(512);
481
482         if (!http_headers || !out) {
483                 ast_free(http_headers);
484                 ast_free(out);
485                 return;
486         }
487
488         ast_str_set(&http_headers, 0,
489                 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
490                 "Content-type: text/html\r\n",
491                 realm ? realm : "Asterisk",
492                 nonce,
493                 opaque,
494                 stale ? ", stale=true" : "");
495
496         ast_str_set(&out, 0,
497                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
498                 "<html><head>\r\n"
499                 "<title>401 Unauthorized</title>\r\n"
500                 "</head><body>\r\n"
501                 "<h1>401 Unauthorized</h1>\r\n"
502                 "<p>%s</p>\r\n"
503                 "<hr />\r\n"
504                 "<address>Asterisk Server</address>\r\n"
505                 "</body></html>\r\n",
506                 text ? text : "");
507
508         ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
509         return;
510 }
511
512 /* send http error response and close socket*/
513 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
514 {
515         struct ast_str *http_headers = ast_str_create(40);
516         struct ast_str *out = ast_str_create(256);
517
518         if (!http_headers || !out) {
519                 ast_free(http_headers);
520                 ast_free(out);
521                 return;
522         }
523
524         ast_str_set(&http_headers, 0, "Content-type: text/html\r\n");
525
526         ast_str_set(&out, 0,
527                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
528                 "<html><head>\r\n"
529                 "<title>%d %s</title>\r\n"
530                 "</head><body>\r\n"
531                 "<h1>%s</h1>\r\n"
532                 "<p>%s</p>\r\n"
533                 "<hr />\r\n"
534                 "<address>Asterisk Server</address>\r\n"
535                 "</body></html>\r\n",
536                         status_code, status_title, status_title, text);
537
538         ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
539         return;
540 }
541
542 /*! \brief
543  * Link the new uri into the list.
544  *
545  * They are sorted by length of
546  * the string, not alphabetically. Duplicate entries are not replaced,
547  * but the insertion order (using <= and not just <) makes sure that
548  * more recent insertions hide older ones.
549  * On a lookup, we just scan the list and stop at the first matching entry.
550  */
551 int ast_http_uri_link(struct ast_http_uri *urih)
552 {
553         struct ast_http_uri *uri;
554         int len = strlen(urih->uri);
555
556         AST_RWLIST_WRLOCK(&uris);
557
558         if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
559                 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
560                 AST_RWLIST_UNLOCK(&uris);
561                 return 0;
562         }
563
564         AST_RWLIST_TRAVERSE(&uris, uri, entry) {
565                 if (AST_RWLIST_NEXT(uri, entry) &&
566                         strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
567                         AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
568                         AST_RWLIST_UNLOCK(&uris);
569
570                         return 0;
571                 }
572         }
573
574         AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
575
576         AST_RWLIST_UNLOCK(&uris);
577
578         return 0;
579 }
580
581 void ast_http_uri_unlink(struct ast_http_uri *urih)
582 {
583         AST_RWLIST_WRLOCK(&uris);
584         AST_RWLIST_REMOVE(&uris, urih, entry);
585         AST_RWLIST_UNLOCK(&uris);
586 }
587
588 void ast_http_uri_unlink_all_with_key(const char *key)
589 {
590         struct ast_http_uri *urih;
591         AST_RWLIST_WRLOCK(&uris);
592         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
593                 if (!strcmp(urih->key, key)) {
594                         AST_RWLIST_REMOVE_CURRENT(entry);
595                         if (urih->dmallocd) {
596                                 ast_free(urih->data);
597                         }
598                         if (urih->mallocd) {
599                                 ast_free(urih);
600                         }
601                 }
602         }
603         AST_RWLIST_TRAVERSE_SAFE_END;
604         AST_RWLIST_UNLOCK(&uris);
605 }
606
607 #define MAX_POST_CONTENT 1025
608
609 /*!
610  * \brief Retrieves the header with the given field name.
611  *
612  * \param headers Headers to search.
613  * \param field_name Name of the header to find.
614  * \return Associated header value.
615  * \return \c NULL if header is not present.
616  */
617 static const char *get_header(struct ast_variable *headers,
618         const char *field_name)
619 {
620         struct ast_variable *v;
621
622         for (v = headers; v; v = v->next) {
623                 if (!strcasecmp(v->name, field_name)) {
624                         return v->value;
625                 }
626         }
627         return NULL;
628 }
629
630 /*!
631  * \brief Retrieves the content type specified in the "Content-Type" header.
632  *
633  * This function only returns the "type/subtype" and any trailing parameter is
634  * not included.
635  *
636  * \note the return value is an allocated string that needs to be freed.
637  *
638  * \retval the content type/subtype or NULL if the header is not found.
639  */
640 static char *get_content_type(struct ast_variable *headers)
641 {
642         const char *content_type = get_header(headers, "Content-Type");
643         const char *param;
644         size_t size;
645
646         if (!content_type) {
647                 return NULL;
648         }
649
650         param = strchr(content_type, ';');
651         size = param ? param - content_type : strlen(content_type);
652
653         return ast_strndup(content_type, size);
654 }
655
656 /*!
657  * \brief Returns the value of the Content-Length header.
658  *
659  * \param headers HTTP headers.
660  * \return Value of the Content-Length header.
661  * \return 0 if header is not present, or is invalid.
662  */
663 static int get_content_length(struct ast_variable *headers)
664 {
665         const char *content_length = get_header(headers, "Content-Length");
666
667         if (!content_length) {
668                 /* Missing content length; assume zero */
669                 return 0;
670         }
671
672         /* atoi() will return 0 for invalid inputs, which is good enough for
673          * the HTTP parsing. */
674         return atoi(content_length);
675 }
676
677 /*!
678  * \brief Returns the value of the Transfer-Encoding header.
679  *
680  * \param headers HTTP headers.
681  * \return Value of the Transfer-Encoding header.
682  * \return 0 if header is not present, or is invalid.
683  */
684 static const char *get_transfer_encoding(struct ast_variable *headers)
685 {
686         return get_header(headers, "Transfer-Encoding");
687 }
688
689 /*!
690  * \brief decode chunked mode hexadecimal value
691  *
692  * \param s string to decode
693  * \param len length of string
694  * \return integer value or -1 for decode error
695  */
696 static int chunked_atoh(const char *s, int len)
697 {
698         int value = 0;
699         char c;
700
701         if (*s < '0') {
702                 /* zero value must be 0\n not just \n */
703                 return -1;
704         }
705
706         while (len--)
707         {
708                 if (*s == '\x0D') {
709                         return value;
710                 }
711                 value <<= 4;
712                 c = *s++;
713                 if (c >= '0' && c <= '9') {
714                         value += c - '0';
715                         continue;
716                 }
717                 if (c >= 'a' && c <= 'f') {
718                         value += 10 + c - 'a';
719                         continue;
720                 }
721                 if (c >= 'A' && c <= 'F') {
722                         value += 10 + c - 'A';
723                         continue;
724                 }
725                 /* invalid character */
726                 return -1;
727         }
728         /* end of string */
729         return -1;
730 }
731
732 /*!
733  * \brief Returns the contents (body) of the HTTP request
734  *
735  * \param return_length ptr to int that returns content length
736  * \param aser HTTP TCP/TLS session object
737  * \param headers List of HTTP headers
738  * \return ptr to content (zero terminated) or NULL on failure
739  * \note Since returned ptr is malloc'd, it should be free'd by caller
740  */
741 static char *ast_http_get_contents(int *return_length,
742         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
743 {
744         const char *transfer_encoding;
745         int res;
746         int content_length = 0;
747         int chunk_length;
748         char chunk_header[8];
749         int bufsize = 250;
750         char *buf;
751
752         transfer_encoding = get_transfer_encoding(headers);
753
754         if (ast_strlen_zero(transfer_encoding) ||
755                 strcasecmp(transfer_encoding, "chunked") != 0) {
756                 /* handle regular non-chunked content */
757                 content_length = get_content_length(headers);
758                 if (content_length <= 0) {
759                         /* no content - not an error */
760                         return NULL;
761                 }
762                 if (content_length > MAX_POST_CONTENT - 1) {
763                         ast_log(LOG_WARNING,
764                                 "Excessively long HTTP content. (%d > %d)\n",
765                                 content_length, MAX_POST_CONTENT);
766                         errno = EFBIG;
767                         return NULL;
768                 }
769                 buf = ast_malloc(content_length + 1);
770                 if (!buf) {
771                         /* Malloc sets ENOMEM */
772                         return NULL;
773                 }
774                 res = fread(buf, 1, content_length, ser->f);
775                 if (res < content_length) {
776                         /* Error, distinguishable by ferror() or feof(), but neither
777                          * is good. Treat either one as I/O error */
778                         ast_log(LOG_WARNING, "Short HTTP request body (%d < %d)\n",
779                                 res, content_length);
780                         errno = EIO;
781                         ast_free(buf);
782                         return NULL;
783                 }
784                 buf[content_length] = 0;
785                 *return_length = content_length;
786                 return buf;
787         }
788
789         /* pre-allocate buffer */
790         buf = ast_malloc(bufsize);
791         if (!buf) {
792                 return NULL;
793         }
794
795         /* handled chunked content */
796         do {
797                 /* get the line of hexadecimal giving chunk size */
798                 if (!fgets(chunk_header, sizeof(chunk_header), ser->f)) {
799                         ast_log(LOG_WARNING,
800                                 "Short HTTP read of chunked header\n");
801                         errno = EIO;
802                         ast_free(buf);
803                         return NULL;
804                 }
805                 chunk_length = chunked_atoh(chunk_header, sizeof(chunk_header));
806                 if (chunk_length < 0) {
807                         ast_log(LOG_WARNING, "Invalid HTTP chunk size\n");
808                         errno = EIO;
809                         ast_free(buf);
810                         return NULL;
811                 }
812                 if (content_length + chunk_length > MAX_POST_CONTENT - 1) {
813                         ast_log(LOG_WARNING,
814                                 "Excessively long HTTP chunk. (%d + %d > %d)\n",
815                                 content_length, chunk_length, MAX_POST_CONTENT);
816                         errno = EFBIG;
817                         ast_free(buf);
818                         return NULL;
819                 }
820
821                 /* insure buffer is large enough +1 */
822                 if (content_length + chunk_length >= bufsize)
823                 {
824                         bufsize *= 2;
825                         buf = ast_realloc(buf, bufsize);
826                         if (!buf) {
827                                 return NULL;
828                         }
829                 }
830
831                 /* read the chunk */
832                 res = fread(buf + content_length, 1, chunk_length, ser->f);
833                 if (res < chunk_length) {
834                         ast_log(LOG_WARNING, "Short HTTP chunk read (%d < %d)\n",
835                                 res, chunk_length);
836                         errno = EIO;
837                         ast_free(buf);
838                         return NULL;
839                 }
840                 content_length += chunk_length;
841
842                 /* insure the next 2 bytes are CRLF */
843                 res = fread(chunk_header, 1, 2, ser->f);
844                 if (res < 2) {
845                         ast_log(LOG_WARNING,
846                                 "Short HTTP chunk sync read (%d < 2)\n", res);
847                         errno = EIO;
848                         ast_free(buf);
849                         return NULL;
850                 }
851                 if (chunk_header[0] != 0x0D || chunk_header[1] != 0x0A) {
852                         ast_log(LOG_WARNING,
853                                 "Post HTTP chunk sync bytes wrong (%d, %d)\n",
854                                 chunk_header[0], chunk_header[1]);
855                         errno = EIO;
856                         ast_free(buf);
857                         return NULL;
858                 }
859         } while (chunk_length);
860
861         buf[content_length] = 0;
862         *return_length = content_length;
863         return buf;
864 }
865
866 struct ast_json *ast_http_get_json(
867         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
868 {
869         int content_length = 0;
870         struct ast_json *body;
871         RAII_VAR(char *, buf, NULL, ast_free);
872         RAII_VAR(char *, type, get_content_type(headers), ast_free);
873
874         /* Use errno to distinguish errors from no body */
875         errno = 0;
876
877         if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
878                 /* Content type is not JSON */
879                 return NULL;
880         }
881
882         buf = ast_http_get_contents(&content_length, ser, headers);
883         if (buf == NULL) {
884                 /* errno already set */
885                 return NULL;
886         }
887
888         if (!content_length) {
889                 /* it is not an error to have zero content */
890                 return NULL;
891         }
892
893         body = ast_json_load_buf(buf, content_length, NULL);
894         if (body == NULL) {
895                 /* Failed to parse JSON; treat as an I/O error */
896                 errno = EIO;
897                 return NULL;
898         }
899
900         return body;
901 }
902
903 /*
904  * get post variables from client Request Entity-Body, if content type is
905  * application/x-www-form-urlencoded
906  */
907 struct ast_variable *ast_http_get_post_vars(
908         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
909 {
910         int content_length = 0;
911         struct ast_variable *v, *post_vars=NULL, *prev = NULL;
912         char *var, *val;
913         RAII_VAR(char *, buf, NULL, ast_free_ptr);
914         RAII_VAR(char *, type, get_content_type(headers), ast_free);
915
916         /* Use errno to distinguish errors from no params */
917         errno = 0;
918
919         if (ast_strlen_zero(type) ||
920             strcasecmp(type, "application/x-www-form-urlencoded")) {
921                 /* Content type is not form data */
922                 return NULL;
923         }
924
925         buf = ast_http_get_contents(&content_length, ser, headers);
926         if (buf == NULL) {
927                 return NULL;
928         }
929
930         while ((val = strsep(&buf, "&"))) {
931                 var = strsep(&val, "=");
932                 if (val) {
933                         ast_uri_decode(val, ast_uri_http_legacy);
934                 } else  {
935                         val = "";
936                 }
937                 ast_uri_decode(var, ast_uri_http_legacy);
938                 if ((v = ast_variable_new(var, val, ""))) {
939                         if (post_vars) {
940                                 prev->next = v;
941                         } else {
942                                 post_vars = v;
943                         }
944                         prev = v;
945                 }
946         }
947
948         return post_vars;
949 }
950
951 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
952         enum ast_http_method method, struct ast_variable *headers)
953 {
954         char *c;
955         int res = -1;
956         char *params = uri;
957         struct ast_http_uri *urih = NULL;
958         int l;
959         struct ast_variable *get_vars = NULL, *v, *prev = NULL;
960         struct http_uri_redirect *redirect;
961
962         ast_debug(2, "HTTP Request URI is %s \n", uri);
963
964         strsep(&params, "?");
965         /* Extract arguments from the request and store them in variables. */
966         if (params) {
967                 char *var, *val;
968
969                 while ((val = strsep(&params, "&"))) {
970                         var = strsep(&val, "=");
971                         if (val) {
972                                 ast_uri_decode(val, ast_uri_http_legacy);
973                         } else  {
974                                 val = "";
975                         }
976                         ast_uri_decode(var, ast_uri_http_legacy);
977                         if ((v = ast_variable_new(var, val, ""))) {
978                                 if (get_vars) {
979                                         prev->next = v;
980                                 } else {
981                                         get_vars = v;
982                                 }
983                                 prev = v;
984                         }
985                 }
986         }
987
988         AST_RWLIST_RDLOCK(&uri_redirects);
989         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
990                 if (!strcasecmp(uri, redirect->target)) {
991                         struct ast_str *http_header = ast_str_create(128);
992                         ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
993                         ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
994
995                         break;
996                 }
997         }
998         AST_RWLIST_UNLOCK(&uri_redirects);
999         if (redirect) {
1000                 goto cleanup;
1001         }
1002
1003         /* We want requests to start with the (optional) prefix and '/' */
1004         l = strlen(prefix);
1005         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
1006                 uri += l + 1;
1007                 /* scan registered uris to see if we match one. */
1008                 AST_RWLIST_RDLOCK(&uris);
1009                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
1010                         l = strlen(urih->uri);
1011                         c = uri + l;    /* candidate */
1012                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
1013                         if (strncasecmp(urih->uri, uri, l) /* no match */
1014                             || (*c && *c != '/')) { /* substring */
1015                                 continue;
1016                         }
1017                         if (*c == '/') {
1018                                 c++;
1019                         }
1020                         if (!*c || urih->has_subtree) {
1021                                 uri = c;
1022                                 break;
1023                         }
1024                 }
1025                 AST_RWLIST_UNLOCK(&uris);
1026         }
1027         if (urih) {
1028                 ast_debug(1, "Match made with [%s]\n", urih->uri);
1029                 if (!urih->no_decode_uri) {
1030                         ast_uri_decode(uri, ast_uri_http_legacy);
1031                 }
1032                 res = urih->callback(ser, urih, uri, method, get_vars, headers);
1033         } else {
1034                 ast_debug(1, "Requested URI [%s] has no handler\n", uri);
1035                 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
1036         }
1037
1038 cleanup:
1039         ast_variables_destroy(get_vars);
1040         return res;
1041 }
1042
1043 #ifdef DO_SSL
1044 #if defined(HAVE_FUNOPEN)
1045 #define HOOK_T int
1046 #define LEN_T int
1047 #else
1048 #define HOOK_T ssize_t
1049 #define LEN_T size_t
1050 #endif
1051
1052 /*!
1053  * replacement read/write functions for SSL support.
1054  * We use wrappers rather than SSL_read/SSL_write directly so
1055  * we can put in some debugging.
1056  */
1057 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
1058 {
1059         int i = SSL_read(cookie, buf, len-1);
1060 #if 0
1061         if (i >= 0)
1062                 buf[i] = '\0';
1063         ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
1064 #endif
1065         return i;
1066 }
1067
1068 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
1069 {
1070 #if 0
1071         char *s = ast_alloca(len+1);
1072         strncpy(s, buf, len);
1073         s[len] = '\0';
1074         ast_verbose("ssl write size %d <%s>\n", (int)len, s);
1075 #endif
1076         return SSL_write(cookie, buf, len);
1077 }
1078
1079 static int ssl_close(void *cookie)
1080 {
1081         close(SSL_get_fd(cookie));
1082         SSL_shutdown(cookie);
1083         SSL_free(cookie);
1084         return 0;
1085 }*/
1086 #endif  /* DO_SSL */
1087
1088 static struct ast_variable *parse_cookies(const char *cookies)
1089 {
1090         char *parse = ast_strdupa(cookies);
1091         char *cur;
1092         struct ast_variable *vars = NULL, *var;
1093
1094         while ((cur = strsep(&parse, ";"))) {
1095                 char *name, *val;
1096
1097                 name = val = cur;
1098                 strsep(&val, "=");
1099
1100                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1101                         continue;
1102                 }
1103
1104                 name = ast_strip(name);
1105                 val = ast_strip_quoted(val, "\"", "\"");
1106
1107                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1108                         continue;
1109                 }
1110
1111                 ast_debug(1, "HTTP Cookie, Name: '%s'  Value: '%s'\n", name, val);
1112
1113                 var = ast_variable_new(name, val, __FILE__);
1114                 var->next = vars;
1115                 vars = var;
1116         }
1117
1118         return vars;
1119 }
1120
1121 /* get cookie from Request headers */
1122 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
1123 {
1124         struct ast_variable *v, *cookies = NULL;
1125
1126         for (v = headers; v; v = v->next) {
1127                 if (!strcasecmp(v->name, "Cookie")) {
1128                         ast_variables_destroy(cookies);
1129                         cookies = parse_cookies(v->value);
1130                 }
1131         }
1132         return cookies;
1133 }
1134
1135 static struct ast_http_auth *auth_create(const char *userid,
1136         const char *password)
1137 {
1138         RAII_VAR(struct ast_http_auth *, auth, NULL, ao2_cleanup);
1139         size_t userid_len;
1140         size_t password_len;
1141
1142         if (!userid || !password) {
1143                 ast_log(LOG_ERROR, "Invalid userid/password\n");
1144                 return NULL;
1145         }
1146
1147         userid_len = strlen(userid) + 1;
1148         password_len = strlen(password) + 1;
1149
1150         /* Allocate enough room to store everything in one memory block */
1151         auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
1152         if (!auth) {
1153                 return NULL;
1154         }
1155
1156         /* Put the userid right after the struct */
1157         auth->userid = (char *)(auth + 1);
1158         strcpy(auth->userid, userid);
1159
1160         /* Put the password right after the userid */
1161         auth->password = auth->userid + userid_len;
1162         strcpy(auth->password, password);
1163
1164         ao2_ref(auth, +1);
1165         return auth;
1166 }
1167
1168 #define BASIC_PREFIX "Basic "
1169 #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
1170
1171 struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
1172 {
1173         struct ast_variable *v;
1174
1175         for (v = headers; v; v = v->next) {
1176                 const char *base64;
1177                 char decoded[256] = {};
1178                 char *username;
1179                 char *password;
1180 #ifdef AST_DEVMODE
1181                 int cnt;
1182 #endif /* AST_DEVMODE */
1183
1184                 if (strcasecmp("Authorization", v->name) != 0) {
1185                         continue;
1186                 }
1187
1188                 if (!ast_begins_with(v->value, BASIC_PREFIX)) {
1189                         ast_log(LOG_DEBUG,
1190                                 "Unsupported Authorization scheme\n");
1191                         continue;
1192                 }
1193
1194                 /* Basic auth header parsing. RFC 2617, section 2.
1195                  *   credentials = "Basic" basic-credentials
1196                  *   basic-credentials = base64-user-pass
1197                  *   base64-user-pass  = <base64 encoding of user-pass,
1198                  *                        except not limited to 76 char/line>
1199                  *   user-pass   = userid ":" password
1200                  */
1201
1202                 base64 = v->value + BASIC_LEN;
1203
1204                 /* This will truncate "userid:password" lines to
1205                  * sizeof(decoded). The array is long enough that this shouldn't
1206                  * be a problem */
1207 #ifdef AST_DEVMODE
1208                 cnt =
1209 #endif /* AST_DEVMODE */
1210                 ast_base64decode((unsigned char*)decoded, base64,
1211                         sizeof(decoded) - 1);
1212                 ast_assert(cnt < sizeof(decoded));
1213
1214                 /* Split the string at the colon */
1215                 password = decoded;
1216                 username = strsep(&password, ":");
1217                 if (!password) {
1218                         ast_log(LOG_WARNING, "Invalid Authorization header\n");
1219                         return NULL;
1220                 }
1221
1222                 return auth_create(username, password);
1223         }
1224
1225         return NULL;
1226 }
1227
1228 /*! Limit the number of request headers in case the sender is being ridiculous. */
1229 #define MAX_HTTP_REQUEST_HEADERS        100
1230
1231 static void *httpd_helper_thread(void *data)
1232 {
1233         char buf[4096];
1234         char header_line[4096];
1235         struct ast_tcptls_session_instance *ser = data;
1236         struct ast_variable *headers = NULL;
1237         struct ast_variable *tail = headers;
1238         char *uri, *method;
1239         enum ast_http_method http_method = AST_HTTP_UNKNOWN;
1240         const char *transfer_encoding;
1241         int remaining_headers;
1242
1243         if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
1244                 goto done;
1245         }
1246
1247         if (!fgets(buf, sizeof(buf), ser->f)) {
1248                 goto done;
1249         }
1250
1251         /* Get method */
1252         method = ast_skip_blanks(buf);
1253         uri = ast_skip_nonblanks(method);
1254         if (*uri) {
1255                 *uri++ = '\0';
1256         }
1257
1258         if (!strcasecmp(method,"GET")) {
1259                 http_method = AST_HTTP_GET;
1260         } else if (!strcasecmp(method,"POST")) {
1261                 http_method = AST_HTTP_POST;
1262         } else if (!strcasecmp(method,"HEAD")) {
1263                 http_method = AST_HTTP_HEAD;
1264         } else if (!strcasecmp(method,"PUT")) {
1265                 http_method = AST_HTTP_PUT;
1266         } else if (!strcasecmp(method,"DELETE")) {
1267                 http_method = AST_HTTP_DELETE;
1268         } else if (!strcasecmp(method,"OPTIONS")) {
1269                 http_method = AST_HTTP_OPTIONS;
1270         }
1271
1272         uri = ast_skip_blanks(uri);     /* Skip white space */
1273
1274         if (*uri) {                     /* terminate at the first blank */
1275                 char *c = ast_skip_nonblanks(uri);
1276
1277                 if (*c) {
1278                         *c = '\0';
1279                 }
1280         } else {
1281                 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
1282                 goto done;
1283         }
1284
1285         /* process "Request Headers" lines */
1286         remaining_headers = MAX_HTTP_REQUEST_HEADERS;
1287         while (fgets(header_line, sizeof(header_line), ser->f)) {
1288                 char *name, *value;
1289
1290                 /* Trim trailing characters */
1291                 ast_trim_blanks(header_line);
1292                 if (ast_strlen_zero(header_line)) {
1293                         break;
1294                 }
1295
1296                 value = header_line;
1297                 name = strsep(&value, ":");
1298                 if (!value) {
1299                         continue;
1300                 }
1301
1302                 value = ast_skip_blanks(value);
1303                 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1304                         continue;
1305                 }
1306
1307                 ast_trim_blanks(name);
1308
1309                 if (!remaining_headers--) {
1310                         /* Too many headers. */
1311                         ast_http_error(ser, 413, "Request Entity Too Large", "Too many headers");
1312                         goto done;
1313                 }
1314                 if (!headers) {
1315                         headers = ast_variable_new(name, value, __FILE__);
1316                         tail = headers;
1317                 } else {
1318                         tail->next = ast_variable_new(name, value, __FILE__);
1319                         tail = tail->next;
1320                 }
1321                 if (!tail) {
1322                         /*
1323                          * Variable allocation failure.
1324                          * Try to make some room.
1325                          */
1326                         ast_variables_destroy(headers);
1327                         headers = NULL;
1328
1329                         ast_http_error(ser, 500, "Server Error", "Out of memory");
1330                         goto done;
1331                 }
1332         }
1333
1334         transfer_encoding = get_transfer_encoding(headers);
1335         /* Transfer encoding defaults to identity */
1336         if (!transfer_encoding) {
1337                 transfer_encoding = "identity";
1338         }
1339
1340         /*
1341          * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
1342          * codings we don't understand.
1343          */
1344         if (strcasecmp(transfer_encoding, "identity") != 0 &&
1345                 strcasecmp(transfer_encoding, "chunked") != 0) {
1346                 /* Transfer encodings not supported */
1347                 ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
1348                 goto done;
1349         }
1350
1351         handle_uri(ser, uri, http_method, headers);
1352
1353 done:
1354         ast_atomic_fetchadd_int(&session_count, -1);
1355
1356         /* clean up all the header information */
1357         ast_variables_destroy(headers);
1358
1359         if (ser->f) {
1360                 fclose(ser->f);
1361         }
1362         ao2_ref(ser, -1);
1363         ser = NULL;
1364         return NULL;
1365 }
1366
1367 /*!
1368  * \brief Add a new URI redirect
1369  * The entries in the redirect list are sorted by length, just like the list
1370  * of URI handlers.
1371  */
1372 static void add_redirect(const char *value)
1373 {
1374         char *target, *dest;
1375         struct http_uri_redirect *redirect, *cur;
1376         unsigned int target_len;
1377         unsigned int total_len;
1378
1379         dest = ast_strdupa(value);
1380         dest = ast_skip_blanks(dest);
1381         target = strsep(&dest, " ");
1382         target = ast_skip_blanks(target);
1383         target = strsep(&target, " "); /* trim trailing whitespace */
1384
1385         if (!dest) {
1386                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
1387                 return;
1388         }
1389
1390         target_len = strlen(target) + 1;
1391         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
1392
1393         if (!(redirect = ast_calloc(1, total_len))) {
1394                 return;
1395         }
1396         redirect->dest = redirect->target + target_len;
1397         strcpy(redirect->target, target);
1398         strcpy(redirect->dest, dest);
1399
1400         AST_RWLIST_WRLOCK(&uri_redirects);
1401
1402         target_len--; /* So we can compare directly with strlen() */
1403         if (AST_RWLIST_EMPTY(&uri_redirects)
1404                 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
1405                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
1406                 AST_RWLIST_UNLOCK(&uri_redirects);
1407
1408                 return;
1409         }
1410
1411         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
1412                 if (AST_RWLIST_NEXT(cur, entry)
1413                         && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
1414                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
1415                         AST_RWLIST_UNLOCK(&uri_redirects);
1416                         return;
1417                 }
1418         }
1419
1420         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
1421
1422         AST_RWLIST_UNLOCK(&uri_redirects);
1423 }
1424
1425 static int __ast_http_load(int reload)
1426 {
1427         struct ast_config *cfg;
1428         struct ast_variable *v;
1429         int enabled=0;
1430         int newenablestatic=0;
1431         char newprefix[MAX_PREFIX] = "";
1432         struct http_uri_redirect *redirect;
1433         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1434         uint32_t bindport = DEFAULT_PORT;
1435         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1436         int num_addrs = 0;
1437         int http_tls_was_enabled = 0;
1438
1439         cfg = ast_config_load2("http.conf", "http", config_flags);
1440         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1441                 return 0;
1442         }
1443
1444         http_tls_was_enabled = (reload && http_tls_cfg.enabled);
1445
1446         http_tls_cfg.enabled = 0;
1447         if (http_tls_cfg.certfile) {
1448                 ast_free(http_tls_cfg.certfile);
1449         }
1450         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1451
1452         if (http_tls_cfg.pvtfile) {
1453                 ast_free(http_tls_cfg.pvtfile);
1454         }
1455         http_tls_cfg.pvtfile = ast_strdup("");
1456
1457         if (http_tls_cfg.cipher) {
1458                 ast_free(http_tls_cfg.cipher);
1459         }
1460         http_tls_cfg.cipher = ast_strdup("");
1461
1462         AST_RWLIST_WRLOCK(&uri_redirects);
1463         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1464                 ast_free(redirect);
1465         }
1466         AST_RWLIST_UNLOCK(&uri_redirects);
1467
1468         ast_sockaddr_setnull(&https_desc.local_address);
1469
1470         if (cfg) {
1471                 v = ast_variable_browse(cfg, "general");
1472                 for (; v; v = v->next) {
1473
1474                         /* read tls config options while preventing unsupported options from being set */
1475                         if (strcasecmp(v->name, "tlscafile")
1476                                 && strcasecmp(v->name, "tlscapath")
1477                                 && strcasecmp(v->name, "tlscadir")
1478                                 && strcasecmp(v->name, "tlsverifyclient")
1479                                 && strcasecmp(v->name, "tlsdontverifyserver")
1480                                 && strcasecmp(v->name, "tlsclientmethod")
1481                                 && strcasecmp(v->name, "sslclientmethod")
1482                                 && strcasecmp(v->name, "tlscipher")
1483                                 && strcasecmp(v->name, "sslcipher")
1484                                 && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1485                                 continue;
1486                         }
1487
1488                         if (!strcasecmp(v->name, "enabled")) {
1489                                 enabled = ast_true(v->value);
1490                         } else if (!strcasecmp(v->name, "enablestatic")) {
1491                                 newenablestatic = ast_true(v->value);
1492                         } else if (!strcasecmp(v->name, "bindport")) {
1493                                 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT, &bindport, DEFAULT_PORT, 0, 65535)) {
1494                                         ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %"PRId32, v->value, DEFAULT_PORT);
1495                                 }
1496                         } else if (!strcasecmp(v->name, "bindaddr")) {
1497                                 if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
1498                                         ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
1499                                 }
1500                         } else if (!strcasecmp(v->name, "prefix")) {
1501                                 if (!ast_strlen_zero(v->value)) {
1502                                         newprefix[0] = '/';
1503                                         ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1504                                 } else {
1505                                         newprefix[0] = '\0';
1506                                 }
1507                         } else if (!strcasecmp(v->name, "redirect")) {
1508                                 add_redirect(v->value);
1509                         } else if (!strcasecmp(v->name, "sessionlimit")) {
1510                                 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
1511                                                         &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
1512                                         ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
1513                                                         v->name, v->value, v->lineno);
1514                                 }
1515                         } else {
1516                                 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1517                         }
1518                 }
1519
1520                 ast_config_destroy(cfg);
1521         }
1522
1523         if (strcmp(prefix, newprefix)) {
1524                 ast_copy_string(prefix, newprefix, sizeof(prefix));
1525         }
1526         enablestatic = newenablestatic;
1527
1528         if (num_addrs && enabled) {
1529                 int i;
1530                 for (i = 0; i < num_addrs; ++i) {
1531                         ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
1532                         if (!ast_sockaddr_port(&http_desc.local_address)) {
1533                                 ast_sockaddr_set_port(&http_desc.local_address, bindport);
1534                         }
1535                         ast_tcptls_server_start(&http_desc);
1536                         if (http_desc.accept_fd == -1) {
1537                                 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
1538                                 ast_sockaddr_setnull(&http_desc.local_address);
1539                         } else {
1540                                 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
1541                                 break;
1542                         }
1543                 }
1544                 /* When no specific TLS bindaddr is specified, we just use
1545                  * the non-TLS bindaddress here.
1546                  */
1547                 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
1548                         ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
1549                         /* Of course, we can't use the same port though.
1550                          * Since no bind address was specified, we just use the
1551                          * default TLS port
1552                          */
1553                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1554                 }
1555         }
1556         if (http_tls_was_enabled && !http_tls_cfg.enabled) {
1557                 ast_tcptls_server_stop(&https_desc);
1558         } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
1559                 /* We can get here either because a TLS-specific address was specified
1560                  * or because we copied the non-TLS address here. In the case where
1561                  * we read an explicit address from the config, there may have been
1562                  * no port specified, so we'll just use the default TLS port.
1563                  */
1564                 if (!ast_sockaddr_port(&https_desc.local_address)) {
1565                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1566                 }
1567                 if (ast_ssl_setup(https_desc.tls_cfg)) {
1568                         ast_tcptls_server_start(&https_desc);
1569                 }
1570         }
1571
1572         return 0;
1573 }
1574
1575 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1576 {
1577         struct ast_http_uri *urih;
1578         struct http_uri_redirect *redirect;
1579
1580         switch (cmd) {
1581         case CLI_INIT:
1582                 e->command = "http show status";
1583                 e->usage =
1584                         "Usage: http show status\n"
1585                         "       Lists status of internal HTTP engine\n";
1586                 return NULL;
1587         case CLI_GENERATE:
1588                 return NULL;
1589         }
1590
1591         if (a->argc != 3) {
1592                 return CLI_SHOWUSAGE;
1593         }
1594         ast_cli(a->fd, "HTTP Server Status:\n");
1595         ast_cli(a->fd, "Prefix: %s\n", prefix);
1596         if (ast_sockaddr_isnull(&http_desc.old_address)) {
1597                 ast_cli(a->fd, "Server Disabled\n\n");
1598         } else {
1599                 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
1600                         ast_sockaddr_stringify(&http_desc.old_address));
1601                 if (http_tls_cfg.enabled) {
1602                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
1603                                 ast_sockaddr_stringify(&https_desc.old_address));
1604                 }
1605         }
1606
1607         ast_cli(a->fd, "Enabled URI's:\n");
1608         AST_RWLIST_RDLOCK(&uris);
1609         if (AST_RWLIST_EMPTY(&uris)) {
1610                 ast_cli(a->fd, "None.\n");
1611         } else {
1612                 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1613                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1614         }
1615         AST_RWLIST_UNLOCK(&uris);
1616
1617         ast_cli(a->fd, "\nEnabled Redirects:\n");
1618         AST_RWLIST_RDLOCK(&uri_redirects);
1619         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1620                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
1621         if (AST_RWLIST_EMPTY(&uri_redirects)) {
1622                 ast_cli(a->fd, "  None.\n");
1623         }
1624         AST_RWLIST_UNLOCK(&uri_redirects);
1625
1626         return CLI_SUCCESS;
1627 }
1628
1629 int ast_http_reload(void)
1630 {
1631         return __ast_http_load(1);
1632 }
1633
1634 static struct ast_cli_entry cli_http[] = {
1635         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1636 };
1637
1638 static void http_shutdown(void)
1639 {
1640         struct http_uri_redirect *redirect;
1641         ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
1642
1643         ast_tcptls_server_stop(&http_desc);
1644         if (http_tls_cfg.enabled) {
1645                 ast_tcptls_server_stop(&https_desc);
1646         }
1647         ast_free(http_tls_cfg.certfile);
1648         ast_free(http_tls_cfg.pvtfile);
1649         ast_free(http_tls_cfg.cipher);
1650
1651         ast_http_uri_unlink(&statusuri);
1652         ast_http_uri_unlink(&staticuri);
1653
1654         AST_RWLIST_WRLOCK(&uri_redirects);
1655         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1656                 ast_free(redirect);
1657         }
1658         AST_RWLIST_UNLOCK(&uri_redirects);
1659 }
1660
1661 int ast_http_init(void)
1662 {
1663         ast_http_uri_link(&statusuri);
1664         ast_http_uri_link(&staticuri);
1665         ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1666         ast_register_atexit(http_shutdown);
1667
1668         return __ast_http_load(0);
1669 }