Path: blob/main/crypto/openssl/doc/designs/ddd/ddd-02-conn-nonblocking-threads.c
34889 views
#include <sys/poll.h>1#include <openssl/ssl.h>23/*4* Demo 2: Client — Managed Connection — Nonblocking5* ==============================================================6*7* This is an example of (part of) an application which uses libssl in an8* asynchronous, nonblocking fashion. The functions show all interactions with9* libssl the application makes, and would hypothetically be linked into a10* larger application.11*12* In this example, libssl still makes syscalls directly using an fd, which is13* configured in nonblocking mode. As such, the application can still be14* abstracted from the details of what that fd is (is it a TCP socket? is it a15* UDP socket?); this code passes the application an fd and the application16* simply calls back into this code when poll()/etc. indicates it is ready.17*/18typedef struct app_conn_st {19SSL *ssl;20BIO *ssl_bio;21int rx_need_tx, tx_need_rx;22} APP_CONN;2324/*25* The application is initializing and wants an SSL_CTX which it will use for26* some number of outgoing connections, which it creates in subsequent calls to27* new_conn. The application may also call this function multiple times to28* create multiple SSL_CTX.29*/30SSL_CTX *create_ssl_ctx(void)31{32SSL_CTX *ctx;3334#ifdef USE_QUIC35ctx = SSL_CTX_new(OSSL_QUIC_client_thread_method());36#else37ctx = SSL_CTX_new(TLS_client_method());38#endif39if (ctx == NULL)40return NULL;4142/* Enable trust chain verification. */43SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);4445/* Load default root CA store. */46if (SSL_CTX_set_default_verify_paths(ctx) == 0) {47SSL_CTX_free(ctx);48return NULL;49}5051return ctx;52}5354/*55* The application wants to create a new outgoing connection using a given56* SSL_CTX.57*58* hostname is a string like "openssl.org:443" or "[::1]:443".59*/60APP_CONN *new_conn(SSL_CTX *ctx, const char *hostname)61{62APP_CONN *conn;63BIO *out, *buf;64SSL *ssl = NULL;65const char *bare_hostname;66#ifdef USE_QUIC67static const unsigned char alpn[] = {5, 'd', 'u', 'm', 'm', 'y'};68#endif6970conn = calloc(1, sizeof(APP_CONN));71if (conn == NULL)72return NULL;7374out = BIO_new_ssl_connect(ctx);75if (out == NULL) {76free(conn);77return NULL;78}7980if (BIO_get_ssl(out, &ssl) == 0) {81BIO_free_all(out);82free(conn);83return NULL;84}8586buf = BIO_new(BIO_f_buffer());87if (buf == NULL) {88BIO_free_all(out);89free(conn);90return NULL;91}9293BIO_push(out, buf);9495if (BIO_set_conn_hostname(out, hostname) == 0) {96BIO_free_all(out);97free(conn);98return NULL;99}100101/* Returns the parsed hostname extracted from the hostname:port string. */102bare_hostname = BIO_get_conn_hostname(out);103if (bare_hostname == NULL) {104BIO_free_all(out);105free(conn);106return NULL;107}108109/* Tell the SSL object the hostname to check certificates against. */110if (SSL_set1_host(ssl, bare_hostname) <= 0) {111BIO_free_all(out);112free(conn);113return NULL;114}115116#ifdef USE_QUIC117/* Configure ALPN, which is required for QUIC. */118if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) {119/* Note: SSL_set_alpn_protos returns 1 for failure. */120BIO_free_all(out);121free(conn);122return NULL;123}124#endif125126/* Make the BIO nonblocking. */127BIO_set_nbio(out, 1);128129conn->ssl_bio = out;130return conn;131}132133/*134* Non-blocking transmission.135*136* Returns -1 on error. Returns -2 if the function would block (corresponds to137* EWOULDBLOCK).138*/139int tx(APP_CONN *conn, const void *buf, int buf_len)140{141int l;142143conn->tx_need_rx = 0;144145l = BIO_write(conn->ssl_bio, buf, buf_len);146if (l <= 0) {147if (BIO_should_retry(conn->ssl_bio)) {148conn->tx_need_rx = BIO_should_read(conn->ssl_bio);149return -2;150} else {151return -1;152}153}154155return l;156}157158/*159* Non-blocking reception.160*161* Returns -1 on error. Returns -2 if the function would block (corresponds to162* EWOULDBLOCK).163*/164int rx(APP_CONN *conn, void *buf, int buf_len)165{166int l;167168conn->rx_need_tx = 0;169170l = BIO_read(conn->ssl_bio, buf, buf_len);171if (l <= 0) {172if (BIO_should_retry(conn->ssl_bio)) {173conn->rx_need_tx = BIO_should_write(conn->ssl_bio);174return -2;175} else {176return -1;177}178}179180return l;181}182183/*184* The application wants to know a fd it can poll on to determine when the185* SSL state machine needs to be pumped.186*/187int get_conn_fd(APP_CONN *conn)188{189#ifdef USE_QUIC190BIO_POLL_DESCRIPTOR d;191192if (!BIO_get_rpoll_descriptor(conn->ssl_bio, &d))193return -1;194195return d.value.fd;196#else197return BIO_get_fd(conn->ssl_bio, NULL);198#endif199}200201/*202* These functions returns zero or more of:203*204* POLLIN: The SSL state machine is interested in socket readability events.205*206* POLLOUT: The SSL state machine is interested in socket writeability events.207*208* POLLERR: The SSL state machine is interested in socket error events.209*210* get_conn_pending_tx returns events which may cause SSL_write to make211* progress and get_conn_pending_rx returns events which may cause SSL_read212* to make progress.213*/214int get_conn_pending_tx(APP_CONN *conn)215{216#ifdef USE_QUIC217return (SSL_net_read_desired(conn->ssl) ? POLLIN : 0)218| (SSL_net_write_desired(conn->ssl) ? POLLOUT : 0)219| POLLERR;220#else221return (conn->tx_need_rx ? POLLIN : 0) | POLLOUT | POLLERR;222#endif223}224225int get_conn_pending_rx(APP_CONN *conn)226{227#ifdef USE_QUIC228return get_conn_pending_tx(conn);229#else230return (conn->rx_need_tx ? POLLOUT : 0) | POLLIN | POLLERR;231#endif232}233234/*235* The application wants to close the connection and free bookkeeping236* structures.237*/238void teardown(APP_CONN *conn)239{240BIO_free_all(conn->ssl_bio);241free(conn);242}243244/*245* The application is shutting down and wants to free a previously246* created SSL_CTX.247*/248void teardown_ctx(SSL_CTX *ctx)249{250SSL_CTX_free(ctx);251}252253/*254* ============================================================================255* Example driver for the above code. This is just to demonstrate that the code256* works and is not intended to be representative of a real application.257*/258int main(int argc, char **argv)259{260static char tx_msg[384], host_port[300];261const char *tx_p = tx_msg;262char rx_buf[2048];263int res = 1, l, tx_len;264int timeout = 2000 /* ms */;265APP_CONN *conn = NULL;266SSL_CTX *ctx = NULL;267268if (argc < 3) {269fprintf(stderr, "usage: %s host port\n", argv[0]);270goto fail;271}272273snprintf(host_port, sizeof(host_port), "%s:%s", argv[1], argv[2]);274tx_len = snprintf(tx_msg, sizeof(tx_msg),275"GET / HTTP/1.0\r\nHost: %s\r\n\r\n", argv[1]);276277ctx = create_ssl_ctx();278if (ctx == NULL) {279fprintf(stderr, "cannot create SSL context\n");280goto fail;281}282283conn = new_conn(ctx, host_port);284if (conn == NULL) {285fprintf(stderr, "cannot establish connection\n");286goto fail;287}288289/* TX */290while (tx_len != 0) {291l = tx(conn, tx_p, tx_len);292if (l > 0) {293tx_p += l;294tx_len -= l;295} else if (l == -1) {296fprintf(stderr, "tx error\n");297} else if (l == -2) {298struct pollfd pfd = {0};299pfd.fd = get_conn_fd(conn);300pfd.events = get_conn_pending_tx(conn);301if (poll(&pfd, 1, timeout) == 0) {302fprintf(stderr, "tx timeout\n");303goto fail;304}305}306}307308/* RX */309for (;;) {310l = rx(conn, rx_buf, sizeof(rx_buf));311if (l > 0) {312fwrite(rx_buf, 1, l, stdout);313} else if (l == -1) {314break;315} else if (l == -2) {316struct pollfd pfd = {0};317pfd.fd = get_conn_fd(conn);318pfd.events = get_conn_pending_rx(conn);319if (poll(&pfd, 1, timeout) == 0) {320fprintf(stderr, "rx timeout\n");321goto fail;322}323}324}325326res = 0;327fail:328if (conn != NULL)329teardown(conn);330if (ctx != NULL)331teardown_ctx(ctx);332return res;333}334335336