Path: blob/main/crypto/openssl/demos/guide/quic-client-non-block.c
34868 views
/*1* Copyright 2023-2025 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89/*10* NB: Changes to this file should also be reflected in11* doc/man7/ossl-guide-quic-client-non-block.pod12*/1314#include <string.h>1516/* Include the appropriate header file for SOCK_DGRAM */17#ifdef _WIN32 /* Windows */18# include <winsock2.h>19#else /* Linux/Unix */20# include <sys/socket.h>21# include <sys/select.h>22#endif2324#include <openssl/bio.h>25#include <openssl/ssl.h>26#include <openssl/err.h>2728/* Helper function to create a BIO connected to the server */29static BIO *create_socket_bio(const char *hostname, const char *port,30int family, BIO_ADDR **peer_addr)31{32int sock = -1;33BIO_ADDRINFO *res;34const BIO_ADDRINFO *ai = NULL;35BIO *bio;3637/*38* Lookup IP address info for the server.39*/40if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_DGRAM, 0,41&res))42return NULL;4344/*45* Loop through all the possible addresses for the server and find one46* we can connect to.47*/48for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {49/*50* Create a UDP socket. We could equally use non-OpenSSL calls such51* as "socket" here for this and the subsequent connect and close52* functions. But for portability reasons and also so that we get53* errors on the OpenSSL stack in the event of a failure we use54* OpenSSL's versions of these functions.55*/56sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0);57if (sock == -1)58continue;5960/* Connect the socket to the server's address */61if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) {62BIO_closesocket(sock);63sock = -1;64continue;65}6667/* Set to nonblocking mode */68if (!BIO_socket_nbio(sock, 1)) {69BIO_closesocket(sock);70sock = -1;71continue;72}7374break;75}7677if (sock != -1) {78*peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));79if (*peer_addr == NULL) {80BIO_closesocket(sock);81return NULL;82}83}8485/* Free the address information resources we allocated earlier */86BIO_ADDRINFO_free(res);8788/* If sock is -1 then we've been unable to connect to the server */89if (sock == -1)90return NULL;9192/* Create a BIO to wrap the socket */93bio = BIO_new(BIO_s_datagram());94if (bio == NULL) {95BIO_closesocket(sock);96return NULL;97}9899/*100* Associate the newly created BIO with the underlying socket. By101* passing BIO_CLOSE here the socket will be automatically closed when102* the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which103* case you must close the socket explicitly when it is no longer104* needed.105*/106BIO_set_fd(bio, sock, BIO_CLOSE);107108return bio;109}110111static void wait_for_activity(SSL *ssl)112{113fd_set wfds, rfds;114int width, sock, isinfinite;115struct timeval tv;116struct timeval *tvp = NULL;117118/* Get hold of the underlying file descriptor for the socket */119sock = SSL_get_fd(ssl);120121FD_ZERO(&wfds);122FD_ZERO(&rfds);123124/*125* Find out if we would like to write to the socket, or read from it (or126* both)127*/128if (SSL_net_write_desired(ssl))129FD_SET(sock, &wfds);130if (SSL_net_read_desired(ssl))131FD_SET(sock, &rfds);132width = sock + 1;133134/*135* Find out when OpenSSL would next like to be called, regardless of136* whether the state of the underlying socket has changed or not.137*/138if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite)139tvp = &tv;140141/*142* Wait until the socket is writeable or readable. We use select here143* for the sake of simplicity and portability, but you could equally use144* poll/epoll or similar functions145*146* NOTE: For the purposes of this demonstration code this effectively147* makes this demo block until it has something more useful to do. In a148* real application you probably want to go and do other work here (e.g.149* update a GUI, or service other connections).150*151* Let's say for example that you want to update the progress counter on152* a GUI every 100ms. One way to do that would be to use the timeout in153* the last parameter to "select" below. If the tvp value is greater154* than 100ms then use 100ms instead. Then, when select returns, you155* check if it did so because of activity on the file descriptors or156* because of the timeout. If the 100ms GUI timeout has expired but the157* tvp timeout has not then go and update the GUI and then restart the158* "select" (with updated timeouts).159*/160161select(width, &rfds, &wfds, NULL, tvp);162}163164static int handle_io_failure(SSL *ssl, int res)165{166switch (SSL_get_error(ssl, res)) {167case SSL_ERROR_WANT_READ:168case SSL_ERROR_WANT_WRITE:169/* Temporary failure. Wait until we can read/write and try again */170wait_for_activity(ssl);171return 1;172173case SSL_ERROR_ZERO_RETURN:174/* EOF */175return 0;176177case SSL_ERROR_SYSCALL:178return -1;179180case SSL_ERROR_SSL:181/*182* Some stream fatal error occurred. This could be because of a183* stream reset - or some failure occurred on the underlying184* connection.185*/186switch (SSL_get_stream_read_state(ssl)) {187case SSL_STREAM_STATE_RESET_REMOTE:188printf("Stream reset occurred\n");189/*190* The stream has been reset but the connection is still191* healthy.192*/193break;194195case SSL_STREAM_STATE_CONN_CLOSED:196printf("Connection closed\n");197/* Connection is already closed. */198break;199200default:201printf("Unknown stream failure\n");202break;203}204/*205* If the failure is due to a verification error we can get more206* information about it from SSL_get_verify_result().207*/208if (SSL_get_verify_result(ssl) != X509_V_OK)209printf("Verify error: %s\n",210X509_verify_cert_error_string(SSL_get_verify_result(ssl)));211return -1;212213default:214return -1;215}216}217/*218* Simple application to send a basic HTTP/1.0 request to a server and219* print the response on the screen. Note that HTTP/1.0 over QUIC is220* non-standard and will not typically be supported by real world servers. This221* is for demonstration purposes only.222*/223int main(int argc, char *argv[])224{225SSL_CTX *ctx = NULL;226SSL *ssl = NULL;227BIO *bio = NULL;228int res = EXIT_FAILURE;229int ret;230unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };231const char *request_start = "GET / HTTP/1.0\r\nConnection: close\r\nHost: ";232const char *request_end = "\r\n\r\n";233size_t written, readbytes = 0;234char buf[160];235BIO_ADDR *peer_addr = NULL;236int eof = 0;237char *hostname, *port;238int ipv6 = 0;239int argnext = 1;240241if (argc < 3) {242printf("Usage: quic-client-non-block [-6] hostname port\n");243goto end;244}245246if (!strcmp(argv[argnext], "-6")) {247if (argc < 4) {248printf("Usage: quic-client-non-block [-6] hostname port\n");249goto end;250}251ipv6 = 1;252argnext++;253}254hostname = argv[argnext++];255port = argv[argnext];256257/*258* Create an SSL_CTX which we can use to create SSL objects from. We259* want an SSL_CTX for creating clients so we use260* OSSL_QUIC_client_method() here.261*/262ctx = SSL_CTX_new(OSSL_QUIC_client_method());263if (ctx == NULL) {264printf("Failed to create the SSL_CTX\n");265goto end;266}267268/*269* Configure the client to abort the handshake if certificate270* verification fails. Virtually all clients should do this unless you271* really know what you are doing.272*/273SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);274275/* Use the default trusted certificate store */276if (!SSL_CTX_set_default_verify_paths(ctx)) {277printf("Failed to set the default trusted certificate store\n");278goto end;279}280281/* Create an SSL object to represent the TLS connection */282ssl = SSL_new(ctx);283if (ssl == NULL) {284printf("Failed to create the SSL object\n");285goto end;286}287288/*289* Create the underlying transport socket/BIO and associate it with the290* connection.291*/292bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET,293&peer_addr);294if (bio == NULL) {295printf("Failed to crete the BIO\n");296goto end;297}298SSL_set_bio(ssl, bio, bio);299300/*301* Tell the server during the handshake which hostname we are attempting302* to connect to in case the server supports multiple hosts.303*/304if (!SSL_set_tlsext_host_name(ssl, hostname)) {305printf("Failed to set the SNI hostname\n");306goto end;307}308309/*310* Ensure we check during certificate verification that the server has311* supplied a certificate for the hostname that we were expecting.312* Virtually all clients should do this unless you really know what you313* are doing.314*/315if (!SSL_set1_host(ssl, hostname)) {316printf("Failed to set the certificate verification hostname");317goto end;318}319320/* SSL_set_alpn_protos returns 0 for success! */321if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {322printf("Failed to set the ALPN for the connection\n");323goto end;324}325326/* Set the IP address of the remote peer */327if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {328printf("Failed to set the initial peer address\n");329goto end;330}331332/*333* The underlying socket is always nonblocking with QUIC, but the default334* behaviour of the SSL object is still to block. We set it for nonblocking335* mode in this demo.336*/337if (!SSL_set_blocking_mode(ssl, 0)) {338printf("Failed to turn off blocking mode\n");339goto end;340}341342/* Do the handshake with the server */343while ((ret = SSL_connect(ssl)) != 1) {344if (handle_io_failure(ssl, ret) == 1)345continue; /* Retry */346printf("Failed to connect to server\n");347goto end; /* Cannot retry: error */348}349350/* Write an HTTP GET request to the peer */351while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {352if (handle_io_failure(ssl, 0) == 1)353continue; /* Retry */354printf("Failed to write start of HTTP request\n");355goto end; /* Cannot retry: error */356}357while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {358if (handle_io_failure(ssl, 0) == 1)359continue; /* Retry */360printf("Failed to write hostname in HTTP request\n");361goto end; /* Cannot retry: error */362}363while (!SSL_write_ex2(ssl, request_end, strlen(request_end),364SSL_WRITE_FLAG_CONCLUDE, &written)) {365if (handle_io_failure(ssl, 0) == 1)366continue; /* Retry */367printf("Failed to write end of HTTP request\n");368goto end; /* Cannot retry: error */369}370371do {372/*373* Get up to sizeof(buf) bytes of the response. We keep reading until374* the server closes the connection.375*/376while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {377switch (handle_io_failure(ssl, 0)) {378case 1:379continue; /* Retry */380case 0:381eof = 1;382continue;383case -1:384default:385printf("Failed reading remaining data\n");386goto end; /* Cannot retry: error */387}388}389/*390* OpenSSL does not guarantee that the returned data is a string or391* that it is NUL terminated so we use fwrite() to write the exact392* number of bytes that we read. The data could be non-printable or393* have NUL characters in the middle of it. For this simple example394* we're going to print it to stdout anyway.395*/396if (!eof)397fwrite(buf, 1, readbytes, stdout);398} while (!eof);399/* In case the response didn't finish with a newline we add one now */400printf("\n");401402/*403* Repeatedly call SSL_shutdown() until the connection is fully404* closed.405*/406while ((ret = SSL_shutdown(ssl)) != 1) {407if (ret < 0 && handle_io_failure(ssl, ret) == 1)408continue; /* Retry */409}410411/* Success! */412res = EXIT_SUCCESS;413end:414/*415* If something bad happened then we will dump the contents of the416* OpenSSL error stack to stderr. There might be some useful diagnostic417* information there.418*/419if (res == EXIT_FAILURE)420ERR_print_errors_fp(stderr);421422/*423* Free the resources we allocated. We do not free the BIO object here424* because ownership of it was immediately transferred to the SSL object425* via SSL_set_bio(). The BIO will be freed when we free the SSL object.426*/427SSL_free(ssl);428SSL_CTX_free(ctx);429BIO_ADDR_free(peer_addr);430return res;431}432433434