• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt/router/netatalk-3.0.5/libevent/sample/
1/*
2  A trivial static http webserver using Libevent's evhttp.
3
4  This is not the best code in the world, and it does some fairly stupid stuff
5  that you would never want to do in a production webserver. Caveat hackor!
6
7 */
8
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12
13#include <sys/types.h>
14#include <sys/stat.h>
15
16#ifdef WIN32
17#include <winsock2.h>
18#include <ws2tcpip.h>
19#include <windows.h>
20#include <io.h>
21#include <fcntl.h>
22#ifndef S_ISDIR
23#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
24#endif
25#else
26#include <sys/stat.h>
27#include <sys/socket.h>
28#include <signal.h>
29#include <fcntl.h>
30#include <unistd.h>
31#include <dirent.h>
32#endif
33
34#include <event2/event.h>
35#include <event2/http.h>
36#include <event2/buffer.h>
37#include <event2/util.h>
38#include <event2/keyvalq_struct.h>
39
40#ifdef _EVENT_HAVE_NETINET_IN_H
41#include <netinet/in.h>
42# ifdef _XOPEN_SOURCE_EXTENDED
43#  include <arpa/inet.h>
44# endif
45#endif
46
47/* Compatibility for possible missing IPv6 declarations */
48#include "../util-internal.h"
49
50#ifdef WIN32
51#define stat _stat
52#define fstat _fstat
53#define open _open
54#define close _close
55#define O_RDONLY _O_RDONLY
56#endif
57
58char uri_root[512];
59
60static const struct table_entry {
61	const char *extension;
62	const char *content_type;
63} content_type_table[] = {
64	{ "txt", "text/plain" },
65	{ "c", "text/plain" },
66	{ "h", "text/plain" },
67	{ "html", "text/html" },
68	{ "htm", "text/htm" },
69	{ "css", "text/css" },
70	{ "gif", "image/gif" },
71	{ "jpg", "image/jpeg" },
72	{ "jpeg", "image/jpeg" },
73	{ "png", "image/png" },
74	{ "pdf", "application/pdf" },
75	{ "ps", "application/postsript" },
76	{ NULL, NULL },
77};
78
79/* Try to guess a good content-type for 'path' */
80static const char *
81guess_content_type(const char *path)
82{
83	const char *last_period, *extension;
84	const struct table_entry *ent;
85	last_period = strrchr(path, '.');
86	if (!last_period || strchr(last_period, '/'))
87		goto not_found; /* no exension */
88	extension = last_period + 1;
89	for (ent = &content_type_table[0]; ent->extension; ++ent) {
90		if (!evutil_ascii_strcasecmp(ent->extension, extension))
91			return ent->content_type;
92	}
93
94not_found:
95	return "application/misc";
96}
97
98/* Callback used for the /dump URI, and for every non-GET request:
99 * dumps all information to stdout and gives back a trivial 200 ok */
100static void
101dump_request_cb(struct evhttp_request *req, void *arg)
102{
103	const char *cmdtype;
104	struct evkeyvalq *headers;
105	struct evkeyval *header;
106	struct evbuffer *buf;
107
108	switch (evhttp_request_get_command(req)) {
109	case EVHTTP_REQ_GET: cmdtype = "GET"; break;
110	case EVHTTP_REQ_POST: cmdtype = "POST"; break;
111	case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
112	case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
113	case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
114	case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
115	case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
116	case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
117	case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
118	default: cmdtype = "unknown"; break;
119	}
120
121	printf("Received a %s request for %s\nHeaders:\n",
122	    cmdtype, evhttp_request_get_uri(req));
123
124	headers = evhttp_request_get_input_headers(req);
125	for (header = headers->tqh_first; header;
126	    header = header->next.tqe_next) {
127		printf("  %s: %s\n", header->key, header->value);
128	}
129
130	buf = evhttp_request_get_input_buffer(req);
131	puts("Input data: <<<");
132	while (evbuffer_get_length(buf)) {
133		int n;
134		char cbuf[128];
135		n = evbuffer_remove(buf, cbuf, sizeof(buf)-1);
136		if (n > 0)
137			(void) fwrite(cbuf, 1, n, stdout);
138	}
139	puts(">>>");
140
141	evhttp_send_reply(req, 200, "OK", NULL);
142}
143
144/* This callback gets invoked when we get any http request that doesn't match
145 * any other callback.  Like any evhttp server callback, it has a simple job:
146 * it must eventually call evhttp_send_error() or evhttp_send_reply().
147 */
148static void
149send_document_cb(struct evhttp_request *req, void *arg)
150{
151	struct evbuffer *evb = NULL;
152	const char *docroot = arg;
153	const char *uri = evhttp_request_get_uri(req);
154	struct evhttp_uri *decoded = NULL;
155	const char *path;
156	char *decoded_path;
157	char *whole_path = NULL;
158	size_t len;
159	int fd = -1;
160	struct stat st;
161
162	if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
163		dump_request_cb(req, arg);
164		return;
165	}
166
167	printf("Got a GET request for <%s>\n",  uri);
168
169	/* Decode the URI */
170	decoded = evhttp_uri_parse(uri);
171	if (!decoded) {
172		printf("It's not a good URI. Sending BADREQUEST\n");
173		evhttp_send_error(req, HTTP_BADREQUEST, 0);
174		return;
175	}
176
177	/* Let's see what path the user asked for. */
178	path = evhttp_uri_get_path(decoded);
179	if (!path) path = "/";
180
181	/* We need to decode it, to see what path the user really wanted. */
182	decoded_path = evhttp_uridecode(path, 0, NULL);
183	if (decoded_path == NULL)
184		goto err;
185	/* Don't allow any ".."s in the path, to avoid exposing stuff outside
186	 * of the docroot.  This test is both overzealous and underzealous:
187	 * it forbids aceptable paths like "/this/one..here", but it doesn't
188	 * do anything to prevent symlink following." */
189	if (strstr(decoded_path, ".."))
190		goto err;
191
192	len = strlen(decoded_path)+strlen(docroot)+2;
193	if (!(whole_path = malloc(len))) {
194		perror("malloc");
195		goto err;
196	}
197	evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);
198
199	if (stat(whole_path, &st)<0) {
200		goto err;
201	}
202
203	/* This holds the content we're sending. */
204	evb = evbuffer_new();
205
206	if (S_ISDIR(st.st_mode)) {
207		/* If it's a directory, read the comments and make a little
208		 * index page */
209#ifdef WIN32
210		HANDLE d;
211		WIN32_FIND_DATAA ent;
212		char *pattern;
213		size_t dirlen;
214#else
215		DIR *d;
216		struct dirent *ent;
217#endif
218		const char *trailing_slash = "";
219
220		if (!strlen(path) || path[strlen(path)-1] != '/')
221			trailing_slash = "/";
222
223#ifdef WIN32
224		dirlen = strlen(whole_path);
225		pattern = malloc(dirlen+3);
226		memcpy(pattern, whole_path, dirlen);
227		pattern[dirlen] = '\\';
228		pattern[dirlen+1] = '*';
229		pattern[dirlen+2] = '\0';
230		d = FindFirstFileA(pattern, &ent);
231		free(pattern);
232		if (d == INVALID_HANDLE_VALUE)
233			goto err;
234#else
235		if (!(d = opendir(whole_path)))
236			goto err;
237#endif
238
239		evbuffer_add_printf(evb, "<html>\n <head>\n"
240		    "  <title>%s</title>\n"
241		    "  <base href='%s%s%s'>\n"
242		    " </head>\n"
243		    " <body>\n"
244		    "  <h1>%s</h1>\n"
245		    "  <ul>\n",
246		    decoded_path, /* XXX html-escape this. */
247		    uri_root, path, /* XXX html-escape this? */
248		    trailing_slash,
249		    decoded_path /* XXX html-escape this */);
250#ifdef WIN32
251		do {
252			const char *name = ent.cFileName;
253#else
254		while ((ent = readdir(d))) {
255			const char *name = ent->d_name;
256#endif
257			evbuffer_add_printf(evb,
258			    "    <li><a href=\"%s\">%s</a>\n",
259			    name, name);/* XXX escape this */
260#ifdef WIN32
261		} while (FindNextFileA(d, &ent));
262#else
263		}
264#endif
265		evbuffer_add_printf(evb, "</ul></body></html>\n");
266#ifdef WIN32
267		CloseHandle(d);
268#else
269		closedir(d);
270#endif
271		evhttp_add_header(evhttp_request_get_output_headers(req),
272		    "Content-Type", "text/html");
273	} else {
274		/* Otherwise it's a file; add it to the buffer to get
275		 * sent via sendfile */
276		const char *type = guess_content_type(decoded_path);
277		if ((fd = open(whole_path, O_RDONLY)) < 0) {
278			perror("open");
279			goto err;
280		}
281
282		if (fstat(fd, &st)<0) {
283			/* Make sure the length still matches, now that we
284			 * opened the file :/ */
285			perror("fstat");
286			goto err;
287		}
288		evhttp_add_header(evhttp_request_get_output_headers(req),
289		    "Content-Type", type);
290		evbuffer_add_file(evb, fd, 0, st.st_size);
291	}
292
293	evhttp_send_reply(req, 200, "OK", evb);
294	goto done;
295err:
296	evhttp_send_error(req, 404, "Document was not found");
297	if (fd>=0)
298		close(fd);
299done:
300	if (decoded)
301		evhttp_uri_free(decoded);
302	if (decoded_path)
303		free(decoded_path);
304	if (whole_path)
305		free(whole_path);
306	if (evb)
307		evbuffer_free(evb);
308}
309
310static void
311syntax(void)
312{
313	fprintf(stdout, "Syntax: http-server <docroot>\n");
314}
315
316int
317main(int argc, char **argv)
318{
319	struct event_base *base;
320	struct evhttp *http;
321	struct evhttp_bound_socket *handle;
322
323	unsigned short port = 0;
324#ifdef WIN32
325	WSADATA WSAData;
326	WSAStartup(0x101, &WSAData);
327#else
328	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
329		return (1);
330#endif
331	if (argc < 2) {
332		syntax();
333		return 1;
334	}
335
336	base = event_base_new();
337	if (!base) {
338		fprintf(stderr, "Couldn't create an event_base: exiting\n");
339		return 1;
340	}
341
342	/* Create a new evhttp object to handle requests. */
343	http = evhttp_new(base);
344	if (!http) {
345		fprintf(stderr, "couldn't create evhttp. Exiting.\n");
346		return 1;
347	}
348
349	/* The /dump URI will dump all requests to stdout and say 200 ok. */
350	evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
351
352	/* We want to accept arbitrary requests, so we need to set a "generic"
353	 * cb.  We can also add callbacks for specific paths. */
354	evhttp_set_gencb(http, send_document_cb, argv[1]);
355
356	/* Now we tell the evhttp what port to listen on */
357	handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
358	if (!handle) {
359		fprintf(stderr, "couldn't bind to port %d. Exiting.\n",
360		    (int)port);
361		return 1;
362	}
363
364	{
365		/* Extract and display the address we're listening on. */
366		struct sockaddr_storage ss;
367		evutil_socket_t fd;
368		ev_socklen_t socklen = sizeof(ss);
369		char addrbuf[128];
370		void *inaddr;
371		const char *addr;
372		int got_port = -1;
373		fd = evhttp_bound_socket_get_fd(handle);
374		memset(&ss, 0, sizeof(ss));
375		if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
376			perror("getsockname() failed");
377			return 1;
378		}
379		if (ss.ss_family == AF_INET) {
380			got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
381			inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
382		} else if (ss.ss_family == AF_INET6) {
383			got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
384			inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
385		} else {
386			fprintf(stderr, "Weird address family %d\n",
387			    ss.ss_family);
388			return 1;
389		}
390		addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
391		    sizeof(addrbuf));
392		if (addr) {
393			printf("Listening on %s:%d\n", addr, got_port);
394			evutil_snprintf(uri_root, sizeof(uri_root),
395			    "http://%s:%d",addr,got_port);
396		} else {
397			fprintf(stderr, "evutil_inet_ntop failed\n");
398			return 1;
399		}
400	}
401
402	event_base_dispatch(base);
403
404	return 0;
405}
406