2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
23 * This program implements a tiny http server supporting the "get" method
24 * only and was inspired by micro-httpd by Jef Poskanzer
27 #include <sys/types.h>
33 #include <netinet/in.h>
35 #include <sys/socket.h>
37 #include <sys/signal.h>
38 #include <arpa/inet.h>
44 #include "asterisk/cli.h"
45 #include "asterisk/http.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/strings.h"
48 #include "asterisk/options.h"
49 #include "asterisk/config.h"
52 #define DEFAULT_PREFIX "asterisk"
54 struct ast_http_server_instance {
57 struct sockaddr_in requestor;
58 ast_http_callback callback;
61 static struct ast_http_uri *uris;
63 static int httpfd = -1;
64 static pthread_t master = AST_PTHREADT_NULL;
65 static char prefix[MAX_PREFIX];
66 static int prefix_len = 0;
67 static struct sockaddr_in oldsin;
68 static int enablestatic=0;
70 /* Limit the kinds of files we're willing to serve up */
75 { "png", "image/png" },
76 { "jpg", "image/jpeg" },
77 { "js", "application/x-javascript" },
78 { "wav", "audio/x-wav" },
79 { "mp3", "audio/mpeg" },
82 static char *ftype2mtype(const char *ftype, char *wkspace, int wkspacelen)
86 for (x=0;x<sizeof(mimetypes) / sizeof(mimetypes[0]); x++) {
87 if (!strcasecmp(ftype, mimetypes[x].ext))
88 return mimetypes[x].mtype;
91 snprintf(wkspace, wkspacelen, "text/%s", ftype ? ftype : "plain");
95 static char *static_callback(struct sockaddr_in *req, const char *uri, struct ast_variable *vars, int *status, char **title, int *contentlength)
107 /* Yuck. I'm not really sold on this, but if you don't deliver static content it makes your configuration
108 substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
109 if (!enablestatic || ast_strlen_zero(uri))
111 /* Disallow any funny filenames at all */
112 if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0]))
114 if (strstr(uri, "/.."))
117 if ((ftype = strrchr(uri, '.')))
119 mtype=ftype2mtype(ftype, wkspace, sizeof(wkspace));
121 /* Cap maximum length */
122 len = strlen(uri) + strlen(ast_config_AST_VAR_DIR) + strlen("/static-http/") + 5;
127 sprintf(path, "%s/static-http/%s", ast_config_AST_VAR_DIR, uri);
130 if (S_ISDIR(st.st_mode))
132 fd = open(path, O_RDONLY);
136 len = st.st_size + strlen(mtype) + 40;
141 sprintf(c, "Content-type: %s\r\n\r\n", mtype);
143 *contentlength = read(fd, c, st.st_size);
144 if (*contentlength < 0) {
154 *title = strdup("Not Found");
155 return ast_http_error(404, "Not Found", NULL, "Nothing to see here. Move along.");
159 *title = strdup("Access Denied");
160 return ast_http_error(403, "Access Denied", NULL, "Sorry, I cannot let you do that, Dave.");
164 static char *httpstatus_callback(struct sockaddr_in *req, const char *uri, struct ast_variable *vars, int *status, char **title, int *contentlength)
167 size_t reslen = sizeof(result);
169 struct ast_variable *v;
170 char iabuf[INET_ADDRSTRLEN];
172 ast_build_string(&c, &reslen,
174 "<title>Asterisk HTTP Status</title>\r\n"
175 "<body bgcolor=\"#ffffff\">\r\n"
176 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
177 "<h2> Asterisk™ HTTP Status</h2></td></tr>\r\n");
179 ast_build_string(&c, &reslen, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
180 ast_build_string(&c, &reslen, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
181 ast_inet_ntoa(iabuf, sizeof(iabuf), oldsin.sin_addr));
182 ast_build_string(&c, &reslen, "<tr><td><i>Bind Port</i></td><td><b>%d</b></td></tr>\r\n",
183 ntohs(oldsin.sin_port));
184 ast_build_string(&c, &reslen, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
187 if (strncasecmp(v->name, "cookie_", 7))
188 ast_build_string(&c, &reslen, "<tr><td><i>Submitted Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
191 ast_build_string(&c, &reslen, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
194 if (!strncasecmp(v->name, "cookie_", 7))
195 ast_build_string(&c, &reslen, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
198 ast_build_string(&c, &reslen, "</table><center><font size=\"-1\"><i>Asterisk and Digium are registered trademarks of Digium, Inc.</i></font></center></body>\r\n");
199 return strdup(result);
202 static struct ast_http_uri statusuri = {
203 .callback = httpstatus_callback,
204 .description = "Asterisk HTTP General Status",
209 static struct ast_http_uri staticuri = {
210 .callback = static_callback,
211 .description = "Asterisk HTTP Static Delivery",
216 char *ast_http_error(int status, const char *title, const char *extra_header, const char *text)
220 "Content-type: text/html\r\n"
223 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
225 "<title>%d %s</title>\r\n"
230 "<address>Asterisk Server</address>\r\n"
231 "</body></html>\r\n",
232 (extra_header ? extra_header : ""), status, title, title, text);
236 int ast_http_uri_link(struct ast_http_uri *urih)
238 struct ast_http_uri *prev=uris;
239 if (!uris || strlen(uris->uri) <= strlen(urih->uri)) {
243 while (prev->next && (strlen(prev->next->uri) > strlen(urih->uri)))
246 urih->next = prev->next;
252 void ast_http_uri_unlink(struct ast_http_uri *urih)
254 struct ast_http_uri *prev = uris;
261 if (prev->next == urih) {
262 prev->next = urih->next;
269 static char *handle_uri(struct sockaddr_in *sin, char *uri, int *status, char **title, int *contentlength, struct ast_variable **cookies)
276 struct ast_http_uri *urih=NULL;
278 struct ast_variable *vars=NULL, *v, *prev = NULL;
281 params = strchr(uri, '?');
285 while ((var = strsep(¶ms, "&"))) {
286 val = strchr(var, '=');
294 if ((v = ast_variable_new(var, val))) {
304 prev->next = *cookies;
309 if (!strncasecmp(uri, prefix, prefix_len)) {
311 if (!*uri || (*uri == '/')) {
316 len = strlen(urih->uri);
317 if (!strncasecmp(urih->uri, uri, len)) {
318 if (!uri[len] || uri[len] == '/') {
322 if (!*turi || urih->has_subtree) {
333 c = urih->callback(sin, uri, vars, status, title, contentlength);
334 ast_variables_destroy(vars);
335 } else if (ast_strlen_zero(uri) && ast_strlen_zero(prefix)) {
336 /* Special case: If no prefix, and no URI, send to /static/index.html */
337 c = ast_http_error(302, "Moved Temporarily", "Location: /static/index.html\r\n", "This is not the page you are looking for...");
339 *title = strdup("Moved Temporarily");
341 c = ast_http_error(404, "Not Found", NULL, "The requested URL was not found on this serer.");
343 *title = strdup("Not Found");
348 static void *ast_httpd_helper_thread(void *data)
353 struct ast_http_server_instance *ser = data;
354 struct ast_variable *var, *prev=NULL, *vars=NULL;
355 char *uri, *c, *title=NULL;
357 int status = 200, contentlength = 0;
360 if (fgets(buf, sizeof(buf), ser->f)) {
363 while(*uri && (*uri > 32)) uri++;
369 /* Skip white space */
370 while (*uri && (*uri < 33)) uri++;
374 while (*c && (*c > 32)) c++;
380 while (fgets(cookie, sizeof(cookie), ser->f)) {
381 /* Trim trailing characters */
382 while(!ast_strlen_zero(cookie) && (cookie[strlen(cookie) - 1] < 33)) {
383 cookie[strlen(cookie) - 1] = '\0';
385 if (ast_strlen_zero(cookie))
387 if (!strncasecmp(cookie, "Cookie: ", 8)) {
389 vval = strchr(vname, '=');
391 /* Ditch the = and the quotes */
397 vval[strlen(vval) - 1] = '\0';
398 var = ast_variable_new(vname, vval);
411 if (!strcasecmp(buf, "get"))
412 c = handle_uri(&ser->requestor, uri, &status, &title, &contentlength, &vars);
414 c = ast_http_error(501, "Not Implemented", NULL, "Attempt to use unimplemented / unsupported method");\
416 c = ast_http_error(400, "Bad Request", NULL, "Invalid Request");
418 /* If they aren't mopped up already, clean up the cookies */
420 ast_variables_destroy(vars);
423 c = ast_http_error(500, "Internal Error", NULL, "Internal Server Error");
426 strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&t));
427 ast_cli(ser->fd, "HTTP/1.1 %d %s\r\n", status, title ? title : "OK");
428 ast_cli(ser->fd, "Server: Asterisk\r\n");
429 ast_cli(ser->fd, "Date: %s\r\n", timebuf);
430 ast_cli(ser->fd, "Connection: close\r\n");
433 tmp = strstr(c, "\r\n\r\n");
435 ast_cli(ser->fd, "Content-length: %d\r\n", contentlength);
436 write(ser->fd, c, (tmp + 4 - c));
437 write(ser->fd, tmp + 4, contentlength);
440 ast_cli(ser->fd, "%s", c);
451 static void *http_root(void *data)
454 struct sockaddr_in sin;
456 struct ast_http_server_instance *ser;
459 ast_wait_for_input(httpfd, -1);
460 sinlen = sizeof(sin);
461 fd = accept(httpfd, (struct sockaddr *)&sin, &sinlen);
463 if ((errno != EAGAIN) && (errno != EINTR))
464 ast_log(LOG_WARNING, "Accept failed: %s\n", strerror(errno));
467 ser = ast_calloc(1, sizeof(*ser));
470 memcpy(&ser->requestor, &sin, sizeof(ser->requestor));
471 if ((ser->f = fdopen(ser->fd, "w+"))) {
472 if (ast_pthread_create(&launched, NULL, ast_httpd_helper_thread, ser)) {
473 ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
478 ast_log(LOG_WARNING, "fdopen failed!\n");
490 char *ast_http_setcookie(const char *var, const char *val, int expires, char *buf, int buflen)
494 ast_build_string(&c, &buflen, "Set-Cookie: %s=\"%s\"; Version=\"1\"", var, val);
496 ast_build_string(&c, &buflen, "; Max-Age=%d", expires);
497 ast_build_string(&c, &buflen, "\r\n");
502 static void http_server_start(struct sockaddr_in *sin)
504 char iabuf[INET_ADDRSTRLEN];
508 /* Do nothing if nothing has changed */
509 if (!memcmp(&oldsin, sin, sizeof(oldsin))) {
510 ast_log(LOG_DEBUG, "Nothing changed in http\n");
514 memcpy(&oldsin, sin, sizeof(oldsin));
516 /* Shutdown a running server if there is one */
517 if (master != AST_PTHREADT_NULL) {
518 pthread_cancel(master);
519 pthread_kill(master, SIGURG);
520 pthread_join(master, NULL);
526 /* If there's no new server, stop here */
527 if (!sin->sin_family)
531 httpfd = socket(AF_INET, SOCK_STREAM, 0);
533 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
537 setsockopt(httpfd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
538 if (bind(httpfd, (struct sockaddr *)sin, sizeof(*sin))) {
539 ast_log(LOG_NOTICE, "Unable to bind http server to %s:%d: %s\n",
540 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port),
546 if (listen(httpfd, 10)) {
547 ast_log(LOG_NOTICE, "Unable to listen!\n");
552 flags = fcntl(httpfd, F_GETFL);
553 fcntl(httpfd, F_SETFL, flags | O_NONBLOCK);
554 if (ast_pthread_create(&master, NULL, http_root, NULL)) {
555 ast_log(LOG_NOTICE, "Unable to launch http server on %s:%d: %s\n",
556 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port),
563 static int __ast_http_load(int reload)
565 struct ast_config *cfg;
566 struct ast_variable *v;
568 int newenablestatic=0;
569 struct sockaddr_in sin;
571 struct ast_hostent ahp;
572 char newprefix[MAX_PREFIX];
573 memset(&sin, 0, sizeof(sin));
575 strcpy(newprefix, DEFAULT_PREFIX);
576 cfg = ast_config_load("http.conf");
578 v = ast_variable_browse(cfg, "general");
580 if (!strcasecmp(v->name, "enabled"))
581 enabled = ast_true(v->value);
582 else if (!strcasecmp(v->name, "enablestatic"))
583 newenablestatic = ast_true(v->value);
584 else if (!strcasecmp(v->name, "bindport"))
585 sin.sin_port = ntohs(atoi(v->value));
586 else if (!strcasecmp(v->name, "bindaddr")) {
587 if ((hp = ast_gethostbyname(v->value, &ahp))) {
588 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
590 ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
592 } else if (!strcasecmp(v->name, "prefix")) {
593 if (!ast_strlen_zero(v->value)) {
595 ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
603 ast_config_destroy(cfg);
606 sin.sin_family = AF_INET;
607 if (strcmp(prefix, newprefix)) {
608 ast_copy_string(prefix, newprefix, sizeof(prefix));
609 prefix_len = strlen(prefix);
611 enablestatic = newenablestatic;
612 http_server_start(&sin);
616 static int handle_show_http(int fd, int argc, char *argv[])
618 char iabuf[INET_ADDRSTRLEN];
619 struct ast_http_uri *urih;
621 return RESULT_SHOWUSAGE;
622 ast_cli(fd, "HTTP Server Status:\n");
623 ast_cli(fd, "Prefix: %s\n", prefix);
624 if (oldsin.sin_family)
625 ast_cli(fd, "Server Enabled and Bound to %s:%d\n\n",
626 ast_inet_ntoa(iabuf, sizeof(iabuf), oldsin.sin_addr),
627 ntohs(oldsin.sin_port));
629 ast_cli(fd, "Server Disabled\n\n");
630 ast_cli(fd, "Enabled URI's:\n");
633 ast_cli(fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
637 ast_cli(fd, "None.\n");
638 return RESULT_SUCCESS;
641 int ast_http_reload(void)
643 return __ast_http_load(1);
646 static char show_http_help[] =
648 " Shows status of internal HTTP engine\n";
650 static struct ast_cli_entry http_cli[] = {
651 { { "show", "http", NULL }, handle_show_http,
652 "Display HTTP status", show_http_help },
655 int ast_http_init(void)
657 ast_http_uri_link(&statusuri);
658 ast_http_uri_link(&staticuri);
659 ast_cli_register_multiple(http_cli, sizeof(http_cli) / sizeof(http_cli[0]));
660 return __ast_http_load(0);