Index installed sounds and implement ARI sounds queries
[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
69 #define MAX_PREFIX 80
70 #define DEFAULT_PORT 8088
71 #define DEFAULT_TLS_PORT 8089
72 #define DEFAULT_SESSION_LIMIT 100
73
74 /* See http.h for more information about the SSL implementation */
75 #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
76 #define DO_SSL  /* comment in/out if you want to support ssl */
77 #endif
78
79 static int session_limit = DEFAULT_SESSION_LIMIT;
80 static int session_count = 0;
81
82 static struct ast_tls_config http_tls_cfg;
83
84 static void *httpd_helper_thread(void *arg);
85
86 /*!
87  * we have up to two accepting threads, one for http, one for https
88  */
89 static struct ast_tcptls_session_args http_desc = {
90         .accept_fd = -1,
91         .master = AST_PTHREADT_NULL,
92         .tls_cfg = NULL,
93         .poll_timeout = -1,
94         .name = "http server",
95         .accept_fn = ast_tcptls_server_root,
96         .worker_fn = httpd_helper_thread,
97 };
98
99 static struct ast_tcptls_session_args https_desc = {
100         .accept_fd = -1,
101         .master = AST_PTHREADT_NULL,
102         .tls_cfg = &http_tls_cfg,
103         .poll_timeout = -1,
104         .name = "https server",
105         .accept_fn = ast_tcptls_server_root,
106         .worker_fn = httpd_helper_thread,
107 };
108
109 static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri);      /*!< list of supported handlers */
110
111 /* all valid URIs must be prepended by the string in prefix. */
112 static char prefix[MAX_PREFIX];
113 static int enablestatic;
114
115 /*! \brief Limit the kinds of files we're willing to serve up */
116 static struct {
117         const char *ext;
118         const char *mtype;
119 } mimetypes[] = {
120         { "png", "image/png" },
121         { "xml", "text/xml" },
122         { "jpg", "image/jpeg" },
123         { "js", "application/x-javascript" },
124         { "wav", "audio/x-wav" },
125         { "mp3", "audio/mpeg" },
126         { "svg", "image/svg+xml" },
127         { "svgz", "image/svg+xml" },
128         { "gif", "image/gif" },
129         { "html", "text/html" },
130         { "htm", "text/html" },
131         { "css", "text/css" },
132         { "cnf", "text/plain" },
133         { "cfg", "text/plain" },
134         { "bin", "application/octet-stream" },
135         { "sbn", "application/octet-stream" },
136         { "ld", "application/octet-stream" },
137 };
138
139 struct http_uri_redirect {
140         AST_LIST_ENTRY(http_uri_redirect) entry;
141         char *dest;
142         char target[0];
143 };
144
145 static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
146
147 static const struct ast_cfhttp_methods_text {
148         enum ast_http_method method;
149         const char *text;
150 } ast_http_methods_text[] = {
151         { AST_HTTP_UNKNOWN,     "UNKNOWN" },
152         { AST_HTTP_GET,         "GET" },
153         { AST_HTTP_POST,        "POST" },
154         { AST_HTTP_HEAD,        "HEAD" },
155         { AST_HTTP_PUT,         "PUT" },
156         { AST_HTTP_DELETE,      "DELETE" },
157         { AST_HTTP_OPTIONS,     "OPTIONS" },
158 };
159
160 const char *ast_get_http_method(enum ast_http_method method)
161 {
162         int x;
163
164         for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
165                 if (ast_http_methods_text[x].method == method) {
166                         return ast_http_methods_text[x].text;
167                 }
168         }
169
170         return NULL;
171 }
172
173 const char *ast_http_ftype2mtype(const char *ftype)
174 {
175         int x;
176
177         if (ftype) {
178                 for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
179                         if (!strcasecmp(ftype, mimetypes[x].ext)) {
180                                 return mimetypes[x].mtype;
181                         }
182                 }
183         }
184         return NULL;
185 }
186
187 uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
188 {
189         uint32_t mngid = 0;
190         struct ast_variable *v, *cookies;
191
192         cookies = ast_http_get_cookies(headers);
193         for (v = cookies; v; v = v->next) {
194                 if (!strcasecmp(v->name, "mansession_id")) {
195                         sscanf(v->value, "%30x", &mngid);
196                         break;
197                 }
198         }
199         if (cookies) {
200                 ast_variables_destroy(cookies);
201         }
202         return mngid;
203 }
204
205 void ast_http_prefix(char *buf, int len)
206 {
207         if (buf) {
208                 ast_copy_string(buf, prefix, len);
209         }
210 }
211
212 static int static_callback(struct ast_tcptls_session_instance *ser,
213         const struct ast_http_uri *urih, const char *uri,
214         enum ast_http_method method, struct ast_variable *get_vars,
215         struct ast_variable *headers)
216 {
217         char *path;
218         const char *ftype;
219         const char *mtype;
220         char wkspace[80];
221         struct stat st;
222         int len;
223         int fd;
224         struct ast_str *http_header;
225         struct timeval tv;
226         struct ast_tm tm;
227         char timebuf[80], etag[23];
228         struct ast_variable *v;
229         int not_modified = 0;
230
231         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
232                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
233                 return -1;
234         }
235
236         /* Yuck.  I'm not really sold on this, but if you don't deliver static content it makes your configuration
237            substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
238         if (!enablestatic || ast_strlen_zero(uri)) {
239                 goto out403;
240         }
241
242         /* Disallow any funny filenames at all (checking first character only??) */
243         if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
244                 goto out403;
245         }
246
247         if (strstr(uri, "/..")) {
248                 goto out403;
249         }
250
251         if ((ftype = strrchr(uri, '.'))) {
252                 ftype++;
253         }
254
255         if (!(mtype = ast_http_ftype2mtype(ftype))) {
256                 snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
257                 mtype = wkspace;
258         }
259
260         /* Cap maximum length */
261         if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
262                 goto out403;
263         }
264
265         path = ast_alloca(len);
266         sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
267         if (stat(path, &st)) {
268                 goto out404;
269         }
270
271         if (S_ISDIR(st.st_mode)) {
272                 goto out404;
273         }
274
275         if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
276                 goto out403;
277         }
278
279         fd = open(path, O_RDONLY);
280         if (fd < 0) {
281                 goto out403;
282         }
283
284         /* make "Etag:" http header value */
285         snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
286
287         /* make "Last-Modified:" http header value */
288         tv.tv_sec = st.st_mtime;
289         tv.tv_usec = 0;
290         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
291
292         /* check received "If-None-Match" request header and Etag value for file */
293         for (v = headers; v; v = v->next) {
294                 if (!strcasecmp(v->name, "If-None-Match")) {
295                         if (!strcasecmp(v->value, etag)) {
296                                 not_modified = 1;
297                         }
298                         break;
299                 }
300         }
301
302         if ( (http_header = ast_str_create(255)) == NULL) {
303                 close(fd);
304                 return -1;
305         }
306
307         ast_str_set(&http_header, 0, "Content-type: %s\r\n"
308                 "ETag: %s\r\n"
309                 "Last-Modified: %s\r\n",
310                 mtype,
311                 etag,
312                 timebuf);
313
314         /* ast_http_send() frees http_header, so we don't need to do it before returning */
315         if (not_modified) {
316                 ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
317         } else {
318                 ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
319         }
320         close(fd);
321         return 0;
322
323 out404:
324         ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
325         return -1;
326
327 out403:
328         ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
329         return -1;
330 }
331
332 static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
333         const struct ast_http_uri *urih, const char *uri,
334         enum ast_http_method method, struct ast_variable *get_vars,
335         struct ast_variable *headers)
336 {
337         struct ast_str *out;
338         struct ast_variable *v, *cookies = NULL;
339
340         if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
341                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
342                 return -1;
343         }
344
345         if ( (out = ast_str_create(512)) == NULL) {
346                 return -1;
347         }
348
349         ast_str_append(&out, 0,
350                 "<title>Asterisk HTTP Status</title>\r\n"
351                 "<body bgcolor=\"#ffffff\">\r\n"
352                 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
353                 "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
354
355         ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
356         ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
357                        ast_sockaddr_stringify_addr(&http_desc.old_address));
358         ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
359                        ast_sockaddr_stringify_port(&http_desc.old_address));
360         if (http_tls_cfg.enabled) {
361                 ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
362                                ast_sockaddr_stringify_port(&https_desc.old_address));
363         }
364         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
365         for (v = get_vars; v; v = v->next) {
366                 ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
367         }
368         ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
369
370         cookies = ast_http_get_cookies(headers);
371         for (v = cookies; v; v = v->next) {
372                 ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
373         }
374         ast_variables_destroy(cookies);
375
376         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");
377         ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
378         return 0;
379 }
380
381 static struct ast_http_uri statusuri = {
382         .callback = httpstatus_callback,
383         .description = "Asterisk HTTP General Status",
384         .uri = "httpstatus",
385         .has_subtree = 0,
386         .data = NULL,
387         .key = __FILE__,
388 };
389
390 static struct ast_http_uri staticuri = {
391         .callback = static_callback,
392         .description = "Asterisk HTTP Static Delivery",
393         .uri = "static",
394         .has_subtree = 1,
395         .data = NULL,
396         .key= __FILE__,
397 };
398
399
400 /* send http/1.1 response */
401 /* free content variable and close socket*/
402 void ast_http_send(struct ast_tcptls_session_instance *ser,
403         enum ast_http_method method, int status_code, const char *status_title,
404         struct ast_str *http_header, struct ast_str *out, const int fd,
405         unsigned int static_content)
406 {
407         struct timeval now = ast_tvnow();
408         struct ast_tm tm;
409         char timebuf[80];
410         int content_length = 0;
411
412         if (!ser || 0 == ser->f) {
413                 return;
414         }
415
416         ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
417
418         /* calc content length */
419         if (out) {
420                 content_length += strlen(ast_str_buffer(out));
421         }
422
423         if (fd) {
424                 content_length += lseek(fd, 0, SEEK_END);
425                 lseek(fd, 0, SEEK_SET);
426         }
427
428         /* send http header */
429         fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
430                 "Server: Asterisk/%s\r\n"
431                 "Date: %s\r\n"
432                 "Connection: close\r\n"
433                 "%s"
434                 "Content-Length: %d\r\n"
435                 "%s"
436                 "\r\n",
437                 status_code, status_title ? status_title : "OK",
438                 ast_get_version(),
439                 timebuf,
440                 static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
441                 content_length,
442                 http_header ? ast_str_buffer(http_header) : ""
443                 );
444
445         /* send content */
446         if (method != AST_HTTP_HEAD || status_code >= 400) {
447                 if (out) {
448                         fprintf(ser->f, "%s", ast_str_buffer(out));
449                 }
450
451                 if (fd) {
452                         char buf[256];
453                         int len;
454                         while ((len = read(fd, buf, sizeof(buf))) > 0) {
455                                 if (fwrite(buf, len, 1, ser->f) != 1) {
456                                         ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
457                                         break;
458                                 }
459                         }
460                 }
461         }
462
463         if (http_header) {
464                 ast_free(http_header);
465         }
466         if (out) {
467                 ast_free(out);
468         }
469
470         fclose(ser->f);
471         ser->f = 0;
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  * get post variables from client Request Entity-Body, if content type is
612  * application/x-www-form-urlencoded
613  */
614 struct ast_variable *ast_http_get_post_vars(
615         struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
616 {
617         int content_length = 0;
618         struct ast_variable *v, *post_vars=NULL, *prev = NULL;
619         char *buf, *var, *val;
620         int res;
621
622         for (v = headers; v; v = v->next) {
623                 if (!strcasecmp(v->name, "Content-Type")) {
624                         if (strcasecmp(v->value, "application/x-www-form-urlencoded")) {
625                                 return NULL;
626                         }
627                         break;
628                 }
629         }
630
631         for (v = headers; v; v = v->next) {
632                 if (!strcasecmp(v->name, "Content-Length")) {
633                         content_length = atoi(v->value);
634                         break;
635                 }
636         }
637
638         if (content_length <= 0) {
639                 return NULL;
640         }
641
642         if (content_length > MAX_POST_CONTENT - 1) {
643                 ast_log(LOG_WARNING, "Excessively long HTTP content. %d is greater than our max of %d\n",
644                                 content_length, MAX_POST_CONTENT);
645                 ast_http_send(ser, AST_HTTP_POST, 413, "Request Entity Too Large", NULL, NULL, 0, 0);
646                 return NULL;
647         }
648
649         buf = ast_malloc(content_length + 1);
650         if (!buf) {
651                 return NULL;
652         }
653
654         res = fread(buf, 1, content_length, ser->f);
655         if (res < content_length) {
656                 /* Error, distinguishable by ferror() or feof(), but neither
657                  * is good. */
658                 goto done;
659         }
660         buf[content_length] = '\0';
661
662         while ((val = strsep(&buf, "&"))) {
663                 var = strsep(&val, "=");
664                 if (val) {
665                         ast_uri_decode(val, ast_uri_http_legacy);
666                 } else  {
667                         val = "";
668                 }
669                 ast_uri_decode(var, ast_uri_http_legacy);
670                 if ((v = ast_variable_new(var, val, ""))) {
671                         if (post_vars) {
672                                 prev->next = v;
673                         } else {
674                                 post_vars = v;
675                         }
676                         prev = v;
677                 }
678         }
679         
680 done:
681         ast_free(buf);
682         return post_vars;
683 }
684
685 static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
686         enum ast_http_method method, struct ast_variable *headers)
687 {
688         char *c;
689         int res = -1;
690         char *params = uri;
691         struct ast_http_uri *urih = NULL;
692         int l;
693         struct ast_variable *get_vars = NULL, *v, *prev = NULL;
694         struct http_uri_redirect *redirect;
695
696         ast_debug(2, "HTTP Request URI is %s \n", uri);
697
698         strsep(&params, "?");
699         /* Extract arguments from the request and store them in variables. */
700         if (params) {
701                 char *var, *val;
702
703                 while ((val = strsep(&params, "&"))) {
704                         var = strsep(&val, "=");
705                         if (val) {
706                                 ast_uri_decode(val, ast_uri_http_legacy);
707                         } else  {
708                                 val = "";
709                         }
710                         ast_uri_decode(var, ast_uri_http_legacy);
711                         if ((v = ast_variable_new(var, val, ""))) {
712                                 if (get_vars) {
713                                         prev->next = v;
714                                 } else {
715                                         get_vars = v;
716                                 }
717                                 prev = v;
718                         }
719                 }
720         }
721
722         AST_RWLIST_RDLOCK(&uri_redirects);
723         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
724                 if (!strcasecmp(uri, redirect->target)) {
725                         struct ast_str *http_header = ast_str_create(128);
726                         ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
727                         ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
728
729                         break;
730                 }
731         }
732         AST_RWLIST_UNLOCK(&uri_redirects);
733         if (redirect) {
734                 goto cleanup;
735         }
736
737         /* We want requests to start with the (optional) prefix and '/' */
738         l = strlen(prefix);
739         if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
740                 uri += l + 1;
741                 /* scan registered uris to see if we match one. */
742                 AST_RWLIST_RDLOCK(&uris);
743                 AST_RWLIST_TRAVERSE(&uris, urih, entry) {
744                         ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
745                         l = strlen(urih->uri);
746                         c = uri + l;    /* candidate */
747                         if (strncasecmp(urih->uri, uri, l) /* no match */
748                             || (*c && *c != '/')) { /* substring */
749                                 continue;
750                         }
751                         if (*c == '/') {
752                                 c++;
753                         }
754                         if (!*c || urih->has_subtree) {
755                                 uri = c;
756                                 break;
757                         }
758                 }
759                 AST_RWLIST_UNLOCK(&uris);
760         }
761         if (urih) {
762                 if (!urih->no_decode_uri) {
763                         ast_uri_decode(uri, ast_uri_http_legacy);
764                 }
765                 res = urih->callback(ser, urih, uri, method, get_vars, headers);
766         } else {
767                 ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
768         }
769
770 cleanup:
771         ast_variables_destroy(get_vars);
772         return res;
773 }
774
775 #ifdef DO_SSL
776 #if defined(HAVE_FUNOPEN)
777 #define HOOK_T int
778 #define LEN_T int
779 #else
780 #define HOOK_T ssize_t
781 #define LEN_T size_t
782 #endif
783
784 /*!
785  * replacement read/write functions for SSL support.
786  * We use wrappers rather than SSL_read/SSL_write directly so
787  * we can put in some debugging.
788  */
789 /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
790 {
791         int i = SSL_read(cookie, buf, len-1);
792 #if 0
793         if (i >= 0)
794                 buf[i] = '\0';
795         ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
796 #endif
797         return i;
798 }
799
800 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
801 {
802 #if 0
803         char *s = ast_alloca(len+1);
804         strncpy(s, buf, len);
805         s[len] = '\0';
806         ast_verbose("ssl write size %d <%s>\n", (int)len, s);
807 #endif
808         return SSL_write(cookie, buf, len);
809 }
810
811 static int ssl_close(void *cookie)
812 {
813         close(SSL_get_fd(cookie));
814         SSL_shutdown(cookie);
815         SSL_free(cookie);
816         return 0;
817 }*/
818 #endif  /* DO_SSL */
819
820 static struct ast_variable *parse_cookies(char *cookies)
821 {
822         char *cur;
823         struct ast_variable *vars = NULL, *var;
824
825         while ((cur = strsep(&cookies, ";"))) {
826                 char *name, *val;
827
828                 name = val = cur;
829                 strsep(&val, "=");
830
831                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
832                         continue;
833                 }
834
835                 name = ast_strip(name);
836                 val = ast_strip_quoted(val, "\"", "\"");
837
838                 if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
839                         continue;
840                 }
841
842                 ast_debug(1, "HTTP Cookie, Name: '%s'  Value: '%s'\n", name, val);
843
844                 var = ast_variable_new(name, val, __FILE__);
845                 var->next = vars;
846                 vars = var;
847         }
848
849         return vars;
850 }
851
852 /* get cookie from Request headers */
853 struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
854 {
855         struct ast_variable *v, *cookies=NULL;
856
857         for (v = headers; v; v = v->next) {
858                 if (!strncasecmp(v->name, "Cookie", 6)) {
859                         char *tmp = ast_strdupa(v->value);
860                         if (cookies) {
861                                 ast_variables_destroy(cookies);
862                         }
863
864                         cookies = parse_cookies(tmp);
865                 }
866         }
867         return cookies;
868 }
869
870
871 static void *httpd_helper_thread(void *data)
872 {
873         char buf[4096];
874         char header_line[4096];
875         struct ast_tcptls_session_instance *ser = data;
876         struct ast_variable *headers = NULL;
877         struct ast_variable *tail = headers;
878         char *uri, *method;
879         enum ast_http_method http_method = AST_HTTP_UNKNOWN;
880
881         if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
882                 goto done;
883         }
884
885         if (!fgets(buf, sizeof(buf), ser->f)) {
886                 goto done;
887         }
888
889         /* Get method */
890         method = ast_skip_blanks(buf);
891         uri = ast_skip_nonblanks(method);
892         if (*uri) {
893                 *uri++ = '\0';
894         }
895
896         if (!strcasecmp(method,"GET")) {
897                 http_method = AST_HTTP_GET;
898         } else if (!strcasecmp(method,"POST")) {
899                 http_method = AST_HTTP_POST;
900         } else if (!strcasecmp(method,"HEAD")) {
901                 http_method = AST_HTTP_HEAD;
902         } else if (!strcasecmp(method,"PUT")) {
903                 http_method = AST_HTTP_PUT;
904         } else if (!strcasecmp(method,"DELETE")) {
905                 http_method = AST_HTTP_DELETE;
906         } else if (!strcasecmp(method,"OPTIONS")) {
907                 http_method = AST_HTTP_OPTIONS;
908         }
909
910         uri = ast_skip_blanks(uri);     /* Skip white space */
911
912         if (*uri) {                     /* terminate at the first blank */
913                 char *c = ast_skip_nonblanks(uri);
914
915                 if (*c) {
916                         *c = '\0';
917                 }
918         }
919
920         /* process "Request Headers" lines */
921         while (fgets(header_line, sizeof(header_line), ser->f)) {
922                 char *name, *value;
923
924                 /* Trim trailing characters */
925                 ast_trim_blanks(header_line);
926                 if (ast_strlen_zero(header_line)) {
927                         break;
928                 }
929
930                 value = header_line;
931                 name = strsep(&value, ":");
932                 if (!value) {
933                         continue;
934                 }
935
936                 value = ast_skip_blanks(value);
937                 if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
938                         continue;
939                 }
940
941                 ast_trim_blanks(name);
942
943                 if (!headers) {
944                         headers = ast_variable_new(name, value, __FILE__);
945                         tail = headers;
946                 } else {
947                         tail->next = ast_variable_new(name, value, __FILE__);
948                         tail = tail->next;
949                 }
950         }
951
952         if (!*uri) {
953                 ast_http_error(ser, 400, "Bad Request", "Invalid Request");
954                 goto done;
955         }
956
957         handle_uri(ser, uri, http_method, headers);
958
959 done:
960         ast_atomic_fetchadd_int(&session_count, -1);
961
962         /* clean up all the header information */
963         if (headers) {
964                 ast_variables_destroy(headers);
965         }
966
967         if (ser->f) {
968                 fclose(ser->f);
969         }
970         ao2_ref(ser, -1);
971         ser = NULL;
972         return NULL;
973 }
974
975 /*!
976  * \brief Add a new URI redirect
977  * The entries in the redirect list are sorted by length, just like the list
978  * of URI handlers.
979  */
980 static void add_redirect(const char *value)
981 {
982         char *target, *dest;
983         struct http_uri_redirect *redirect, *cur;
984         unsigned int target_len;
985         unsigned int total_len;
986
987         dest = ast_strdupa(value);
988         dest = ast_skip_blanks(dest);
989         target = strsep(&dest, " ");
990         target = ast_skip_blanks(target);
991         target = strsep(&target, " "); /* trim trailing whitespace */
992
993         if (!dest) {
994                 ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
995                 return;
996         }
997
998         target_len = strlen(target) + 1;
999         total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
1000
1001         if (!(redirect = ast_calloc(1, total_len))) {
1002                 return;
1003         }
1004         redirect->dest = redirect->target + target_len;
1005         strcpy(redirect->target, target);
1006         strcpy(redirect->dest, dest);
1007
1008         AST_RWLIST_WRLOCK(&uri_redirects);
1009
1010         target_len--; /* So we can compare directly with strlen() */
1011         if (AST_RWLIST_EMPTY(&uri_redirects)
1012                 || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
1013                 AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
1014                 AST_RWLIST_UNLOCK(&uri_redirects);
1015
1016                 return;
1017         }
1018
1019         AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
1020                 if (AST_RWLIST_NEXT(cur, entry)
1021                         && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
1022                         AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
1023                         AST_RWLIST_UNLOCK(&uri_redirects);
1024                         return;
1025                 }
1026         }
1027
1028         AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
1029
1030         AST_RWLIST_UNLOCK(&uri_redirects);
1031 }
1032
1033 static int __ast_http_load(int reload)
1034 {
1035         struct ast_config *cfg;
1036         struct ast_variable *v;
1037         int enabled=0;
1038         int newenablestatic=0;
1039         char newprefix[MAX_PREFIX] = "";
1040         struct http_uri_redirect *redirect;
1041         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1042         uint32_t bindport = DEFAULT_PORT;
1043         struct ast_sockaddr *addrs = NULL;
1044         int num_addrs = 0;
1045         int http_tls_was_enabled = 0;
1046
1047         cfg = ast_config_load2("http.conf", "http", config_flags);
1048         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1049                 return 0;
1050         }
1051
1052         http_tls_was_enabled = (reload && http_tls_cfg.enabled);
1053
1054         http_tls_cfg.enabled = 0;
1055         if (http_tls_cfg.certfile) {
1056                 ast_free(http_tls_cfg.certfile);
1057         }
1058         http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
1059
1060         if (http_tls_cfg.pvtfile) {
1061                 ast_free(http_tls_cfg.pvtfile);
1062         }
1063         http_tls_cfg.pvtfile = ast_strdup("");
1064
1065         if (http_tls_cfg.cipher) {
1066                 ast_free(http_tls_cfg.cipher);
1067         }
1068         http_tls_cfg.cipher = ast_strdup("");
1069
1070         AST_RWLIST_WRLOCK(&uri_redirects);
1071         while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
1072                 ast_free(redirect);
1073         }
1074         AST_RWLIST_UNLOCK(&uri_redirects);
1075
1076         ast_sockaddr_setnull(&https_desc.local_address);
1077
1078         if (cfg) {
1079                 v = ast_variable_browse(cfg, "general");
1080                 for (; v; v = v->next) {
1081
1082                         /* read tls config options while preventing unsupported options from being set */
1083                         if (strcasecmp(v->name, "tlscafile")
1084                                 && strcasecmp(v->name, "tlscapath")
1085                                 && strcasecmp(v->name, "tlscadir")
1086                                 && strcasecmp(v->name, "tlsverifyclient")
1087                                 && strcasecmp(v->name, "tlsdontverifyserver")
1088                                 && strcasecmp(v->name, "tlsclientmethod")
1089                                 && strcasecmp(v->name, "sslclientmethod")
1090                                 && strcasecmp(v->name, "tlscipher")
1091                                 && strcasecmp(v->name, "sslcipher")
1092                                 && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
1093                                 continue;
1094                         }
1095
1096                         if (!strcasecmp(v->name, "enabled")) {
1097                                 enabled = ast_true(v->value);
1098                         } else if (!strcasecmp(v->name, "enablestatic")) {
1099                                 newenablestatic = ast_true(v->value);
1100                         } else if (!strcasecmp(v->name, "bindport")) {
1101                                 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT, &bindport, DEFAULT_PORT, 0, 65535)) {
1102                                         ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %"PRId32, v->value, DEFAULT_PORT);
1103                                 }
1104                         } else if (!strcasecmp(v->name, "bindaddr")) {
1105                                 if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
1106                                         ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
1107                                 }
1108                         } else if (!strcasecmp(v->name, "prefix")) {
1109                                 if (!ast_strlen_zero(v->value)) {
1110                                         newprefix[0] = '/';
1111                                         ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
1112                                 } else {
1113                                         newprefix[0] = '\0';
1114                                 }
1115                         } else if (!strcasecmp(v->name, "redirect")) {
1116                                 add_redirect(v->value);
1117                         } else if (!strcasecmp(v->name, "sessionlimit")) {
1118                                 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
1119                                                         &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
1120                                         ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
1121                                                         v->name, v->value, v->lineno);
1122                                 }
1123                         } else {
1124                                 ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
1125                         }
1126                 }
1127
1128                 ast_config_destroy(cfg);
1129         }
1130
1131         if (strcmp(prefix, newprefix)) {
1132                 ast_copy_string(prefix, newprefix, sizeof(prefix));
1133         }
1134         enablestatic = newenablestatic;
1135
1136         if (num_addrs && enabled) {
1137                 int i;
1138                 for (i = 0; i < num_addrs; ++i) {
1139                         ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
1140                         if (!ast_sockaddr_port(&http_desc.local_address)) {
1141                                 ast_sockaddr_set_port(&http_desc.local_address, bindport);
1142                         }
1143                         ast_tcptls_server_start(&http_desc);
1144                         if (http_desc.accept_fd == -1) {
1145                                 ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
1146                                 ast_sockaddr_setnull(&http_desc.local_address);
1147                         } else {
1148                                 ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
1149                                 break;
1150                         }
1151                 }
1152                 /* When no specific TLS bindaddr is specified, we just use
1153                  * the non-TLS bindaddress here.
1154                  */
1155                 if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
1156                         ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
1157                         /* Of course, we can't use the same port though.
1158                          * Since no bind address was specified, we just use the
1159                          * default TLS port
1160                          */
1161                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1162                 }
1163         }
1164         if (http_tls_was_enabled && !http_tls_cfg.enabled) {
1165                 ast_tcptls_server_stop(&https_desc);
1166         } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
1167                 /* We can get here either because a TLS-specific address was specified
1168                  * or because we copied the non-TLS address here. In the case where
1169                  * we read an explicit address from the config, there may have been
1170                  * no port specified, so we'll just use the default TLS port.
1171                  */
1172                 if (!ast_sockaddr_port(&https_desc.local_address)) {
1173                         ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
1174                 }
1175                 if (ast_ssl_setup(https_desc.tls_cfg)) {
1176                         ast_tcptls_server_start(&https_desc);
1177                 }
1178         }
1179
1180         return 0;
1181 }
1182
1183 static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1184 {
1185         struct ast_http_uri *urih;
1186         struct http_uri_redirect *redirect;
1187
1188         switch (cmd) {
1189         case CLI_INIT:
1190                 e->command = "http show status";
1191                 e->usage =
1192                         "Usage: http show status\n"
1193                         "       Lists status of internal HTTP engine\n";
1194                 return NULL;
1195         case CLI_GENERATE:
1196                 return NULL;
1197         }
1198
1199         if (a->argc != 3) {
1200                 return CLI_SHOWUSAGE;
1201         }
1202         ast_cli(a->fd, "HTTP Server Status:\n");
1203         ast_cli(a->fd, "Prefix: %s\n", prefix);
1204         if (ast_sockaddr_isnull(&http_desc.old_address)) {
1205                 ast_cli(a->fd, "Server Disabled\n\n");
1206         } else {
1207                 ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
1208                         ast_sockaddr_stringify(&http_desc.old_address));
1209                 if (http_tls_cfg.enabled) {
1210                         ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
1211                                 ast_sockaddr_stringify(&https_desc.old_address));
1212                 }
1213         }
1214
1215         ast_cli(a->fd, "Enabled URI's:\n");
1216         AST_RWLIST_RDLOCK(&uris);
1217         if (AST_RWLIST_EMPTY(&uris)) {
1218                 ast_cli(a->fd, "None.\n");
1219         } else {
1220                 AST_RWLIST_TRAVERSE(&uris, urih, entry)
1221                         ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
1222         }
1223         AST_RWLIST_UNLOCK(&uris);
1224
1225         ast_cli(a->fd, "\nEnabled Redirects:\n");
1226         AST_RWLIST_RDLOCK(&uri_redirects);
1227         AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
1228                 ast_cli(a->fd, "  %s => %s\n", redirect->target, redirect->dest);
1229         if (AST_RWLIST_EMPTY(&uri_redirects)) {
1230                 ast_cli(a->fd, "  None.\n");
1231         }
1232         AST_RWLIST_UNLOCK(&uri_redirects);
1233
1234         return CLI_SUCCESS;
1235 }
1236
1237 int ast_http_reload(void)
1238 {
1239         return __ast_http_load(1);
1240 }
1241
1242 static struct ast_cli_entry cli_http[] = {
1243         AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
1244 };
1245
1246 static void http_shutdown(void)
1247 {
1248         ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
1249 }
1250
1251 int ast_http_init(void)
1252 {
1253         ast_http_uri_link(&statusuri);
1254         ast_http_uri_link(&staticuri);
1255         ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
1256         ast_register_atexit(http_shutdown);
1257
1258         return __ast_http_load(0);
1259 }