HTTP: Add TCP_NODELAY to accepted connections
[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 += ast_str_strlen(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 (content_length) {
447                         if (fwrite(ast_str_buffer(out), content_length, 1, ser->f) != 1) {
448                                 ast_log(LOG_ERROR, "fwrite() failed: %s\n", strerror(errno));
449                         }
450                 }
451
452                 if (fd) {
453                         char buf[256];
454                         int len;
455                         while ((len = read(fd, buf, sizeof(buf))) > 0) {
456                                 if (fwrite(buf, len, 1, ser->f) != 1) {
457                                         ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
458                                         break;
459                                 }
460                         }
461                 }
462         }
463
464         if (http_header) {
465                 ast_free(http_header);
466         }
467         if (out) {
468                 ast_free(out);
469         }
470
471         ast_tcptls_close_session_file(ser);
472         return;
473 }
474
475 /* Send http "401 Unauthorized" responce and close socket*/
476 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
477         const unsigned long nonce, const unsigned long opaque, int stale,
478         const char *text)
479 {
480         struct ast_str *http_headers = ast_str_create(128);
481         struct ast_str *out = ast_str_create(512);
482
483         if (!http_headers || !out) {
484                 ast_free(http_headers);
485                 ast_free(out);
486                 return;
487         }
488
489         ast_str_set(&http_headers, 0,
490                 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
491                 "Content-type: text/html\r\n",
492                 realm ? realm : "Asterisk",
493                 nonce,
494                 opaque,
495                 stale ? ", stale=true" : "");
496
497         ast_str_set(&out, 0,
498                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
499                 "<html><head>\r\n"
500                 "<title>401 Unauthorized</title>\r\n"
501                 "</head><body>\r\n"
502                 "<h1>401 Unauthorized</h1>\r\n"
503                 "<p>%s</p>\r\n"
504                 "<hr />\r\n"
505                 "<address>Asterisk Server</address>\r\n"
506                 "</body></html>\r\n",
507                 text ? text : "");
508
509         ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
510         return;
511 }
512
513 /* send http error response and close socket*/
514 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
515 {
516         struct ast_str *http_headers = ast_str_create(40);
517         struct ast_str *out = ast_str_create(256);
518
519         if (!http_headers || !out) {
520                 ast_free(http_headers);
521                 ast_free(out);
522                 return;
523         }
524
525         ast_str_set(&http_headers, 0, "Content-type: text/html\r\n");
526
527         ast_str_set(&out, 0,
528                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
529                 "<html><head>\r\n"
530                 "<title>%d %s</title>\r\n"
531                 "</head><body>\r\n"
532                 "<h1>%s</h1>\r\n"
533                 "<p>%s</p>\r\n"
534                 "<hr />\r\n"
535                 "<address>Asterisk Server</address>\r\n"
536                 "</body></html>\r\n",
537                         status_code, status_title, status_title, text);
538
539         ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
540         return;
541 }
542
543 /*! \brief
544  * Link the new uri into the list.
545  *
546  * They are sorted by length of
547  * the string, not alphabetically. Duplicate entries are not replaced,
548  * but the insertion order (using <= and not just <) makes sure that
549  * more recent insertions hide older ones.
550  * On a lookup, we just scan the list and stop at the first matching entry.
551  */
552 int ast_http_uri_link(struct ast_http_uri *urih)
553 {
554         struct ast_http_uri *uri;
555         int len = strlen(urih->uri);
556
557         AST_RWLIST_WRLOCK(&uris);
558
559         if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
560                 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
561                 AST_RWLIST_UNLOCK(&uris);
562                 return 0;
563         }
564
565         AST_RWLIST_TRAVERSE(&uris, uri, entry) {
566                 if (AST_RWLIST_NEXT(uri, entry) &&
567                         strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
568                         AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
569                         AST_RWLIST_UNLOCK(&uris);
570
571                         return 0;
572                 }
573         }
574
575         AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
576
577         AST_RWLIST_UNLOCK(&uris);
578
579         return 0;
580 }
581
582 void ast_http_uri_unlink(struct ast_http_uri *urih)
583 {
584         AST_RWLIST_WRLOCK(&uris);
585         AST_RWLIST_REMOVE(&uris, urih, entry);
586         AST_RWLIST_UNLOCK(&uris);
587 }
588
589 void ast_http_uri_unlink_all_with_key(const char *key)
590 {
591         struct ast_http_uri *urih;
592         AST_RWLIST_WRLOCK(&uris);
593         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
594                 if (!strcmp(urih->key, key)) {
595                         AST_RWLIST_REMOVE_CURRENT(entry);
596                         if (urih->dmallocd) {
597                                 ast_free(urih->data);
598                         }
599                         if (urih->mallocd) {
600                                 ast_free(urih);
601                         }
602                 }
603         }
604         AST_RWLIST_TRAVERSE_SAFE_END;
605         AST_RWLIST_UNLOCK(&uris);
606 }
607
608 #define MAX_POST_CONTENT 1025
609
610 /*!
611  * \brief Retrieves the header with the given field name.
612  *
613  * \param headers Headers to search.
614  * \param field_name Name of the header to find.
615  * \return Associated header value.
616  * \return \c NULL if header is not present.
617  */
618 static const char *get_header(struct ast_variable *headers,
619         const char *field_name)
620 {
621         struct ast_variable *v;
622
623         for (v = headers; v; v = v->next) {
624                 if (!strcasecmp(v->name, field_name)) {
625                         return v->value;
626                 }
627         }
628         return NULL;
629 }
630
631 /*!
632  * \brief Retrieves the content type specified in the "Content-Type" header.
633  *
634  * This function only returns the "type/subtype" and any trailing parameter is
635  * not included.
636  *
637  * \note the return value is an allocated string that needs to be freed.
638  *
639  * \retval the content type/subtype or NULL if the header is not found.
640  */
641 static char *get_content_type(struct ast_variable *headers)
642 {
643         const char *content_type = get_header(headers, "Content-Type");
644         const char *param;
645         size_t size;
646
647         if (!content_type) {
648                 return NULL;
649         }
650
651         param = strchr(content_type, ';');
652         size = param ? param - content_type : strlen(content_type);
653
654         return ast_strndup(content_type, size);
655 }
656
657 /*!
658  * \brief Returns the value of the Content-Length header.
659  *
660  * \param headers HTTP headers.
661  * \return Value of the Content-Length header.
662  * \return 0 if header is not present, or is invalid.
663  */
664 static int get_content_length(struct ast_variable *headers)
665 {
666         const char *content_length = get_header(headers, "Content-Length");
667
668         if (!content_length) {
669                 /* Missing content length; assume zero */
670                 return 0;
671         }
672
673         /* atoi() will return 0 for invalid inputs, which is good enough for
674          * the HTTP parsing. */
675         return atoi(content_length);
676 }
677
678 /*!
679  * \brief Returns the value of the Transfer-Encoding header.
680  *
681  * \param headers HTTP headers.
682  * \return Value of the Transfer-Encoding header.
683  * \return 0 if header is not present, or is invalid.
684  */
685 static const char *get_transfer_encoding(struct ast_variable *headers)
686 {
687         return get_header(headers, "Transfer-Encoding");
688 }
689
690 /*!
691  * \brief decode chunked mode hexadecimal value
692  *
693  * \param s string to decode
694  * \param len length of string
695  * \return integer value or -1 for decode error
696  */
697 static int chunked_atoh(const char *s, int len)
698 {
699         int value = 0;
700         char c;
701
702         if (*s < '0') {
703                 /* zero value must be 0\n not just \n */
704                 return -1;
705         }
706
707         while (len--)
708         {
709                 if (*s == '\x0D') {
710                         return value;
711                 }
712                 value <<= 4;
713                 c = *s++;
714                 if (c >= '0' && c <= '9') {
715                         value += c - '0';
716                         continue;
717                 }
718                 if (c >= 'a' && c <= 'f') {
719                         value += 10 + c - 'a';
720                         continue;
721                 }
722                 if (c >= 'A' && c <= 'F') {
723                         value += 10 + c - 'A';
724                         continue;
725                 }
726                 /* invalid character */
727                 return -1;
728         }
729         /* end of string */
730         return -1;
731 }
732
733 /*!
734  * \brief Returns the contents (body) of the HTTP request
735  *
736  * \param return_length ptr to int that returns content length
737  * \param aser HTTP TCP/TLS session object
738  * \param headers List of HTTP headers
739  * \return ptr to content (zero terminated) or NULL on failure
740  * \note Since returned ptr is malloc'd, it should be free'd by caller
741  */
742 static char *ast_http_get_contents(int *return_length,
743         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
744 {
745         const char *transfer_encoding;
746         int res;
747         int content_length = 0;
748         int chunk_length;
749         char chunk_header[8];
750         int bufsize = 250;
751         char *buf;
752
753         transfer_encoding = get_transfer_encoding(headers);
754
755         if (ast_strlen_zero(transfer_encoding) ||
756                 strcasecmp(transfer_encoding, "chunked") != 0) {
757                 /* handle regular non-chunked content */
758                 content_length = get_content_length(headers);
759                 if (content_length <= 0) {
760                         /* no content - not an error */
761                         return NULL;
762                 }
763                 if (content_length > MAX_POST_CONTENT - 1) {
764                         ast_log(LOG_WARNING,
765                                 "Excessively long HTTP content. (%d > %d)\n",
766                                 content_length, MAX_POST_CONTENT);
767                         errno = EFBIG;
768                         return NULL;
769                 }
770                 buf = ast_malloc(content_length + 1);
771                 if (!buf) {
772                         /* Malloc sets ENOMEM */
773                         return NULL;
774                 }
775                 res = fread(buf, 1, content_length, ser->f);
776                 if (res < content_length) {
777                         /* Error, distinguishable by ferror() or feof(), but neither
778                          * is good. Treat either one as I/O error */
779                         ast_log(LOG_WARNING, "Short HTTP request body (%d < %d)\n",
780                                 res, content_length);
781                         errno = EIO;
782                         ast_free(buf);
783                         return NULL;
784                 }
785                 buf[content_length] = 0;
786                 *return_length = content_length;
787                 return buf;
788         }
789
790         /* pre-allocate buffer */
791         buf = ast_malloc(bufsize);
792         if (!buf) {
793                 return NULL;
794         }
795
796         /* handled chunked content */
797         do {
798                 /* get the line of hexadecimal giving chunk size */
799                 if (!fgets(chunk_header, sizeof(chunk_header), ser->f)) {
800                         ast_log(LOG_WARNING,
801                                 "Short HTTP read of chunked header\n");
802                         errno = EIO;
803                         ast_free(buf);
804                         return NULL;
805                 }
806                 chunk_length = chunked_atoh(chunk_header, sizeof(chunk_header));
807                 if (chunk_length < 0) {
808                         ast_log(LOG_WARNING, "Invalid HTTP chunk size\n");
809                         errno = EIO;
810                         ast_free(buf);
811                         return NULL;
812                 }
813                 if (content_length + chunk_length > MAX_POST_CONTENT - 1) {
814                         ast_log(LOG_WARNING,
815                                 "Excessively long HTTP chunk. (%d + %d > %d)\n",
816                                 content_length, chunk_length, MAX_POST_CONTENT);
817                         errno = EFBIG;
818                         ast_free(buf);
819                         return NULL;
820                 }
821
822                 /* insure buffer is large enough +1 */
823                 if (content_length + chunk_length >= bufsize)
824                 {
825                         bufsize *= 2;
826                         buf = ast_realloc(buf, bufsize);
827                         if (!buf) {
828                                 return NULL;
829                         }
830                 }
831
832                 /* read the chunk */
833                 res = fread(buf + content_length, 1, chunk_length, ser->f);
834                 if (res < chunk_length) {
835                         ast_log(LOG_WARNING, "Short HTTP chunk read (%d < %d)\n",
836                                 res, chunk_length);
837                         errno = EIO;
838                         ast_free(buf);
839                         return NULL;
840                 }
841                 content_length += chunk_length;
842
843                 /* insure the next 2 bytes are CRLF */
844                 res = fread(chunk_header, 1, 2, ser->f);
845                 if (res < 2) {
846                         ast_log(LOG_WARNING,
847                                 "Short HTTP chunk sync read (%d < 2)\n", res);
848                         errno = EIO;
849                         ast_free(buf);
850                         return NULL;
851                 }
852                 if (chunk_header[0] != 0x0D || chunk_header[1] != 0x0A) {
853                         ast_log(LOG_WARNING,
854                                 "Post HTTP chunk sync bytes wrong (%d, %d)\n",
855                                 chunk_header[0], chunk_header[1]);
856                         errno = EIO;
857                         ast_free(buf);
858                         return NULL;
859                 }
860         } while (chunk_length);
861
862         buf[content_length] = 0;
863         *return_length = content_length;
864         return buf;
865 }
866
867 struct ast_json *ast_http_get_json(
868         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
869 {
870         int content_length = 0;
871         struct ast_json *body;
872         RAII_VAR(char *, buf, NULL, ast_free);
873         RAII_VAR(char *, type, get_content_type(headers), ast_free);
874
875         /* Use errno to distinguish errors from no body */
876         errno = 0;
877
878         if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
879                 /* Content type is not JSON */
880                 return NULL;
881         }
882
883         buf = ast_http_get_contents(&content_length, ser, headers);
884         if (buf == NULL) {
885                 /* errno already set */
886                 return NULL;
887         }
888
889         if (!content_length) {
890                 /* it is not an error to have zero content */
891                 return NULL;
892         }
893
894         body = ast_json_load_buf(buf, content_length, NULL);
895         if (body == NULL) {
896                 /* Failed to parse JSON; treat as an I/O error */
897                 errno = EIO;
898                 return NULL;
899         }
900
901         return body;
902 }
903
904 /*
905  * get post variables from client Request Entity-Body, if content type is
906  * application/x-www-form-urlencoded
907  */
908 struct ast_variable *ast_http_get_post_vars(
909         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
910 {
911         int content_length = 0;
912         struct ast_variable *v, *post_vars=NULL, *prev = NULL;
913         char *var, *val;
914         RAII_VAR(char *, buf, NULL, ast_free_ptr);
915         RAII_VAR(char *, type, get_content_type(headers), ast_free);
916
917         /* Use errno to distinguish errors from no params */
918         errno = 0;
919
920         if (ast_strlen_zero(type) ||
921             strcasecmp(type, "application/x-www-form-urlencoded")) {
922                 /* Content type is not form data */
923                 return NULL;
924         }
925
926         buf = ast_http_get_contents(&content_length, ser, headers);
927         if (buf == NULL) {
928                 return NULL;
929         }
930
931         while ((val = strsep(&buf, "&"))) {
932                 var = strsep(&val, "=");
933                 if (val) {
934                         ast_uri_decode(val, ast_uri_http_legacy);
935                 } else  {
936                         val = "";
937                 }
938                 ast_uri_decode(var, ast_uri_http_legacy);
939                 if ((v = ast_variable_new(var, val, ""))) {
940                         if (post_vars) {
941                                 prev->next = v;
942                         } else {
943                                 post_vars = v;
944                         }
945                         prev = v;
946                 }
947         }
948
949         return post_vars;
950 }
951
952 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
953         enum ast_http_method method, struct ast_variable *headers)
954 {
955         char *c;
956         int res = -1;
957         char *params = uri;
958         struct ast_http_uri *urih = NULL;
959         int l;
960         struct ast_variable *get_vars = NULL, *v, *prev = NULL;
961         struct http_uri_redirect *redirect;
962
963         ast_debug(2, "HTTP Request URI is %s \n", uri);
964
965         strsep(&params, "?");
966         /* Extract arguments from the request and store them in variables. */
967         if (params) {
968                 char *var, *val;
969
970                 while ((val = strsep(&params, "&"))) {
971                         var = strsep(&val, "=");
972                         if (val) {
973                                 ast_uri_decode(val, ast_uri_http_legacy);
974                         } else  {
975                                 val = "";
976                         }
977                         ast_uri_decode(var, ast_uri_http_legacy);
978                         if ((v = ast_variable_new(var, val, ""))) {
979                                 if (get_vars) {
980                                         prev->next = v;
981                                 } else {
982                                         get_vars = v;
983                                 }
984                                 prev = v;
985                         }
986                 }
987         }
988
989         AST_RWLIST_RDLOCK(&uri_redirects);
990         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
991                 if (!strcasecmp(uri, redirect->target)) {
992                         struct ast_str *http_header = ast_str_create(128);
993                         ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
994                         ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
995
996                         break;
997                 }
998         }
999         AST_RWLIST_UNLOCK(&uri_redirects);
1000         if (redirect) {
1001                 goto cleanup;
1002         }
1003
1004         /* We want requests to start with the (optional) prefix and '/' */
1005         l = strlen(prefix);
1006         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
1007                 uri += l + 1;
1008                 /* scan registered uris to see if we match one. */
1009                 AST_RWLIST_RDLOCK(&uris);
1010                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
1011                         l = strlen(urih->uri);
1012                         c = uri + l;    /* candidate */
1013                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
1014                         if (strncasecmp(urih->uri, uri, l) /* no match */
1015                             || (*c && *c != '/')) { /* substring */
1016                                 continue;
1017                         }
1018                         if (*c == '/') {
1019                                 c++;
1020                         }
1021                         if (!*c || urih->has_subtree) {
1022                                 uri = c;
1023                                 break;
1024                         }
1025                 }
1026                 AST_RWLIST_UNLOCK(&uris);
1027         }
1028         if (urih) {
1029                 ast_debug(1, "Match made with [%s]\n", urih->uri);
1030                 if (!urih->no_decode_uri) {
1031                         ast_uri_decode(uri, ast_uri_http_legacy);
1032                 }
1033                 res = urih->callback(ser, urih, uri, method, get_vars, headers);
1034         } else {
1035                 ast_debug(1, "Requested URI [%s] has no handler\n", uri);
1036                 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
1037         }
1038
1039 cleanup:
1040         ast_variables_destroy(get_vars);
1041         return res;
1042 }
1043
1044 #ifdef DO_SSL
1045 #if defined(HAVE_FUNOPEN)
1046 #define HOOK_T int
1047 #define LEN_T int
1048 #else
1049 #define HOOK_T ssize_t
1050 #define LEN_T size_t
1051 #endif
1052
1053 /*!
1054  * replacement read/write functions for SSL support.
1055  * We use wrappers rather than SSL_read/SSL_write directly so
1056  * we can put in some debugging.
1057  */
1058 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
1059 {
1060         int i = SSL_read(cookie, buf, len-1);
1061 #if 0
1062         if (i >= 0)
1063                 buf[i] = '\0';
1064         ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
1065 #endif
1066         return i;
1067 }
1068
1069 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
1070 {
1071 #if 0
1072         char *s = ast_alloca(len+1);
1073         strncpy(s, buf, len);
1074         s[len] = '\0';
1075         ast_verbose("ssl write size %d <%s>\n", (int)len, s);
1076 #endif
1077         return SSL_write(cookie, buf, len);
1078 }
1079
1080 static int ssl_close(void *cookie)
1081 {
1082         close(SSL_get_fd(cookie));
1083         SSL_shutdown(cookie);
1084         SSL_free(cookie);
1085         return 0;
1086 }*/
1087 #endif  /* DO_SSL */
1088
1089 static struct ast_variable *parse_cookies(const char *cookies)
1090 {
1091         char *parse = ast_strdupa(cookies);
1092         char *cur;
1093         struct ast_variable *vars = NULL, *var;
1094
1095         while ((cur = strsep(&parse, ";"))) {
1096                 char *name, *val;
1097
1098                 name = val = cur;
1099                 strsep(&val, "=");
1100
1101                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1102                         continue;
1103                 }
1104
1105                 name = ast_strip(name);
1106                 val = ast_strip_quoted(val, "\"", "\"");
1107
1108                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
1109                         continue;
1110                 }
1111
1112                 ast_debug(1, "HTTP Cookie, Name: '%s'  Value: '%s'\n", name, val);
1113
1114                 var = ast_variable_new(name, val, __FILE__);
1115                 var->next = vars;
1116                 vars = var;
1117         }
1118
1119         return vars;
1120 }
1121
1122 /* get cookie from Request headers */
1123 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
1124 {
1125         struct ast_variable *v, *cookies = NULL;
1126
1127         for (v = headers; v; v = v->next) {
1128                 if (!strcasecmp(v->name, "Cookie")) {
1129                         ast_variables_destroy(cookies);
1130                         cookies = parse_cookies(v->value);
1131                 }
1132         }
1133         return cookies;
1134 }
1135
1136 static struct ast_http_auth *auth_create(const char *userid,
1137         const char *password)
1138 {
1139         RAII_VAR(struct ast_http_auth *, auth, NULL, ao2_cleanup);
1140         size_t userid_len;
1141         size_t password_len;
1142
1143         if (!userid || !password) {
1144                 ast_log(LOG_ERROR, "Invalid userid/password\n");
1145                 return NULL;
1146         }
1147
1148         userid_len = strlen(userid) + 1;
1149         password_len = strlen(password) + 1;
1150
1151         /* Allocate enough room to store everything in one memory block */
1152         auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
1153         if (!auth) {
1154                 return NULL;
1155         }
1156
1157         /* Put the userid right after the struct */
1158         auth->userid = (char *)(auth + 1);
1159         strcpy(auth->userid, userid);
1160
1161         /* Put the password right after the userid */
1162         auth->password = auth->userid + userid_len;
1163         strcpy(auth->password, password);
1164
1165         ao2_ref(auth, +1);
1166         return auth;
1167 }
1168
1169 #define BASIC_PREFIX "Basic "
1170 #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
1171
1172 struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
1173 {
1174         struct ast_variable *v;
1175
1176         for (v = headers; v; v = v->next) {
1177                 const char *base64;
1178                 char decoded[256] = {};
1179                 char *username;
1180                 char *password;
1181 #ifdef AST_DEVMODE
1182                 int cnt;
1183 #endif /* AST_DEVMODE */
1184
1185                 if (strcasecmp("Authorization", v->name) != 0) {
1186                         continue;
1187                 }
1188
1189                 if (!ast_begins_with(v->value, BASIC_PREFIX)) {
1190                         ast_log(LOG_DEBUG,
1191                                 "Unsupported Authorization scheme\n");
1192                         continue;
1193                 }
1194
1195                 /* Basic auth header parsing. RFC 2617, section 2.
1196                  *   credentials = "Basic" basic-credentials
1197                  *   basic-credentials = base64-user-pass
1198                  *   base64-user-pass  = <base64 encoding of user-pass,
1199                  *                        except not limited to 76 char/line>
1200                  *   user-pass   = userid ":" password
1201                  */
1202
1203                 base64 = v->value + BASIC_LEN;
1204
1205                 /* This will truncate "userid:password" lines to
1206                  * sizeof(decoded). The array is long enough that this shouldn't
1207                  * be a problem */
1208 #ifdef AST_DEVMODE
1209                 cnt =
1210 #endif /* AST_DEVMODE */
1211                 ast_base64decode((unsigned char*)decoded, base64,
1212                         sizeof(decoded) - 1);
1213                 ast_assert(cnt < sizeof(decoded));
1214
1215                 /* Split the string at the colon */
1216                 password = decoded;
1217                 username = strsep(&password, ":");
1218                 if (!password) {
1219                         ast_log(LOG_WARNING, "Invalid Authorization header\n");
1220                         return NULL;
1221                 }
1222
1223                 return auth_create(username, password);
1224         }
1225
1226         return NULL;
1227 }
1228
1229 /*! Limit the number of request headers in case the sender is being ridiculous. */
1230 #define MAX_HTTP_REQUEST_HEADERS        100
1231
1232 static void *httpd_helper_thread(void *data)
1233 {
1234         char buf[4096];
1235         char header_line[4096];
1236         struct ast_tcptls_session_instance *ser = data;
1237         struct ast_variable *headers = NULL;
1238         struct ast_variable *tail = headers;
1239         char *uri, *method;
1240         enum ast_http_method http_method = AST_HTTP_UNKNOWN;
1241         const char *transfer_encoding;
1242         int remaining_headers;
1243         struct protoent *p;
1244
1245         if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
1246                 goto done;
1247         }
1248
1249         /* here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
1250          * This is necessary to prevent delays (caused by buffering) as we
1251          * write to the socket in bits and pieces. */
1252         p = getprotobyname("tcp");
1253         if (p) {
1254                 int arg = 1;
1255                 if( setsockopt(ser->fd, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
1256                         ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection: %s\n", strerror(errno));
1257                         ast_log(LOG_WARNING, "Some HTTP requests may be slow to respond.\n");
1258                 }
1259         } else {
1260                 ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection, getprotobyname(\"tcp\") failed\n");
1261                 ast_log(LOG_WARNING, "Some HTTP requests may be slow to respond.\n");
1262         }
1263
1264         if (!fgets(buf, sizeof(buf), ser->f)) {
1265                 goto done;
1266         }
1267
1268         /* Get method */
1269         method = ast_skip_blanks(buf);
1270         uri = ast_skip_nonblanks(method);
1271         if (*uri) {
1272                 *uri++ = '\0';
1273         }
1274
1275         if (!strcasecmp(method,"GET")) {
1276                 http_method = AST_HTTP_GET;
1277         } else if (!strcasecmp(method,"POST")) {
1278                 http_method = AST_HTTP_POST;
1279         } else if (!strcasecmp(method,"HEAD")) {
1280                 http_method = AST_HTTP_HEAD;
1281         } else if (!strcasecmp(method,"PUT")) {
1282                 http_method = AST_HTTP_PUT;
1283         } else if (!strcasecmp(method,"DELETE")) {
1284                 http_method = AST_HTTP_DELETE;
1285         } else if (!strcasecmp(method,"OPTIONS")) {
1286                 http_method = AST_HTTP_OPTIONS;
1287         }
1288
1289         uri = ast_skip_blanks(uri);     /* Skip white space */
1290
1291         if (*uri) {                     /* terminate at the first blank */
1292                 char *c = ast_skip_nonblanks(uri);
1293
1294                 if (*c) {
1295                         *c = '\0';
1296                 }
1297         } else {
1298                 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
1299                 goto done;
1300         }
1301
1302         /* process "Request Headers" lines */
1303         remaining_headers = MAX_HTTP_REQUEST_HEADERS;
1304         while (fgets(header_line, sizeof(header_line), ser->f)) {
1305                 char *name, *value;
1306
1307                 /* Trim trailing characters */
1308                 ast_trim_blanks(header_line);
1309                 if (ast_strlen_zero(header_line)) {
1310                         break;
1311                 }
1312
1313                 value = header_line;
1314                 name = strsep(&value, ":");
1315                 if (!value) {
1316                         continue;
1317                 }
1318
1319                 value = ast_skip_blanks(value);
1320                 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1321                         continue;
1322                 }
1323
1324                 ast_trim_blanks(name);
1325
1326                 if (!remaining_headers--) {
1327                         /* Too many headers. */
1328                         ast_http_error(ser, 413, "Request Entity Too Large", "Too many headers");
1329                         goto done;
1330                 }
1331                 if (!headers) {
1332                         headers = ast_variable_new(name, value, __FILE__);
1333                         tail = headers;
1334                 } else {
1335                         tail->next = ast_variable_new(name, value, __FILE__);
1336                         tail = tail->next;
1337                 }
1338                 if (!tail) {
1339                         /*
1340                          * Variable allocation failure.
1341                          * Try to make some room.
1342                          */
1343                         ast_variables_destroy(headers);
1344                         headers = NULL;
1345
1346                         ast_http_error(ser, 500, "Server Error", "Out of memory");
1347                         goto done;
1348                 }
1349         }
1350
1351         transfer_encoding = get_transfer_encoding(headers);
1352         /* Transfer encoding defaults to identity */
1353         if (!transfer_encoding) {
1354                 transfer_encoding = "identity";
1355         }
1356
1357         /*
1358          * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
1359          * codings we don't understand.
1360          */
1361         if (strcasecmp(transfer_encoding, "identity") != 0 &&
1362                 strcasecmp(transfer_encoding, "chunked") != 0) {
1363                 /* Transfer encodings not supported */
1364                 ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
1365                 goto done;
1366         }
1367
1368         handle_uri(ser, uri, http_method, headers);
1369
1370 done:
1371         ast_atomic_fetchadd_int(&session_count, -1);
1372
1373         /* clean up all the header information */
1374         ast_variables_destroy(headers);
1375
1376         if (ser->f) {
1377                 fclose(ser->f);
1378         }
1379         ao2_ref(ser, -1);
1380         ser = NULL;
1381         return NULL;
1382 }
1383
1384 /*!
1385  * \brief Add a new URI redirect
1386  * The entries in the redirect list are sorted by length, just like the list
1387  * of URI handlers.
1388  */
1389 static void add_redirect(const char *value)
1390 {
1391         char *target, *dest;
1392         struct http_uri_redirect *redirect, *cur;
1393         unsigned int target_len;
1394         unsigned int total_len;
1395
1396         dest = ast_strdupa(value);
1397         dest = ast_skip_blanks(dest);
1398         target = strsep(&dest, " ");
1399         target = ast_skip_blanks(target);
1400         target = strsep(&target, " "); /* trim trailing whitespace */
1401
1402         if (!dest) {
1403                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
1404                 return;
1405         }
1406
1407         target_len = strlen(target) + 1;
1408         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
1409
1410         if (!(redirect = ast_calloc(1, total_len))) {
1411                 return;
1412         }
1413         redirect->dest = redirect->target + target_len;
1414         strcpy(redirect->target, target);
1415         strcpy(redirect->dest, dest);
1416
1417         AST_RWLIST_WRLOCK(&uri_redirects);
1418
1419         target_len--; /* So we can compare directly with strlen() */
1420         if (AST_RWLIST_EMPTY(&uri_redirects)
1421                 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
1422                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
1423                 AST_RWLIST_UNLOCK(&uri_redirects);
1424
1425                 return;
1426         }
1427
1428         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
1429                 if (AST_RWLIST_NEXT(cur, entry)
1430                         && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
1431                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
1432                         AST_RWLIST_UNLOCK(&uri_redirects);
1433                         return;
1434                 }
1435         }
1436
1437         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
1438
1439         AST_RWLIST_UNLOCK(&uri_redirects);
1440 }
1441
1442 static int __ast_http_load(int reload)
1443 {
1444         struct ast_config *cfg;
1445         struct ast_variable *v;
1446         int enabled=0;
1447         int newenablestatic=0;
1448         char newprefix[MAX_PREFIX] = "";
1449         struct http_uri_redirect *redirect;
1450         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1451         uint32_t bindport = DEFAULT_PORT;
1452         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1453         int num_addrs = 0;
1454         int http_tls_was_enabled = 0;
1455
1456         cfg = ast_config_load2("http.conf", "http", config_flags);
1457         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1458                 return 0;
1459         }
1460
1461         http_tls_was_enabled = (reload && http_tls_cfg.enabled);
1462
1463         http_tls_cfg.enabled = 0;
1464         if (http_tls_cfg.certfile) {
1465                 ast_free(http_tls_cfg.certfile);
1466         }
1467         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1468
1469         if (http_tls_cfg.pvtfile) {
1470                 ast_free(http_tls_cfg.pvtfile);
1471         }
1472         http_tls_cfg.pvtfile = ast_strdup("");
1473
1474         if (http_tls_cfg.cipher) {
1475                 ast_free(http_tls_cfg.cipher);
1476         }
1477         http_tls_cfg.cipher = ast_strdup("");
1478
1479         AST_RWLIST_WRLOCK(&uri_redirects);
1480         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1481                 ast_free(redirect);
1482         }
1483         AST_RWLIST_UNLOCK(&uri_redirects);
1484
1485         ast_sockaddr_setnull(&https_desc.local_address);
1486
1487         if (cfg) {
1488                 v = ast_variable_browse(cfg, "general");
1489                 for (; v; v = v->next) {
1490
1491                         /* read tls config options while preventing unsupported options from being set */
1492                         if (strcasecmp(v->name, "tlscafile")
1493                                 && strcasecmp(v->name, "tlscapath")
1494                                 && strcasecmp(v->name, "tlscadir")
1495                                 && strcasecmp(v->name, "tlsverifyclient")
1496                                 && strcasecmp(v->name, "tlsdontverifyserver")
1497                                 && strcasecmp(v->name, "tlsclientmethod")
1498                                 && strcasecmp(v->name, "sslclientmethod")
1499                                 && strcasecmp(v->name, "tlscipher")
1500                                 && strcasecmp(v->name, "sslcipher")
1501                                 && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1502                                 continue;
1503                         }
1504
1505                         if (!strcasecmp(v->name, "enabled")) {
1506                                 enabled = ast_true(v->value);
1507                         } else if (!strcasecmp(v->name, "enablestatic")) {
1508                                 newenablestatic = ast_true(v->value);
1509                         } else if (!strcasecmp(v->name, "bindport")) {
1510                                 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT, &bindport, DEFAULT_PORT, 0, 65535)) {
1511                                         ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %"PRId32, v->value, DEFAULT_PORT);
1512                                 }
1513                         } else if (!strcasecmp(v->name, "bindaddr")) {
1514                                 if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
1515                                         ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
1516                                 }
1517                         } else if (!strcasecmp(v->name, "prefix")) {
1518                                 if (!ast_strlen_zero(v->value)) {
1519                                         newprefix[0] = '/';
1520                                         ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1521                                 } else {
1522                                         newprefix[0] = '\0';
1523                                 }
1524                         } else if (!strcasecmp(v->name, "redirect")) {
1525                                 add_redirect(v->value);
1526                         } else if (!strcasecmp(v->name, "sessionlimit")) {
1527                                 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
1528                                                         &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
1529                                         ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
1530                                                         v->name, v->value, v->lineno);
1531                                 }
1532                         } else {
1533                                 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1534                         }
1535                 }
1536
1537                 ast_config_destroy(cfg);
1538         }
1539
1540         if (strcmp(prefix, newprefix)) {
1541                 ast_copy_string(prefix, newprefix, sizeof(prefix));
1542         }
1543         enablestatic = newenablestatic;
1544
1545         if (num_addrs && enabled) {
1546                 int i;
1547                 for (i = 0; i < num_addrs; ++i) {
1548                         ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
1549                         if (!ast_sockaddr_port(&http_desc.local_address)) {
1550                                 ast_sockaddr_set_port(&http_desc.local_address, bindport);
1551                         }
1552                         ast_tcptls_server_start(&http_desc);
1553                         if (http_desc.accept_fd == -1) {
1554                                 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
1555                                 ast_sockaddr_setnull(&http_desc.local_address);
1556                         } else {
1557                                 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
1558                                 break;
1559                         }
1560                 }
1561                 /* When no specific TLS bindaddr is specified, we just use
1562                  * the non-TLS bindaddress here.
1563                  */
1564                 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
1565                         ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
1566                         /* Of course, we can't use the same port though.
1567                          * Since no bind address was specified, we just use the
1568                          * default TLS port
1569                          */
1570                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1571                 }
1572         }
1573         if (http_tls_was_enabled && !http_tls_cfg.enabled) {
1574                 ast_tcptls_server_stop(&https_desc);
1575         } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
1576                 /* We can get here either because a TLS-specific address was specified
1577                  * or because we copied the non-TLS address here. In the case where
1578                  * we read an explicit address from the config, there may have been
1579                  * no port specified, so we'll just use the default TLS port.
1580                  */
1581                 if (!ast_sockaddr_port(&https_desc.local_address)) {
1582                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1583                 }
1584                 if (ast_ssl_setup(https_desc.tls_cfg)) {
1585                         ast_tcptls_server_start(&https_desc);
1586                 }
1587         }
1588
1589         return 0;
1590 }
1591
1592 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1593 {
1594         struct ast_http_uri *urih;
1595         struct http_uri_redirect *redirect;
1596
1597         switch (cmd) {
1598         case CLI_INIT:
1599                 e->command = "http show status";
1600                 e->usage =
1601                         "Usage: http show status\n"
1602                         "       Lists status of internal HTTP engine\n";
1603                 return NULL;
1604         case CLI_GENERATE:
1605                 return NULL;
1606         }
1607
1608         if (a->argc != 3) {
1609                 return CLI_SHOWUSAGE;
1610         }
1611         ast_cli(a->fd, "HTTP Server Status:\n");
1612         ast_cli(a->fd, "Prefix: %s\n", prefix);
1613         if (ast_sockaddr_isnull(&http_desc.old_address)) {
1614                 ast_cli(a->fd, "Server Disabled\n\n");
1615         } else {
1616                 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
1617                         ast_sockaddr_stringify(&http_desc.old_address));
1618                 if (http_tls_cfg.enabled) {
1619                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
1620                                 ast_sockaddr_stringify(&https_desc.old_address));
1621                 }
1622         }
1623
1624         ast_cli(a->fd, "Enabled URI's:\n");
1625         AST_RWLIST_RDLOCK(&uris);
1626         if (AST_RWLIST_EMPTY(&uris)) {
1627                 ast_cli(a->fd, "None.\n");
1628         } else {
1629                 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1630                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1631         }
1632         AST_RWLIST_UNLOCK(&uris);
1633
1634         ast_cli(a->fd, "\nEnabled Redirects:\n");
1635         AST_RWLIST_RDLOCK(&uri_redirects);
1636         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1637                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
1638         if (AST_RWLIST_EMPTY(&uri_redirects)) {
1639                 ast_cli(a->fd, "  None.\n");
1640         }
1641         AST_RWLIST_UNLOCK(&uri_redirects);
1642
1643         return CLI_SUCCESS;
1644 }
1645
1646 int ast_http_reload(void)
1647 {
1648         return __ast_http_load(1);
1649 }
1650
1651 static struct ast_cli_entry cli_http[] = {
1652         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1653 };
1654
1655 static void http_shutdown(void)
1656 {
1657         struct http_uri_redirect *redirect;
1658         ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
1659
1660         ast_tcptls_server_stop(&http_desc);
1661         if (http_tls_cfg.enabled) {
1662                 ast_tcptls_server_stop(&https_desc);
1663         }
1664         ast_free(http_tls_cfg.certfile);
1665         ast_free(http_tls_cfg.pvtfile);
1666         ast_free(http_tls_cfg.cipher);
1667
1668         ast_http_uri_unlink(&statusuri);
1669         ast_http_uri_unlink(&staticuri);
1670
1671         AST_RWLIST_WRLOCK(&uri_redirects);
1672         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1673                 ast_free(redirect);
1674         }
1675         AST_RWLIST_UNLOCK(&uri_redirects);
1676 }
1677
1678 int ast_http_init(void)
1679 {
1680         ast_http_uri_link(&statusuri);
1681         ast_http_uri_link(&staticuri);
1682         ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1683         ast_register_atexit(http_shutdown);
1684
1685         return __ast_http_load(0);
1686 }