xref: /libevent-2.1.12/sample/https-client.c (revision aacd674c)
1 /*
2   This is an example of how to hook up evhttp with bufferevent_ssl
3 
4   It just GETs an https URL given on the command-line and prints the response
5   body to stdout.
6 
7   Actually, it also accepts plain http URLs to make it easy to compare http vs
8   https code paths.
9 
10   Loosely based on le-proxy.c.
11  */
12 
13 #include <stdio.h>
14 #include <assert.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <errno.h>
18 
19 #ifdef WIN32
20 #include <winsock2.h>
21 #include <ws2tcpip.h>
22 #else
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #endif
26 
27 #include <event2/bufferevent_ssl.h>
28 #include <event2/bufferevent.h>
29 #include <event2/buffer.h>
30 #include <event2/listener.h>
31 #include <event2/util.h>
32 #include <event2/http.h>
33 #include <event2/http_struct.h>
34 
35 #include <openssl/ssl.h>
36 #include <openssl/err.h>
37 #include <openssl/rand.h>
38 
39 static struct event_base *base;
40 
41 static void
42 http_request_done(struct evhttp_request *req, void *ctx)
43 {
44 	char buffer[256];
45 	int nread;
46 
47 	if (req == NULL) {
48 		/* If req is NULL, it means an error occurred, but
49 		 * sadly we are mostly left guessing what the error
50 		 * might have been.  We'll do our best... */
51 		struct bufferevent *bev = (struct bufferevent *) ctx;
52 		unsigned long oslerr;
53 		int printed_err = 0;
54 		int errcode = EVUTIL_SOCKET_ERROR();
55 		fprintf(stderr, "some request failed - no idea which one though!\n");
56 		/* Print out the OpenSSL error queue that libevent
57 		 * squirreled away for us, if any. */
58 		while ((oslerr = bufferevent_get_openssl_error(bev))) {
59 			ERR_error_string_n(oslerr, buffer, sizeof(buffer));
60 			fprintf(stderr, "%s\n", buffer);
61 			printed_err = 1;
62 		}
63 		/* If the OpenSSL error queue was empty, maybe it was a
64 		 * socket error; let's try printing that. */
65 		if (! printed_err)
66 			fprintf(stderr, "socket error = %s (%d)\n",
67 				evutil_socket_error_to_string(errcode),
68 				errcode);
69 		return;
70 	}
71 
72 	fprintf(stderr, "Response line: %d %s\n",
73 		req->response_code, req->response_code_line);
74 
75 	while ((nread = evbuffer_remove(req->input_buffer, buffer, sizeof(buffer)))
76 	       > 0) {
77 		/* These are just arbitrary chunks of 256 bytes.
78 		 * They are not lines, so we can't treat them as such. */
79 		fwrite(buffer, nread, 1, stdout);
80 	}
81 }
82 
83 static void
84 syntax(void)
85 {
86 	fputs("Syntax:\n", stderr);
87 	fputs("   https-client <https-url>\n", stderr);
88 	fputs("Example:\n", stderr);
89 	fputs("   https-client https://ip.appspot.com/\n", stderr);
90 
91 	exit(1);
92 }
93 
94 static void
95 die(const char *msg)
96 {
97 	fputs(msg, stderr);
98 	exit(1);
99 }
100 
101 static void
102 die_openssl(const char *func)
103 {
104 	fprintf (stderr, "%s failed:\n", func);
105 
106 	/* This is the OpenSSL function that prints the contents of the
107 	 * error stack to the specified file handle. */
108 	ERR_print_errors_fp (stderr);
109 
110 	exit(1);
111 }
112 
113 int
114 main(int argc, char **argv)
115 {
116 	int r;
117 
118 	struct evhttp_uri *http_uri;
119 	const char *url, *scheme, *host, *path, *query;
120 	char uri[256];
121 	int port;
122 
123 	SSL_CTX *ssl_ctx;
124 	SSL *ssl;
125 	struct bufferevent *bev;
126 	struct evhttp_connection *evcon;
127 	struct evhttp_request *req;
128 
129 	if (argc != 2)
130 		syntax();
131 
132 	url = argv[1];
133 	http_uri = evhttp_uri_parse(url);
134 	if (http_uri == NULL) {
135 		die("malformed url");
136 	}
137 
138 	scheme = evhttp_uri_get_scheme(http_uri);
139 	if (scheme == NULL || (strcasecmp(scheme, "https") != 0 &&
140 	                       strcasecmp(scheme, "http") != 0)) {
141 		die("url must be http or https");
142 	}
143 
144 	host = evhttp_uri_get_host(http_uri);
145 	if (host == NULL) {
146 		die("url must have a host");
147 	}
148 
149 	port = evhttp_uri_get_port(http_uri);
150 	if (port == -1) {
151 		port = (strcasecmp(scheme, "http") == 0) ? 80 : 443;
152 	}
153 
154 	path = evhttp_uri_get_path(http_uri);
155 	if (path == NULL) {
156 		path = "/";
157 	}
158 
159 	query = evhttp_uri_get_query(http_uri);
160 	if (query == NULL) {
161 		snprintf(uri, sizeof(uri) - 1, "%s", path);
162 	} else {
163 		snprintf(uri, sizeof(uri) - 1, "%s?%s", path, query);
164 	}
165 	uri[sizeof(uri) - 1] = '\0';
166 
167 	// Initialize OpenSSL
168 	SSL_library_init();
169 	ERR_load_crypto_strings();
170 	SSL_load_error_strings();
171 	OpenSSL_add_all_algorithms();
172 
173 	/* This isn't strictly necessary... OpenSSL performs RAND_poll
174 	 * automatically on first use of random number generator. */
175 	r = RAND_poll();
176 	if (r == 0) {
177 		die_openssl("RAND_poll");
178 	}
179 
180 	/* Create a new OpenSSL context */
181 	ssl_ctx = SSL_CTX_new(SSLv23_method());
182 	if (!ssl_ctx)
183 		die_openssl("SSL_CTX_new");
184 
185 	/* Attempt to use the system's trusted root certificates.
186 	 * (This path is only valid for Debian-based systems.) */
187 	if (1 != SSL_CTX_load_verify_locations(ssl_ctx,
188 					       "/etc/ssl/certs/ca-certificates.crt",
189 					       NULL))
190 		die_openssl("SSL_CTX_load_verify_locations");
191 	SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
192 
193 	// Create event base
194 	base = event_base_new();
195 	if (!base) {
196 		perror("event_base_new()");
197 		return 1;
198 	}
199 
200 	// Create OpenSSL bufferevent and stack evhttp on top of it
201 	ssl = SSL_new(ssl_ctx);
202 	if (ssl == NULL) {
203 		die_openssl("SSL_new()");
204 	}
205 
206 	if (strcasecmp(scheme, "http") == 0) {
207 		bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
208 	} else {
209 		bev = bufferevent_openssl_socket_new(base, -1, ssl,
210 			BUFFEREVENT_SSL_CONNECTING,
211 			BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
212 	}
213 
214 	if (bev == NULL) {
215 		fprintf(stderr, "bufferevent_openssl_socket_new() failed\n");
216 		return 1;
217 	}
218 
219 	bufferevent_openssl_set_allow_dirty_shutdown(bev, 1);
220 
221 	// For simplicity, we let DNS resolution block. Everything else should be
222 	// asynchronous though.
223 	evcon = evhttp_connection_base_bufferevent_new(base, NULL, bev,
224 		host, port);
225 	if (evcon == NULL) {
226 		fprintf(stderr, "evhttp_connection_base_bufferevent_new() failed\n");
227 		return 1;
228 	}
229 
230 	// Fire off the request
231 	req = evhttp_request_new(http_request_done, bev);
232 	if (req == NULL) {
233 		fprintf(stderr, "evhttp_request_new() failed\n");
234 		return 1;
235 	}
236 
237 	evhttp_add_header(req->output_headers, "Host", host);
238 	evhttp_add_header(req->output_headers, "Connection", "close");
239 
240 	r = evhttp_make_request(evcon, req, EVHTTP_REQ_GET, uri);
241 	if (r != 0) {
242 		fprintf(stderr, "evhttp_make_request() failed\n");
243 		return 1;
244 	}
245 
246 	event_base_dispatch(base);
247 
248 	evhttp_connection_free(evcon);
249 	event_base_free(base);
250 
251 	return 0;
252 }
253