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