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