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