2 * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. The name of the author may not be used to endorse or promote products
13 * derived from this software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 // Get rid of OSX 10.7 and greater deprecation warnings.
28 #if defined(__APPLE__) && defined(__clang__)
29 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
32 #include "event2/event-config.h"
33 #include "evconfig-private.h"
35 #include <sys/types.h>
37 #ifdef EVENT__HAVE_SYS_TIME_H
45 #ifdef EVENT__HAVE_STDARG_H
48 #ifdef EVENT__HAVE_UNISTD_H
56 #include "event2/bufferevent.h"
57 #include "event2/bufferevent_struct.h"
58 #include "event2/bufferevent_ssl.h"
59 #include "event2/buffer.h"
60 #include "event2/event.h"
62 #include "mm-internal.h"
63 #include "bufferevent-internal.h"
64 #include "log-internal.h"
66 #include <openssl/ssl.h>
67 #include <openssl/err.h>
68 #include "openssl-compat.h"
71 * Define an OpenSSL bio that targets a bufferevent.
74 /* --------------------
75 A BIO is an OpenSSL abstraction that handles reading and writing data. The
76 library will happily speak SSL over anything that implements a BIO
79 Here we define a BIO implementation that directs its output to a
80 bufferevent. We'll want to use this only when none of OpenSSL's built-in
81 IO mechanisms work for us.
82 -------------------- */
84 /* every BIO type needs its own integer type value. */
85 #define BIO_TYPE_LIBEVENT 57
86 /* ???? Arguably, we should set BIO_TYPE_FILTER or BIO_TYPE_SOURCE_SINK on
94 printf("Error was %d\n", val);
96 while ((err = ERR_get_error())) {
97 const char *msg = (const char*)ERR_reason_error_string(err);
98 const char *lib = (const char*)ERR_lib_error_string(err);
99 const char *func = (const char*)ERR_func_error_string(err);
101 printf("%s in %s %s\n", msg, lib, func);
105 #define print_err(v) ((void)0)
108 /* Called to initialize a new BIO */
110 bio_bufferevent_new(BIO *b)
113 BIO_set_data(b, NULL); /* We'll be putting the bufferevent in this field.*/
117 /* Called to uninitialize the BIO. */
119 bio_bufferevent_free(BIO *b)
123 if (BIO_get_shutdown(b)) {
124 if (BIO_get_init(b) && BIO_get_data(b))
125 bufferevent_free(BIO_get_data(b));
131 /* Called to extract data from the BIO. */
133 bio_bufferevent_read(BIO *b, char *out, int outlen)
136 struct evbuffer *input;
138 BIO_clear_retry_flags(b);
142 if (!BIO_get_data(b))
145 input = bufferevent_get_input(BIO_get_data(b));
146 if (evbuffer_get_length(input) == 0) {
147 /* If there's no data to read, say so. */
148 BIO_set_retry_read(b);
151 r = evbuffer_remove(input, out, outlen);
157 /* Called to write data into the BIO */
159 bio_bufferevent_write(BIO *b, const char *in, int inlen)
161 struct bufferevent *bufev = BIO_get_data(b);
162 struct evbuffer *output;
165 BIO_clear_retry_flags(b);
167 if (!BIO_get_data(b))
170 output = bufferevent_get_output(bufev);
171 outlen = evbuffer_get_length(output);
173 /* Copy only as much data onto the output buffer as can fit under the
174 * high-water mark. */
175 if (bufev->wm_write.high && bufev->wm_write.high <= (outlen+inlen)) {
176 if (bufev->wm_write.high <= outlen) {
177 /* If no data can fit, we'll need to retry later. */
178 BIO_set_retry_write(b);
181 inlen = bufev->wm_write.high - outlen;
184 EVUTIL_ASSERT(inlen > 0);
185 evbuffer_add(output, in, inlen);
189 /* Called to handle various requests */
191 bio_bufferevent_ctrl(BIO *b, int cmd, long num, void *ptr)
193 struct bufferevent *bufev = BIO_get_data(b);
197 case BIO_CTRL_GET_CLOSE:
198 ret = BIO_get_shutdown(b);
200 case BIO_CTRL_SET_CLOSE:
201 BIO_set_shutdown(b, (int)num);
203 case BIO_CTRL_PENDING:
204 ret = evbuffer_get_length(bufferevent_get_input(bufev)) != 0;
206 case BIO_CTRL_WPENDING:
207 ret = evbuffer_get_length(bufferevent_get_output(bufev)) != 0;
209 /* XXXX These two are given a special-case treatment because
210 * of cargo-cultism. I should come up with a better reason. */
222 /* Called to write a string to the BIO */
224 bio_bufferevent_puts(BIO *b, const char *s)
226 return bio_bufferevent_write(b, s, strlen(s));
229 /* Method table for the bufferevent BIO */
230 static BIO_METHOD *methods_bufferevent;
232 /* Return the method table for the bufferevents BIO */
234 BIO_s_bufferevent(void)
236 if (methods_bufferevent == NULL) {
237 methods_bufferevent = BIO_meth_new(BIO_TYPE_LIBEVENT, "bufferevent");
238 if (methods_bufferevent == NULL)
240 BIO_meth_set_write(methods_bufferevent, bio_bufferevent_write);
241 BIO_meth_set_read(methods_bufferevent, bio_bufferevent_read);
242 BIO_meth_set_puts(methods_bufferevent, bio_bufferevent_puts);
243 BIO_meth_set_ctrl(methods_bufferevent, bio_bufferevent_ctrl);
244 BIO_meth_set_create(methods_bufferevent, bio_bufferevent_new);
245 BIO_meth_set_destroy(methods_bufferevent, bio_bufferevent_free);
247 return methods_bufferevent;
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. */
253 BIO_new_bufferevent(struct bufferevent *bufferevent)
258 if (!(result = BIO_new(BIO_s_bufferevent())))
260 BIO_set_init(result, 1);
261 BIO_set_data(result, bufferevent);
262 /* We don't tell the BIO to close the bufferevent; we do it ourselves on
263 * be_openssl_destruct() */
264 BIO_set_shutdown(result, 0);
268 /* --------------------
269 Now, here's the OpenSSL-based implementation of bufferevent.
271 The implementation comes in two flavors: one that connects its SSL object
272 to an underlying bufferevent using a BIO_bufferevent, and one that has the
273 SSL object connect to a socket directly. The latter should generally be
274 faster, except on Windows, where your best bet is using a
277 (OpenSSL supports many other BIO types, too. But we can't use any unless
278 we have a good way to get notified when they become readable/writable.)
279 -------------------- */
281 struct bio_data_counts {
282 unsigned long n_written;
283 unsigned long n_read;
286 struct bufferevent_openssl {
287 /* Shared fields with common bufferevent implementation code.
288 If we were set up with an underlying bufferevent, we use the
289 events here as timers only. If we have an SSL, then we use
290 the events as socket events.
292 struct bufferevent_private bev;
293 /* An underlying bufferevent that we're directing our output to.
294 If it's NULL, then we're connected to an fd, not an evbuffer. */
295 struct bufferevent *underlying;
296 /* The SSL object doing our encryption. */
299 /* A callback that's invoked when data arrives on our outbuf so we
300 know to write data to the SSL. */
301 struct evbuffer_cb_entry *outbuf_cb;
303 /* A count of how much data the bios have read/written total. Used
304 for rate-limiting. */
305 struct bio_data_counts counts;
307 /* If this value is greater than 0, then the last SSL_write blocked,
308 * and we need to try it again with this many bytes. */
309 ev_ssize_t last_write;
312 ev_uint32_t errors[NUM_ERRORS];
314 /* When we next get available space, we should say "read" instead of
315 "write". This can happen if there's a renegotiation during a read
317 unsigned read_blocked_on_write : 1;
318 /* When we next get data, we should say "write" instead of "read". */
319 unsigned write_blocked_on_read : 1;
320 /* Treat TCP close before SSL close on SSL >= v3 as clean EOF. */
321 unsigned allow_dirty_shutdown : 1;
323 unsigned n_errors : 2;
325 /* Are we currently connecting, accepting, or doing IO? */
327 /* If we reset fd, we sould reset state too */
328 unsigned old_state : 2;
331 static int be_openssl_enable(struct bufferevent *, short);
332 static int be_openssl_disable(struct bufferevent *, short);
333 static void be_openssl_unlink(struct bufferevent *);
334 static void be_openssl_destruct(struct bufferevent *);
335 static int be_openssl_adj_timeouts(struct bufferevent *);
336 static int be_openssl_flush(struct bufferevent *bufev,
337 short iotype, enum bufferevent_flush_mode mode);
338 static int be_openssl_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
340 const struct bufferevent_ops bufferevent_ops_openssl = {
342 evutil_offsetof(struct bufferevent_openssl, bev.bev),
347 be_openssl_adj_timeouts,
352 /* Given a bufferevent, return a pointer to the bufferevent_openssl that
353 * contains it, if any. */
354 static inline struct bufferevent_openssl *
355 upcast(struct bufferevent *bev)
357 struct bufferevent_openssl *bev_o;
358 if (!BEV_IS_OPENSSL(bev))
360 bev_o = (void*)( ((char*)bev) -
361 evutil_offsetof(struct bufferevent_openssl, bev.bev));
362 EVUTIL_ASSERT(BEV_IS_OPENSSL(&bev_o->bev.bev));
367 put_error(struct bufferevent_openssl *bev_ssl, unsigned long err)
369 if (bev_ssl->n_errors == NUM_ERRORS)
371 /* The error type according to openssl is "unsigned long", but
372 openssl never uses more than 32 bits of it. It _can't_ use more
373 than 32 bits of it, since it needs to report errors on systems
374 where long is only 32 bits.
376 bev_ssl->errors[bev_ssl->n_errors++] = (ev_uint32_t) err;
379 /* Have the base communications channel (either the underlying bufferevent or
380 * ev_read and ev_write) start reading. Take the read-blocked-on-write flag
383 start_reading(struct bufferevent_openssl *bev_ssl)
385 if (bev_ssl->underlying) {
386 bufferevent_unsuspend_read_(bev_ssl->underlying,
387 BEV_SUSPEND_FILT_READ);
390 struct bufferevent *bev = &bev_ssl->bev.bev;
392 r = bufferevent_add_event_(&bev->ev_read, &bev->timeout_read);
393 if (r == 0 && bev_ssl->read_blocked_on_write)
394 r = bufferevent_add_event_(&bev->ev_write,
395 &bev->timeout_write);
400 /* Have the base communications channel (either the underlying bufferevent or
401 * ev_read and ev_write) start writing. Take the write-blocked-on-read flag
404 start_writing(struct bufferevent_openssl *bev_ssl)
407 if (bev_ssl->underlying) {
408 if (bev_ssl->write_blocked_on_read) {
409 bufferevent_unsuspend_read_(bev_ssl->underlying,
410 BEV_SUSPEND_FILT_READ);
413 struct bufferevent *bev = &bev_ssl->bev.bev;
414 r = bufferevent_add_event_(&bev->ev_write, &bev->timeout_write);
415 if (!r && bev_ssl->write_blocked_on_read)
416 r = bufferevent_add_event_(&bev->ev_read,
423 stop_reading(struct bufferevent_openssl *bev_ssl)
425 if (bev_ssl->write_blocked_on_read)
427 if (bev_ssl->underlying) {
428 bufferevent_suspend_read_(bev_ssl->underlying,
429 BEV_SUSPEND_FILT_READ);
431 struct bufferevent *bev = &bev_ssl->bev.bev;
432 event_del(&bev->ev_read);
437 stop_writing(struct bufferevent_openssl *bev_ssl)
439 if (bev_ssl->read_blocked_on_write)
441 if (bev_ssl->underlying) {
442 bufferevent_unsuspend_read_(bev_ssl->underlying,
443 BEV_SUSPEND_FILT_READ);
445 struct bufferevent *bev = &bev_ssl->bev.bev;
446 event_del(&bev->ev_write);
451 set_rbow(struct bufferevent_openssl *bev_ssl)
453 if (!bev_ssl->underlying)
454 stop_reading(bev_ssl);
455 bev_ssl->read_blocked_on_write = 1;
456 return start_writing(bev_ssl);
460 set_wbor(struct bufferevent_openssl *bev_ssl)
462 if (!bev_ssl->underlying)
463 stop_writing(bev_ssl);
464 bev_ssl->write_blocked_on_read = 1;
465 return start_reading(bev_ssl);
469 clear_rbow(struct bufferevent_openssl *bev_ssl)
471 struct bufferevent *bev = &bev_ssl->bev.bev;
473 bev_ssl->read_blocked_on_write = 0;
474 if (!(bev->enabled & EV_WRITE))
475 stop_writing(bev_ssl);
476 if (bev->enabled & EV_READ)
477 r = start_reading(bev_ssl);
483 clear_wbor(struct bufferevent_openssl *bev_ssl)
485 struct bufferevent *bev = &bev_ssl->bev.bev;
487 bev_ssl->write_blocked_on_read = 0;
488 if (!(bev->enabled & EV_READ))
489 stop_reading(bev_ssl);
490 if (bev->enabled & EV_WRITE)
491 r = start_writing(bev_ssl);
496 conn_closed(struct bufferevent_openssl *bev_ssl, int when, int errcode, int ret)
498 int event = BEV_EVENT_ERROR;
499 int dirty_shutdown = 0;
503 case SSL_ERROR_ZERO_RETURN:
504 /* Possibly a clean shutdown. */
505 if (SSL_get_shutdown(bev_ssl->ssl) & SSL_RECEIVED_SHUTDOWN)
506 event = BEV_EVENT_EOF;
510 case SSL_ERROR_SYSCALL:
511 /* IO error; possibly a dirty shutdown. */
512 if ((ret == 0 || ret == -1) && ERR_peek_error() == 0)
514 put_error(bev_ssl, errcode);
517 /* Protocol error. */
518 put_error(bev_ssl, errcode);
520 case SSL_ERROR_WANT_X509_LOOKUP:
521 /* XXXX handle this. */
522 put_error(bev_ssl, errcode);
525 case SSL_ERROR_WANT_READ:
526 case SSL_ERROR_WANT_WRITE:
527 case SSL_ERROR_WANT_CONNECT:
528 case SSL_ERROR_WANT_ACCEPT:
530 /* should be impossible; treat as normal error. */
531 event_warnx("BUG: Unexpected OpenSSL error code %d", errcode);
535 while ((err = ERR_get_error())) {
536 put_error(bev_ssl, err);
539 if (dirty_shutdown && bev_ssl->allow_dirty_shutdown)
540 event = BEV_EVENT_EOF;
542 stop_reading(bev_ssl);
543 stop_writing(bev_ssl);
545 /* when is BEV_EVENT_{READING|WRITING} */
546 event = when | event;
547 bufferevent_run_eventcb_(&bev_ssl->bev.bev, event, 0);
551 init_bio_counts(struct bufferevent_openssl *bev_ssl)
555 wbio = SSL_get_wbio(bev_ssl->ssl);
556 bev_ssl->counts.n_written = wbio ? BIO_number_written(wbio) : 0;
557 rbio = SSL_get_rbio(bev_ssl->ssl);
558 bev_ssl->counts.n_read = rbio ? BIO_number_read(rbio) : 0;
562 decrement_buckets(struct bufferevent_openssl *bev_ssl)
564 unsigned long num_w = BIO_number_written(SSL_get_wbio(bev_ssl->ssl));
565 unsigned long num_r = BIO_number_read(SSL_get_rbio(bev_ssl->ssl));
566 /* These next two subtractions can wrap around. That's okay. */
567 unsigned long w = num_w - bev_ssl->counts.n_written;
568 unsigned long r = num_r - bev_ssl->counts.n_read;
570 bufferevent_decrement_write_buckets_(&bev_ssl->bev, w);
572 bufferevent_decrement_read_buckets_(&bev_ssl->bev, r);
573 bev_ssl->counts.n_written = num_w;
574 bev_ssl->counts.n_read = num_r;
577 #define OP_MADE_PROGRESS 1
581 /* Return a bitmask of OP_MADE_PROGRESS (if we read anything); OP_BLOCKED (if
582 we're now blocked); and OP_ERR (if an error occurred). */
584 do_read(struct bufferevent_openssl *bev_ssl, int n_to_read) {
586 struct bufferevent *bev = &bev_ssl->bev.bev;
587 struct evbuffer *input = bev->input;
588 int r, n, i, n_used = 0, atmost;
589 struct evbuffer_iovec space[2];
592 if (bev_ssl->bev.read_suspended)
595 atmost = bufferevent_get_read_max_(&bev_ssl->bev);
596 if (n_to_read > atmost)
599 n = evbuffer_reserve_space(input, n_to_read, space, 2);
603 for (i=0; i<n; ++i) {
604 if (bev_ssl->bev.read_suspended)
607 r = SSL_read(bev_ssl->ssl, space[i].iov_base, space[i].iov_len);
609 result |= OP_MADE_PROGRESS;
610 if (bev_ssl->read_blocked_on_write)
611 if (clear_rbow(bev_ssl) < 0)
612 return OP_ERR | result;
614 space[i].iov_len = r;
615 decrement_buckets(bev_ssl);
617 int err = SSL_get_error(bev_ssl->ssl, r);
620 case SSL_ERROR_WANT_READ:
621 /* Can't read until underlying has more data. */
622 if (bev_ssl->read_blocked_on_write)
623 if (clear_rbow(bev_ssl) < 0)
624 return OP_ERR | result;
626 case SSL_ERROR_WANT_WRITE:
627 /* This read operation requires a write, and the
628 * underlying is full */
629 if (!bev_ssl->read_blocked_on_write)
630 if (set_rbow(bev_ssl) < 0)
631 return OP_ERR | result;
634 conn_closed(bev_ssl, BEV_EVENT_READING, err, r);
637 result |= OP_BLOCKED;
638 break; /* out of the loop */
643 evbuffer_commit_space(input, space, n_used);
644 if (bev_ssl->underlying)
645 BEV_RESET_GENERIC_READ_TIMEOUT(bev);
651 /* Return a bitmask of OP_MADE_PROGRESS (if we wrote anything); OP_BLOCKED (if
652 we're now blocked); and OP_ERR (if an error occurred). */
654 do_write(struct bufferevent_openssl *bev_ssl, int atmost)
656 int i, r, n, n_written = 0;
657 struct bufferevent *bev = &bev_ssl->bev.bev;
658 struct evbuffer *output = bev->output;
659 struct evbuffer_iovec space[8];
662 if (bev_ssl->last_write > 0)
663 atmost = bev_ssl->last_write;
665 atmost = bufferevent_get_write_max_(&bev_ssl->bev);
667 n = evbuffer_peek(output, atmost, NULL, space, 8);
669 return OP_ERR | result;
673 for (i=0; i < n; ++i) {
674 if (bev_ssl->bev.write_suspended)
677 /* SSL_write will (reasonably) return 0 if we tell it to
678 send 0 data. Skip this case so we don't interpret the
679 result as an error */
680 if (space[i].iov_len == 0)
684 r = SSL_write(bev_ssl->ssl, space[i].iov_base,
687 result |= OP_MADE_PROGRESS;
688 if (bev_ssl->write_blocked_on_read)
689 if (clear_wbor(bev_ssl) < 0)
690 return OP_ERR | result;
692 bev_ssl->last_write = -1;
693 decrement_buckets(bev_ssl);
695 int err = SSL_get_error(bev_ssl->ssl, r);
698 case SSL_ERROR_WANT_WRITE:
699 /* Can't read until underlying has more data. */
700 if (bev_ssl->write_blocked_on_read)
701 if (clear_wbor(bev_ssl) < 0)
702 return OP_ERR | result;
703 bev_ssl->last_write = space[i].iov_len;
705 case SSL_ERROR_WANT_READ:
706 /* This read operation requires a write, and the
707 * underlying is full */
708 if (!bev_ssl->write_blocked_on_read)
709 if (set_wbor(bev_ssl) < 0)
710 return OP_ERR | result;
711 bev_ssl->last_write = space[i].iov_len;
714 conn_closed(bev_ssl, BEV_EVENT_WRITING, err, r);
715 bev_ssl->last_write = -1;
718 result |= OP_BLOCKED;
723 evbuffer_drain(output, n_written);
724 if (bev_ssl->underlying)
725 BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
727 bufferevent_trigger_nolock_(bev, EV_WRITE, BEV_OPT_DEFER_CALLBACKS);
732 #define WRITE_FRAME 15000
734 #define READ_DEFAULT 4096
736 /* Try to figure out how many bytes to read; return 0 if we shouldn't be
739 bytes_to_read(struct bufferevent_openssl *bev)
741 struct evbuffer *input = bev->bev.bev.input;
742 struct event_watermark *wm = &bev->bev.bev.wm_read;
743 int result = READ_DEFAULT;
745 /* XXX 99% of this is generic code that nearly all bufferevents will
748 if (bev->write_blocked_on_read) {
752 if (! (bev->bev.bev.enabled & EV_READ)) {
756 if (bev->bev.read_suspended) {
761 if (evbuffer_get_length(input) >= wm->high) {
765 result = wm->high - evbuffer_get_length(input);
767 result = READ_DEFAULT;
770 /* Respect the rate limit */
771 limit = bufferevent_get_read_max_(&bev->bev);
772 if (result > limit) {
780 /* Things look readable. If write is blocked on read, write till it isn't.
781 * Read from the underlying buffer until we block or we hit our high-water
785 consider_reading(struct bufferevent_openssl *bev_ssl)
789 int all_result_flags = 0;
791 while (bev_ssl->write_blocked_on_read) {
792 r = do_write(bev_ssl, WRITE_FRAME);
793 if (r & (OP_BLOCKED|OP_ERR))
796 if (bev_ssl->write_blocked_on_read)
799 n_to_read = bytes_to_read(bev_ssl);
802 r = do_read(bev_ssl, n_to_read);
803 all_result_flags |= r;
805 if (r & (OP_BLOCKED|OP_ERR))
808 if (bev_ssl->bev.read_suspended)
811 /* Read all pending data. This won't hit the network
812 * again, and will (most importantly) put us in a state
813 * where we don't need to read anything else until the
814 * socket is readable again. It'll potentially make us
815 * overrun our read high-watermark (somewhat
816 * regrettable). The damage to the rate-limit has
817 * already been done, since OpenSSL went and read a
818 * whole SSL record anyway. */
819 n_to_read = SSL_pending(bev_ssl->ssl);
821 /* XXX This if statement is actually a bad bug, added to avoid
824 * The bad bug: It can potentially cause resource unfairness
825 * by reading too much data from the underlying bufferevent;
826 * it can potentially cause read looping if the underlying
827 * bufferevent is a bufferevent_pair and deferred callbacks
830 * The worse bug: If we didn't do this, then we would
831 * potentially not read any more from bev_ssl->underlying
832 * until more data arrived there, which could lead to us
835 if (!n_to_read && bev_ssl->underlying)
836 n_to_read = bytes_to_read(bev_ssl);
839 if (all_result_flags & OP_MADE_PROGRESS) {
840 struct bufferevent *bev = &bev_ssl->bev.bev;
842 bufferevent_trigger_nolock_(bev, EV_READ, 0);
845 if (!bev_ssl->underlying) {
846 /* Should be redundant, but let's avoid busy-looping */
847 if (bev_ssl->bev.read_suspended ||
848 !(bev_ssl->bev.bev.enabled & EV_READ)) {
849 event_del(&bev_ssl->bev.bev.ev_read);
855 consider_writing(struct bufferevent_openssl *bev_ssl)
858 struct evbuffer *output = bev_ssl->bev.bev.output;
859 struct evbuffer *target = NULL;
860 struct event_watermark *wm = NULL;
862 while (bev_ssl->read_blocked_on_write) {
863 r = do_read(bev_ssl, 1024); /* XXXX 1024 is a hack */
864 if (r & OP_MADE_PROGRESS) {
865 struct bufferevent *bev = &bev_ssl->bev.bev;
867 bufferevent_trigger_nolock_(bev, EV_READ, 0);
869 if (r & (OP_ERR|OP_BLOCKED))
872 if (bev_ssl->read_blocked_on_write)
874 if (bev_ssl->underlying) {
875 target = bev_ssl->underlying->output;
876 wm = &bev_ssl->underlying->wm_write;
878 while ((bev_ssl->bev.bev.enabled & EV_WRITE) &&
879 (! bev_ssl->bev.write_suspended) &&
880 evbuffer_get_length(output) &&
881 (!target || (! wm->high || evbuffer_get_length(target) < wm->high))) {
884 n_to_write = wm->high - evbuffer_get_length(target);
886 n_to_write = WRITE_FRAME;
887 r = do_write(bev_ssl, n_to_write);
888 if (r & (OP_BLOCKED|OP_ERR))
892 if (!bev_ssl->underlying) {
893 if (evbuffer_get_length(output) == 0) {
894 event_del(&bev_ssl->bev.bev.ev_write);
895 } else if (bev_ssl->bev.write_suspended ||
896 !(bev_ssl->bev.bev.enabled & EV_WRITE)) {
897 /* Should be redundant, but let's avoid busy-looping */
898 event_del(&bev_ssl->bev.bev.ev_write);
904 be_openssl_readcb(struct bufferevent *bev_base, void *ctx)
906 struct bufferevent_openssl *bev_ssl = ctx;
907 consider_reading(bev_ssl);
911 be_openssl_writecb(struct bufferevent *bev_base, void *ctx)
913 struct bufferevent_openssl *bev_ssl = ctx;
914 consider_writing(bev_ssl);
918 be_openssl_eventcb(struct bufferevent *bev_base, short what, void *ctx)
920 struct bufferevent_openssl *bev_ssl = ctx;
923 if (what & BEV_EVENT_EOF) {
924 if (bev_ssl->allow_dirty_shutdown)
925 event = BEV_EVENT_EOF;
927 event = BEV_EVENT_ERROR;
928 } else if (what & BEV_EVENT_TIMEOUT) {
929 /* We sure didn't set this. Propagate it to the user. */
931 } else if (what & BEV_EVENT_ERROR) {
932 /* An error occurred on the connection. Propagate it to the user. */
934 } else if (what & BEV_EVENT_CONNECTED) {
935 /* Ignore it. We're saying SSL_connect() already, which will
939 bufferevent_run_eventcb_(&bev_ssl->bev.bev, event, 0);
943 be_openssl_readeventcb(evutil_socket_t fd, short what, void *ptr)
945 struct bufferevent_openssl *bev_ssl = ptr;
946 bufferevent_incref_and_lock_(&bev_ssl->bev.bev);
947 if (what == EV_TIMEOUT) {
948 bufferevent_run_eventcb_(&bev_ssl->bev.bev,
949 BEV_EVENT_TIMEOUT|BEV_EVENT_READING, 0);
951 consider_reading(bev_ssl);
953 bufferevent_decref_and_unlock_(&bev_ssl->bev.bev);
957 be_openssl_writeeventcb(evutil_socket_t fd, short what, void *ptr)
959 struct bufferevent_openssl *bev_ssl = ptr;
960 bufferevent_incref_and_lock_(&bev_ssl->bev.bev);
961 if (what == EV_TIMEOUT) {
962 bufferevent_run_eventcb_(&bev_ssl->bev.bev,
963 BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING, 0);
965 consider_writing(bev_ssl);
967 bufferevent_decref_and_unlock_(&bev_ssl->bev.bev);
970 static evutil_socket_t
971 be_openssl_auto_fd(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
973 if (!bev_ssl->underlying) {
974 struct bufferevent *bev = &bev_ssl->bev.bev;
975 if (event_initialized(&bev->ev_read) && fd < 0) {
976 fd = event_get_fd(&bev->ev_read);
983 set_open_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
985 if (bev_ssl->underlying) {
986 bufferevent_setcb(bev_ssl->underlying,
987 be_openssl_readcb, be_openssl_writecb, be_openssl_eventcb,
991 struct bufferevent *bev = &bev_ssl->bev.bev;
992 int rpending=0, wpending=0, r1=0, r2=0;
994 if (event_initialized(&bev->ev_read)) {
995 rpending = event_pending(&bev->ev_read, EV_READ, NULL);
996 wpending = event_pending(&bev->ev_write, EV_WRITE, NULL);
998 event_del(&bev->ev_read);
999 event_del(&bev->ev_write);
1002 event_assign(&bev->ev_read, bev->ev_base, fd,
1003 EV_READ|EV_PERSIST|EV_FINALIZE,
1004 be_openssl_readeventcb, bev_ssl);
1005 event_assign(&bev->ev_write, bev->ev_base, fd,
1006 EV_WRITE|EV_PERSIST|EV_FINALIZE,
1007 be_openssl_writeeventcb, bev_ssl);
1010 r1 = bufferevent_add_event_(&bev->ev_read, &bev->timeout_read);
1012 r2 = bufferevent_add_event_(&bev->ev_write, &bev->timeout_write);
1014 return (r1<0 || r2<0) ? -1 : 0;
1019 do_handshake(struct bufferevent_openssl *bev_ssl)
1023 switch (bev_ssl->state) {
1025 case BUFFEREVENT_SSL_OPEN:
1028 case BUFFEREVENT_SSL_CONNECTING:
1029 case BUFFEREVENT_SSL_ACCEPTING:
1031 r = SSL_do_handshake(bev_ssl->ssl);
1034 decrement_buckets(bev_ssl);
1037 evutil_socket_t fd = event_get_fd(&bev_ssl->bev.bev.ev_read);
1039 bev_ssl->state = BUFFEREVENT_SSL_OPEN;
1040 set_open_callbacks(bev_ssl, fd); /* XXXX handle failure */
1041 /* Call do_read and do_write as needed */
1042 bufferevent_enable(&bev_ssl->bev.bev, bev_ssl->bev.bev.enabled);
1043 bufferevent_run_eventcb_(&bev_ssl->bev.bev,
1044 BEV_EVENT_CONNECTED, 0);
1047 int err = SSL_get_error(bev_ssl->ssl, r);
1050 case SSL_ERROR_WANT_WRITE:
1051 stop_reading(bev_ssl);
1052 return start_writing(bev_ssl);
1053 case SSL_ERROR_WANT_READ:
1054 stop_writing(bev_ssl);
1055 return start_reading(bev_ssl);
1057 conn_closed(bev_ssl, BEV_EVENT_READING, err, r);
1064 be_openssl_handshakecb(struct bufferevent *bev_base, void *ctx)
1066 struct bufferevent_openssl *bev_ssl = ctx;
1067 do_handshake(bev_ssl);/* XXX handle failure */
1071 be_openssl_handshakeeventcb(evutil_socket_t fd, short what, void *ptr)
1073 struct bufferevent_openssl *bev_ssl = ptr;
1075 bufferevent_incref_and_lock_(&bev_ssl->bev.bev);
1076 if (what & EV_TIMEOUT) {
1077 bufferevent_run_eventcb_(&bev_ssl->bev.bev, BEV_EVENT_TIMEOUT, 0);
1079 do_handshake(bev_ssl);/* XXX handle failure */
1080 bufferevent_decref_and_unlock_(&bev_ssl->bev.bev);
1084 set_handshake_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
1086 if (bev_ssl->underlying) {
1087 bufferevent_setcb(bev_ssl->underlying,
1088 be_openssl_handshakecb, be_openssl_handshakecb,
1095 if (bufferevent_setfd(bev_ssl->underlying, fd))
1098 return do_handshake(bev_ssl);
1100 struct bufferevent *bev = &bev_ssl->bev.bev;
1102 if (event_initialized(&bev->ev_read)) {
1103 event_del(&bev->ev_read);
1104 event_del(&bev->ev_write);
1107 event_assign(&bev->ev_read, bev->ev_base, fd,
1108 EV_READ|EV_PERSIST|EV_FINALIZE,
1109 be_openssl_handshakeeventcb, bev_ssl);
1110 event_assign(&bev->ev_write, bev->ev_base, fd,
1111 EV_WRITE|EV_PERSIST|EV_FINALIZE,
1112 be_openssl_handshakeeventcb, bev_ssl);
1114 bufferevent_enable(bev, bev->enabled);
1120 bufferevent_ssl_renegotiate(struct bufferevent *bev)
1122 struct bufferevent_openssl *bev_ssl = upcast(bev);
1125 if (SSL_renegotiate(bev_ssl->ssl) < 0)
1127 bev_ssl->state = BUFFEREVENT_SSL_CONNECTING;
1128 if (set_handshake_callbacks(bev_ssl, be_openssl_auto_fd(bev_ssl, -1)) < 0)
1130 if (!bev_ssl->underlying)
1131 return do_handshake(bev_ssl);
1136 be_openssl_outbuf_cb(struct evbuffer *buf,
1137 const struct evbuffer_cb_info *cbinfo, void *arg)
1139 struct bufferevent_openssl *bev_ssl = arg;
1141 /* XXX need to hold a reference here. */
1143 if (cbinfo->n_added && bev_ssl->state == BUFFEREVENT_SSL_OPEN) {
1144 if (cbinfo->orig_size == 0)
1145 r = bufferevent_add_event_(&bev_ssl->bev.bev.ev_write,
1146 &bev_ssl->bev.bev.timeout_write);
1148 if (bev_ssl->underlying)
1149 consider_writing(bev_ssl);
1151 /* XXX Handle r < 0 */
1157 be_openssl_enable(struct bufferevent *bev, short events)
1159 struct bufferevent_openssl *bev_ssl = upcast(bev);
1162 if (events & EV_READ)
1163 r1 = start_reading(bev_ssl);
1164 if (events & EV_WRITE)
1165 r2 = start_writing(bev_ssl);
1167 if (bev_ssl->underlying) {
1168 if (events & EV_READ)
1169 BEV_RESET_GENERIC_READ_TIMEOUT(bev);
1170 if (events & EV_WRITE)
1171 BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
1173 if (events & EV_READ)
1174 consider_reading(bev_ssl);
1175 if (events & EV_WRITE)
1176 consider_writing(bev_ssl);
1178 return (r1 < 0 || r2 < 0) ? -1 : 0;
1182 be_openssl_disable(struct bufferevent *bev, short events)
1184 struct bufferevent_openssl *bev_ssl = upcast(bev);
1186 if (events & EV_READ)
1187 stop_reading(bev_ssl);
1188 if (events & EV_WRITE)
1189 stop_writing(bev_ssl);
1191 if (bev_ssl->underlying) {
1192 if (events & EV_READ)
1193 BEV_DEL_GENERIC_READ_TIMEOUT(bev);
1194 if (events & EV_WRITE)
1195 BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
1201 be_openssl_unlink(struct bufferevent *bev)
1203 struct bufferevent_openssl *bev_ssl = upcast(bev);
1205 if (bev_ssl->bev.options & BEV_OPT_CLOSE_ON_FREE) {
1206 if (bev_ssl->underlying) {
1207 if (BEV_UPCAST(bev_ssl->underlying)->refcnt < 2) {
1208 event_warnx("BEV_OPT_CLOSE_ON_FREE set on an "
1209 "bufferevent with too few references");
1211 bufferevent_free(bev_ssl->underlying);
1212 /* We still have a reference to it, via our
1213 * BIO. So we don't drop this. */
1214 // bev_ssl->underlying = NULL;
1218 if (bev_ssl->underlying) {
1219 if (bev_ssl->underlying->errorcb == be_openssl_eventcb)
1220 bufferevent_setcb(bev_ssl->underlying,
1221 NULL,NULL,NULL,NULL);
1222 bufferevent_unsuspend_read_(bev_ssl->underlying,
1223 BEV_SUSPEND_FILT_READ);
1229 be_openssl_destruct(struct bufferevent *bev)
1231 struct bufferevent_openssl *bev_ssl = upcast(bev);
1233 if (bev_ssl->bev.options & BEV_OPT_CLOSE_ON_FREE) {
1234 if (! bev_ssl->underlying) {
1235 evutil_socket_t fd = EVUTIL_INVALID_SOCKET;
1236 BIO *bio = SSL_get_wbio(bev_ssl->ssl);
1238 fd = BIO_get_fd(bio, NULL);
1240 evutil_closesocket(fd);
1242 SSL_free(bev_ssl->ssl);
1247 be_openssl_adj_timeouts(struct bufferevent *bev)
1249 struct bufferevent_openssl *bev_ssl = upcast(bev);
1251 if (bev_ssl->underlying) {
1252 return bufferevent_generic_adj_timeouts_(bev);
1254 return bufferevent_generic_adj_existing_timeouts_(bev);
1259 be_openssl_flush(struct bufferevent *bufev,
1260 short iotype, enum bufferevent_flush_mode mode)
1262 /* XXXX Implement this. */
1267 be_openssl_set_fd(struct bufferevent_openssl *bev_ssl,
1268 enum bufferevent_ssl_state state, evutil_socket_t fd)
1270 bev_ssl->state = state;
1273 case BUFFEREVENT_SSL_ACCEPTING:
1274 if (!SSL_clear(bev_ssl->ssl))
1276 SSL_set_accept_state(bev_ssl->ssl);
1277 if (set_handshake_callbacks(bev_ssl, fd) < 0)
1280 case BUFFEREVENT_SSL_CONNECTING:
1281 if (!SSL_clear(bev_ssl->ssl))
1283 SSL_set_connect_state(bev_ssl->ssl);
1284 if (set_handshake_callbacks(bev_ssl, fd) < 0)
1287 case BUFFEREVENT_SSL_OPEN:
1288 if (set_open_callbacks(bev_ssl, fd) < 0)
1299 be_openssl_ctrl(struct bufferevent *bev,
1300 enum bufferevent_ctrl_op op, union bufferevent_ctrl_data *data)
1302 struct bufferevent_openssl *bev_ssl = upcast(bev);
1304 case BEV_CTRL_SET_FD:
1305 if (!bev_ssl->underlying) {
1307 bio = BIO_new_socket((int)data->fd, 0);
1308 SSL_set_bio(bev_ssl->ssl, bio, bio);
1311 if (!(bio = BIO_new_bufferevent(bev_ssl->underlying)))
1313 SSL_set_bio(bev_ssl->ssl, bio, bio);
1316 return be_openssl_set_fd(bev_ssl, bev_ssl->old_state, data->fd);
1317 case BEV_CTRL_GET_FD:
1318 if (bev_ssl->underlying) {
1319 data->fd = event_get_fd(&bev_ssl->underlying->ev_read);
1321 data->fd = event_get_fd(&bev->ev_read);
1324 case BEV_CTRL_GET_UNDERLYING:
1325 data->ptr = bev_ssl->underlying;
1327 case BEV_CTRL_CANCEL_ALL:
1334 bufferevent_openssl_get_ssl(struct bufferevent *bufev)
1336 struct bufferevent_openssl *bev_ssl = upcast(bufev);
1339 return bev_ssl->ssl;
1342 static struct bufferevent *
1343 bufferevent_openssl_new_impl(struct event_base *base,
1344 struct bufferevent *underlying,
1347 enum bufferevent_ssl_state state,
1350 struct bufferevent_openssl *bev_ssl = NULL;
1351 struct bufferevent_private *bev_p = NULL;
1352 int tmp_options = options & ~BEV_OPT_THREADSAFE;
1354 /* Only one can be set. */
1355 if (underlying != NULL && fd >= 0)
1358 if (!(bev_ssl = mm_calloc(1, sizeof(struct bufferevent_openssl))))
1361 bev_p = &bev_ssl->bev;
1363 if (bufferevent_init_common_(bev_p, base,
1364 &bufferevent_ops_openssl, tmp_options) < 0)
1367 /* Don't explode if we decide to realloc a chunk we're writing from in
1368 * the output buffer. */
1369 SSL_set_mode(ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1371 bev_ssl->underlying = underlying;
1374 bev_ssl->outbuf_cb = evbuffer_add_cb(bev_p->bev.output,
1375 be_openssl_outbuf_cb, bev_ssl);
1377 if (options & BEV_OPT_THREADSAFE)
1378 bufferevent_enable_locking_(&bev_ssl->bev.bev, NULL);
1381 bufferevent_init_generic_timeout_cbs_(&bev_ssl->bev.bev);
1382 bufferevent_incref_(underlying);
1385 bev_ssl->old_state = state;
1386 bev_ssl->last_write = -1;
1388 init_bio_counts(bev_ssl);
1390 fd = be_openssl_auto_fd(bev_ssl, fd);
1391 if (be_openssl_set_fd(bev_ssl, state, fd))
1395 bufferevent_setwatermark(underlying, EV_READ, 0, 0);
1396 bufferevent_enable(underlying, EV_READ|EV_WRITE);
1397 if (state == BUFFEREVENT_SSL_OPEN)
1398 bufferevent_suspend_read_(underlying,
1399 BEV_SUSPEND_FILT_READ);
1402 return &bev_ssl->bev.bev;
1404 if (options & BEV_OPT_CLOSE_ON_FREE)
1407 bev_ssl->ssl = NULL;
1408 bufferevent_free(&bev_ssl->bev.bev);
1413 struct bufferevent *
1414 bufferevent_openssl_filter_new(struct event_base *base,
1415 struct bufferevent *underlying,
1417 enum bufferevent_ssl_state state,
1421 struct bufferevent *bev;
1425 if (!(bio = BIO_new_bufferevent(underlying)))
1428 SSL_set_bio(ssl, bio, bio);
1430 bev = bufferevent_openssl_new_impl(
1431 base, underlying, -1, ssl, state, options);
1435 if (options & BEV_OPT_CLOSE_ON_FREE)
1440 struct bufferevent *
1441 bufferevent_openssl_socket_new(struct event_base *base,
1444 enum bufferevent_ssl_state state,
1447 /* Does the SSL already have an fd? */
1448 BIO *bio = SSL_get_wbio(ssl);
1452 have_fd = BIO_get_fd(bio, NULL);
1455 /* The SSL is already configured with an fd. */
1457 /* We should learn the fd from the SSL. */
1458 fd = (evutil_socket_t) have_fd;
1459 } else if (have_fd == (long)fd) {
1460 /* We already know the fd from the SSL; do nothing */
1462 /* We specified an fd different from that of the SSL.
1463 This is probably an error on our part. Fail. */
1466 BIO_set_close(bio, 0);
1468 /* The SSL isn't configured with a BIO with an fd. */
1470 /* ... and we have an fd we want to use. */
1471 bio = BIO_new_socket((int)fd, 0);
1472 SSL_set_bio(ssl, bio, bio);
1474 /* Leave the fd unset. */
1478 return bufferevent_openssl_new_impl(
1479 base, NULL, fd, ssl, state, options);
1482 if (options & BEV_OPT_CLOSE_ON_FREE)
1488 bufferevent_openssl_get_allow_dirty_shutdown(struct bufferevent *bev)
1490 int allow_dirty_shutdown = -1;
1491 struct bufferevent_openssl *bev_ssl;
1493 bev_ssl = upcast(bev);
1495 allow_dirty_shutdown = bev_ssl->allow_dirty_shutdown;
1497 return allow_dirty_shutdown;
1501 bufferevent_openssl_set_allow_dirty_shutdown(struct bufferevent *bev,
1502 int allow_dirty_shutdown)
1504 struct bufferevent_openssl *bev_ssl;
1506 bev_ssl = upcast(bev);
1508 bev_ssl->allow_dirty_shutdown = !!allow_dirty_shutdown;
1513 bufferevent_get_openssl_error(struct bufferevent *bev)
1515 unsigned long err = 0;
1516 struct bufferevent_openssl *bev_ssl;
1518 bev_ssl = upcast(bev);
1519 if (bev_ssl && bev_ssl->n_errors) {
1520 err = bev_ssl->errors[--bev_ssl->n_errors];