2
0

ddd-05-mem-nonblocking.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. #include <sys/poll.h>
  2. #include <openssl/ssl.h>
  3. /*
  4. * Demo 5: Client — Client Uses Memory BIO — Nonblocking
  5. * =====================================================
  6. *
  7. * This is an example of (part of) an application which uses libssl in an
  8. * asynchronous, nonblocking fashion. The application passes memory BIOs to
  9. * OpenSSL, meaning that it controls both when data is read/written from an SSL
  10. * object on the decrypted side but also when encrypted data from the network is
  11. * shunted to/from OpenSSL. In this way OpenSSL is used as a pure state machine
  12. * which does not make its own network I/O calls. OpenSSL never sees or creates
  13. * any file descriptor for a network socket. The functions below show all
  14. * interactions with libssl the application makes, and would hypothetically be
  15. * linked into a larger application.
  16. */
  17. typedef struct app_conn_st {
  18. SSL *ssl;
  19. BIO *ssl_bio, *net_bio;
  20. int rx_need_tx, tx_need_rx;
  21. } APP_CONN;
  22. /*
  23. * The application is initializing and wants an SSL_CTX which it will use for
  24. * some number of outgoing connections, which it creates in subsequent calls to
  25. * new_conn. The application may also call this function multiple times to
  26. * create multiple SSL_CTX.
  27. */
  28. SSL_CTX *create_ssl_ctx(void)
  29. {
  30. SSL_CTX *ctx;
  31. #ifdef USE_QUIC
  32. ctx = SSL_CTX_new(OSSL_QUIC_client_method());
  33. #else
  34. ctx = SSL_CTX_new(TLS_client_method());
  35. #endif
  36. if (ctx == NULL)
  37. return NULL;
  38. /* Enable trust chain verification. */
  39. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
  40. /* Load default root CA store. */
  41. if (SSL_CTX_set_default_verify_paths(ctx) == 0) {
  42. SSL_CTX_free(ctx);
  43. return NULL;
  44. }
  45. return ctx;
  46. }
  47. /*
  48. * The application wants to create a new outgoing connection using a given
  49. * SSL_CTX.
  50. *
  51. * hostname is a string like "openssl.org" used for certificate validation.
  52. */
  53. APP_CONN *new_conn(SSL_CTX *ctx, const char *bare_hostname)
  54. {
  55. BIO *ssl_bio, *internal_bio, *net_bio;
  56. APP_CONN *conn;
  57. SSL *ssl;
  58. #ifdef USE_QUIC
  59. static const unsigned char alpn[] = {5, 'd', 'u', 'm', 'm', 'y'};
  60. #endif
  61. conn = calloc(1, sizeof(APP_CONN));
  62. if (conn == NULL)
  63. return NULL;
  64. ssl = conn->ssl = SSL_new(ctx);
  65. if (ssl == NULL) {
  66. free(conn);
  67. return NULL;
  68. }
  69. SSL_set_connect_state(ssl); /* cannot fail */
  70. #ifdef USE_QUIC
  71. if (BIO_new_bio_dgram_pair(&internal_bio, 0, &net_bio, 0) <= 0) {
  72. #else
  73. if (BIO_new_bio_pair(&internal_bio, 0, &net_bio, 0) <= 0) {
  74. #endif
  75. SSL_free(ssl);
  76. free(conn);
  77. return NULL;
  78. }
  79. SSL_set_bio(ssl, internal_bio, internal_bio);
  80. if (SSL_set1_host(ssl, bare_hostname) <= 0) {
  81. SSL_free(ssl);
  82. free(conn);
  83. return NULL;
  84. }
  85. if (SSL_set_tlsext_host_name(ssl, bare_hostname) <= 0) {
  86. SSL_free(ssl);
  87. free(conn);
  88. return NULL;
  89. }
  90. ssl_bio = BIO_new(BIO_f_ssl());
  91. if (ssl_bio == NULL) {
  92. SSL_free(ssl);
  93. free(conn);
  94. return NULL;
  95. }
  96. if (BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE) <= 0) {
  97. SSL_free(ssl);
  98. BIO_free(ssl_bio);
  99. return NULL;
  100. }
  101. #ifdef USE_QUIC
  102. /* Configure ALPN, which is required for QUIC. */
  103. if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) {
  104. /* Note: SSL_set_alpn_protos returns 1 for failure. */
  105. SSL_free(ssl);
  106. BIO_free(ssl_bio);
  107. return NULL;
  108. }
  109. #endif
  110. conn->ssl_bio = ssl_bio;
  111. conn->net_bio = net_bio;
  112. return conn;
  113. }
  114. /*
  115. * Non-blocking transmission.
  116. *
  117. * Returns -1 on error. Returns -2 if the function would block (corresponds to
  118. * EWOULDBLOCK).
  119. */
  120. int tx(APP_CONN *conn, const void *buf, int buf_len)
  121. {
  122. int rc, l;
  123. l = BIO_write(conn->ssl_bio, buf, buf_len);
  124. if (l <= 0) {
  125. rc = SSL_get_error(conn->ssl, l);
  126. switch (rc) {
  127. case SSL_ERROR_WANT_READ:
  128. conn->tx_need_rx = 1;
  129. case SSL_ERROR_WANT_CONNECT:
  130. case SSL_ERROR_WANT_WRITE:
  131. return -2;
  132. default:
  133. return -1;
  134. }
  135. } else {
  136. conn->tx_need_rx = 0;
  137. }
  138. return l;
  139. }
  140. /*
  141. * Non-blocking reception.
  142. *
  143. * Returns -1 on error. Returns -2 if the function would block (corresponds to
  144. * EWOULDBLOCK).
  145. */
  146. int rx(APP_CONN *conn, void *buf, int buf_len)
  147. {
  148. int rc, l;
  149. l = BIO_read(conn->ssl_bio, buf, buf_len);
  150. if (l <= 0) {
  151. rc = SSL_get_error(conn->ssl, l);
  152. switch (rc) {
  153. case SSL_ERROR_WANT_WRITE:
  154. conn->rx_need_tx = 1;
  155. case SSL_ERROR_WANT_READ:
  156. return -2;
  157. default:
  158. return -1;
  159. }
  160. } else {
  161. conn->rx_need_tx = 0;
  162. }
  163. return l;
  164. }
  165. /*
  166. * Called to get data which has been enqueued for transmission to the network
  167. * by OpenSSL. For QUIC, this always outputs a single datagram.
  168. *
  169. * IMPORTANT (QUIC): If buf_len is inadequate to hold the datagram, it is truncated
  170. * (similar to read(2)). A buffer size of at least 1472 must be used by default
  171. * to guarantee this does not occur.
  172. */
  173. int read_net_tx(APP_CONN *conn, void *buf, int buf_len)
  174. {
  175. return BIO_read(conn->net_bio, buf, buf_len);
  176. }
  177. /*
  178. * Called to feed data which has been received from the network to OpenSSL.
  179. *
  180. * QUIC: buf must contain the entirety of a single datagram. It will be consumed
  181. * entirely (return value == buf_len) or not at all.
  182. */
  183. int write_net_rx(APP_CONN *conn, const void *buf, int buf_len)
  184. {
  185. return BIO_write(conn->net_bio, buf, buf_len);
  186. }
  187. /*
  188. * Determine how much data can be written to the network RX BIO.
  189. */
  190. size_t net_rx_space(APP_CONN *conn)
  191. {
  192. return BIO_ctrl_get_write_guarantee(conn->net_bio);
  193. }
  194. /*
  195. * Determine how much data is currently queued for transmission in the network
  196. * TX BIO.
  197. */
  198. size_t net_tx_avail(APP_CONN *conn)
  199. {
  200. return BIO_ctrl_pending(conn->net_bio);
  201. }
  202. /*
  203. * These functions returns zero or more of:
  204. *
  205. * POLLIN: The SSL state machine is interested in socket readability events.
  206. *
  207. * POLLOUT: The SSL state machine is interested in socket writeability events.
  208. *
  209. * POLLERR: The SSL state machine is interested in socket error events.
  210. *
  211. * get_conn_pending_tx returns events which may cause SSL_write to make
  212. * progress and get_conn_pending_rx returns events which may cause SSL_read
  213. * to make progress.
  214. */
  215. int get_conn_pending_tx(APP_CONN *conn)
  216. {
  217. #ifdef USE_QUIC
  218. return (SSL_net_read_desired(conn->ssl) ? POLLIN : 0)
  219. | (SSL_net_write_desired(conn->ssl) ? POLLOUT : 0)
  220. | POLLERR;
  221. #else
  222. return (conn->tx_need_rx ? POLLIN : 0) | POLLOUT | POLLERR;
  223. #endif
  224. }
  225. int get_conn_pending_rx(APP_CONN *conn)
  226. {
  227. #ifdef USE_QUIC
  228. return get_conn_pending_tx(conn);
  229. #else
  230. return (conn->rx_need_tx ? POLLOUT : 0) | POLLIN | POLLERR;
  231. #endif
  232. }
  233. /*
  234. * The application wants to close the connection and free bookkeeping
  235. * structures.
  236. */
  237. void teardown(APP_CONN *conn)
  238. {
  239. BIO_free_all(conn->ssl_bio);
  240. BIO_free_all(conn->net_bio);
  241. free(conn);
  242. }
  243. /*
  244. * The application is shutting down and wants to free a previously
  245. * created SSL_CTX.
  246. */
  247. void teardown_ctx(SSL_CTX *ctx)
  248. {
  249. SSL_CTX_free(ctx);
  250. }
  251. /*
  252. * ============================================================================
  253. * Example driver for the above code. This is just to demonstrate that the code
  254. * works and is not intended to be representative of a real application.
  255. */
  256. #include <sys/types.h>
  257. #include <sys/socket.h>
  258. #include <sys/signal.h>
  259. #include <netdb.h>
  260. #include <unistd.h>
  261. #include <fcntl.h>
  262. #include <errno.h>
  263. static int pump(APP_CONN *conn, int fd, int events, int timeout)
  264. {
  265. int l, l2;
  266. char buf[2048]; /* QUIC: would need to be changed if < 1472 */
  267. size_t wspace;
  268. struct pollfd pfd = {0};
  269. pfd.fd = fd;
  270. pfd.events = (events & (POLLIN | POLLERR));
  271. if (net_rx_space(conn) == 0)
  272. pfd.events &= ~POLLIN;
  273. if (net_tx_avail(conn) > 0)
  274. pfd.events |= POLLOUT;
  275. if ((pfd.events & (POLLIN|POLLOUT)) == 0)
  276. return 1;
  277. if (poll(&pfd, 1, timeout) == 0)
  278. return -1;
  279. if (pfd.revents & POLLIN) {
  280. while ((wspace = net_rx_space(conn)) > 0) {
  281. l = read(fd, buf, wspace > sizeof(buf) ? sizeof(buf) : wspace);
  282. if (l <= 0) {
  283. switch (errno) {
  284. case EAGAIN:
  285. goto stop;
  286. default:
  287. if (l == 0) /* EOF */
  288. goto stop;
  289. fprintf(stderr, "error on read: %d\n", errno);
  290. return -1;
  291. }
  292. break;
  293. }
  294. l2 = write_net_rx(conn, buf, l);
  295. if (l2 < l)
  296. fprintf(stderr, "short write %d %d\n", l2, l);
  297. } stop:;
  298. }
  299. if (pfd.revents & POLLOUT) {
  300. for (;;) {
  301. l = read_net_tx(conn, buf, sizeof(buf));
  302. if (l <= 0)
  303. break;
  304. l2 = write(fd, buf, l);
  305. if (l2 < l)
  306. fprintf(stderr, "short read %d %d\n", l2, l);
  307. }
  308. }
  309. return 1;
  310. }
  311. int main(int argc, char **argv)
  312. {
  313. int rc, fd = -1, res = 1;
  314. static char tx_msg[300];
  315. const char *tx_p = tx_msg;
  316. char rx_buf[2048];
  317. int l, tx_len;
  318. int timeout = 2000 /* ms */;
  319. APP_CONN *conn = NULL;
  320. struct addrinfo hints = {0}, *result = NULL;
  321. SSL_CTX *ctx = NULL;
  322. if (argc < 3) {
  323. fprintf(stderr, "usage: %s host port\n", argv[0]);
  324. goto fail;
  325. }
  326. tx_len = snprintf(tx_msg, sizeof(tx_msg),
  327. "GET / HTTP/1.0\r\nHost: %s\r\n\r\n",
  328. argv[1]);
  329. ctx = create_ssl_ctx();
  330. if (ctx == NULL) {
  331. fprintf(stderr, "cannot create SSL context\n");
  332. goto fail;
  333. }
  334. hints.ai_family = AF_INET;
  335. hints.ai_socktype = SOCK_STREAM;
  336. hints.ai_flags = AI_PASSIVE;
  337. rc = getaddrinfo(argv[1], argv[2], &hints, &result);
  338. if (rc < 0) {
  339. fprintf(stderr, "cannot resolve\n");
  340. goto fail;
  341. }
  342. signal(SIGPIPE, SIG_IGN);
  343. #ifdef USE_QUIC
  344. fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  345. #else
  346. fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  347. #endif
  348. if (fd < 0) {
  349. fprintf(stderr, "cannot create socket\n");
  350. goto fail;
  351. }
  352. rc = connect(fd, result->ai_addr, result->ai_addrlen);
  353. if (rc < 0) {
  354. fprintf(stderr, "cannot connect\n");
  355. goto fail;
  356. }
  357. rc = fcntl(fd, F_SETFL, O_NONBLOCK);
  358. if (rc < 0) {
  359. fprintf(stderr, "cannot make socket nonblocking\n");
  360. goto fail;
  361. }
  362. conn = new_conn(ctx, argv[1]);
  363. if (conn == NULL) {
  364. fprintf(stderr, "cannot establish connection\n");
  365. goto fail;
  366. }
  367. /* TX */
  368. while (tx_len != 0) {
  369. l = tx(conn, tx_p, tx_len);
  370. if (l > 0) {
  371. tx_p += l;
  372. tx_len -= l;
  373. } else if (l == -1) {
  374. fprintf(stderr, "tx error\n");
  375. } else if (l == -2) {
  376. if (pump(conn, fd, get_conn_pending_tx(conn), timeout) != 1) {
  377. fprintf(stderr, "pump error\n");
  378. goto fail;
  379. }
  380. }
  381. }
  382. /* RX */
  383. for (;;) {
  384. l = rx(conn, rx_buf, sizeof(rx_buf));
  385. if (l > 0) {
  386. fwrite(rx_buf, 1, l, stdout);
  387. } else if (l == -1) {
  388. break;
  389. } else if (l == -2) {
  390. if (pump(conn, fd, get_conn_pending_rx(conn), timeout) != 1) {
  391. fprintf(stderr, "pump error\n");
  392. goto fail;
  393. }
  394. }
  395. }
  396. res = 0;
  397. fail:
  398. if (conn != NULL)
  399. teardown(conn);
  400. if (ctx != NULL)
  401. teardown_ctx(ctx);
  402. if (result != NULL)
  403. freeaddrinfo(result);
  404. return res;
  405. }