fix asterisk header include format and add the doxygen header
[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                 ser = calloc(1, sizeof(*ser));
301                 if (ser) {
302                         ser->fd = fd;
303                         if ((ser->f = fdopen(ser->fd, "w+"))) {
304                                 if (ast_pthread_create(&launched, NULL, ast_httpd_helper_thread, ser)) {
305                                         ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
306                                         fclose(ser->f);
307                                         free(ser);
308                                 }
309                         } else {
310                                 ast_log(LOG_WARNING, "fdopen failed!\n");
311                                 close(ser->fd);
312                                 free(ser);
313                         }
314                 } else {
315                         ast_log(LOG_WARNING, "Out of memory!\n");
316                         close(fd);
317                 }
318         }
319         return NULL;
320 }
321
322 static void http_server_start(struct sockaddr_in *sin)
323 {
324         char iabuf[INET_ADDRSTRLEN];
325         int flags;
326         int x = 1;
327         
328         /* Do nothing if nothing has changed */
329         if (!memcmp(&oldsin, sin, sizeof(oldsin))) {
330                 ast_log(LOG_DEBUG, "Nothing changed in http\n");
331                 return;
332         }
333         
334         memcpy(&oldsin, sin, sizeof(oldsin));
335         
336         /* Shutdown a running server if there is one */
337         if (master != AST_PTHREADT_NULL) {
338                 pthread_cancel(master);
339                 pthread_kill(master, SIGURG);
340                 pthread_join(master, NULL);
341         }
342         
343         if (httpfd != -1)
344                 close(httpfd);
345
346         /* If there's no new server, stop here */
347         if (!sin->sin_family)
348                 return;
349         
350         
351         httpfd = socket(AF_INET, SOCK_STREAM, 0);
352         if (httpfd < 0) {
353                 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
354                 return;
355         }
356         
357         setsockopt(httpfd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
358         if (bind(httpfd, (struct sockaddr *)sin, sizeof(*sin))) {
359                 ast_log(LOG_NOTICE, "Unable to bind http server to %s:%d: %s\n",
360                         ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port),
361                         strerror(errno));
362                 close(httpfd);
363                 httpfd = -1;
364                 return;
365         }
366         if (listen(httpfd, 10)) {
367                 ast_log(LOG_NOTICE, "Unable to listen!\n");
368                 close(httpfd);
369                 httpfd = -1;
370                 return;
371         }
372         flags = fcntl(httpfd, F_GETFL);
373         fcntl(httpfd, F_SETFL, flags | O_NONBLOCK);
374         if (ast_pthread_create(&master, NULL, http_root, NULL)) {
375                 ast_log(LOG_NOTICE, "Unable to launch http server on %s:%d: %s\n",
376                                 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port),
377                                 strerror(errno));
378                 close(httpfd);
379                 httpfd = -1;
380         }
381 }
382
383 static int __ast_http_load(int reload)
384 {
385         struct ast_config *cfg;
386         struct ast_variable *v;
387         int enabled=0;
388         struct sockaddr_in sin;
389         struct hostent *hp;
390         struct ast_hostent ahp;
391         char newprefix[MAX_PREFIX];
392         memset(&sin, 0, sizeof(sin));
393         sin.sin_port = 8088;
394         strcpy(newprefix, DEFAULT_PREFIX);
395         cfg = ast_config_load("http.conf");
396         if (cfg) {
397                 v = ast_variable_browse(cfg, "general");
398                 while(v) {
399                         if (!strcasecmp(v->name, "enabled"))
400                                 enabled = ast_true(v->value);
401                         else if (!strcasecmp(v->name, "bindport"))
402                                 sin.sin_port = ntohs(atoi(v->value));
403                         else if (!strcasecmp(v->name, "bindaddr")) {
404                                 if ((hp = ast_gethostbyname(v->value, &ahp))) {
405                                         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
406                                 } else {
407                                         ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
408                                 }
409                         } else if (!strcasecmp(v->name, "prefix"))
410                                 ast_copy_string(newprefix, v->value, sizeof(newprefix));
411                         v = v->next;
412                 }
413                 ast_config_destroy(cfg);
414         }
415         if (enabled)
416                 sin.sin_family = AF_INET;
417         if (strcmp(prefix, newprefix)) {
418                 ast_copy_string(prefix, newprefix, sizeof(prefix));
419                 prefix_len = strlen(prefix);
420         }
421         http_server_start(&sin);
422         return 0;
423 }
424
425 static int handle_show_http(int fd, int argc, char *argv[])
426 {
427         char iabuf[INET_ADDRSTRLEN];
428         struct ast_http_uri *urih;
429         if (argc != 2)
430                 return RESULT_SHOWUSAGE;
431         ast_cli(fd, "HTTP Server Status:\n");
432         ast_cli(fd, "Prefix: %s\n", prefix);
433         if (oldsin.sin_family)
434                 ast_cli(fd, "Server Enabled and Bound to %s:%d\n\n",
435                         ast_inet_ntoa(iabuf, sizeof(iabuf), oldsin.sin_addr),
436                         ntohs(oldsin.sin_port));
437         else
438                 ast_cli(fd, "Server Disabled\n\n");
439         ast_cli(fd, "Enabled URI's:\n");
440         urih = uris;
441         while(urih){
442                 ast_cli(fd, "/%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
443                 urih = urih->next;
444         }
445         if (!uris)
446                 ast_cli(fd, "None.\n");
447         return RESULT_SUCCESS;
448 }
449
450 int ast_http_reload(void)
451 {
452         return __ast_http_load(1);
453 }
454
455 static char show_http_help[] =
456 "Usage: show http\n"
457 "       Shows status of internal HTTP engine\n";
458
459 static struct ast_cli_entry http_cli[] = {
460         { { "show", "http", NULL }, handle_show_http,
461           "Display HTTP status", show_http_help },
462 };
463
464 int ast_http_init(void)
465 {
466         ast_http_uri_link(&statusuri);
467         ast_cli_register_multiple(http_cli, sizeof(http_cli) / sizeof(http_cli[0]));
468         return __ast_http_load(0);
469 }