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