ari:Add application/json parameter support
[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         if (cookies) {
201                 ast_variables_destroy(cookies);
202         }
203         return mngid;
204 }
205
206 void ast_http_prefix(char *buf, int len)
207 {
208         if (buf) {
209                 ast_copy_string(buf, prefix, len);
210         }
211 }
212
213 static int static_callback(struct ast_tcptls_session_instance *ser,
214         const struct ast_http_uri *urih, const char *uri,
215         enum ast_http_method method, struct ast_variable *get_vars,
216         struct ast_variable *headers)
217 {
218         char *path;
219         const char *ftype;
220         const char *mtype;
221         char wkspace[80];
222         struct stat st;
223         int len;
224         int fd;
225         struct ast_str *http_header;
226         struct timeval tv;
227         struct ast_tm tm;
228         char timebuf[80], etag[23];
229         struct ast_variable *v;
230         int not_modified = 0;
231
232         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
233                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
234                 return -1;
235         }
236
237         /* Yuck.  I'm not really sold on this, but if you don't deliver static content it makes your configuration
238            substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
239         if (!enablestatic || ast_strlen_zero(uri)) {
240                 goto out403;
241         }
242
243         /* Disallow any funny filenames at all (checking first character only??) */
244         if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
245                 goto out403;
246         }
247
248         if (strstr(uri, "/..")) {
249                 goto out403;
250         }
251
252         if ((ftype = strrchr(uri, '.'))) {
253                 ftype++;
254         }
255
256         if (!(mtype = ast_http_ftype2mtype(ftype))) {
257                 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
258                 mtype = wkspace;
259         }
260
261         /* Cap maximum length */
262         if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
263                 goto out403;
264         }
265
266         path = ast_alloca(len);
267         sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
268         if (stat(path, &st)) {
269                 goto out404;
270         }
271
272         if (S_ISDIR(st.st_mode)) {
273                 goto out404;
274         }
275
276         if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
277                 goto out403;
278         }
279
280         fd = open(path, O_RDONLY);
281         if (fd < 0) {
282                 goto out403;
283         }
284
285         /* make "Etag:" http header value */
286         snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
287
288         /* make "Last-Modified:" http header value */
289         tv.tv_sec = st.st_mtime;
290         tv.tv_usec = 0;
291         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
292
293         /* check received "If-None-Match" request header and Etag value for file */
294         for (v = headers; v; v = v->next) {
295                 if (!strcasecmp(v->name, "If-None-Match")) {
296                         if (!strcasecmp(v->value, etag)) {
297                                 not_modified = 1;
298                         }
299                         break;
300                 }
301         }
302
303         if ( (http_header = ast_str_create(255)) == NULL) {
304                 close(fd);
305                 return -1;
306         }
307
308         ast_str_set(&http_header, 0, "Content-type: %s\r\n"
309                 "ETag: %s\r\n"
310                 "Last-Modified: %s\r\n",
311                 mtype,
312                 etag,
313                 timebuf);
314
315         /* ast_http_send() frees http_header, so we don't need to do it before returning */
316         if (not_modified) {
317                 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
318         } else {
319                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
320         }
321         close(fd);
322         return 0;
323
324 out404:
325         ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
326         return -1;
327
328 out403:
329         ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
330         return -1;
331 }
332
333 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
334         const struct ast_http_uri *urih, const char *uri,
335         enum ast_http_method method, struct ast_variable *get_vars,
336         struct ast_variable *headers)
337 {
338         struct ast_str *out;
339         struct ast_variable *v, *cookies = NULL;
340
341         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
342                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
343                 return -1;
344         }
345
346         if ( (out = ast_str_create(512)) == NULL) {
347                 return -1;
348         }
349
350         ast_str_append(&out, 0,
351                 "<title>Asterisk HTTP Status</title>\r\n"
352                 "<body bgcolor=\"#ffffff\">\r\n"
353                 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
354                 "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
355
356         ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
357         ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
358                        ast_sockaddr_stringify_addr(&http_desc.old_address));
359         ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
360                        ast_sockaddr_stringify_port(&http_desc.old_address));
361         if (http_tls_cfg.enabled) {
362                 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
363                                ast_sockaddr_stringify_port(&https_desc.old_address));
364         }
365         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
366         for (v = get_vars; v; v = v->next) {
367                 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
368         }
369         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
370
371         cookies = ast_http_get_cookies(headers);
372         for (v = cookies; v; v = v->next) {
373                 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
374         }
375         ast_variables_destroy(cookies);
376
377         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");
378         ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
379         return 0;
380 }
381
382 static struct ast_http_uri statusuri = {
383         .callback = httpstatus_callback,
384         .description = "Asterisk HTTP General Status",
385         .uri = "httpstatus",
386         .has_subtree = 0,
387         .data = NULL,
388         .key = __FILE__,
389 };
390
391 static struct ast_http_uri staticuri = {
392         .callback = static_callback,
393         .description = "Asterisk HTTP Static Delivery",
394         .uri = "static",
395         .has_subtree = 1,
396         .data = NULL,
397         .key= __FILE__,
398 };
399
400
401 /* send http/1.1 response */
402 /* free content variable and close socket*/
403 void ast_http_send(struct ast_tcptls_session_instance *ser,
404         enum ast_http_method method, int status_code, const char *status_title,
405         struct ast_str *http_header, struct ast_str *out, const int fd,
406         unsigned int static_content)
407 {
408         struct timeval now = ast_tvnow();
409         struct ast_tm tm;
410         char timebuf[80];
411         int content_length = 0;
412
413         if (!ser || 0 == ser->f) {
414                 return;
415         }
416
417         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
418
419         /* calc content length */
420         if (out) {
421                 content_length += strlen(ast_str_buffer(out));
422         }
423
424         if (fd) {
425                 content_length += lseek(fd, 0, SEEK_END);
426                 lseek(fd, 0, SEEK_SET);
427         }
428
429         /* send http header */
430         fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
431                 "Server: Asterisk/%s\r\n"
432                 "Date: %s\r\n"
433                 "Connection: close\r\n"
434                 "%s"
435                 "Content-Length: %d\r\n"
436                 "%s"
437                 "\r\n",
438                 status_code, status_title ? status_title : "OK",
439                 ast_get_version(),
440                 timebuf,
441                 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
442                 content_length,
443                 http_header ? ast_str_buffer(http_header) : ""
444                 );
445
446         /* send content */
447         if (method != AST_HTTP_HEAD || status_code >= 400) {
448                 if (out) {
449                         fprintf(ser->f, "%s", ast_str_buffer(out));
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         fclose(ser->f);
472         ser->f = 0;
473         return;
474 }
475
476 /* Send http "401 Unauthorized" responce and close socket*/
477 void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
478         const unsigned long nonce, const unsigned long opaque, int stale,
479         const char *text)
480 {
481         struct ast_str *http_headers = ast_str_create(128);
482         struct ast_str *out = ast_str_create(512);
483
484         if (!http_headers || !out) {
485                 ast_free(http_headers);
486                 ast_free(out);
487                 return;
488         }
489
490         ast_str_set(&http_headers, 0,
491                 "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
492                 "Content-type: text/html\r\n",
493                 realm ? realm : "Asterisk",
494                 nonce,
495                 opaque,
496                 stale ? ", stale=true" : "");
497
498         ast_str_set(&out, 0,
499                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
500                 "<html><head>\r\n"
501                 "<title>401 Unauthorized</title>\r\n"
502                 "</head><body>\r\n"
503                 "<h1>401 Unauthorized</h1>\r\n"
504                 "<p>%s</p>\r\n"
505                 "<hr />\r\n"
506                 "<address>Asterisk Server</address>\r\n"
507                 "</body></html>\r\n",
508                 text ? text : "");
509
510         ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
511         return;
512 }
513
514 /* send http error response and close socket*/
515 void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
516 {
517         struct ast_str *http_headers = ast_str_create(40);
518         struct ast_str *out = ast_str_create(256);
519
520         if (!http_headers || !out) {
521                 ast_free(http_headers);
522                 ast_free(out);
523                 return;
524         }
525
526         ast_str_set(&http_headers, 0, "Content-type: text/html\r\n");
527
528         ast_str_set(&out, 0,
529                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
530                 "<html><head>\r\n"
531                 "<title>%d %s</title>\r\n"
532                 "</head><body>\r\n"
533                 "<h1>%s</h1>\r\n"
534                 "<p>%s</p>\r\n"
535                 "<hr />\r\n"
536                 "<address>Asterisk Server</address>\r\n"
537                 "</body></html>\r\n",
538                         status_code, status_title, status_title, text);
539
540         ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
541         return;
542 }
543
544 /*! \brief
545  * Link the new uri into the list.
546  *
547  * They are sorted by length of
548  * the string, not alphabetically. Duplicate entries are not replaced,
549  * but the insertion order (using <= and not just <) makes sure that
550  * more recent insertions hide older ones.
551  * On a lookup, we just scan the list and stop at the first matching entry.
552  */
553 int ast_http_uri_link(struct ast_http_uri *urih)
554 {
555         struct ast_http_uri *uri;
556         int len = strlen(urih->uri);
557
558         AST_RWLIST_WRLOCK(&uris);
559
560         if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
561                 AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
562                 AST_RWLIST_UNLOCK(&uris);
563                 return 0;
564         }
565
566         AST_RWLIST_TRAVERSE(&uris, uri, entry) {
567                 if (AST_RWLIST_NEXT(uri, entry) &&
568                         strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
569                         AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
570                         AST_RWLIST_UNLOCK(&uris);
571
572                         return 0;
573                 }
574         }
575
576         AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
577
578         AST_RWLIST_UNLOCK(&uris);
579
580         return 0;
581 }
582
583 void ast_http_uri_unlink(struct ast_http_uri *urih)
584 {
585         AST_RWLIST_WRLOCK(&uris);
586         AST_RWLIST_REMOVE(&uris, urih, entry);
587         AST_RWLIST_UNLOCK(&uris);
588 }
589
590 void ast_http_uri_unlink_all_with_key(const char *key)
591 {
592         struct ast_http_uri *urih;
593         AST_RWLIST_WRLOCK(&uris);
594         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
595                 if (!strcmp(urih->key, key)) {
596                         AST_RWLIST_REMOVE_CURRENT(entry);
597                         if (urih->dmallocd) {
598                                 ast_free(urih->data);
599                         }
600                         if (urih->mallocd) {
601                                 ast_free(urih);
602                         }
603                 }
604         }
605         AST_RWLIST_TRAVERSE_SAFE_END;
606         AST_RWLIST_UNLOCK(&uris);
607 }
608
609 #define MAX_POST_CONTENT 1025
610
611 static const char *get_content_type(struct ast_variable *headers)
612 {
613         struct ast_variable *v;
614
615         for (v = headers; v; v = v->next) {
616                 if (strcasecmp(v->name, "Content-Type") == 0) {
617                         return v->value;
618                 }
619         }
620
621         /* Missing content type; assume empty string */
622         return "";
623 }
624
625 static int get_content_length(struct ast_variable *headers)
626 {
627         struct ast_variable *v;
628
629         for (v = headers; v; v = v->next) {
630                 if (!strcasecmp(v->name, "Content-Length")) {
631                         return atoi(v->value);
632                 }
633         }
634
635         /* Missing content length; assume zero */
636         return 0;
637 }
638
639 struct ast_json *ast_http_get_json(
640         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
641 {
642         int content_length = 0;
643         int res;
644         struct ast_json *body;
645         RAII_VAR(char *, buf, NULL, ast_free);
646
647         /* Use errno to distinguish errors from no body */
648         errno = 0;
649
650         if (strcasecmp(get_content_type(headers), "application/json") != 0) {
651                 /* Content type is not JSON */
652                 return NULL;
653         }
654
655         content_length = get_content_length(headers);
656
657         if (content_length <= 0) {
658                 /* No content (or streaming content). */
659                 return NULL;
660         }
661
662         if (content_length > MAX_POST_CONTENT - 1) {
663                 ast_log(LOG_WARNING,
664                         "Excessively long HTTP content. (%d > %d)\n",
665                         content_length, MAX_POST_CONTENT);
666                 errno = EFBIG;
667                 return NULL;
668         }
669
670         buf = ast_malloc(content_length);
671         if (!buf) {
672                 /* Malloc sets ENOMEM */
673                 return NULL;
674         }
675
676         res = fread(buf, 1, content_length, ser->f);
677         if (res < content_length) {
678                 /* Error, distinguishable by ferror() or feof(), but neither
679                  * is good. Treat either one as I/O error */
680                 ast_log(LOG_WARNING, "Short HTTP request body (%d < %d)\n",
681                         res, content_length);
682                 errno = EIO;
683                 return NULL;
684         }
685
686         body = ast_json_load_buf(buf, content_length, NULL);
687         if (body == NULL) {
688                 /* Failed to parse JSON; treat as an I/O error */
689                 errno = EIO;
690                 return NULL;
691         }
692
693         return body;
694 }
695
696 /*
697  * get post variables from client Request Entity-Body, if content type is
698  * application/x-www-form-urlencoded
699  */
700 struct ast_variable *ast_http_get_post_vars(
701         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
702 {
703         int content_length = 0;
704         struct ast_variable *v, *post_vars=NULL, *prev = NULL;
705         char *var, *val;
706         RAII_VAR(char *, buf, NULL, ast_free_ptr);
707         int res;
708
709         /* Use errno to distinguish errors from no params */
710         errno = 0;
711
712         if (strcasecmp(get_content_type(headers), "application/x-www-form-urlencoded") != 0) {
713                 /* Content type is not form data */
714                 return NULL;
715         }
716
717         content_length = get_content_length(headers);
718
719         if (content_length <= 0) {
720                 return NULL;
721         }
722
723         if (content_length > MAX_POST_CONTENT - 1) {
724                 ast_log(LOG_WARNING,
725                         "Excessively long HTTP content. (%d > %d)\n",
726                         content_length, MAX_POST_CONTENT);
727                 errno = EFBIG;
728                 return NULL;
729         }
730
731         buf = ast_malloc(content_length + 1);
732         if (!buf) {
733                 /* malloc sets errno to ENOMEM */
734                 return NULL;
735         }
736
737         res = fread(buf, 1, content_length, ser->f);
738         if (res < content_length) {
739                 /* Error, distinguishable by ferror() or feof(), but neither
740                  * is good. Treat either one as I/O error */
741                 errno = EIO;
742                 return NULL;
743         }
744         buf[content_length] = '\0';
745
746         while ((val = strsep(&buf, "&"))) {
747                 var = strsep(&val, "=");
748                 if (val) {
749                         ast_uri_decode(val, ast_uri_http_legacy);
750                 } else  {
751                         val = "";
752                 }
753                 ast_uri_decode(var, ast_uri_http_legacy);
754                 if ((v = ast_variable_new(var, val, ""))) {
755                         if (post_vars) {
756                                 prev->next = v;
757                         } else {
758                                 post_vars = v;
759                         }
760                         prev = v;
761                 }
762         }
763
764         return post_vars;
765 }
766
767 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
768         enum ast_http_method method, struct ast_variable *headers)
769 {
770         char *c;
771         int res = -1;
772         char *params = uri;
773         struct ast_http_uri *urih = NULL;
774         int l;
775         struct ast_variable *get_vars = NULL, *v, *prev = NULL;
776         struct http_uri_redirect *redirect;
777
778         ast_debug(2, "HTTP Request URI is %s \n", uri);
779
780         strsep(&params, "?");
781         /* Extract arguments from the request and store them in variables. */
782         if (params) {
783                 char *var, *val;
784
785                 while ((val = strsep(&params, "&"))) {
786                         var = strsep(&val, "=");
787                         if (val) {
788                                 ast_uri_decode(val, ast_uri_http_legacy);
789                         } else  {
790                                 val = "";
791                         }
792                         ast_uri_decode(var, ast_uri_http_legacy);
793                         if ((v = ast_variable_new(var, val, ""))) {
794                                 if (get_vars) {
795                                         prev->next = v;
796                                 } else {
797                                         get_vars = v;
798                                 }
799                                 prev = v;
800                         }
801                 }
802         }
803
804         AST_RWLIST_RDLOCK(&uri_redirects);
805         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
806                 if (!strcasecmp(uri, redirect->target)) {
807                         struct ast_str *http_header = ast_str_create(128);
808                         ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
809                         ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
810
811                         break;
812                 }
813         }
814         AST_RWLIST_UNLOCK(&uri_redirects);
815         if (redirect) {
816                 goto cleanup;
817         }
818
819         /* We want requests to start with the (optional) prefix and '/' */
820         l = strlen(prefix);
821         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
822                 uri += l + 1;
823                 /* scan registered uris to see if we match one. */
824                 AST_RWLIST_RDLOCK(&uris);
825                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
826                         l = strlen(urih->uri);
827                         c = uri + l;    /* candidate */
828                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
829                         if (strncasecmp(urih->uri, uri, l) /* no match */
830                             || (*c && *c != '/')) { /* substring */
831                                 continue;
832                         }
833                         if (*c == '/') {
834                                 c++;
835                         }
836                         if (!*c || urih->has_subtree) {
837                                 uri = c;
838                                 break;
839                         }
840                 }
841                 AST_RWLIST_UNLOCK(&uris);
842         }
843         if (urih) {
844                 ast_debug(1, "Match made with [%s]\n", urih->uri);
845                 if (!urih->no_decode_uri) {
846                         ast_uri_decode(uri, ast_uri_http_legacy);
847                 }
848                 res = urih->callback(ser, urih, uri, method, get_vars, headers);
849         } else {
850                 ast_debug(1, "Requested URI [%s] has no handler\n", uri);
851                 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
852         }
853
854 cleanup:
855         ast_variables_destroy(get_vars);
856         return res;
857 }
858
859 #ifdef DO_SSL
860 #if defined(HAVE_FUNOPEN)
861 #define HOOK_T int
862 #define LEN_T int
863 #else
864 #define HOOK_T ssize_t
865 #define LEN_T size_t
866 #endif
867
868 /*!
869  * replacement read/write functions for SSL support.
870  * We use wrappers rather than SSL_read/SSL_write directly so
871  * we can put in some debugging.
872  */
873 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
874 {
875         int i = SSL_read(cookie, buf, len-1);
876 #if 0
877         if (i >= 0)
878                 buf[i] = '\0';
879         ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
880 #endif
881         return i;
882 }
883
884 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
885 {
886 #if 0
887         char *s = ast_alloca(len+1);
888         strncpy(s, buf, len);
889         s[len] = '\0';
890         ast_verbose("ssl write size %d <%s>\n", (int)len, s);
891 #endif
892         return SSL_write(cookie, buf, len);
893 }
894
895 static int ssl_close(void *cookie)
896 {
897         close(SSL_get_fd(cookie));
898         SSL_shutdown(cookie);
899         SSL_free(cookie);
900         return 0;
901 }*/
902 #endif  /* DO_SSL */
903
904 static struct ast_variable *parse_cookies(char *cookies)
905 {
906         char *cur;
907         struct ast_variable *vars = NULL, *var;
908
909         while ((cur = strsep(&cookies, ";"))) {
910                 char *name, *val;
911
912                 name = val = cur;
913                 strsep(&val, "=");
914
915                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
916                         continue;
917                 }
918
919                 name = ast_strip(name);
920                 val = ast_strip_quoted(val, "\"", "\"");
921
922                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
923                         continue;
924                 }
925
926                 ast_debug(1, "HTTP Cookie, Name: '%s'  Value: '%s'\n", name, val);
927
928                 var = ast_variable_new(name, val, __FILE__);
929                 var->next = vars;
930                 vars = var;
931         }
932
933         return vars;
934 }
935
936 /* get cookie from Request headers */
937 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
938 {
939         struct ast_variable *v, *cookies=NULL;
940
941         for (v = headers; v; v = v->next) {
942                 if (!strcasecmp(v->name, "Cookie")) {
943                         char *tmp = ast_strdupa(v->value);
944                         if (cookies) {
945                                 ast_variables_destroy(cookies);
946                         }
947
948                         cookies = parse_cookies(tmp);
949                 }
950         }
951         return cookies;
952 }
953
954 static struct ast_http_auth *auth_create(const char *userid,
955         const char *password)
956 {
957         RAII_VAR(struct ast_http_auth *, auth, NULL, ao2_cleanup);
958         size_t userid_len;
959         size_t password_len;
960
961         if (!userid || !password) {
962                 ast_log(LOG_ERROR, "Invalid userid/password\n");
963                 return NULL;
964         }
965
966         userid_len = strlen(userid) + 1;
967         password_len = strlen(password) + 1;
968
969         /* Allocate enough room to store everything in one memory block */
970         auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
971         if (!auth) {
972                 return NULL;
973         }
974
975         /* Put the userid right after the struct */
976         auth->userid = (char *)(auth + 1);
977         strcpy(auth->userid, userid);
978
979         /* Put the password right after the userid */
980         auth->password = auth->userid + userid_len;
981         strcpy(auth->password, password);
982
983         ao2_ref(auth, +1);
984         return auth;
985 }
986
987 #define BASIC_PREFIX "Basic "
988 #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
989
990 struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
991 {
992         struct ast_variable *v;
993
994         for (v = headers; v; v = v->next) {
995                 const char *base64;
996                 char decoded[256] = {};
997                 char *username;
998                 char *password;
999 #ifdef AST_DEVMODE
1000                 int cnt;
1001 #endif /* AST_DEVMODE */
1002
1003                 if (strcasecmp("Authorization", v->name) != 0) {
1004                         continue;
1005                 }
1006
1007                 if (!ast_begins_with(v->value, BASIC_PREFIX)) {
1008                         ast_log(LOG_DEBUG,
1009                                 "Unsupported Authorization scheme\n");
1010                         continue;
1011                 }
1012
1013                 /* Basic auth header parsing. RFC 2617, section 2.
1014                  *   credentials = "Basic" basic-credentials
1015                  *   basic-credentials = base64-user-pass
1016                  *   base64-user-pass  = <base64 encoding of user-pass,
1017                  *                        except not limited to 76 char/line>
1018                  *   user-pass   = userid ":" password
1019                  */
1020
1021                 base64 = v->value + BASIC_LEN;
1022
1023                 /* This will truncate "userid:password" lines to
1024                  * sizeof(decoded). The array is long enough that this shouldn't
1025                  * be a problem */
1026 #ifdef AST_DEVMODE
1027                 cnt =
1028 #endif /* AST_DEVMODE */
1029                 ast_base64decode((unsigned char*)decoded, base64,
1030                         sizeof(decoded) - 1);
1031                 ast_assert(cnt < sizeof(decoded));
1032
1033                 /* Split the string at the colon */
1034                 password = decoded;
1035                 username = strsep(&password, ":");
1036                 if (!password) {
1037                         ast_log(LOG_WARNING, "Invalid Authorization header\n");
1038                         return NULL;
1039                 }
1040
1041                 return auth_create(username, password);
1042         }
1043
1044         return NULL;
1045 }
1046
1047 static void *httpd_helper_thread(void *data)
1048 {
1049         char buf[4096];
1050         char header_line[4096];
1051         struct ast_tcptls_session_instance *ser = data;
1052         struct ast_variable *headers = NULL;
1053         struct ast_variable *tail = headers;
1054         char *uri, *method;
1055         enum ast_http_method http_method = AST_HTTP_UNKNOWN;
1056
1057         if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
1058                 goto done;
1059         }
1060
1061         if (!fgets(buf, sizeof(buf), ser->f)) {
1062                 goto done;
1063         }
1064
1065         /* Get method */
1066         method = ast_skip_blanks(buf);
1067         uri = ast_skip_nonblanks(method);
1068         if (*uri) {
1069                 *uri++ = '\0';
1070         }
1071
1072         if (!strcasecmp(method,"GET")) {
1073                 http_method = AST_HTTP_GET;
1074         } else if (!strcasecmp(method,"POST")) {
1075                 http_method = AST_HTTP_POST;
1076         } else if (!strcasecmp(method,"HEAD")) {
1077                 http_method = AST_HTTP_HEAD;
1078         } else if (!strcasecmp(method,"PUT")) {
1079                 http_method = AST_HTTP_PUT;
1080         } else if (!strcasecmp(method,"DELETE")) {
1081                 http_method = AST_HTTP_DELETE;
1082         } else if (!strcasecmp(method,"OPTIONS")) {
1083                 http_method = AST_HTTP_OPTIONS;
1084         }
1085
1086         uri = ast_skip_blanks(uri);     /* Skip white space */
1087
1088         if (*uri) {                     /* terminate at the first blank */
1089                 char *c = ast_skip_nonblanks(uri);
1090
1091                 if (*c) {
1092                         *c = '\0';
1093                 }
1094         }
1095
1096         /* process "Request Headers" lines */
1097         while (fgets(header_line, sizeof(header_line), ser->f)) {
1098                 char *name, *value;
1099
1100                 /* Trim trailing characters */
1101                 ast_trim_blanks(header_line);
1102                 if (ast_strlen_zero(header_line)) {
1103                         break;
1104                 }
1105
1106                 value = header_line;
1107                 name = strsep(&value, ":");
1108                 if (!value) {
1109                         continue;
1110                 }
1111
1112                 value = ast_skip_blanks(value);
1113                 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
1114                         continue;
1115                 }
1116
1117                 ast_trim_blanks(name);
1118
1119                 if (!headers) {
1120                         headers = ast_variable_new(name, value, __FILE__);
1121                         tail = headers;
1122                 } else {
1123                         tail->next = ast_variable_new(name, value, __FILE__);
1124                         tail = tail->next;
1125                 }
1126         }
1127
1128         if (!*uri) {
1129                 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
1130                 goto done;
1131         }
1132
1133         handle_uri(ser, uri, http_method, headers);
1134
1135 done:
1136         ast_atomic_fetchadd_int(&session_count, -1);
1137
1138         /* clean up all the header information */
1139         if (headers) {
1140                 ast_variables_destroy(headers);
1141         }
1142
1143         if (ser->f) {
1144                 fclose(ser->f);
1145         }
1146         ao2_ref(ser, -1);
1147         ser = NULL;
1148         return NULL;
1149 }
1150
1151 /*!
1152  * \brief Add a new URI redirect
1153  * The entries in the redirect list are sorted by length, just like the list
1154  * of URI handlers.
1155  */
1156 static void add_redirect(const char *value)
1157 {
1158         char *target, *dest;
1159         struct http_uri_redirect *redirect, *cur;
1160         unsigned int target_len;
1161         unsigned int total_len;
1162
1163         dest = ast_strdupa(value);
1164         dest = ast_skip_blanks(dest);
1165         target = strsep(&dest, " ");
1166         target = ast_skip_blanks(target);
1167         target = strsep(&target, " "); /* trim trailing whitespace */
1168
1169         if (!dest) {
1170                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
1171                 return;
1172         }
1173
1174         target_len = strlen(target) + 1;
1175         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
1176
1177         if (!(redirect = ast_calloc(1, total_len))) {
1178                 return;
1179         }
1180         redirect->dest = redirect->target + target_len;
1181         strcpy(redirect->target, target);
1182         strcpy(redirect->dest, dest);
1183
1184         AST_RWLIST_WRLOCK(&uri_redirects);
1185
1186         target_len--; /* So we can compare directly with strlen() */
1187         if (AST_RWLIST_EMPTY(&uri_redirects)
1188                 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
1189                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
1190                 AST_RWLIST_UNLOCK(&uri_redirects);
1191
1192                 return;
1193         }
1194
1195         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
1196                 if (AST_RWLIST_NEXT(cur, entry)
1197                         && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
1198                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
1199                         AST_RWLIST_UNLOCK(&uri_redirects);
1200                         return;
1201                 }
1202         }
1203
1204         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
1205
1206         AST_RWLIST_UNLOCK(&uri_redirects);
1207 }
1208
1209 static int __ast_http_load(int reload)
1210 {
1211         struct ast_config *cfg;
1212         struct ast_variable *v;
1213         int enabled=0;
1214         int newenablestatic=0;
1215         char newprefix[MAX_PREFIX] = "";
1216         struct http_uri_redirect *redirect;
1217         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1218         uint32_t bindport = DEFAULT_PORT;
1219         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1220         int num_addrs = 0;
1221         int http_tls_was_enabled = 0;
1222
1223         cfg = ast_config_load2("http.conf", "http", config_flags);
1224         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1225                 return 0;
1226         }
1227
1228         http_tls_was_enabled = (reload && http_tls_cfg.enabled);
1229
1230         http_tls_cfg.enabled = 0;
1231         if (http_tls_cfg.certfile) {
1232                 ast_free(http_tls_cfg.certfile);
1233         }
1234         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1235
1236         if (http_tls_cfg.pvtfile) {
1237                 ast_free(http_tls_cfg.pvtfile);
1238         }
1239         http_tls_cfg.pvtfile = ast_strdup("");
1240
1241         if (http_tls_cfg.cipher) {
1242                 ast_free(http_tls_cfg.cipher);
1243         }
1244         http_tls_cfg.cipher = ast_strdup("");
1245
1246         AST_RWLIST_WRLOCK(&uri_redirects);
1247         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1248                 ast_free(redirect);
1249         }
1250         AST_RWLIST_UNLOCK(&uri_redirects);
1251
1252         ast_sockaddr_setnull(&https_desc.local_address);
1253
1254         if (cfg) {
1255                 v = ast_variable_browse(cfg, "general");
1256                 for (; v; v = v->next) {
1257
1258                         /* read tls config options while preventing unsupported options from being set */
1259                         if (strcasecmp(v->name, "tlscafile")
1260                                 && strcasecmp(v->name, "tlscapath")
1261                                 && strcasecmp(v->name, "tlscadir")
1262                                 && strcasecmp(v->name, "tlsverifyclient")
1263                                 && strcasecmp(v->name, "tlsdontverifyserver")
1264                                 && strcasecmp(v->name, "tlsclientmethod")
1265                                 && strcasecmp(v->name, "sslclientmethod")
1266                                 && strcasecmp(v->name, "tlscipher")
1267                                 && strcasecmp(v->name, "sslcipher")
1268                                 && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1269                                 continue;
1270                         }
1271
1272                         if (!strcasecmp(v->name, "enabled")) {
1273                                 enabled = ast_true(v->value);
1274                         } else if (!strcasecmp(v->name, "enablestatic")) {
1275                                 newenablestatic = ast_true(v->value);
1276                         } else if (!strcasecmp(v->name, "bindport")) {
1277                                 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT, &bindport, DEFAULT_PORT, 0, 65535)) {
1278                                         ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %"PRId32, v->value, DEFAULT_PORT);
1279                                 }
1280                         } else if (!strcasecmp(v->name, "bindaddr")) {
1281                                 if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
1282                                         ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
1283                                 }
1284                         } else if (!strcasecmp(v->name, "prefix")) {
1285                                 if (!ast_strlen_zero(v->value)) {
1286                                         newprefix[0] = '/';
1287                                         ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1288                                 } else {
1289                                         newprefix[0] = '\0';
1290                                 }
1291                         } else if (!strcasecmp(v->name, "redirect")) {
1292                                 add_redirect(v->value);
1293                         } else if (!strcasecmp(v->name, "sessionlimit")) {
1294                                 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
1295                                                         &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
1296                                         ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
1297                                                         v->name, v->value, v->lineno);
1298                                 }
1299                         } else {
1300                                 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1301                         }
1302                 }
1303
1304                 ast_config_destroy(cfg);
1305         }
1306
1307         if (strcmp(prefix, newprefix)) {
1308                 ast_copy_string(prefix, newprefix, sizeof(prefix));
1309         }
1310         enablestatic = newenablestatic;
1311
1312         if (num_addrs && enabled) {
1313                 int i;
1314                 for (i = 0; i < num_addrs; ++i) {
1315                         ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
1316                         if (!ast_sockaddr_port(&http_desc.local_address)) {
1317                                 ast_sockaddr_set_port(&http_desc.local_address, bindport);
1318                         }
1319                         ast_tcptls_server_start(&http_desc);
1320                         if (http_desc.accept_fd == -1) {
1321                                 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
1322                                 ast_sockaddr_setnull(&http_desc.local_address);
1323                         } else {
1324                                 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
1325                                 break;
1326                         }
1327                 }
1328                 /* When no specific TLS bindaddr is specified, we just use
1329                  * the non-TLS bindaddress here.
1330                  */
1331                 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
1332                         ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
1333                         /* Of course, we can't use the same port though.
1334                          * Since no bind address was specified, we just use the
1335                          * default TLS port
1336                          */
1337                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1338                 }
1339         }
1340         if (http_tls_was_enabled && !http_tls_cfg.enabled) {
1341                 ast_tcptls_server_stop(&https_desc);
1342         } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
1343                 /* We can get here either because a TLS-specific address was specified
1344                  * or because we copied the non-TLS address here. In the case where
1345                  * we read an explicit address from the config, there may have been
1346                  * no port specified, so we'll just use the default TLS port.
1347                  */
1348                 if (!ast_sockaddr_port(&https_desc.local_address)) {
1349                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1350                 }
1351                 if (ast_ssl_setup(https_desc.tls_cfg)) {
1352                         ast_tcptls_server_start(&https_desc);
1353                 }
1354         }
1355
1356         return 0;
1357 }
1358
1359 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1360 {
1361         struct ast_http_uri *urih;
1362         struct http_uri_redirect *redirect;
1363
1364         switch (cmd) {
1365         case CLI_INIT:
1366                 e->command = "http show status";
1367                 e->usage =
1368                         "Usage: http show status\n"
1369                         "       Lists status of internal HTTP engine\n";
1370                 return NULL;
1371         case CLI_GENERATE:
1372                 return NULL;
1373         }
1374
1375         if (a->argc != 3) {
1376                 return CLI_SHOWUSAGE;
1377         }
1378         ast_cli(a->fd, "HTTP Server Status:\n");
1379         ast_cli(a->fd, "Prefix: %s\n", prefix);
1380         if (ast_sockaddr_isnull(&http_desc.old_address)) {
1381                 ast_cli(a->fd, "Server Disabled\n\n");
1382         } else {
1383                 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
1384                         ast_sockaddr_stringify(&http_desc.old_address));
1385                 if (http_tls_cfg.enabled) {
1386                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
1387                                 ast_sockaddr_stringify(&https_desc.old_address));
1388                 }
1389         }
1390
1391         ast_cli(a->fd, "Enabled URI's:\n");
1392         AST_RWLIST_RDLOCK(&uris);
1393         if (AST_RWLIST_EMPTY(&uris)) {
1394                 ast_cli(a->fd, "None.\n");
1395         } else {
1396                 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1397                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1398         }
1399         AST_RWLIST_UNLOCK(&uris);
1400
1401         ast_cli(a->fd, "\nEnabled Redirects:\n");
1402         AST_RWLIST_RDLOCK(&uri_redirects);
1403         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1404                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
1405         if (AST_RWLIST_EMPTY(&uri_redirects)) {
1406                 ast_cli(a->fd, "  None.\n");
1407         }
1408         AST_RWLIST_UNLOCK(&uri_redirects);
1409
1410         return CLI_SUCCESS;
1411 }
1412
1413 int ast_http_reload(void)
1414 {
1415         return __ast_http_load(1);
1416 }
1417
1418 static struct ast_cli_entry cli_http[] = {
1419         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1420 };
1421
1422 static void http_shutdown(void)
1423 {
1424         struct http_uri_redirect *redirect;
1425         ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
1426
1427         ast_tcptls_server_stop(&http_desc);
1428         if (http_tls_cfg.enabled) {
1429                 ast_tcptls_server_stop(&https_desc);
1430         }
1431         ast_free(http_tls_cfg.certfile);
1432         ast_free(http_tls_cfg.pvtfile);
1433         ast_free(http_tls_cfg.cipher);
1434
1435         ast_http_uri_unlink(&statusuri);
1436         ast_http_uri_unlink(&staticuri);
1437
1438         AST_RWLIST_WRLOCK(&uri_redirects);
1439         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1440                 ast_free(redirect);
1441         }
1442         AST_RWLIST_UNLOCK(&uri_redirects);
1443 }
1444
1445 int ast_http_init(void)
1446 {
1447         ast_http_uri_link(&statusuri);
1448         ast_http_uri_link(&staticuri);
1449         ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1450         ast_register_atexit(http_shutdown);
1451
1452         return __ast_http_load(0);
1453 }