Squashed 'third_party/libevent/' content from commit d8ceae8

Change-Id: I84e1b23561eb225b9f288717b028e6bc9e5a27e1
git-subtree-dir: third_party/libevent
git-subtree-split: d8ceae81b83f3d0a56e2f41d4c429b2702a8e302
diff --git a/sample/Makefile.am b/sample/Makefile.am
new file mode 100644
index 0000000..c926f4e
--- /dev/null
+++ b/sample/Makefile.am
@@ -0,0 +1,29 @@
+# sample/Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
+AUTOMAKE_OPTIONS = foreign no-dependencies
+
+LDADD = $(LIBEVENT_GC_SECTIONS) ../libevent.la
+AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/compat -I$(top_srcdir)/include -I../include
+
+noinst_PROGRAMS = event-test time-test signal-test dns-example hello-world http-server
+
+event_test_SOURCES = event-test.c
+time_test_SOURCES = time-test.c
+signal_test_SOURCES = signal-test.c
+dns_example_SOURCES = dns-example.c
+hello_world_SOURCES = hello-world.c
+http_server_SOURCES = http-server.c
+
+if OPENSSL
+noinst_PROGRAMS += le-proxy
+le_proxy_SOURCES = le-proxy.c
+le_proxy_LDADD = $(LDADD) ../libevent_openssl.la -lssl -lcrypto ${OPENSSL_LIBADD}
+endif
+
+verify:
+
+DISTCLEANFILES = *~
diff --git a/sample/dns-example.c b/sample/dns-example.c
new file mode 100644
index 0000000..f139033
--- /dev/null
+++ b/sample/dns-example.c
@@ -0,0 +1,248 @@
+/*
+  This example code shows how to use the high-level, low-level, and
+  server-level interfaces of evdns.
+
+  XXX It's pretty ugly and should probably be cleaned up.
+ */
+
+#include <event2/event-config.h>
+
+/* Compatibility for possible missing IPv6 declarations */
+#include "../ipv6-internal.h"
+
+#include <sys/types.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#endif
+
+#include <event2/event.h>
+#include <event2/dns.h>
+#include <event2/dns_struct.h>
+#include <event2/util.h>
+
+#ifdef _EVENT_HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define u32 ev_uint32_t
+#define u8 ev_uint8_t
+
+static const char *
+debug_ntoa(u32 address)
+{
+	static char buf[32];
+	u32 a = ntohl(address);
+	evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
+					(int)(u8)((a>>24)&0xff),
+					(int)(u8)((a>>16)&0xff),
+					(int)(u8)((a>>8 )&0xff),
+					(int)(u8)((a	)&0xff));
+	return buf;
+}
+
+static void
+main_callback(int result, char type, int count, int ttl,
+			  void *addrs, void *orig) {
+	char *n = (char*)orig;
+	int i;
+	for (i = 0; i < count; ++i) {
+		if (type == DNS_IPv4_A) {
+			printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
+		} else if (type == DNS_PTR) {
+			printf("%s: %s\n", n, ((char**)addrs)[i]);
+		}
+	}
+	if (!count) {
+		printf("%s: No answer (%d)\n", n, result);
+	}
+	fflush(stdout);
+}
+
+static void
+gai_callback(int err, struct evutil_addrinfo *ai, void *arg)
+{
+	const char *name = arg;
+	int i;
+	if (err) {
+		printf("%s: %s\n", name, evutil_gai_strerror(err));
+	}
+	if (ai && ai->ai_canonname)
+		printf("    %s ==> %s\n", name, ai->ai_canonname);
+	for (i=0; ai; ai = ai->ai_next, ++i) {
+		char buf[128];
+		if (ai->ai_family == PF_INET) {
+			struct sockaddr_in *sin =
+			    (struct sockaddr_in*)ai->ai_addr;
+			evutil_inet_ntop(AF_INET, &sin->sin_addr, buf,
+			    sizeof(buf));
+			printf("[%d] %s: %s\n",i,name,buf);
+		} else {
+			struct sockaddr_in6 *sin6 =
+			    (struct sockaddr_in6*)ai->ai_addr;
+			evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf,
+			    sizeof(buf));
+			printf("[%d] %s: %s\n",i,name,buf);
+		}
+	}
+}
+
+static void
+evdns_server_callback(struct evdns_server_request *req, void *data)
+{
+	int i, r;
+	(void)data;
+	/* dummy; give 192.168.11.11 as an answer for all A questions,
+	 *	give foo.bar.example.com as an answer for all PTR questions. */
+	for (i = 0; i < req->nquestions; ++i) {
+		u32 ans = htonl(0xc0a80b0bUL);
+		if (req->questions[i]->type == EVDNS_TYPE_A &&
+		    req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
+			printf(" -- replying for %s (A)\n", req->questions[i]->name);
+			r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
+										  1, &ans, 10);
+			if (r<0)
+				printf("eeep, didn't work.\n");
+		} else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
+		    req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
+			printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
+			r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
+											"foo.bar.example.com", 10);
+			if (r<0)
+				printf("ugh, no luck");
+		} else {
+			printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
+				   req->questions[i]->type, req->questions[i]->dns_question_class);
+		}
+	}
+
+	r = evdns_server_request_respond(req, 0);
+	if (r<0)
+		printf("eeek, couldn't send reply.\n");
+}
+
+static int verbose = 0;
+
+static void
+logfn(int is_warn, const char *msg) {
+	if (!is_warn && !verbose)
+		return;
+	fprintf(stderr, "%s: %s\n", is_warn?"WARN":"INFO", msg);
+}
+
+int
+main(int c, char **v) {
+	int idx;
+	int reverse = 0, servertest = 0, use_getaddrinfo = 0;
+	struct event_base *event_base = NULL;
+	struct evdns_base *evdns_base = NULL;
+	const char *resolv_conf = NULL;
+	if (c<2) {
+		fprintf(stderr, "syntax: %s [-x] [-v] [-c resolv.conf] hostname\n", v[0]);
+		fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
+		return 1;
+	}
+	idx = 1;
+	while (idx < c && v[idx][0] == '-') {
+		if (!strcmp(v[idx], "-x"))
+			reverse = 1;
+		else if (!strcmp(v[idx], "-v"))
+			verbose = 1;
+		else if (!strcmp(v[idx], "-g"))
+			use_getaddrinfo = 1;
+		else if (!strcmp(v[idx], "-servertest"))
+			servertest = 1;
+		else if (!strcmp(v[idx], "-c")) {
+			if (idx + 1 < c)
+				resolv_conf = v[++idx];
+			else
+				fprintf(stderr, "-c needs an argument\n");
+		} else
+			fprintf(stderr, "Unknown option %s\n", v[idx]);
+		++idx;
+	}
+
+#ifdef WIN32
+	{
+		WSADATA WSAData;
+		WSAStartup(0x101, &WSAData);
+	}
+#endif
+
+	event_base = event_base_new();
+	evdns_base = evdns_base_new(event_base, 0);
+	evdns_set_log_fn(logfn);
+
+	if (servertest) {
+		evutil_socket_t sock;
+		struct sockaddr_in my_addr;
+		sock = socket(PF_INET, SOCK_DGRAM, 0);
+		if (sock == -1) {
+			perror("socket");
+			exit(1);
+		}
+		evutil_make_socket_nonblocking(sock);
+		my_addr.sin_family = AF_INET;
+		my_addr.sin_port = htons(10053);
+		my_addr.sin_addr.s_addr = INADDR_ANY;
+		if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
+			perror("bind");
+			exit(1);
+		}
+		evdns_add_server_port_with_base(event_base, sock, 0, evdns_server_callback, NULL);
+	}
+	if (idx < c) {
+		int res;
+#ifdef WIN32
+		if (resolv_conf == NULL)
+			res = evdns_base_config_windows_nameservers(evdns_base);
+		else
+#endif
+			res = evdns_base_resolv_conf_parse(evdns_base,
+			    DNS_OPTION_NAMESERVERS,
+			    resolv_conf ? resolv_conf : "/etc/resolv.conf");
+
+		if (res < 0) {
+			fprintf(stderr, "Couldn't configure nameservers");
+			return 1;
+		}
+	}
+
+	printf("EVUTIL_AI_CANONNAME in example = %d\n", EVUTIL_AI_CANONNAME);
+	for (; idx < c; ++idx) {
+		if (reverse) {
+			struct in_addr addr;
+			if (evutil_inet_pton(AF_INET, v[idx], &addr)!=1) {
+				fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
+				continue;
+			}
+			fprintf(stderr, "resolving %s...\n",v[idx]);
+			evdns_base_resolve_reverse(evdns_base, &addr, 0, main_callback, v[idx]);
+		} else if (use_getaddrinfo) {
+			struct evutil_addrinfo hints;
+			memset(&hints, 0, sizeof(hints));
+			hints.ai_family = PF_UNSPEC;
+			hints.ai_protocol = IPPROTO_TCP;
+			hints.ai_flags = EVUTIL_AI_CANONNAME;
+			fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
+			evdns_getaddrinfo(evdns_base, v[idx], NULL, &hints,
+			    gai_callback, v[idx]);
+		} else {
+			fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
+			evdns_base_resolve_ipv4(evdns_base, v[idx], 0, main_callback, v[idx]);
+		}
+	}
+	fflush(stdout);
+	event_base_dispatch(event_base);
+	return 0;
+}
+
diff --git a/sample/event-test.c b/sample/event-test.c
new file mode 100644
index 0000000..a1483e6
--- /dev/null
+++ b/sample/event-test.c
@@ -0,0 +1,143 @@
+/*
+ * XXX This sample code was once meant to show how to use the basic Libevent
+ * interfaces, but it never worked on non-Unix platforms, and some of the
+ * interfaces have changed since it was first written.  It should probably
+ * be removed or replaced with something better.
+ *
+ * Compile with:
+ * cc -I/usr/local/include -o event-test event-test.c -L/usr/local/lib -levent
+ */
+
+#include <event2/event-config.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifndef WIN32
+#include <sys/queue.h>
+#include <unistd.h>
+#include <sys/time.h>
+#else
+#include <winsock2.h>
+#include <windows.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event.h>
+
+static void
+fifo_read(evutil_socket_t fd, short event, void *arg)
+{
+	char buf[255];
+	int len;
+	struct event *ev = arg;
+#ifdef WIN32
+	DWORD dwBytesRead;
+#endif
+
+	/* Reschedule this event */
+	event_add(ev, NULL);
+
+	fprintf(stderr, "fifo_read called with fd: %d, event: %d, arg: %p\n",
+	    (int)fd, event, arg);
+#ifdef WIN32
+	len = ReadFile((HANDLE)fd, buf, sizeof(buf) - 1, &dwBytesRead, NULL);
+
+	/* Check for end of file. */
+	if (len && dwBytesRead == 0) {
+		fprintf(stderr, "End Of File");
+		event_del(ev);
+		return;
+	}
+
+	buf[dwBytesRead] = '\0';
+#else
+	len = read(fd, buf, sizeof(buf) - 1);
+
+	if (len == -1) {
+		perror("read");
+		return;
+	} else if (len == 0) {
+		fprintf(stderr, "Connection closed\n");
+		return;
+	}
+
+	buf[len] = '\0';
+#endif
+	fprintf(stdout, "Read: %s\n", buf);
+}
+
+int
+main(int argc, char **argv)
+{
+	struct event evfifo;
+#ifdef WIN32
+	HANDLE socket;
+	/* Open a file. */
+	socket = CreateFileA("test.txt",	/* open File */
+			GENERIC_READ,		/* open for reading */
+			0,			/* do not share */
+			NULL,			/* no security */
+			OPEN_EXISTING,		/* existing file only */
+			FILE_ATTRIBUTE_NORMAL,	/* normal file */
+			NULL);			/* no attr. template */
+
+	if (socket == INVALID_HANDLE_VALUE)
+		return 1;
+
+#else
+	struct stat st;
+	const char *fifo = "event.fifo";
+	int socket;
+
+	if (lstat(fifo, &st) == 0) {
+		if ((st.st_mode & S_IFMT) == S_IFREG) {
+			errno = EEXIST;
+			perror("lstat");
+			exit(1);
+		}
+	}
+
+	unlink(fifo);
+	if (mkfifo(fifo, 0600) == -1) {
+		perror("mkfifo");
+		exit(1);
+	}
+
+	/* Linux pipes are broken, we need O_RDWR instead of O_RDONLY */
+#ifdef __linux
+	socket = open(fifo, O_RDWR | O_NONBLOCK, 0);
+#else
+	socket = open(fifo, O_RDONLY | O_NONBLOCK, 0);
+#endif
+
+	if (socket == -1) {
+		perror("open");
+		exit(1);
+	}
+
+	fprintf(stderr, "Write data to %s\n", fifo);
+#endif
+	/* Initalize the event library */
+	event_init();
+
+	/* Initalize one event */
+#ifdef WIN32
+	event_set(&evfifo, (evutil_socket_t)socket, EV_READ, fifo_read, &evfifo);
+#else
+	event_set(&evfifo, socket, EV_READ, fifo_read, &evfifo);
+#endif
+
+	/* Add it to the active events, without a timeout */
+	event_add(&evfifo, NULL);
+
+	event_dispatch();
+#ifdef WIN32
+	CloseHandle(socket);
+#endif
+	return (0);
+}
+
diff --git a/sample/hello-world.c b/sample/hello-world.c
new file mode 100644
index 0000000..d40af52
--- /dev/null
+++ b/sample/hello-world.c
@@ -0,0 +1,141 @@
+/*
+  This exmple program provides a trivial server program that listens for TCP
+  connections on port 9995.  When they arrive, it writes a short message to
+  each client connection, and closes each connection once it is flushed.
+
+  Where possible, it exits cleanly in response to a SIGINT (ctrl-c).
+*/
+
+
+#include <string.h>
+#include <errno.h>
+#include <stdio.h>
+#include <signal.h>
+#ifndef WIN32
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+#  include <arpa/inet.h>
+# endif
+#include <sys/socket.h>
+#endif
+
+#include <event2/bufferevent.h>
+#include <event2/buffer.h>
+#include <event2/listener.h>
+#include <event2/util.h>
+#include <event2/event.h>
+
+static const char MESSAGE[] = "Hello, World!\n";
+
+static const int PORT = 9995;
+
+static void listener_cb(struct evconnlistener *, evutil_socket_t,
+    struct sockaddr *, int socklen, void *);
+static void conn_writecb(struct bufferevent *, void *);
+static void conn_eventcb(struct bufferevent *, short, void *);
+static void signal_cb(evutil_socket_t, short, void *);
+
+int
+main(int argc, char **argv)
+{
+	struct event_base *base;
+	struct evconnlistener *listener;
+	struct event *signal_event;
+
+	struct sockaddr_in sin;
+#ifdef WIN32
+	WSADATA wsa_data;
+	WSAStartup(0x0201, &wsa_data);
+#endif
+
+	base = event_base_new();
+	if (!base) {
+		fprintf(stderr, "Could not initialize libevent!\n");
+		return 1;
+	}
+
+	memset(&sin, 0, sizeof(sin));
+	sin.sin_family = AF_INET;
+	sin.sin_port = htons(PORT);
+
+	listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
+	    LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
+	    (struct sockaddr*)&sin,
+	    sizeof(sin));
+
+	if (!listener) {
+		fprintf(stderr, "Could not create a listener!\n");
+		return 1;
+	}
+
+	signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);
+
+	if (!signal_event || event_add(signal_event, NULL)<0) {
+		fprintf(stderr, "Could not create/add a signal event!\n");
+		return 1;
+	}
+
+	event_base_dispatch(base);
+
+	evconnlistener_free(listener);
+	event_free(signal_event);
+	event_base_free(base);
+
+	printf("done\n");
+	return 0;
+}
+
+static void
+listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
+    struct sockaddr *sa, int socklen, void *user_data)
+{
+	struct event_base *base = user_data;
+	struct bufferevent *bev;
+
+	bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
+	if (!bev) {
+		fprintf(stderr, "Error constructing bufferevent!");
+		event_base_loopbreak(base);
+		return;
+	}
+	bufferevent_setcb(bev, NULL, conn_writecb, conn_eventcb, NULL);
+	bufferevent_enable(bev, EV_WRITE);
+	bufferevent_disable(bev, EV_READ);
+
+	bufferevent_write(bev, MESSAGE, strlen(MESSAGE));
+}
+
+static void
+conn_writecb(struct bufferevent *bev, void *user_data)
+{
+	struct evbuffer *output = bufferevent_get_output(bev);
+	if (evbuffer_get_length(output) == 0) {
+		printf("flushed answer\n");
+		bufferevent_free(bev);
+	}
+}
+
+static void
+conn_eventcb(struct bufferevent *bev, short events, void *user_data)
+{
+	if (events & BEV_EVENT_EOF) {
+		printf("Connection closed.\n");
+	} else if (events & BEV_EVENT_ERROR) {
+		printf("Got an error on the connection: %s\n",
+		    strerror(errno));/*XXX win32*/
+	}
+	/* None of the other events can happen here, since we haven't enabled
+	 * timeouts */
+	bufferevent_free(bev);
+}
+
+static void
+signal_cb(evutil_socket_t sig, short events, void *user_data)
+{
+	struct event_base *base = user_data;
+	struct timeval delay = { 2, 0 };
+
+	printf("Caught an interrupt signal; exiting cleanly in two seconds.\n");
+
+	event_base_loopexit(base, &delay);
+}
diff --git a/sample/http-server.c b/sample/http-server.c
new file mode 100644
index 0000000..a63f3e9
--- /dev/null
+++ b/sample/http-server.c
@@ -0,0 +1,405 @@
+/*
+  A trivial static http webserver using Libevent's evhttp.
+
+  This is not the best code in the world, and it does some fairly stupid stuff
+  that you would never want to do in a production webserver. Caveat hackor!
+
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <io.h>
+#include <fcntl.h>
+#ifndef S_ISDIR
+#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
+#endif
+#else
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <signal.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <dirent.h>
+#endif
+
+#include <event2/event.h>
+#include <event2/http.h>
+#include <event2/buffer.h>
+#include <event2/util.h>
+#include <event2/keyvalq_struct.h>
+
+#ifdef _EVENT_HAVE_NETINET_IN_H
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+#  include <arpa/inet.h>
+# endif
+#endif
+
+/* Compatibility for possible missing IPv6 declarations */
+#include "../util-internal.h"
+
+#ifdef WIN32
+#define stat _stat
+#define fstat _fstat
+#define open _open
+#define close _close
+#define O_RDONLY _O_RDONLY
+#endif
+
+char uri_root[512];
+
+static const struct table_entry {
+	const char *extension;
+	const char *content_type;
+} content_type_table[] = {
+	{ "txt", "text/plain" },
+	{ "c", "text/plain" },
+	{ "h", "text/plain" },
+	{ "html", "text/html" },
+	{ "htm", "text/htm" },
+	{ "css", "text/css" },
+	{ "gif", "image/gif" },
+	{ "jpg", "image/jpeg" },
+	{ "jpeg", "image/jpeg" },
+	{ "png", "image/png" },
+	{ "pdf", "application/pdf" },
+	{ "ps", "application/postsript" },
+	{ NULL, NULL },
+};
+
+/* Try to guess a good content-type for 'path' */
+static const char *
+guess_content_type(const char *path)
+{
+	const char *last_period, *extension;
+	const struct table_entry *ent;
+	last_period = strrchr(path, '.');
+	if (!last_period || strchr(last_period, '/'))
+		goto not_found; /* no exension */
+	extension = last_period + 1;
+	for (ent = &content_type_table[0]; ent->extension; ++ent) {
+		if (!evutil_ascii_strcasecmp(ent->extension, extension))
+			return ent->content_type;
+	}
+
+not_found:
+	return "application/misc";
+}
+
+/* Callback used for the /dump URI, and for every non-GET request:
+ * dumps all information to stdout and gives back a trivial 200 ok */
+static void
+dump_request_cb(struct evhttp_request *req, void *arg)
+{
+	const char *cmdtype;
+	struct evkeyvalq *headers;
+	struct evkeyval *header;
+	struct evbuffer *buf;
+
+	switch (evhttp_request_get_command(req)) {
+	case EVHTTP_REQ_GET: cmdtype = "GET"; break;
+	case EVHTTP_REQ_POST: cmdtype = "POST"; break;
+	case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
+	case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
+	case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
+	case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
+	case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
+	case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
+	case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
+	default: cmdtype = "unknown"; break;
+	}
+
+	printf("Received a %s request for %s\nHeaders:\n",
+	    cmdtype, evhttp_request_get_uri(req));
+
+	headers = evhttp_request_get_input_headers(req);
+	for (header = headers->tqh_first; header;
+	    header = header->next.tqe_next) {
+		printf("  %s: %s\n", header->key, header->value);
+	}
+
+	buf = evhttp_request_get_input_buffer(req);
+	puts("Input data: <<<");
+	while (evbuffer_get_length(buf)) {
+		int n;
+		char cbuf[128];
+		n = evbuffer_remove(buf, cbuf, sizeof(cbuf));
+		if (n > 0)
+			(void) fwrite(cbuf, 1, n, stdout);
+	}
+	puts(">>>");
+
+	evhttp_send_reply(req, 200, "OK", NULL);
+}
+
+/* This callback gets invoked when we get any http request that doesn't match
+ * any other callback.  Like any evhttp server callback, it has a simple job:
+ * it must eventually call evhttp_send_error() or evhttp_send_reply().
+ */
+static void
+send_document_cb(struct evhttp_request *req, void *arg)
+{
+	struct evbuffer *evb = NULL;
+	const char *docroot = arg;
+	const char *uri = evhttp_request_get_uri(req);
+	struct evhttp_uri *decoded = NULL;
+	const char *path;
+	char *decoded_path;
+	char *whole_path = NULL;
+	size_t len;
+	int fd = -1;
+	struct stat st;
+
+	if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
+		dump_request_cb(req, arg);
+		return;
+	}
+
+	printf("Got a GET request for <%s>\n",  uri);
+
+	/* Decode the URI */
+	decoded = evhttp_uri_parse(uri);
+	if (!decoded) {
+		printf("It's not a good URI. Sending BADREQUEST\n");
+		evhttp_send_error(req, HTTP_BADREQUEST, 0);
+		return;
+	}
+
+	/* Let's see what path the user asked for. */
+	path = evhttp_uri_get_path(decoded);
+	if (!path) path = "/";
+
+	/* We need to decode it, to see what path the user really wanted. */
+	decoded_path = evhttp_uridecode(path, 0, NULL);
+	if (decoded_path == NULL)
+		goto err;
+	/* Don't allow any ".."s in the path, to avoid exposing stuff outside
+	 * of the docroot.  This test is both overzealous and underzealous:
+	 * it forbids aceptable paths like "/this/one..here", but it doesn't
+	 * do anything to prevent symlink following." */
+	if (strstr(decoded_path, ".."))
+		goto err;
+
+	len = strlen(decoded_path)+strlen(docroot)+2;
+	if (!(whole_path = malloc(len))) {
+		perror("malloc");
+		goto err;
+	}
+	evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);
+
+	if (stat(whole_path, &st)<0) {
+		goto err;
+	}
+
+	/* This holds the content we're sending. */
+	evb = evbuffer_new();
+
+	if (S_ISDIR(st.st_mode)) {
+		/* If it's a directory, read the comments and make a little
+		 * index page */
+#ifdef WIN32
+		HANDLE d;
+		WIN32_FIND_DATAA ent;
+		char *pattern;
+		size_t dirlen;
+#else
+		DIR *d;
+		struct dirent *ent;
+#endif
+		const char *trailing_slash = "";
+
+		if (!strlen(path) || path[strlen(path)-1] != '/')
+			trailing_slash = "/";
+
+#ifdef WIN32
+		dirlen = strlen(whole_path);
+		pattern = malloc(dirlen+3);
+		memcpy(pattern, whole_path, dirlen);
+		pattern[dirlen] = '\\';
+		pattern[dirlen+1] = '*';
+		pattern[dirlen+2] = '\0';
+		d = FindFirstFileA(pattern, &ent);
+		free(pattern);
+		if (d == INVALID_HANDLE_VALUE)
+			goto err;
+#else
+		if (!(d = opendir(whole_path)))
+			goto err;
+#endif
+
+		evbuffer_add_printf(evb, "<html>\n <head>\n"
+		    "  <title>%s</title>\n"
+		    "  <base href='%s%s%s'>\n"
+		    " </head>\n"
+		    " <body>\n"
+		    "  <h1>%s</h1>\n"
+		    "  <ul>\n",
+		    decoded_path, /* XXX html-escape this. */
+		    uri_root, path, /* XXX html-escape this? */
+		    trailing_slash,
+		    decoded_path /* XXX html-escape this */);
+#ifdef WIN32
+		do {
+			const char *name = ent.cFileName;
+#else
+		while ((ent = readdir(d))) {
+			const char *name = ent->d_name;
+#endif
+			evbuffer_add_printf(evb,
+			    "    <li><a href=\"%s\">%s</a>\n",
+			    name, name);/* XXX escape this */
+#ifdef WIN32
+		} while (FindNextFileA(d, &ent));
+#else
+		}
+#endif
+		evbuffer_add_printf(evb, "</ul></body></html>\n");
+#ifdef WIN32
+		FindClose(d);
+#else
+		closedir(d);
+#endif
+		evhttp_add_header(evhttp_request_get_output_headers(req),
+		    "Content-Type", "text/html");
+	} else {
+		/* Otherwise it's a file; add it to the buffer to get
+		 * sent via sendfile */
+		const char *type = guess_content_type(decoded_path);
+		if ((fd = open(whole_path, O_RDONLY)) < 0) {
+			perror("open");
+			goto err;
+		}
+
+		if (fstat(fd, &st)<0) {
+			/* Make sure the length still matches, now that we
+			 * opened the file :/ */
+			perror("fstat");
+			goto err;
+		}
+		evhttp_add_header(evhttp_request_get_output_headers(req),
+		    "Content-Type", type);
+		evbuffer_add_file(evb, fd, 0, st.st_size);
+	}
+
+	evhttp_send_reply(req, 200, "OK", evb);
+	goto done;
+err:
+	evhttp_send_error(req, 404, "Document was not found");
+	if (fd>=0)
+		close(fd);
+done:
+	if (decoded)
+		evhttp_uri_free(decoded);
+	if (decoded_path)
+		free(decoded_path);
+	if (whole_path)
+		free(whole_path);
+	if (evb)
+		evbuffer_free(evb);
+}
+
+static void
+syntax(void)
+{
+	fprintf(stdout, "Syntax: http-server <docroot>\n");
+}
+
+int
+main(int argc, char **argv)
+{
+	struct event_base *base;
+	struct evhttp *http;
+	struct evhttp_bound_socket *handle;
+
+	unsigned short port = 0;
+#ifdef WIN32
+	WSADATA WSAData;
+	WSAStartup(0x101, &WSAData);
+#else
+	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+		return (1);
+#endif
+	if (argc < 2) {
+		syntax();
+		return 1;
+	}
+
+	base = event_base_new();
+	if (!base) {
+		fprintf(stderr, "Couldn't create an event_base: exiting\n");
+		return 1;
+	}
+
+	/* Create a new evhttp object to handle requests. */
+	http = evhttp_new(base);
+	if (!http) {
+		fprintf(stderr, "couldn't create evhttp. Exiting.\n");
+		return 1;
+	}
+
+	/* The /dump URI will dump all requests to stdout and say 200 ok. */
+	evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
+
+	/* We want to accept arbitrary requests, so we need to set a "generic"
+	 * cb.  We can also add callbacks for specific paths. */
+	evhttp_set_gencb(http, send_document_cb, argv[1]);
+
+	/* Now we tell the evhttp what port to listen on */
+	handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
+	if (!handle) {
+		fprintf(stderr, "couldn't bind to port %d. Exiting.\n",
+		    (int)port);
+		return 1;
+	}
+
+	{
+		/* Extract and display the address we're listening on. */
+		struct sockaddr_storage ss;
+		evutil_socket_t fd;
+		ev_socklen_t socklen = sizeof(ss);
+		char addrbuf[128];
+		void *inaddr;
+		const char *addr;
+		int got_port = -1;
+		fd = evhttp_bound_socket_get_fd(handle);
+		memset(&ss, 0, sizeof(ss));
+		if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
+			perror("getsockname() failed");
+			return 1;
+		}
+		if (ss.ss_family == AF_INET) {
+			got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
+			inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
+		} else if (ss.ss_family == AF_INET6) {
+			got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
+			inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
+		} else {
+			fprintf(stderr, "Weird address family %d\n",
+			    ss.ss_family);
+			return 1;
+		}
+		addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
+		    sizeof(addrbuf));
+		if (addr) {
+			printf("Listening on %s:%d\n", addr, got_port);
+			evutil_snprintf(uri_root, sizeof(uri_root),
+			    "http://%s:%d",addr,got_port);
+		} else {
+			fprintf(stderr, "evutil_inet_ntop failed\n");
+			return 1;
+		}
+	}
+
+	event_base_dispatch(base);
+
+	return 0;
+}
diff --git a/sample/le-proxy.c b/sample/le-proxy.c
new file mode 100644
index 0000000..446bfb5
--- /dev/null
+++ b/sample/le-proxy.c
@@ -0,0 +1,278 @@
+/*
+  This example code shows how to write an (optionally encrypting) SSL proxy
+  with Libevent's bufferevent layer.
+
+  XXX It's a little ugly and should probably be cleaned up.
+ */
+
+#include <stdio.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#endif
+
+#include <event2/bufferevent_ssl.h>
+#include <event2/bufferevent.h>
+#include <event2/buffer.h>
+#include <event2/listener.h>
+#include <event2/util.h>
+
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <openssl/rand.h>
+
+static struct event_base *base;
+static struct sockaddr_storage listen_on_addr;
+static struct sockaddr_storage connect_to_addr;
+static int connect_to_addrlen;
+static int use_wrapper = 1;
+
+static SSL_CTX *ssl_ctx = NULL;
+
+#define MAX_OUTPUT (512*1024)
+
+static void drained_writecb(struct bufferevent *bev, void *ctx);
+static void eventcb(struct bufferevent *bev, short what, void *ctx);
+
+static void
+readcb(struct bufferevent *bev, void *ctx)
+{
+	struct bufferevent *partner = ctx;
+	struct evbuffer *src, *dst;
+	size_t len;
+	src = bufferevent_get_input(bev);
+	len = evbuffer_get_length(src);
+	if (!partner) {
+		evbuffer_drain(src, len);
+		return;
+	}
+	dst = bufferevent_get_output(partner);
+	evbuffer_add_buffer(dst, src);
+
+	if (evbuffer_get_length(dst) >= MAX_OUTPUT) {
+		/* We're giving the other side data faster than it can
+		 * pass it on.  Stop reading here until we have drained the
+		 * other side to MAX_OUTPUT/2 bytes. */
+		bufferevent_setcb(partner, readcb, drained_writecb,
+		    eventcb, bev);
+		bufferevent_setwatermark(partner, EV_WRITE, MAX_OUTPUT/2,
+		    MAX_OUTPUT);
+		bufferevent_disable(bev, EV_READ);
+	}
+}
+
+static void
+drained_writecb(struct bufferevent *bev, void *ctx)
+{
+	struct bufferevent *partner = ctx;
+
+	/* We were choking the other side until we drained our outbuf a bit.
+	 * Now it seems drained. */
+	bufferevent_setcb(bev, readcb, NULL, eventcb, partner);
+	bufferevent_setwatermark(bev, EV_WRITE, 0, 0);
+	if (partner)
+		bufferevent_enable(partner, EV_READ);
+}
+
+static void
+close_on_finished_writecb(struct bufferevent *bev, void *ctx)
+{
+	struct evbuffer *b = bufferevent_get_output(bev);
+
+	if (evbuffer_get_length(b) == 0) {
+		bufferevent_free(bev);
+	}
+}
+
+static void
+eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+	struct bufferevent *partner = ctx;
+
+	if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
+		if (what & BEV_EVENT_ERROR) {
+			unsigned long err;
+			while ((err = (bufferevent_get_openssl_error(bev)))) {
+				const char *msg = (const char*)
+				    ERR_reason_error_string(err);
+				const char *lib = (const char*)
+				    ERR_lib_error_string(err);
+				const char *func = (const char*)
+				    ERR_func_error_string(err);
+				fprintf(stderr,
+				    "%s in %s %s\n", msg, lib, func);
+			}
+			if (errno)
+				perror("connection error");
+		}
+
+		if (partner) {
+			/* Flush all pending data */
+			readcb(bev, ctx);
+
+			if (evbuffer_get_length(
+				    bufferevent_get_output(partner))) {
+				/* We still have to flush data from the other
+				 * side, but when that's done, close the other
+				 * side. */
+				bufferevent_setcb(partner,
+				    NULL, close_on_finished_writecb,
+				    eventcb, NULL);
+				bufferevent_disable(partner, EV_READ);
+			} else {
+				/* We have nothing left to say to the other
+				 * side; close it. */
+				bufferevent_free(partner);
+			}
+		}
+		bufferevent_free(bev);
+	}
+}
+
+static void
+syntax(void)
+{
+	fputs("Syntax:\n", stderr);
+	fputs("   le-proxy [-s] [-W] <listen-on-addr> <connect-to-addr>\n", stderr);
+	fputs("Example:\n", stderr);
+	fputs("   le-proxy 127.0.0.1:8888 1.2.3.4:80\n", stderr);
+
+	exit(1);
+}
+
+static void
+accept_cb(struct evconnlistener *listener, evutil_socket_t fd,
+    struct sockaddr *a, int slen, void *p)
+{
+	struct bufferevent *b_out, *b_in;
+	/* Create two linked bufferevent objects: one to connect, one for the
+	 * new connection */
+	b_in = bufferevent_socket_new(base, fd,
+	    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+
+	if (!ssl_ctx || use_wrapper)
+		b_out = bufferevent_socket_new(base, -1,
+		    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+	else {
+		SSL *ssl = SSL_new(ssl_ctx);
+		b_out = bufferevent_openssl_socket_new(base, -1, ssl,
+		    BUFFEREVENT_SSL_CONNECTING,
+		    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+	}
+
+	assert(b_in && b_out);
+
+	if (bufferevent_socket_connect(b_out,
+		(struct sockaddr*)&connect_to_addr, connect_to_addrlen)<0) {
+		perror("bufferevent_socket_connect");
+		bufferevent_free(b_out);
+		bufferevent_free(b_in);
+		return;
+	}
+
+	if (ssl_ctx && use_wrapper) {
+		struct bufferevent *b_ssl;
+		SSL *ssl = SSL_new(ssl_ctx);
+		b_ssl = bufferevent_openssl_filter_new(base,
+		    b_out, ssl, BUFFEREVENT_SSL_CONNECTING,
+		    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+		if (!b_ssl) {
+			perror("Bufferevent_openssl_new");
+			bufferevent_free(b_out);
+			bufferevent_free(b_in);
+		}
+		b_out = b_ssl;
+	}
+
+	bufferevent_setcb(b_in, readcb, NULL, eventcb, b_out);
+	bufferevent_setcb(b_out, readcb, NULL, eventcb, b_in);
+
+	bufferevent_enable(b_in, EV_READ|EV_WRITE);
+	bufferevent_enable(b_out, EV_READ|EV_WRITE);
+}
+
+int
+main(int argc, char **argv)
+{
+	int i;
+	int socklen;
+
+	int use_ssl = 0;
+	struct evconnlistener *listener;
+
+	if (argc < 3)
+		syntax();
+
+	for (i=1; i < argc; ++i) {
+		if (!strcmp(argv[i], "-s")) {
+			use_ssl = 1;
+		} else if (!strcmp(argv[i], "-W")) {
+			use_wrapper = 0;
+		} else if (argv[i][0] == '-') {
+			syntax();
+		} else
+			break;
+	}
+
+	if (i+2 != argc)
+		syntax();
+
+	memset(&listen_on_addr, 0, sizeof(listen_on_addr));
+	socklen = sizeof(listen_on_addr);
+	if (evutil_parse_sockaddr_port(argv[i],
+		(struct sockaddr*)&listen_on_addr, &socklen)<0) {
+		int p = atoi(argv[i]);
+		struct sockaddr_in *sin = (struct sockaddr_in*)&listen_on_addr;
+		if (p < 1 || p > 65535)
+			syntax();
+		sin->sin_port = htons(p);
+		sin->sin_addr.s_addr = htonl(0x7f000001);
+		sin->sin_family = AF_INET;
+		socklen = sizeof(struct sockaddr_in);
+	}
+
+	memset(&connect_to_addr, 0, sizeof(connect_to_addr));
+	connect_to_addrlen = sizeof(connect_to_addr);
+	if (evutil_parse_sockaddr_port(argv[i+1],
+		(struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0)
+		syntax();
+
+	base = event_base_new();
+	if (!base) {
+		perror("event_base_new()");
+		return 1;
+	}
+
+	if (use_ssl) {
+		int r;
+		SSL_library_init();
+		ERR_load_crypto_strings();
+		SSL_load_error_strings();
+		OpenSSL_add_all_algorithms();
+		r = RAND_poll();
+		if (r == 0) {
+			fprintf(stderr, "RAND_poll() failed.\n");
+			return 1;
+		}
+		ssl_ctx = SSL_CTX_new(SSLv23_method());
+	}
+
+	listener = evconnlistener_new_bind(base, accept_cb, NULL,
+	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_CLOSE_ON_EXEC|LEV_OPT_REUSEABLE,
+	    -1, (struct sockaddr*)&listen_on_addr, socklen);
+
+	event_base_dispatch(base);
+
+	evconnlistener_free(listener);
+	event_base_free(base);
+
+	return 0;
+}
diff --git a/sample/signal-test.c b/sample/signal-test.c
new file mode 100644
index 0000000..f969e23
--- /dev/null
+++ b/sample/signal-test.c
@@ -0,0 +1,76 @@
+/*
+ * Compile with:
+ * cc -I/usr/local/include -o signal-test \
+ *   signal-test.c -L/usr/local/lib -levent
+ */
+
+#include <sys/types.h>
+
+#include <event2/event-config.h>
+
+#include <sys/stat.h>
+#ifndef WIN32
+#include <sys/queue.h>
+#include <unistd.h>
+#include <sys/time.h>
+#else
+#include <winsock2.h>
+#include <windows.h>
+#endif
+#include <signal.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event.h>
+
+#ifdef _EVENT___func__
+#define __func__ _EVENT___func__
+#endif
+
+int called = 0;
+
+static void
+signal_cb(evutil_socket_t fd, short event, void *arg)
+{
+	struct event *signal = arg;
+
+	printf("%s: got signal %d\n", __func__, EVENT_SIGNAL(signal));
+
+	if (called >= 2)
+		event_del(signal);
+
+	called++;
+}
+
+int
+main(int argc, char **argv)
+{
+	struct event signal_int;
+	struct event_base* base;
+#ifdef WIN32
+	WORD wVersionRequested;
+	WSADATA wsaData;
+
+	wVersionRequested = MAKEWORD(2, 2);
+
+	(void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+	/* Initalize the event library */
+	base = event_base_new();
+
+	/* Initalize one event */
+	event_assign(&signal_int, base, SIGINT, EV_SIGNAL|EV_PERSIST, signal_cb,
+	    &signal_int);
+
+	event_add(&signal_int, NULL);
+
+	event_base_dispatch(base);
+	event_base_free(base);
+
+	return (0);
+}
+
diff --git a/sample/time-test.c b/sample/time-test.c
new file mode 100644
index 0000000..77d4e20
--- /dev/null
+++ b/sample/time-test.c
@@ -0,0 +1,107 @@
+/*
+ * XXX This sample code was once meant to show how to use the basic Libevent
+ * interfaces, but it never worked on non-Unix platforms, and some of the
+ * interfaces have changed since it was first written.  It should probably
+ * be removed or replaced with something better.
+ *
+ * Compile with:
+ * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
+ */
+
+#include <sys/types.h>
+
+#include <event2/event-config.h>
+
+#include <sys/stat.h>
+#ifndef WIN32
+#include <sys/queue.h>
+#include <unistd.h>
+#endif
+#include <time.h>
+#ifdef _EVENT_HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event2/event.h>
+#include <event2/event_struct.h>
+#include <event2/util.h>
+
+#ifdef WIN32
+#include <winsock2.h>
+#endif
+
+struct timeval lasttime;
+
+int event_is_persistent;
+
+static void
+timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+	struct timeval newtime, difference;
+	struct event *timeout = arg;
+	double elapsed;
+
+	evutil_gettimeofday(&newtime, NULL);
+	evutil_timersub(&newtime, &lasttime, &difference);
+	elapsed = difference.tv_sec +
+	    (difference.tv_usec / 1.0e6);
+
+	printf("timeout_cb called at %d: %.3f seconds elapsed.\n",
+	    (int)newtime.tv_sec, elapsed);
+	lasttime = newtime;
+
+	if (! event_is_persistent) {
+		struct timeval tv;
+		evutil_timerclear(&tv);
+		tv.tv_sec = 2;
+		event_add(timeout, &tv);
+	}
+}
+
+int
+main(int argc, char **argv)
+{
+	struct event timeout;
+	struct timeval tv;
+	struct event_base *base;
+	int flags;
+
+#ifdef WIN32
+	WORD wVersionRequested;
+	WSADATA wsaData;
+
+	wVersionRequested = MAKEWORD(2, 2);
+
+	(void)WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+	if (argc == 2 && !strcmp(argv[1], "-p")) {
+		event_is_persistent = 1;
+		flags = EV_PERSIST;
+	} else {
+		event_is_persistent = 0;
+		flags = 0;
+	}
+
+	/* Initalize the event library */
+	base = event_base_new();
+
+	/* Initalize one event */
+	event_assign(&timeout, base, -1, flags, timeout_cb, (void*) &timeout);
+
+	evutil_timerclear(&tv);
+	tv.tv_sec = 2;
+	event_add(&timeout, &tv);
+
+	evutil_gettimeofday(&lasttime, NULL);
+
+	event_base_dispatch(base);
+
+	return (0);
+}
+