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