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