Path: blob/main/crypto/openssl/doc/designs/ddd/ddd-02-conn-nonblocking.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_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}8586/*87* NOTE: QUIC cannot operate with a buffering BIO between the QUIC SSL88* object in the network. In this case, the call to BIO_push() is not89* supported by the QUIC SSL object and will be ignored, thus this code90* works without removing this line. However, the buffering BIO is not91* actually used as a result and should be removed when adapting code to use92* QUIC.93*94* Setting a buffer as the underlying BIO on the QUIC SSL object using95* SSL_set_bio() will not work, though BIO_s_dgram_pair is available for96* buffering the input and output to the QUIC SSL object on the network side97* if desired.98*/99buf = BIO_new(BIO_f_buffer());100if (buf == NULL) {101BIO_free_all(out);102free(conn);103return NULL;104}105106BIO_push(out, buf);107108if (BIO_set_conn_hostname(out, hostname) == 0) {109BIO_free_all(out);110free(conn);111return NULL;112}113114/* Returns the parsed hostname extracted from the hostname:port string. */115bare_hostname = BIO_get_conn_hostname(out);116if (bare_hostname == NULL) {117BIO_free_all(out);118free(conn);119return NULL;120}121122/* Tell the SSL object the hostname to check certificates against. */123if (SSL_set1_host(ssl, bare_hostname) <= 0) {124BIO_free_all(out);125free(conn);126return NULL;127}128129#ifdef USE_QUIC130/* Configure ALPN, which is required for QUIC. */131if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn))) {132/* Note: SSL_set_alpn_protos returns 1 for failure. */133BIO_free_all(out);134return NULL;135}136#endif137138/* Make the BIO nonblocking. */139BIO_set_nbio(out, 1);140141conn->ssl_bio = out;142return conn;143}144145/*146* Non-blocking transmission.147*148* Returns -1 on error. Returns -2 if the function would block (corresponds to149* EWOULDBLOCK).150*/151int tx(APP_CONN *conn, const void *buf, int buf_len)152{153int l;154155conn->tx_need_rx = 0;156157l = BIO_write(conn->ssl_bio, buf, buf_len);158if (l <= 0) {159if (BIO_should_retry(conn->ssl_bio)) {160conn->tx_need_rx = BIO_should_read(conn->ssl_bio);161return -2;162} else {163return -1;164}165}166167return l;168}169170/*171* Non-blocking reception.172*173* Returns -1 on error. Returns -2 if the function would block (corresponds to174* EWOULDBLOCK).175*/176int rx(APP_CONN *conn, void *buf, int buf_len)177{178int l;179180conn->rx_need_tx = 0;181182l = BIO_read(conn->ssl_bio, buf, buf_len);183if (l <= 0) {184if (BIO_should_retry(conn->ssl_bio)) {185conn->rx_need_tx = BIO_should_write(conn->ssl_bio);186return -2;187} else {188return -1;189}190}191192return l;193}194195/*196* The application wants to know a fd it can poll on to determine when the197* SSL state machine needs to be pumped.198*/199int get_conn_fd(APP_CONN *conn)200{201#ifdef USE_QUIC202BIO_POLL_DESCRIPTOR d;203204if (!BIO_get_rpoll_descriptor(conn->ssl_bio, &d))205return -1;206207return d.value.fd;208#else209return BIO_get_fd(conn->ssl_bio, NULL);210#endif211}212213/*214* These functions returns zero or more of:215*216* POLLIN: The SSL state machine is interested in socket readability events.217*218* POLLOUT: The SSL state machine is interested in socket writeability events.219*220* POLLERR: The SSL state machine is interested in socket error events.221*222* get_conn_pending_tx returns events which may cause SSL_write to make223* progress and get_conn_pending_rx returns events which may cause SSL_read224* to make progress.225*/226int get_conn_pending_tx(APP_CONN *conn)227{228#ifdef USE_QUIC229return (SSL_net_read_desired(conn->ssl) ? POLLIN : 0)230| (SSL_net_write_desired(conn->ssl) ? POLLOUT : 0)231| POLLERR;232#else233return (conn->tx_need_rx ? POLLIN : 0) | POLLOUT | POLLERR;234#endif235}236237int get_conn_pending_rx(APP_CONN *conn)238{239#ifdef USE_QUIC240return get_conn_pending_tx(conn);241#else242return (conn->rx_need_tx ? POLLOUT : 0) | POLLIN | POLLERR;243#endif244}245246#ifdef USE_QUIC247/*248* Returns the number of milliseconds after which some call to libssl must be249* made. Any call (BIO_read/BIO_write/BIO_pump) will do. Returns -1 if250* there is no need for such a call. This may change after the next call251* to libssl.252*/253static inline int timeval_to_ms(const struct timeval *t);254255int get_conn_pump_timeout(APP_CONN *conn)256{257struct timeval tv;258int is_infinite;259260if (!SSL_get_event_timeout(conn->ssl, &tv, &is_infinite))261return -1;262263return is_infinite ? -1 : timeval_to_ms(&tv);264}265266/*267* Called to advance internals of libssl state machines without having to268* perform an application-level read/write.269*/270void pump(APP_CONN *conn)271{272SSL_handle_events(conn->ssl);273}274#endif275276/*277* The application wants to close the connection and free bookkeeping278* structures.279*/280void teardown(APP_CONN *conn)281{282BIO_free_all(conn->ssl_bio);283free(conn);284}285286/*287* The application is shutting down and wants to free a previously288* created SSL_CTX.289*/290void teardown_ctx(SSL_CTX *ctx)291{292SSL_CTX_free(ctx);293}294295/*296* ============================================================================297* Example driver for the above code. This is just to demonstrate that the code298* works and is not intended to be representative of a real application.299*/300#include <sys/time.h>301302static inline void ms_to_timeval(struct timeval *t, int ms)303{304t->tv_sec = ms < 0 ? -1 : ms/1000;305t->tv_usec = ms < 0 ? 0 : (ms%1000)*1000;306}307308static inline int timeval_to_ms(const struct timeval *t)309{310return t->tv_sec*1000 + t->tv_usec/1000;311}312313int main(int argc, char **argv)314{315static char tx_msg[384], host_port[300];316const char *tx_p = tx_msg;317char rx_buf[2048];318int res = 1, l, tx_len;319#ifdef USE_QUIC320struct timeval timeout;321#else322int timeout = 2000 /* ms */;323#endif324APP_CONN *conn = NULL;325SSL_CTX *ctx = NULL;326327#ifdef USE_QUIC328ms_to_timeval(&timeout, 2000);329#endif330331if (argc < 3) {332fprintf(stderr, "usage: %s host port\n", argv[0]);333goto fail;334}335336snprintf(host_port, sizeof(host_port), "%s:%s", argv[1], argv[2]);337tx_len = snprintf(tx_msg, sizeof(tx_msg),338"GET / HTTP/1.0\r\nHost: %s\r\n\r\n", argv[1]);339340ctx = create_ssl_ctx();341if (ctx == NULL) {342fprintf(stderr, "cannot create SSL context\n");343goto fail;344}345346conn = new_conn(ctx, host_port);347if (conn == NULL) {348fprintf(stderr, "cannot establish connection\n");349goto fail;350}351352/* TX */353while (tx_len != 0) {354l = tx(conn, tx_p, tx_len);355if (l > 0) {356tx_p += l;357tx_len -= l;358} else if (l == -1) {359fprintf(stderr, "tx error\n");360} else if (l == -2) {361#ifdef USE_QUIC362struct timeval start, now, deadline, t;363#endif364struct pollfd pfd = {0};365366#ifdef USE_QUIC367ms_to_timeval(&t, get_conn_pump_timeout(conn));368if (t.tv_sec < 0 || timercmp(&t, &timeout, >))369t = timeout;370371gettimeofday(&start, NULL);372timeradd(&start, &timeout, &deadline);373#endif374375pfd.fd = get_conn_fd(conn);376pfd.events = get_conn_pending_tx(conn);377#ifdef USE_QUIC378if (poll(&pfd, 1, timeval_to_ms(&t)) == 0)379#else380if (poll(&pfd, 1, timeout) == 0)381#endif382{383#ifdef USE_QUIC384pump(conn);385386gettimeofday(&now, NULL);387if (timercmp(&now, &deadline, >=))388#endif389{390fprintf(stderr, "tx timeout\n");391goto fail;392}393}394}395}396397/* RX */398for (;;) {399l = rx(conn, rx_buf, sizeof(rx_buf));400if (l > 0) {401fwrite(rx_buf, 1, l, stdout);402} else if (l == -1) {403break;404} else if (l == -2) {405#ifdef USE_QUIC406struct timeval start, now, deadline, t;407#endif408struct pollfd pfd = {0};409410#ifdef USE_QUIC411ms_to_timeval(&t, get_conn_pump_timeout(conn));412if (t.tv_sec < 0 || timercmp(&t, &timeout, >))413t = timeout;414415gettimeofday(&start, NULL);416timeradd(&start, &timeout, &deadline);417#endif418419pfd.fd = get_conn_fd(conn);420pfd.events = get_conn_pending_rx(conn);421#ifdef USE_QUIC422if (poll(&pfd, 1, timeval_to_ms(&t)) == 0)423#else424if (poll(&pfd, 1, timeout) == 0)425#endif426{427#ifdef USE_QUIC428pump(conn);429430gettimeofday(&now, NULL);431if (timercmp(&now, &deadline, >=))432#endif433{434fprintf(stderr, "rx timeout\n");435goto fail;436}437}438}439}440441res = 0;442fail:443if (conn != NULL)444teardown(conn);445if (ctx != NULL)446teardown_ctx(ctx);447return res;448}449450451