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