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