bufferevent_openssl.c 39 KB

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