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