1 /*	$NetBSD: bufferevent_openssl.c,v 1.1.1.1 2013/04/11 16:43:25 christos Exp $	*/
2 /*
3  * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/types.h>
29 
30 #include "event2/event-config.h"
31 #include <sys/cdefs.h>
32 __RCSID("$NetBSD: bufferevent_openssl.c,v 1.1.1.1 2013/04/11 16:43:25 christos Exp $");
33 
34 #ifdef _EVENT_HAVE_SYS_TIME_H
35 #include <sys/time.h>
36 #endif
37 
38 #include <errno.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #ifdef _EVENT_HAVE_STDARG_H
43 #include <stdarg.h>
44 #endif
45 #ifdef _EVENT_HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 
49 #ifdef WIN32
50 #include <winsock2.h>
51 #endif
52 
53 #include "event2/bufferevent.h"
54 #include "event2/bufferevent_struct.h"
55 #include "event2/bufferevent_ssl.h"
56 #include "event2/buffer.h"
57 #include "event2/event.h"
58 
59 #include "mm-internal.h"
60 #include "bufferevent-internal.h"
61 #include "log-internal.h"
62 
63 #include <openssl/bio.h>
64 #include <openssl/ssl.h>
65 #include <openssl/err.h>
66 
67 /*
68  * Define an OpenSSL bio that targets a bufferevent.
69  */
70 
71 /* --------------------
72    A BIO is an OpenSSL abstraction that handles reading and writing data.  The
73    library will happily speak SSL over anything that implements a BIO
74    interface.
75 
76    Here we define a BIO implementation that directs its output to a
77    bufferevent.  We'll want to use this only when none of OpenSSL's built-in
78    IO mechanisms work for us.
79    -------------------- */
80 
81 /* every BIO type needs its own integer type value. */
82 #define BIO_TYPE_LIBEVENT 57
83 /* ???? Arguably, we should set BIO_TYPE_FILTER or BIO_TYPE_SOURCE_SINK on
84  * this. */
85 
86 #if 0
87 static void
88 print_err(int val)
89 {
90 	int err;
91 	printf("Error was %d\n", val);
92 
93 	while ((err = ERR_get_error())) {
94 		const char *msg = (const char*)ERR_reason_error_string(err);
95 		const char *lib = (const char*)ERR_lib_error_string(err);
96 		const char *func = (const char*)ERR_func_error_string(err);
97 
98 		printf("%s in %s %s\n", msg, lib, func);
99 	}
100 }
101 #else
102 #define print_err(v) ((void)0)
103 #endif
104 
105 /* Called to initialize a new BIO */
106 static int
bio_bufferevent_new(BIO * b)107 bio_bufferevent_new(BIO *b)
108 {
109 	b->init = 0;
110 	b->num = -1;
111 	b->ptr = NULL; /* We'll be putting the bufferevent in this field.*/
112 	b->flags = 0;
113 	return 1;
114 }
115 
116 /* Called to uninitialize the BIO. */
117 static int
bio_bufferevent_free(BIO * b)118 bio_bufferevent_free(BIO *b)
119 {
120 	if (!b)
121 		return 0;
122 	if (b->shutdown) {
123 		if (b->init && b->ptr)
124 			bufferevent_free(b->ptr);
125 		b->init = 0;
126 		b->flags = 0;
127 		b->ptr = NULL;
128 	}
129 	return 1;
130 }
131 
132 /* Called to extract data from the BIO. */
133 static int
bio_bufferevent_read(BIO * b,char * out,int outlen)134 bio_bufferevent_read(BIO *b, char *out, int outlen)
135 {
136 	int r = 0;
137 	struct evbuffer *input;
138 
139 	BIO_clear_retry_flags(b);
140 
141 	if (!out)
142 		return 0;
143 	if (!b->ptr)
144 		return -1;
145 
146 	input = bufferevent_get_input(b->ptr);
147 	if (evbuffer_get_length(input) == 0) {
148 		/* If there's no data to read, say so. */
149 		BIO_set_retry_read(b);
150 		return -1;
151 	} else {
152 		r = evbuffer_remove(input, out, outlen);
153 	}
154 
155 	return r;
156 }
157 
158 /* Called to write data info the BIO */
159 static int
bio_bufferevent_write(BIO * b,const char * in,int inlen)160 bio_bufferevent_write(BIO *b, const char *in, int inlen)
161 {
162 	struct bufferevent *bufev = b->ptr;
163 	struct evbuffer *output;
164 	size_t outlen;
165 
166 	BIO_clear_retry_flags(b);
167 
168 	if (!b->ptr)
169 		return -1;
170 
171 	output = bufferevent_get_output(bufev);
172 	outlen = evbuffer_get_length(output);
173 
174 	/* Copy only as much data onto the output buffer as can fit under the
175 	 * high-water mark. */
176 	if (bufev->wm_write.high && bufev->wm_write.high <= (outlen+inlen)) {
177 		if (bufev->wm_write.high <= outlen) {
178 			/* If no data can fit, we'll need to retry later. */
179 			BIO_set_retry_write(b);
180 			return -1;
181 		}
182 		inlen = bufev->wm_write.high - outlen;
183 	}
184 
185 	EVUTIL_ASSERT(inlen > 0);
186 	evbuffer_add(output, in, inlen);
187 	return inlen;
188 }
189 
190 /* Called to handle various requests */
191 static long
bio_bufferevent_ctrl(BIO * b,int cmd,long num,void * ptr)192 bio_bufferevent_ctrl(BIO *b, int cmd, long num, void *ptr)
193 {
194 	struct bufferevent *bufev = b->ptr;
195 	long ret = 1;
196 
197 	switch (cmd) {
198 	case BIO_CTRL_GET_CLOSE:
199 		ret = b->shutdown;
200 		break;
201 	case BIO_CTRL_SET_CLOSE:
202 		b->shutdown = (int)num;
203 		break;
204 	case BIO_CTRL_PENDING:
205 		ret = evbuffer_get_length(bufferevent_get_input(bufev)) != 0;
206 		break;
207 	case BIO_CTRL_WPENDING:
208 		ret = evbuffer_get_length(bufferevent_get_output(bufev)) != 0;
209 		break;
210 	/* XXXX These two are given a special-case treatment because
211 	 * of cargo-cultism.  I should come up with a better reason. */
212 	case BIO_CTRL_DUP:
213 	case BIO_CTRL_FLUSH:
214 		ret = 1;
215 		break;
216 	default:
217 		ret = 0;
218 		break;
219 	}
220 	return ret;
221 }
222 
223 /* Called to write a string to the BIO */
224 static int
bio_bufferevent_puts(BIO * b,const char * s)225 bio_bufferevent_puts(BIO *b, const char *s)
226 {
227 	return bio_bufferevent_write(b, s, strlen(s));
228 }
229 
230 /* Method table for the bufferevent BIO */
231 static BIO_METHOD methods_bufferevent = {
232 	BIO_TYPE_LIBEVENT, "bufferevent",
233 	bio_bufferevent_write,
234 	bio_bufferevent_read,
235 	bio_bufferevent_puts,
236 	NULL /* bio_bufferevent_gets */,
237 	bio_bufferevent_ctrl,
238 	bio_bufferevent_new,
239 	bio_bufferevent_free,
240 	NULL /* callback_ctrl */,
241 };
242 
243 /* Return the method table for the bufferevents BIO */
244 static BIO_METHOD *
BIO_s_bufferevent(void)245 BIO_s_bufferevent(void)
246 {
247 	return &methods_bufferevent;
248 }
249 
250 /* Create a new BIO to wrap communication around a bufferevent.  If close_flag
251  * is true, the bufferevent will be freed when the BIO is closed. */
252 static BIO *
BIO_new_bufferevent(struct bufferevent * bufferevent,int close_flag)253 BIO_new_bufferevent(struct bufferevent *bufferevent, int close_flag)
254 {
255 	BIO *result;
256 	if (!bufferevent)
257 		return NULL;
258 	if (!(result = BIO_new(BIO_s_bufferevent())))
259 		return NULL;
260 	result->init = 1;
261 	result->ptr = bufferevent;
262 	result->shutdown = close_flag ? 1 : 0;
263 	return result;
264 }
265 
266 /* --------------------
267    Now, here's the OpenSSL-based implementation of bufferevent.
268 
269    The implementation comes in two flavors: one that connects its SSL object
270    to an underlying bufferevent using a BIO_bufferevent, and one that has the
271    SSL object connect to a socket directly.  The latter should generally be
272    faster, except on Windows, where your best bet is using a
273    bufferevent_async.
274 
275    (OpenSSL supports many other BIO types, too.  But we can't use any unless
276    we have a good way to get notified when they become readable/writable.)
277    -------------------- */
278 
279 struct bio_data_counts {
280 	unsigned long n_written;
281 	unsigned long n_read;
282 };
283 
284 struct bufferevent_openssl {
285 	/* Shared fields with common bufferevent implementation code.
286 	   If we were set up with an underlying bufferevent, we use the
287 	   events here as timers only.  If we have an SSL, then we use
288 	   the events as socket events.
289 	 */
290 	struct bufferevent_private bev;
291 	/* An underlying bufferevent that we're directing our output to.
292 	   If it's NULL, then we're connected to an fd, not an evbuffer. */
293 	struct bufferevent *underlying;
294 	/* The SSL object doing our encryption. */
295 	SSL *ssl;
296 
297 	/* A callback that's invoked when data arrives on our outbuf so we
298 	   know to write data to the SSL. */
299 	struct evbuffer_cb_entry *outbuf_cb;
300 
301 	/* A count of how much data the bios have read/written total.  Used
302 	   for rate-limiting. */
303 	struct bio_data_counts counts;
304 
305 	/* If this value is greater than 0, then the last SSL_write blocked,
306 	 * and we need to try it again with this many bytes. */
307 	ev_ssize_t last_write;
308 
309 #define NUM_ERRORS 3
310 	ev_uint32_t errors[NUM_ERRORS];
311 
312 	/* When we next get available space, we should say "read" instead of
313 	   "write". This can happen if there's a renegotiation during a read
314 	   operation. */
315 	unsigned read_blocked_on_write : 1;
316 	/* When we next get data, we should say "write" instead of "read". */
317 	unsigned write_blocked_on_read : 1;
318 	/* XXX */
319 	unsigned allow_dirty_shutdown : 1;
320 	/* XXXX */
321 	unsigned fd_is_set : 1;
322 	/* XXX */
323 	unsigned n_errors : 2;
324 
325 	/* Are we currently connecting, accepting, or doing IO? */
326 	unsigned state : 2;
327 };
328 
329 static int be_openssl_enable(struct bufferevent *, short);
330 static int be_openssl_disable(struct bufferevent *, short);
331 static void be_openssl_destruct(struct bufferevent *);
332 static int be_openssl_adj_timeouts(struct bufferevent *);
333 static int be_openssl_flush(struct bufferevent *bufev,
334     short iotype, enum bufferevent_flush_mode mode);
335 static int be_openssl_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
336 
337 const struct bufferevent_ops bufferevent_ops_openssl = {
338 	"ssl",
339 	evutil_offsetof(struct bufferevent_openssl, bev.bev),
340 	be_openssl_enable,
341 	be_openssl_disable,
342 	be_openssl_destruct,
343 	be_openssl_adj_timeouts,
344 	be_openssl_flush,
345 	be_openssl_ctrl,
346 };
347 
348 /* Given a bufferevent, return a pointer to the bufferevent_openssl that
349  * contains it, if any. */
350 static inline struct bufferevent_openssl *
upcast(struct bufferevent * bev)351 upcast(struct bufferevent *bev)
352 {
353 	struct bufferevent_openssl *bev_o;
354 	if (bev->be_ops != &bufferevent_ops_openssl)
355 		return NULL;
356 	bev_o = (void*)( ((char*)bev) -
357 			 evutil_offsetof(struct bufferevent_openssl, bev.bev));
358 	EVUTIL_ASSERT(bev_o->bev.bev.be_ops == &bufferevent_ops_openssl);
359 	return bev_o;
360 }
361 
362 static inline void
put_error(struct bufferevent_openssl * bev_ssl,unsigned long err)363 put_error(struct bufferevent_openssl *bev_ssl, unsigned long err)
364 {
365 	if (bev_ssl->n_errors == NUM_ERRORS)
366 		return;
367 	/* The error type according to openssl is "unsigned long", but
368 	   openssl never uses more than 32 bits of it.  It _can't_ use more
369 	   than 32 bits of it, since it needs to report errors on systems
370 	   where long is only 32 bits.
371 	 */
372 	bev_ssl->errors[bev_ssl->n_errors++] = (ev_uint32_t) err;
373 }
374 
375 /* Have the base communications channel (either the underlying bufferevent or
376  * ev_read and ev_write) start reading.  Take the read-blocked-on-write flag
377  * into account. */
378 static int
start_reading(struct bufferevent_openssl * bev_ssl)379 start_reading(struct bufferevent_openssl *bev_ssl)
380 {
381 	if (bev_ssl->underlying) {
382 		bufferevent_unsuspend_read(bev_ssl->underlying,
383 		    BEV_SUSPEND_FILT_READ);
384 		return 0;
385 	} else {
386 		struct bufferevent *bev = &bev_ssl->bev.bev;
387 		int r;
388 		r = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
389 		if (r == 0 && bev_ssl->read_blocked_on_write)
390 			r = _bufferevent_add_event(&bev->ev_write,
391 			    &bev->timeout_write);
392 		return r;
393 	}
394 }
395 
396 /* Have the base communications channel (either the underlying bufferevent or
397  * ev_read and ev_write) start writing.  Take the write-blocked-on-read flag
398  * into account. */
399 static int
start_writing(struct bufferevent_openssl * bev_ssl)400 start_writing(struct bufferevent_openssl *bev_ssl)
401 {
402 	int r = 0;
403 	if (bev_ssl->underlying) {
404 		;
405 	} else {
406 		struct bufferevent *bev = &bev_ssl->bev.bev;
407 		r = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
408 		if (!r && bev_ssl->write_blocked_on_read)
409 			r = _bufferevent_add_event(&bev->ev_read,
410 			    &bev->timeout_read);
411 	}
412 	return r;
413 }
414 
415 static void
stop_reading(struct bufferevent_openssl * bev_ssl)416 stop_reading(struct bufferevent_openssl *bev_ssl)
417 {
418 	if (bev_ssl->write_blocked_on_read)
419 		return;
420 	if (bev_ssl->underlying) {
421 		bufferevent_suspend_read(bev_ssl->underlying,
422 		    BEV_SUSPEND_FILT_READ);
423 	} else {
424 		struct bufferevent *bev = &bev_ssl->bev.bev;
425 		event_del(&bev->ev_read);
426 	}
427 }
428 
429 static void
stop_writing(struct bufferevent_openssl * bev_ssl)430 stop_writing(struct bufferevent_openssl *bev_ssl)
431 {
432 	if (bev_ssl->read_blocked_on_write)
433 		return;
434 	if (bev_ssl->underlying) {
435 		;
436 	} else {
437 		struct bufferevent *bev = &bev_ssl->bev.bev;
438 		event_del(&bev->ev_write);
439 	}
440 }
441 
442 static int
set_rbow(struct bufferevent_openssl * bev_ssl)443 set_rbow(struct bufferevent_openssl *bev_ssl)
444 {
445 	if (!bev_ssl->underlying)
446 		stop_reading(bev_ssl);
447 	bev_ssl->read_blocked_on_write = 1;
448 	return start_writing(bev_ssl);
449 }
450 
451 static int
set_wbor(struct bufferevent_openssl * bev_ssl)452 set_wbor(struct bufferevent_openssl *bev_ssl)
453 {
454 	if (!bev_ssl->underlying)
455 		stop_writing(bev_ssl);
456 	bev_ssl->write_blocked_on_read = 1;
457 	return start_reading(bev_ssl);
458 }
459 
460 static int
clear_rbow(struct bufferevent_openssl * bev_ssl)461 clear_rbow(struct bufferevent_openssl *bev_ssl)
462 {
463 	struct bufferevent *bev = &bev_ssl->bev.bev;
464 	int r = 0;
465 	bev_ssl->read_blocked_on_write = 0;
466 	if (!(bev->enabled & EV_WRITE))
467 		stop_writing(bev_ssl);
468 	if (bev->enabled & EV_READ)
469 		r = start_reading(bev_ssl);
470 	return r;
471 }
472 
473 
474 static int
clear_wbor(struct bufferevent_openssl * bev_ssl)475 clear_wbor(struct bufferevent_openssl *bev_ssl)
476 {
477 	struct bufferevent *bev = &bev_ssl->bev.bev;
478 	int r = 0;
479 	bev_ssl->write_blocked_on_read = 0;
480 	if (!(bev->enabled & EV_READ))
481 		stop_reading(bev_ssl);
482 	if (bev->enabled & EV_WRITE)
483 		r = start_writing(bev_ssl);
484 	return r;
485 }
486 
487 static void
conn_closed(struct bufferevent_openssl * bev_ssl,int errcode,int ret)488 conn_closed(struct bufferevent_openssl *bev_ssl, int errcode, int ret)
489 {
490 	int event = BEV_EVENT_ERROR;
491 	int dirty_shutdown = 0;
492 	unsigned long err;
493 
494 	switch (errcode) {
495 	case SSL_ERROR_ZERO_RETURN:
496 		/* Possibly a clean shutdown. */
497 		if (SSL_get_shutdown(bev_ssl->ssl) & SSL_RECEIVED_SHUTDOWN)
498 			event = BEV_EVENT_EOF;
499 		else
500 			dirty_shutdown = 1;
501 		break;
502 	case SSL_ERROR_SYSCALL:
503 		/* IO error; possibly a dirty shutdown. */
504 		if (ret == 0 && ERR_peek_error() == 0)
505 			dirty_shutdown = 1;
506 		break;
507 	case SSL_ERROR_SSL:
508 		/* Protocol error. */
509 		break;
510 	case SSL_ERROR_WANT_X509_LOOKUP:
511 		/* XXXX handle this. */
512 		break;
513 	case SSL_ERROR_NONE:
514 	case SSL_ERROR_WANT_READ:
515 	case SSL_ERROR_WANT_WRITE:
516 	case SSL_ERROR_WANT_CONNECT:
517 	case SSL_ERROR_WANT_ACCEPT:
518 	default:
519 		/* should be impossible; treat as normal error. */
520 		event_warnx("BUG: Unexpected OpenSSL error code %d", errcode);
521 		break;
522 	}
523 
524 	while ((err = ERR_get_error())) {
525 		put_error(bev_ssl, err);
526 	}
527 
528 	if (dirty_shutdown && bev_ssl->allow_dirty_shutdown)
529 		event = BEV_EVENT_EOF;
530 
531 	stop_reading(bev_ssl);
532 	stop_writing(bev_ssl);
533 
534 	_bufferevent_run_eventcb(&bev_ssl->bev.bev, event);
535 }
536 
537 static void
init_bio_counts(struct bufferevent_openssl * bev_ssl)538 init_bio_counts(struct bufferevent_openssl *bev_ssl)
539 {
540 	bev_ssl->counts.n_written =
541 	    BIO_number_written(SSL_get_wbio(bev_ssl->ssl));
542 	bev_ssl->counts.n_read =
543 	    BIO_number_read(SSL_get_rbio(bev_ssl->ssl));
544 }
545 
546 static inline void
decrement_buckets(struct bufferevent_openssl * bev_ssl)547 decrement_buckets(struct bufferevent_openssl *bev_ssl)
548 {
549 	unsigned long num_w = BIO_number_written(SSL_get_wbio(bev_ssl->ssl));
550 	unsigned long num_r = BIO_number_read(SSL_get_rbio(bev_ssl->ssl));
551 	/* These next two subtractions can wrap around. That's okay. */
552 	unsigned long w = num_w - bev_ssl->counts.n_written;
553 	unsigned long r = num_r - bev_ssl->counts.n_read;
554 	if (w)
555 		_bufferevent_decrement_write_buckets(&bev_ssl->bev, w);
556 	if (r)
557 		_bufferevent_decrement_read_buckets(&bev_ssl->bev, r);
558 	bev_ssl->counts.n_written = num_w;
559 	bev_ssl->counts.n_read = num_r;
560 }
561 
562 #define OP_MADE_PROGRESS 1
563 #define OP_BLOCKED 2
564 #define OP_ERR 4
565 
566 /* Return a bitmask of OP_MADE_PROGRESS (if we read anything); OP_BLOCKED (if
567    we're now blocked); and OP_ERR (if an error occurred). */
568 static int
do_read(struct bufferevent_openssl * bev_ssl,int n_to_read)569 do_read(struct bufferevent_openssl *bev_ssl, int n_to_read) {
570 	/* Requires lock */
571 	struct bufferevent *bev = &bev_ssl->bev.bev;
572 	struct evbuffer *input = bev->input;
573 	int r, n, i, n_used = 0, atmost;
574 	struct evbuffer_iovec space[2];
575 	int result = 0;
576 
577 	if (bev_ssl->bev.read_suspended)
578 		return 0;
579 
580 	atmost = _bufferevent_get_read_max(&bev_ssl->bev);
581 	if (n_to_read > atmost)
582 		n_to_read = atmost;
583 
584 	n = evbuffer_reserve_space(input, n_to_read, space, 2);
585 	if (n < 0)
586 		return OP_ERR;
587 
588 	for (i=0; i<n; ++i) {
589 		if (bev_ssl->bev.read_suspended)
590 			break;
591 		r = SSL_read(bev_ssl->ssl, space[i].iov_base, space[i].iov_len);
592 		if (r>0) {
593 			result |= OP_MADE_PROGRESS;
594 			if (bev_ssl->read_blocked_on_write)
595 				if (clear_rbow(bev_ssl) < 0)
596 					return OP_ERR | result;
597 			++n_used;
598 			space[i].iov_len = r;
599 			decrement_buckets(bev_ssl);
600 		} else {
601 			int err = SSL_get_error(bev_ssl->ssl, r);
602 			print_err(err);
603 			switch (err) {
604 			case SSL_ERROR_WANT_READ:
605 				/* Can't read until underlying has more data. */
606 				if (bev_ssl->read_blocked_on_write)
607 					if (clear_rbow(bev_ssl) < 0)
608 						return OP_ERR | result;
609 				break;
610 			case SSL_ERROR_WANT_WRITE:
611 				/* This read operation requires a write, and the
612 				 * underlying is full */
613 				if (!bev_ssl->read_blocked_on_write)
614 					if (set_rbow(bev_ssl) < 0)
615 						return OP_ERR | result;
616 				break;
617 			default:
618 				conn_closed(bev_ssl, err, r);
619 				break;
620 			}
621 			result |= OP_BLOCKED;
622 			break; /* out of the loop */
623 		}
624 	}
625 
626 	if (n_used) {
627 		evbuffer_commit_space(input, space, n_used);
628 		if (bev_ssl->underlying)
629 			BEV_RESET_GENERIC_READ_TIMEOUT(bev);
630 	}
631 
632 	return result;
633 }
634 
635 /* Return a bitmask of OP_MADE_PROGRESS (if we wrote anything); OP_BLOCKED (if
636    we're now blocked); and OP_ERR (if an error occurred). */
637 static int
do_write(struct bufferevent_openssl * bev_ssl,int atmost)638 do_write(struct bufferevent_openssl *bev_ssl, int atmost)
639 {
640 	int i, r, n, n_written = 0;
641 	struct bufferevent *bev = &bev_ssl->bev.bev;
642 	struct evbuffer *output = bev->output;
643 	struct evbuffer_iovec space[8];
644 	int result = 0;
645 
646 	if (bev_ssl->last_write > 0)
647 		atmost = bev_ssl->last_write;
648 	else
649 		atmost = _bufferevent_get_write_max(&bev_ssl->bev);
650 
651 	n = evbuffer_peek(output, atmost, NULL, space, 8);
652 	if (n < 0)
653 		return OP_ERR | result;
654 
655 	if (n > 8)
656 		n = 8;
657 	for (i=0; i < n; ++i) {
658 		if (bev_ssl->bev.write_suspended)
659 			break;
660 
661 		/* SSL_write will (reasonably) return 0 if we tell it to
662 		   send 0 data.  Skip this case so we don't interpret the
663 		   result as an error */
664 		if (space[i].iov_len == 0)
665 			continue;
666 
667 		r = SSL_write(bev_ssl->ssl, space[i].iov_base,
668 		    space[i].iov_len);
669 		if (r > 0) {
670 			result |= OP_MADE_PROGRESS;
671 			if (bev_ssl->write_blocked_on_read)
672 				if (clear_wbor(bev_ssl) < 0)
673 					return OP_ERR | result;
674 			n_written += r;
675 			bev_ssl->last_write = -1;
676 			decrement_buckets(bev_ssl);
677 		} else {
678 			int err = SSL_get_error(bev_ssl->ssl, r);
679 			print_err(err);
680 			switch (err) {
681 			case SSL_ERROR_WANT_WRITE:
682 				/* Can't read until underlying has more data. */
683 				if (bev_ssl->write_blocked_on_read)
684 					if (clear_wbor(bev_ssl) < 0)
685 						return OP_ERR | result;
686 				bev_ssl->last_write = space[i].iov_len;
687 				break;
688 			case SSL_ERROR_WANT_READ:
689 				/* This read operation requires a write, and the
690 				 * underlying is full */
691 				if (!bev_ssl->write_blocked_on_read)
692 					if (set_wbor(bev_ssl) < 0)
693 						return OP_ERR | result;
694 				bev_ssl->last_write = space[i].iov_len;
695 				break;
696 			default:
697 				conn_closed(bev_ssl, err, r);
698 				bev_ssl->last_write = -1;
699 				break;
700 			}
701 			result |= OP_BLOCKED;
702 			break;
703 		}
704 	}
705 	if (n_written) {
706 		evbuffer_drain(output, n_written);
707 		if (bev_ssl->underlying)
708 			BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
709 
710 		if (evbuffer_get_length(output) <= bev->wm_write.low)
711 			_bufferevent_run_writecb(bev);
712 	}
713 	return result;
714 }
715 
716 #define WRITE_FRAME 15000
717 
718 #define READ_DEFAULT 4096
719 
720 /* Try to figure out how many bytes to read; return 0 if we shouldn't be
721  * reading. */
722 static int
bytes_to_read(struct bufferevent_openssl * bev)723 bytes_to_read(struct bufferevent_openssl *bev)
724 {
725 	struct evbuffer *input = bev->bev.bev.input;
726 	struct event_watermark *wm = &bev->bev.bev.wm_read;
727 	int result = READ_DEFAULT;
728 	ev_ssize_t limit;
729 	/* XXX 99% of this is generic code that nearly all bufferevents will
730 	 * want. */
731 
732 	if (bev->write_blocked_on_read) {
733 		return 0;
734 	}
735 
736 	if (! (bev->bev.bev.enabled & EV_READ)) {
737 		return 0;
738 	}
739 
740 	if (bev->bev.read_suspended) {
741 		return 0;
742 	}
743 
744 	if (wm->high) {
745 		if (evbuffer_get_length(input) >= wm->high) {
746 			return 0;
747 		}
748 
749 		result = wm->high - evbuffer_get_length(input);
750 	} else {
751 		result = READ_DEFAULT;
752 	}
753 
754 	/* Respect the rate limit */
755 	limit = _bufferevent_get_read_max(&bev->bev);
756 	if (result > limit) {
757 		result = limit;
758 	}
759 
760 	return result;
761 }
762 
763 
764 /* Things look readable.  If write is blocked on read, write till it isn't.
765  * Read from the underlying buffer until we block or we hit our high-water
766  * mark.
767  */
768 static void
consider_reading(struct bufferevent_openssl * bev_ssl)769 consider_reading(struct bufferevent_openssl *bev_ssl)
770 {
771 	int r;
772 	int n_to_read;
773 	int all_result_flags = 0;
774 
775 	while (bev_ssl->write_blocked_on_read) {
776 		r = do_write(bev_ssl, WRITE_FRAME);
777 		if (r & (OP_BLOCKED|OP_ERR))
778 			break;
779 	}
780 	if (bev_ssl->write_blocked_on_read)
781 		return;
782 
783 	n_to_read = bytes_to_read(bev_ssl);
784 
785 	while (n_to_read) {
786 		r = do_read(bev_ssl, n_to_read);
787 		all_result_flags |= r;
788 
789 		if (r & (OP_BLOCKED|OP_ERR))
790 			break;
791 
792 		if (bev_ssl->bev.read_suspended)
793 			break;
794 
795 		/* Read all pending data.  This won't hit the network
796 		 * again, and will (most importantly) put us in a state
797 		 * where we don't need to read anything else until the
798 		 * socket is readable again.  It'll potentially make us
799 		 * overrun our read high-watermark (somewhat
800 		 * regrettable).  The damage to the rate-limit has
801 		 * already been done, since OpenSSL went and read a
802 		 * whole SSL record anyway. */
803 		n_to_read = SSL_pending(bev_ssl->ssl);
804 
805 		/* XXX This if statement is actually a bad bug, added to avoid
806 		 * XXX a worse bug.
807 		 *
808 		 * The bad bug: It can potentially cause resource unfairness
809 		 * by reading too much data from the underlying bufferevent;
810 		 * it can potentially cause read looping if the underlying
811 		 * bufferevent is a bufferevent_pair and deferred callbacks
812 		 * aren't used.
813 		 *
814 		 * The worse bug: If we didn't do this, then we would
815 		 * potentially not read any more from bev_ssl->underlying
816 		 * until more data arrived there, which could lead to us
817 		 * waiting forever.
818 		 */
819 		if (!n_to_read && bev_ssl->underlying)
820 			n_to_read = bytes_to_read(bev_ssl);
821 	}
822 
823 	if (all_result_flags & OP_MADE_PROGRESS) {
824 		struct bufferevent *bev = &bev_ssl->bev.bev;
825 		struct evbuffer *input = bev->input;
826 
827 		if (evbuffer_get_length(input) >= bev->wm_read.low) {
828 			_bufferevent_run_readcb(bev);
829 		}
830 	}
831 
832 	if (!bev_ssl->underlying) {
833 		/* Should be redundant, but let's avoid busy-looping */
834 		if (bev_ssl->bev.read_suspended ||
835 		    !(bev_ssl->bev.bev.enabled & EV_READ)) {
836 			event_del(&bev_ssl->bev.bev.ev_read);
837 		}
838 	}
839 }
840 
841 static void
consider_writing(struct bufferevent_openssl * bev_ssl)842 consider_writing(struct bufferevent_openssl *bev_ssl)
843 {
844 	int r;
845 	struct evbuffer *output = bev_ssl->bev.bev.output;
846 	struct evbuffer *target = NULL;
847 	struct event_watermark *wm = NULL;
848 
849 	while (bev_ssl->read_blocked_on_write) {
850 		r = do_read(bev_ssl, 1024); /* XXXX 1024 is a hack */
851 		if (r & OP_MADE_PROGRESS) {
852 			struct bufferevent *bev = &bev_ssl->bev.bev;
853 			struct evbuffer *input = bev->input;
854 
855 			if (evbuffer_get_length(input) >= bev->wm_read.low) {
856 				_bufferevent_run_readcb(bev);
857 			}
858 		}
859 		if (r & (OP_ERR|OP_BLOCKED))
860 			break;
861 	}
862 	if (bev_ssl->read_blocked_on_write)
863 		return;
864 	if (bev_ssl->underlying) {
865 		target = bev_ssl->underlying->output;
866 		wm = &bev_ssl->underlying->wm_write;
867 	}
868 	while ((bev_ssl->bev.bev.enabled & EV_WRITE) &&
869 	    (! bev_ssl->bev.write_suspended) &&
870 	    evbuffer_get_length(output) &&
871 	    (!target || (! wm->high || evbuffer_get_length(target) < wm->high))) {
872 		int n_to_write;
873 		if (wm && wm->high)
874 			n_to_write = wm->high - evbuffer_get_length(target);
875 		else
876 			n_to_write = WRITE_FRAME;
877 		r = do_write(bev_ssl, n_to_write);
878 		if (r & (OP_BLOCKED|OP_ERR))
879 			break;
880 	}
881 
882 	if (!bev_ssl->underlying) {
883 		if (evbuffer_get_length(output) == 0) {
884 			event_del(&bev_ssl->bev.bev.ev_write);
885 		} else if (bev_ssl->bev.write_suspended ||
886 		    !(bev_ssl->bev.bev.enabled & EV_WRITE)) {
887 			/* Should be redundant, but let's avoid busy-looping */
888 			event_del(&bev_ssl->bev.bev.ev_write);
889 		}
890 	}
891 }
892 
893 static void
be_openssl_readcb(struct bufferevent * bev_base,void * ctx)894 be_openssl_readcb(struct bufferevent *bev_base, void *ctx)
895 {
896 	struct bufferevent_openssl *bev_ssl = ctx;
897 	consider_reading(bev_ssl);
898 }
899 
900 static void
be_openssl_writecb(struct bufferevent * bev_base,void * ctx)901 be_openssl_writecb(struct bufferevent *bev_base, void *ctx)
902 {
903 	struct bufferevent_openssl *bev_ssl = ctx;
904 	consider_writing(bev_ssl);
905 }
906 
907 static void
be_openssl_eventcb(struct bufferevent * bev_base,short what,void * ctx)908 be_openssl_eventcb(struct bufferevent *bev_base, short what, void *ctx)
909 {
910 	struct bufferevent_openssl *bev_ssl = ctx;
911 	int event = 0;
912 
913 	if (what & BEV_EVENT_EOF) {
914 		if (bev_ssl->allow_dirty_shutdown)
915 			event = BEV_EVENT_EOF;
916 		else
917 			event = BEV_EVENT_ERROR;
918 	} else if (what & BEV_EVENT_TIMEOUT) {
919 		/* We sure didn't set this.  Propagate it to the user. */
920 		event = what;
921 	} else if (what & BEV_EVENT_ERROR) {
922 		/* An error occurred on the connection.  Propagate it to the user. */
923 		event = what;
924 	} else if (what & BEV_EVENT_CONNECTED) {
925 		/* Ignore it.  We're saying SSL_connect() already, which will
926 		   eat it. */
927 	}
928 	if (event)
929 		_bufferevent_run_eventcb(&bev_ssl->bev.bev, event);
930 }
931 
932 static void
be_openssl_readeventcb(evutil_socket_t fd,short what,void * ptr)933 be_openssl_readeventcb(evutil_socket_t fd, short what, void *ptr)
934 {
935 	struct bufferevent_openssl *bev_ssl = ptr;
936 	_bufferevent_incref_and_lock(&bev_ssl->bev.bev);
937 	if (what == EV_TIMEOUT) {
938 		_bufferevent_run_eventcb(&bev_ssl->bev.bev,
939 		    BEV_EVENT_TIMEOUT|BEV_EVENT_READING);
940 	} else {
941 		consider_reading(bev_ssl);
942 	}
943 	_bufferevent_decref_and_unlock(&bev_ssl->bev.bev);
944 }
945 
946 static void
be_openssl_writeeventcb(evutil_socket_t fd,short what,void * ptr)947 be_openssl_writeeventcb(evutil_socket_t fd, short what, void *ptr)
948 {
949 	struct bufferevent_openssl *bev_ssl = ptr;
950 	_bufferevent_incref_and_lock(&bev_ssl->bev.bev);
951 	if (what == EV_TIMEOUT) {
952 		_bufferevent_run_eventcb(&bev_ssl->bev.bev,
953 		    BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING);
954 	} else {
955 		consider_writing(bev_ssl);
956 	}
957 	_bufferevent_decref_and_unlock(&bev_ssl->bev.bev);
958 }
959 
960 static int
set_open_callbacks(struct bufferevent_openssl * bev_ssl,evutil_socket_t fd)961 set_open_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
962 {
963 	if (bev_ssl->underlying) {
964 		bufferevent_setcb(bev_ssl->underlying,
965 		    be_openssl_readcb, be_openssl_writecb, be_openssl_eventcb,
966 		    bev_ssl);
967 		return 0;
968 	} else {
969 		struct bufferevent *bev = &bev_ssl->bev.bev;
970 		int rpending=0, wpending=0, r1=0, r2=0;
971 		if (fd < 0 && bev_ssl->fd_is_set)
972 			fd = event_get_fd(&bev->ev_read);
973 		if (bev_ssl->fd_is_set) {
974 			rpending = event_pending(&bev->ev_read, EV_READ, NULL);
975 			wpending = event_pending(&bev->ev_write, EV_WRITE, NULL);
976 			event_del(&bev->ev_read);
977 			event_del(&bev->ev_write);
978 		}
979 		event_assign(&bev->ev_read, bev->ev_base, fd,
980 		    EV_READ|EV_PERSIST, be_openssl_readeventcb, bev_ssl);
981 		event_assign(&bev->ev_write, bev->ev_base, fd,
982 		    EV_WRITE|EV_PERSIST, be_openssl_writeeventcb, bev_ssl);
983 		if (rpending)
984 			r1 = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
985 		if (wpending)
986 			r2 = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
987 		if (fd >= 0) {
988 			bev_ssl->fd_is_set = 1;
989 		}
990 		return (r1<0 || r2<0) ? -1 : 0;
991 	}
992 }
993 
994 static int
do_handshake(struct bufferevent_openssl * bev_ssl)995 do_handshake(struct bufferevent_openssl *bev_ssl)
996 {
997 	int r;
998 
999 	switch (bev_ssl->state) {
1000 	default:
1001 	case BUFFEREVENT_SSL_OPEN:
1002 		EVUTIL_ASSERT(0);
1003 		return -1;
1004 	case BUFFEREVENT_SSL_CONNECTING:
1005 	case BUFFEREVENT_SSL_ACCEPTING:
1006 		r = SSL_do_handshake(bev_ssl->ssl);
1007 		break;
1008 	}
1009 	decrement_buckets(bev_ssl);
1010 
1011 	if (r==1) {
1012 		/* We're done! */
1013 		bev_ssl->state = BUFFEREVENT_SSL_OPEN;
1014 		set_open_callbacks(bev_ssl, -1); /* XXXX handle failure */
1015 		/* Call do_read and do_write as needed */
1016 		bufferevent_enable(&bev_ssl->bev.bev, bev_ssl->bev.bev.enabled);
1017 		_bufferevent_run_eventcb(&bev_ssl->bev.bev,
1018 		    BEV_EVENT_CONNECTED);
1019 		return 1;
1020 	} else {
1021 		int err = SSL_get_error(bev_ssl->ssl, r);
1022 		print_err(err);
1023 		switch (err) {
1024 		case SSL_ERROR_WANT_WRITE:
1025 			if (!bev_ssl->underlying) {
1026 				stop_reading(bev_ssl);
1027 				return start_writing(bev_ssl);
1028 			}
1029 			return 0;
1030 		case SSL_ERROR_WANT_READ:
1031 			if (!bev_ssl->underlying) {
1032 				stop_writing(bev_ssl);
1033 				return start_reading(bev_ssl);
1034 			}
1035 			return 0;
1036 		default:
1037 			conn_closed(bev_ssl, err, r);
1038 			return -1;
1039 		}
1040 	}
1041 }
1042 
1043 static void
be_openssl_handshakecb(struct bufferevent * bev_base,void * ctx)1044 be_openssl_handshakecb(struct bufferevent *bev_base, void *ctx)
1045 {
1046 	struct bufferevent_openssl *bev_ssl = ctx;
1047 	do_handshake(bev_ssl);/* XXX handle failure */
1048 }
1049 
1050 static void
be_openssl_handshakeeventcb(evutil_socket_t fd,short what,void * ptr)1051 be_openssl_handshakeeventcb(evutil_socket_t fd, short what, void *ptr)
1052 {
1053 	struct bufferevent_openssl *bev_ssl = ptr;
1054 
1055 	_bufferevent_incref_and_lock(&bev_ssl->bev.bev);
1056 	if (what & EV_TIMEOUT) {
1057 		_bufferevent_run_eventcb(&bev_ssl->bev.bev, BEV_EVENT_TIMEOUT);
1058 	} else
1059 		do_handshake(bev_ssl);/* XXX handle failure */
1060 	_bufferevent_decref_and_unlock(&bev_ssl->bev.bev);
1061 }
1062 
1063 static int
set_handshake_callbacks(struct bufferevent_openssl * bev_ssl,evutil_socket_t fd)1064 set_handshake_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
1065 {
1066 	if (bev_ssl->underlying) {
1067 		bufferevent_setcb(bev_ssl->underlying,
1068 		    be_openssl_handshakecb, be_openssl_handshakecb,
1069 		    be_openssl_eventcb,
1070 		    bev_ssl);
1071 		return do_handshake(bev_ssl);
1072 	} else {
1073 		struct bufferevent *bev = &bev_ssl->bev.bev;
1074 		int r1=0, r2=0;
1075 		if (fd < 0 && bev_ssl->fd_is_set)
1076 			fd = event_get_fd(&bev->ev_read);
1077 		if (bev_ssl->fd_is_set) {
1078 			event_del(&bev->ev_read);
1079 			event_del(&bev->ev_write);
1080 		}
1081 		event_assign(&bev->ev_read, bev->ev_base, fd,
1082 		    EV_READ|EV_PERSIST, be_openssl_handshakeeventcb, bev_ssl);
1083 		event_assign(&bev->ev_write, bev->ev_base, fd,
1084 		    EV_WRITE|EV_PERSIST, be_openssl_handshakeeventcb, bev_ssl);
1085 		if (fd >= 0) {
1086 			r1 = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
1087 			r2 = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
1088 			bev_ssl->fd_is_set = 1;
1089 		}
1090 		return (r1<0 || r2<0) ? -1 : 0;
1091 	}
1092 }
1093 
1094 int
bufferevent_ssl_renegotiate(struct bufferevent * bev)1095 bufferevent_ssl_renegotiate(struct bufferevent *bev)
1096 {
1097 	struct bufferevent_openssl *bev_ssl = upcast(bev);
1098 	if (!bev_ssl)
1099 		return -1;
1100 	if (SSL_renegotiate(bev_ssl->ssl) < 0)
1101 		return -1;
1102 	bev_ssl->state = BUFFEREVENT_SSL_CONNECTING;
1103 	if (set_handshake_callbacks(bev_ssl, -1) < 0)
1104 		return -1;
1105 	if (!bev_ssl->underlying)
1106 		return do_handshake(bev_ssl);
1107 	return 0;
1108 }
1109 
1110 static void
be_openssl_outbuf_cb(struct evbuffer * buf,const struct evbuffer_cb_info * cbinfo,void * arg)1111 be_openssl_outbuf_cb(struct evbuffer *buf,
1112     const struct evbuffer_cb_info *cbinfo, void *arg)
1113 {
1114 	struct bufferevent_openssl *bev_ssl = arg;
1115 	int r = 0;
1116 	/* XXX need to hold a reference here. */
1117 
1118 	if (cbinfo->n_added && bev_ssl->state == BUFFEREVENT_SSL_OPEN) {
1119 		if (cbinfo->orig_size == 0)
1120 			r = _bufferevent_add_event(&bev_ssl->bev.bev.ev_write,
1121 			    &bev_ssl->bev.bev.timeout_write);
1122 		consider_writing(bev_ssl);
1123 	}
1124 	/* XXX Handle r < 0 */
1125         (void)r;
1126 }
1127 
1128 
1129 static int
be_openssl_enable(struct bufferevent * bev,short events)1130 be_openssl_enable(struct bufferevent *bev, short events)
1131 {
1132 	struct bufferevent_openssl *bev_ssl = upcast(bev);
1133 	int r1 = 0, r2 = 0;
1134 
1135 	if (bev_ssl->state != BUFFEREVENT_SSL_OPEN)
1136 		return 0;
1137 
1138 	if (events & EV_READ)
1139 		r1 = start_reading(bev_ssl);
1140 	if (events & EV_WRITE)
1141 		r2 = start_writing(bev_ssl);
1142 
1143 	if (bev_ssl->underlying) {
1144 		if (events & EV_READ)
1145 			BEV_RESET_GENERIC_READ_TIMEOUT(bev);
1146 		if (events & EV_WRITE)
1147 			BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
1148 
1149 		if (events & EV_READ)
1150 			consider_reading(bev_ssl);
1151 		if (events & EV_WRITE)
1152 			consider_writing(bev_ssl);
1153 	}
1154 	return (r1 < 0 || r2 < 0) ? -1 : 0;
1155 }
1156 
1157 static int
be_openssl_disable(struct bufferevent * bev,short events)1158 be_openssl_disable(struct bufferevent *bev, short events)
1159 {
1160 	struct bufferevent_openssl *bev_ssl = upcast(bev);
1161 	if (bev_ssl->state != BUFFEREVENT_SSL_OPEN)
1162 		return 0;
1163 
1164 	if (events & EV_READ)
1165 		stop_reading(bev_ssl);
1166 	if (events & EV_WRITE)
1167 		stop_writing(bev_ssl);
1168 
1169 	if (bev_ssl->underlying) {
1170 		if (events & EV_READ)
1171 			BEV_DEL_GENERIC_READ_TIMEOUT(bev);
1172 		if (events & EV_WRITE)
1173 			BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
1174 	}
1175 	return 0;
1176 }
1177 
1178 static void
be_openssl_destruct(struct bufferevent * bev)1179 be_openssl_destruct(struct bufferevent *bev)
1180 {
1181 	struct bufferevent_openssl *bev_ssl = upcast(bev);
1182 
1183 	if (bev_ssl->underlying) {
1184 		_bufferevent_del_generic_timeout_cbs(bev);
1185 	} else {
1186 		event_del(&bev->ev_read);
1187 		event_del(&bev->ev_write);
1188 	}
1189 
1190 	if (bev_ssl->bev.options & BEV_OPT_CLOSE_ON_FREE) {
1191 		if (bev_ssl->underlying) {
1192 			if (BEV_UPCAST(bev_ssl->underlying)->refcnt < 2) {
1193 				event_warnx("BEV_OPT_CLOSE_ON_FREE set on an "
1194 				    "bufferevent with too few references");
1195 			} else {
1196 				bufferevent_free(bev_ssl->underlying);
1197 				bev_ssl->underlying = NULL;
1198 			}
1199 		} else {
1200 			evutil_socket_t fd = -1;
1201 			BIO *bio = SSL_get_wbio(bev_ssl->ssl);
1202 			if (bio)
1203 				fd = BIO_get_fd(bio, NULL);
1204 			if (fd >= 0)
1205 				evutil_closesocket(fd);
1206 		}
1207 		SSL_free(bev_ssl->ssl);
1208 	} else {
1209 		if (bev_ssl->underlying) {
1210 			if (bev_ssl->underlying->errorcb == be_openssl_eventcb)
1211 				bufferevent_setcb(bev_ssl->underlying,
1212 				    NULL,NULL,NULL,NULL);
1213 			bufferevent_unsuspend_read(bev_ssl->underlying,
1214 			    BEV_SUSPEND_FILT_READ);
1215 		}
1216 	}
1217 }
1218 
1219 static int
be_openssl_adj_timeouts(struct bufferevent * bev)1220 be_openssl_adj_timeouts(struct bufferevent *bev)
1221 {
1222 	struct bufferevent_openssl *bev_ssl = upcast(bev);
1223 
1224 	if (bev_ssl->underlying)
1225 		return _bufferevent_generic_adj_timeouts(bev);
1226 	else {
1227 		int r1=0, r2=0;
1228 		if (event_pending(&bev->ev_read, EV_READ, NULL))
1229 			r1 = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
1230 		if (event_pending(&bev->ev_write, EV_WRITE, NULL))
1231 			r2 = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
1232 		return (r1<0 || r2<0) ? -1 : 0;
1233 	}
1234 }
1235 
1236 static int
be_openssl_flush(struct bufferevent * bufev,short iotype,enum bufferevent_flush_mode mode)1237 be_openssl_flush(struct bufferevent *bufev,
1238     short iotype, enum bufferevent_flush_mode mode)
1239 {
1240 	/* XXXX Implement this. */
1241 	return 0;
1242 }
1243 
1244 static int
be_openssl_ctrl(struct bufferevent * bev,enum bufferevent_ctrl_op op,union bufferevent_ctrl_data * data)1245 be_openssl_ctrl(struct bufferevent *bev,
1246     enum bufferevent_ctrl_op op, union bufferevent_ctrl_data *data)
1247 {
1248 	struct bufferevent_openssl *bev_ssl = upcast(bev);
1249 	switch (op) {
1250 	case BEV_CTRL_SET_FD:
1251 		if (bev_ssl->underlying)
1252 			return -1;
1253 		{
1254 			BIO *bio;
1255 			bio = BIO_new_socket(data->fd, 0);
1256 			SSL_set_bio(bev_ssl->ssl, bio, bio);
1257 			bev_ssl->fd_is_set = 1;
1258 		}
1259 		if (bev_ssl->state == BUFFEREVENT_SSL_OPEN)
1260 			return set_open_callbacks(bev_ssl, data->fd);
1261 		else {
1262 			return set_handshake_callbacks(bev_ssl, data->fd);
1263 		}
1264 	case BEV_CTRL_GET_FD:
1265 		if (bev_ssl->underlying)
1266 			return -1;
1267 		if (!bev_ssl->fd_is_set)
1268 			return -1;
1269 		data->fd = event_get_fd(&bev->ev_read);
1270 		return 0;
1271 	case BEV_CTRL_GET_UNDERLYING:
1272 		if (!bev_ssl->underlying)
1273 			return -1;
1274 		data->ptr = bev_ssl->underlying;
1275 		return 0;
1276 	case BEV_CTRL_CANCEL_ALL:
1277 	default:
1278 		return -1;
1279 	}
1280 }
1281 
1282 SSL *
bufferevent_openssl_get_ssl(struct bufferevent * bufev)1283 bufferevent_openssl_get_ssl(struct bufferevent *bufev)
1284 {
1285 	struct bufferevent_openssl *bev_ssl = upcast(bufev);
1286 	if (!bev_ssl)
1287 		return NULL;
1288 	return bev_ssl->ssl;
1289 }
1290 
1291 static struct bufferevent *
bufferevent_openssl_new_impl(struct event_base * base,struct bufferevent * underlying,evutil_socket_t fd,SSL * ssl,enum bufferevent_ssl_state state,int options)1292 bufferevent_openssl_new_impl(struct event_base *base,
1293     struct bufferevent *underlying,
1294     evutil_socket_t fd,
1295     SSL *ssl,
1296     enum bufferevent_ssl_state state,
1297     int options)
1298 {
1299 	struct bufferevent_openssl *bev_ssl = NULL;
1300 	struct bufferevent_private *bev_p = NULL;
1301 	int tmp_options = options & ~BEV_OPT_THREADSAFE;
1302 
1303 	if (underlying != NULL && fd >= 0)
1304 		return NULL; /* Only one can be set. */
1305 
1306 	if (!(bev_ssl = mm_calloc(1, sizeof(struct bufferevent_openssl))))
1307 		goto err;
1308 
1309 	bev_p = &bev_ssl->bev;
1310 
1311 	if (bufferevent_init_common(bev_p, base,
1312 		&bufferevent_ops_openssl, tmp_options) < 0)
1313 		goto err;
1314 
1315 	/* Don't explode if we decide to realloc a chunk we're writing from in
1316 	 * the output buffer. */
1317 	SSL_set_mode(ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1318 
1319 	bev_ssl->underlying = underlying;
1320 	bev_ssl->ssl = ssl;
1321 
1322 	bev_ssl->outbuf_cb = evbuffer_add_cb(bev_p->bev.output,
1323 	    be_openssl_outbuf_cb, bev_ssl);
1324 
1325 	if (options & BEV_OPT_THREADSAFE)
1326 		bufferevent_enable_locking(&bev_ssl->bev.bev, NULL);
1327 
1328 	if (underlying) {
1329 		_bufferevent_init_generic_timeout_cbs(&bev_ssl->bev.bev);
1330 		bufferevent_incref(underlying);
1331 	}
1332 
1333 	bev_ssl->state = state;
1334 	bev_ssl->last_write = -1;
1335 
1336 	init_bio_counts(bev_ssl);
1337 
1338 	switch (state) {
1339 	case BUFFEREVENT_SSL_ACCEPTING:
1340 		SSL_set_accept_state(bev_ssl->ssl);
1341 		if (set_handshake_callbacks(bev_ssl, fd) < 0)
1342 			goto err;
1343 		break;
1344 	case BUFFEREVENT_SSL_CONNECTING:
1345 		SSL_set_connect_state(bev_ssl->ssl);
1346 		if (set_handshake_callbacks(bev_ssl, fd) < 0)
1347 			goto err;
1348 		break;
1349 	case BUFFEREVENT_SSL_OPEN:
1350 		if (set_open_callbacks(bev_ssl, fd) < 0)
1351 			goto err;
1352 		break;
1353 	default:
1354 		goto err;
1355 	}
1356 
1357 	if (underlying) {
1358 		bufferevent_setwatermark(underlying, EV_READ, 0, 0);
1359 		bufferevent_enable(underlying, EV_READ|EV_WRITE);
1360 		if (state == BUFFEREVENT_SSL_OPEN)
1361 			bufferevent_suspend_read(underlying,
1362 			    BEV_SUSPEND_FILT_READ);
1363 	} else {
1364 		bev_ssl->bev.bev.enabled = EV_READ|EV_WRITE;
1365 		if (bev_ssl->fd_is_set) {
1366 			if (state != BUFFEREVENT_SSL_OPEN)
1367 				if (event_add(&bev_ssl->bev.bev.ev_read, NULL) < 0)
1368 					goto err;
1369 			if (event_add(&bev_ssl->bev.bev.ev_write, NULL) < 0)
1370 				goto err;
1371 		}
1372 	}
1373 
1374 	return &bev_ssl->bev.bev;
1375 err:
1376 	if (bev_ssl)
1377 		bufferevent_free(&bev_ssl->bev.bev);
1378 	return NULL;
1379 }
1380 
1381 struct bufferevent *
bufferevent_openssl_filter_new(struct event_base * base,struct bufferevent * underlying,SSL * ssl,enum bufferevent_ssl_state state,int options)1382 bufferevent_openssl_filter_new(struct event_base *base,
1383     struct bufferevent *underlying,
1384     SSL *ssl,
1385     enum bufferevent_ssl_state state,
1386     int options)
1387 {
1388 	/* We don't tell the BIO to close the bufferevent; we do it ourselves
1389 	 * on be_openssl_destruct */
1390 	int close_flag = 0; /* options & BEV_OPT_CLOSE_ON_FREE; */
1391 	BIO *bio;
1392 	if (!underlying)
1393 		return NULL;
1394 	if (!(bio = BIO_new_bufferevent(underlying, close_flag)))
1395 		return NULL;
1396 
1397 	SSL_set_bio(ssl, bio, bio);
1398 
1399 	return bufferevent_openssl_new_impl(
1400 		base, underlying, -1, ssl, state, options);
1401 }
1402 
1403 struct bufferevent *
bufferevent_openssl_socket_new(struct event_base * base,evutil_socket_t fd,SSL * ssl,enum bufferevent_ssl_state state,int options)1404 bufferevent_openssl_socket_new(struct event_base *base,
1405     evutil_socket_t fd,
1406     SSL *ssl,
1407     enum bufferevent_ssl_state state,
1408     int options)
1409 {
1410 	/* Does the SSL already have an fd? */
1411 	BIO *bio = SSL_get_wbio(ssl);
1412 	long have_fd = -1;
1413 
1414 	if (bio)
1415 		have_fd = BIO_get_fd(bio, NULL);
1416 
1417 	if (have_fd >= 0) {
1418 		/* The SSL is already configured with an fd. */
1419 		if (fd < 0) {
1420 			/* We should learn the fd from the SSL. */
1421 			fd = (evutil_socket_t) have_fd;
1422 		} else if (have_fd == (long)fd) {
1423 			/* We already know the fd from the SSL; do nothing */
1424 		} else {
1425 			/* We specified an fd different from that of the SSL.
1426 			   This is probably an error on our part.  Fail. */
1427 			return NULL;
1428 		}
1429 		(void) BIO_set_close(bio, 0);
1430 	} else {
1431 		/* The SSL isn't configured with a BIO with an fd. */
1432 		if (fd >= 0) {
1433 			/* ... and we have an fd we want to use. */
1434 			bio = BIO_new_socket(fd, 0);
1435 			SSL_set_bio(ssl, bio, bio);
1436 		} else {
1437 			/* Leave the fd unset. */
1438 		}
1439 	}
1440 
1441 	return bufferevent_openssl_new_impl(
1442 		base, NULL, fd, ssl, state, options);
1443 }
1444 
1445 unsigned long
bufferevent_get_openssl_error(struct bufferevent * bev)1446 bufferevent_get_openssl_error(struct bufferevent *bev)
1447 {
1448 	unsigned long err = 0;
1449 	struct bufferevent_openssl *bev_ssl;
1450 	BEV_LOCK(bev);
1451 	bev_ssl = upcast(bev);
1452 	if (bev_ssl && bev_ssl->n_errors) {
1453 		err = bev_ssl->errors[--bev_ssl->n_errors];
1454 	}
1455 	BEV_UNLOCK(bev);
1456 	return err;
1457 }
1458