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