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