Fix build of asterisk again (ahem, committers!)
[asterisk/asterisk.git] / 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
22  *
23  * This program implements a tiny http server supporting the "get" method
24  * only and was inspired by micro-httpd by Jef Poskanzer 
25  */
26
27 #include <sys/types.h>
28 #include <stdio.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <time.h>
32 #include <string.h>
33 #include <netinet/in.h>
34 #include <sys/time.h>
35 #include <sys/socket.h>
36 #include <sys/signal.h>
37 #include <arpa/inet.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <pthread.h>
41
42 #include "asterisk/cli.h"
43 #include "asterisk/http.h"
44 #include "asterisk/utils.h"
45 #include "asterisk/strings.h"
46
47 #define MAX_PREFIX 80
48 #define DEFAULT_PREFIX "asterisk"
49
50 struct ast_http_server_instance {
51         FILE *f;
52         int fd;
53         struct sockaddr_in requestor;
54         ast_http_callback callback;
55 };
56
57 static struct ast_http_uri *uris;
58
59 static int httpfd = -1;
60 static pthread_t master = AST_PTHREADT_NULL;
61 static char prefix[MAX_PREFIX];
62 static int prefix_len = 0;
63 static struct sockaddr_in oldsin;
64
65
66 static char *httpstatus_callback(struct sockaddr_in *req, const char *uri, struct ast_variable *vars, int *status, char **title, int *contentlength)
67 {
68         char result[4096];
69         size_t reslen = sizeof(result);
70         char *c=result;
71         struct ast_variable *v;
72         char iabuf[INET_ADDRSTRLEN];
73
74         ast_build_string(&c, &reslen,
75                 "\r\n"
76                 "<title>Asterisk HTTP Status</title>\r\n"
77                 "<body bgcolor=\"#ffffff\">\r\n"
78                 "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
79                 "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
80
81         ast_build_string(&c, &reslen, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
82         ast_build_string(&c, &reslen, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
83                         ast_inet_ntoa(iabuf, sizeof(iabuf), oldsin.sin_addr));
84         ast_build_string(&c, &reslen, "<tr><td><i>Bind Port</i></td><td><b>%d</b></td></tr>\r\n",
85                         ntohs(oldsin.sin_port));
86         ast_build_string(&c, &reslen, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
87         v = vars;
88         while(v) {
89                 ast_build_string(&c, &reslen, "<tr><td><i>Submitted Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
90                 v = v->next;
91         }
92         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");
93         return strdup(result);
94 }
95
96 static struct ast_http_uri statusuri = {
97         .callback = httpstatus_callback,
98         .description = "Asterisk HTTP General Status",
99         .uri = "httpstatus",
100         .has_subtree = 0,
101 };
102         
103 char *ast_http_error(int status, const char *title, const char *extra_header, const char *text)
104 {
105         char *c = NULL;
106         asprintf(&c,
107                 "Content-type: text/html\r\n"
108                 "%s"
109                 "\r\n"
110                 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
111                 "<html><head>\r\n"
112                 "<title>%d %s</title>\r\n"
113                 "</head><body>\r\n"
114                 "<h1>%s</h1>\r\n"
115                 "<p>%s</p>\r\n"
116                 "<hr />\r\n"
117                 "<address>Asterisk Server</address>\r\n"
118                 "</body></html>\r\n",
119                         (extra_header ? extra_header : ""), status, title, title, text);
120         return c;
121 }
122
123 int ast_http_uri_link(struct ast_http_uri *urih)
124 {
125         struct ast_http_uri *prev=uris;
126         if (!uris || strlen(uris->uri) <= strlen(urih->uri)) {
127                 urih->next = uris;
128                 uris = urih;
129         } else {
130                 while (prev->next && (strlen(prev->next->uri) > strlen(urih->uri)))
131                         prev = prev->next;
132                 /* Insert it here */
133                 urih->next = prev->next;
134                 prev->next = urih;
135         }
136         return 0;
137 }       
138
139 void ast_http_uri_unlink(struct ast_http_uri *urih)
140 {
141         struct ast_http_uri *prev = uris;
142         if (!uris)
143                 return;
144         if (uris == urih) {
145                 uris = uris->next;
146         }
147         while(prev->next) {
148                 if (prev->next == urih) {
149                         prev->next = urih->next;
150                         break;
151                 }
152                 prev = prev->next;
153         }
154 }
155
156 static char *handle_uri(struct sockaddr_in *sin, char *uri, int *status, char **title, int *contentlength)
157 {
158         char *c;
159         char *turi;
160         char *params;
161         char *var;
162         char *val;
163         struct ast_http_uri *urih=NULL;
164         int len;
165         struct ast_variable *vars=NULL, *v, *prev = NULL;
166         
167         
168         if (*uri == '/')
169                 uri++;
170         params = strchr(uri, '?');
171         if (params) {
172                 *params = '\0';
173                 params++;
174                 while ((var = strsep(&params, "&"))) {
175                         val = strchr(var, '=');
176                         if (val) {
177                                 *val = '\0';
178                                 val++;
179                         } else 
180                                 val = "";
181                         ast_uri_decode(val);
182                         ast_uri_decode(var);
183                         if ((v = ast_variable_new(var, val))) {
184                                 if (vars)
185                                         prev->next = v;
186                                 else
187                                         vars = v;
188                                 prev = v;
189                         }
190                 }
191         }
192         ast_uri_decode(uri);
193         if (!strncasecmp(uri, prefix, prefix_len)) {
194                 uri += prefix_len;
195                 if (!*uri || (*uri == '/')) {
196                         if (*uri == '/')
197                                 uri++;
198                         urih = uris;
199                         while(urih) {
200                                 len = strlen(urih->uri);
201                                 if (!strncasecmp(urih->uri, uri, len)) {
202                                         if (!uri[len] || uri[len] == '/') {
203                                                 turi = uri + len;
204                                                 if (*turi == '/')
205                                                         turi++;
206                                                 if (!*turi || urih->has_subtree) {
207                                                         uri = turi;
208                                                         break;
209                                                 }
210                                         }
211                                 }
212                                 urih = urih->next;
213                         }
214                 }
215         }
216         if (urih) {
217                 c = urih->callback(sin, uri, vars, status, title, contentlength);
218                 ast_variables_destroy(vars);
219         } else {
220                 c = ast_http_error(404, "Not Found", NULL, "The requested URL was not found on this serer.");
221                 *status = 404;
222                 *title = strdup("Not Found");
223         }
224         return c;
225 }
226
227 static void *ast_httpd_helper_thread(void *data)
228 {
229         char buf[4096];
230         char timebuf[256];
231         struct ast_http_server_instance *ser = data;
232         char *uri, *c, *title=NULL;
233         int status = 200, contentlength = 0;
234         time_t t;
235
236         if (fgets(buf, sizeof(buf), ser->f)) {
237                 /* Skip method */
238                 uri = buf;
239                 while(*uri && (*uri > 32)) uri++;
240                 if (*uri) {
241                         *uri = '\0';
242                         uri++;
243                 }
244
245                 /* Skip white space */
246                 while (*uri && (*uri < 33)) uri++;
247
248                 if (*uri) {
249                         c = uri;
250                         while (*c && (*c > 32)) c++;
251                         if (*c) {
252                                 *c = '\0';
253                         }
254                 }
255                 if (*uri) {
256                         if (!strcasecmp(buf, "get")) 
257                                 c = handle_uri(&ser->requestor, uri, &status, &title, &contentlength);
258                         else 
259                                 c = ast_http_error(501, "Not Implemented", NULL, "Attempt to use unimplemented / unsupported method");\
260                 } else 
261                         c = ast_http_error(400, "Bad Request", NULL, "Invalid Request");
262                 if (!c)
263                         c = ast_http_error(500, "Internal Error", NULL, "Internal Server Error");
264                 if (c) {
265                         time(&t);
266                         strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&t));
267                         ast_cli(ser->fd, "HTTP/1.1 GET %d %s\r\n", status, title ? title : "OK");
268                         ast_cli(ser->fd, "Server: Asterisk\r\n");
269                         ast_cli(ser->fd, "Date: %s\r\n", timebuf);
270                         if (contentlength)
271                                 ast_cli(ser->fd, "Content-length: %d\r\n", contentlength);
272                         ast_cli(ser->fd, "Connection: close\r\n");
273                         ast_cli(ser->fd, "%s", c);
274                         free(c);
275                 }
276                 if (title)
277                         free(title);
278         }
279         fclose(ser->f);
280         free(ser);
281         return NULL;
282 }
283
284 static void *http_root(void *data)
285 {
286         int fd;
287         struct sockaddr_in sin;
288         int sinlen;
289         struct ast_http_server_instance *ser;
290         pthread_t launched;
291         for (;;) {
292                 ast_wait_for_input(httpfd, -1);
293                 sinlen = sizeof(sin);
294                 fd = accept(httpfd, (struct sockaddr *)&sin, &sinlen);
295                 if (fd < 0) {
296                         if ((errno != EAGAIN) && (errno != EINTR))
297                                 ast_log(LOG_WARNING, "Accept failed: %s\n", strerror(errno));
298                         continue;
299                 }
300                 if (!(ser = ast_calloc(1, sizeof(*ser)))) {
301                         close(fd);
302                         continue;
303                 }
304                 ser->fd = fd;
305                 if ((ser->f = fdopen(ser->fd, "w+"))) {
306                         if (ast_pthread_create(&launched, NULL, ast_httpd_helper_thread, ser)) {
307                                 ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
308                                 fclose(ser->f);
309                                 free(ser);
310                         }
311                 } else {
312                         ast_log(LOG_WARNING, "fdopen failed!\n");
313                         close(ser->fd);
314                         free(ser);
315                 }
316         }
317         return NULL;
318 }
319
320 static void http_server_start(struct sockaddr_in *sin)
321 {
322         char iabuf[INET_ADDRSTRLEN];
323         int flags;
324         int x = 1;
325         
326         /* Do nothing if nothing has changed */
327         if (!memcmp(&oldsin, sin, sizeof(oldsin))) {
328                 ast_log(LOG_DEBUG, "Nothing changed in http\n");
329                 return;
330         }
331         
332         memcpy(&oldsin, sin, sizeof(oldsin));
333         
334         /* Shutdown a running server if there is one */
335         if (master != AST_PTHREADT_NULL) {
336                 pthread_cancel(master);
337                 pthread_kill(master, SIGURG);
338                 pthread_join(master, NULL);
339         }
340         
341         if (httpfd != -1)
342                 close(httpfd);
343
344         /* If there's no new server, stop here */
345         if (!sin->sin_family)
346                 return;
347         
348         
349         httpfd = socket(AF_INET, SOCK_STREAM, 0);
350         if (httpfd < 0) {
351                 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
352                 return;
353         }
354         
355         setsockopt(httpfd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
356         if (bind(httpfd, (struct sockaddr *)sin, sizeof(*sin))) {
357                 ast_log(LOG_NOTICE, "Unable to bind http server to %s:%d: %s\n",
358                         ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port),
359                         strerror(errno));
360                 close(httpfd);
361                 httpfd = -1;
362                 return;
363         }
364         if (listen(httpfd, 10)) {
365                 ast_log(LOG_NOTICE, "Unable to listen!\n");
366                 close(httpfd);
367                 httpfd = -1;
368                 return;
369         }
370         flags = fcntl(httpfd, F_GETFL);
371         fcntl(httpfd, F_SETFL, flags | O_NONBLOCK);
372         if (ast_pthread_create(&master, NULL, http_root, NULL)) {
373                 ast_log(LOG_NOTICE, "Unable to launch http server on %s:%d: %s\n",
374                                 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port),
375                                 strerror(errno));
376                 close(httpfd);
377                 httpfd = -1;
378         }
379 }
380
381 static int __ast_http_load(int reload)
382 {
383         struct ast_config *cfg;
384         struct ast_variable *v;
385         int enabled=0;
386         struct sockaddr_in sin;
387         struct hostent *hp;
388         struct ast_hostent ahp;
389         char newprefix[MAX_PREFIX];
390         memset(&sin, 0, sizeof(sin));
391         sin.sin_port = 8088;
392         strcpy(newprefix, DEFAULT_PREFIX);
393         cfg = ast_config_load("http.conf");
394         if (cfg) {
395                 v = ast_variable_browse(cfg, "general");
396                 while(v) {
397                         if (!strcasecmp(v->name, "enabled"))
398                                 enabled = ast_true(v->value);
399                         else if (!strcasecmp(v->name, "bindport"))
400                                 sin.sin_port = ntohs(atoi(v->value));
401                         else if (!strcasecmp(v->name, "bindaddr")) {
402                                 if ((hp = ast_gethostbyname(v->value, &ahp))) {
403                                         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
404                                 } else {
405                                         ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
406                                 }
407                         } else if (!strcasecmp(v->name, "prefix"))
408                                 ast_copy_string(newprefix, v->value, sizeof(newprefix));
409                         v = v->next;
410                 }
411                 ast_config_destroy(cfg);
412         }
413         if (enabled)
414                 sin.sin_family = AF_INET;
415         if (strcmp(prefix, newprefix)) {
416                 ast_copy_string(prefix, newprefix, sizeof(prefix));
417                 prefix_len = strlen(prefix);
418         }
419         http_server_start(&sin);
420         return 0;
421 }
422
423 static int handle_show_http(int fd, int argc, char *argv[])
424 {
425         char iabuf[INET_ADDRSTRLEN];
426         struct ast_http_uri *urih;
427         if (argc != 2)
428                 return RESULT_SHOWUSAGE;
429         ast_cli(fd, "HTTP Server Status:\n");
430         ast_cli(fd, "Prefix: %s\n", prefix);
431         if (oldsin.sin_family)
432                 ast_cli(fd, "Server Enabled and Bound to %s:%d\n\n",
433                         ast_inet_ntoa(iabuf, sizeof(iabuf), oldsin.sin_addr),
434                         ntohs(oldsin.sin_port));
435         else
436                 ast_cli(fd, "Server Disabled\n\n");
437         ast_cli(fd, "Enabled URI's:\n");
438         urih = uris;
439         while(urih){
440                 ast_cli(fd, "/%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
441                 urih = urih->next;
442         }
443         if (!uris)
444                 ast_cli(fd, "None.\n");
445         return RESULT_SUCCESS;
446 }
447
448 int ast_http_reload(void)
449 {
450         return __ast_http_load(1);
451 }
452
453 static char show_http_help[] =
454 "Usage: show http\n"
455 "       Shows status of internal HTTP engine\n";
456
457 static struct ast_cli_entry http_cli[] = {
458         { { "show", "http", NULL }, handle_show_http,
459           "Display HTTP status", show_http_help },
460 };
461
462 int ast_http_init(void)
463 {
464         ast_http_uri_link(&statusuri);
465         ast_cli_register_multiple(http_cli, sizeof(http_cli) / sizeof(http_cli[0]));
466         return __ast_http_load(0);
467 }