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