Path: blob/main/crypto/openssl/demos/guide/quic-server-non-block.c
34876 views
/*1* Copyright 2024-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-server-non-block.pod12*/1314#include <string.h>1516/* Include the appropriate header file for SOCK_STREAM */17#ifdef _WIN32 /* Windows */18# include <stdarg.h>19# include <winsock2.h>20#else /* Linux/Unix */21# include <err.h>22# include <sys/socket.h>23# include <sys/select.h>24# include <netinet/in.h>25# include <unistd.h>26#endif2728#include <openssl/bio.h>29#include <openssl/ssl.h>30#include <openssl/err.h>31#include <openssl/quic.h>3233#ifdef _WIN3234static const char *progname;3536static void vwarnx(const char *fmt, va_list ap)37{38if (progname != NULL)39fprintf(stderr, "%s: ", progname);40vfprintf(stderr, fmt, ap);41putc('\n', stderr);42}4344static void errx(int status, const char *fmt, ...)45{46va_list ap;4748va_start(ap, fmt);49vwarnx(fmt, ap);50va_end(ap);51exit(status);52}5354static void warnx(const char *fmt, ...)55{56va_list ap;5758va_start(ap, fmt);59vwarnx(fmt, ap);60va_end(ap);61}62#endif6364/*65* ALPN strings for TLS handshake. Only 'http/1.0' and 'hq-interop'66* are accepted.67*/68static const unsigned char alpn_ossltest[] = {698, 'h', 't', 't', 'p', '/', '1', '.', '0',7010, 'h', 'q', '-', 'i', 'n', 't', 'e', 'r', 'o', 'p',71};7273/*74* This callback validates and negotiates the desired ALPN on the server side.75*/76static int select_alpn(SSL *ssl, const unsigned char **out,77unsigned char *out_len, const unsigned char *in,78unsigned int in_len, void *arg)79{80if (SSL_select_next_proto((unsigned char **)out, out_len, alpn_ossltest,81sizeof(alpn_ossltest), in,82in_len) == OPENSSL_NPN_NEGOTIATED)83return SSL_TLSEXT_ERR_OK;84return SSL_TLSEXT_ERR_ALERT_FATAL;85}8687/* Create SSL_CTX. */88static SSL_CTX *create_ctx(const char *cert_path, const char *key_path)89{90SSL_CTX *ctx;9192/*93* An SSL_CTX holds shared configuration information for multiple94* subsequent per-client connections. We specifically load a QUIC95* server method here.96*/97ctx = SSL_CTX_new(OSSL_QUIC_server_method());98if (ctx == NULL)99goto err;100101/*102* Load the server's certificate *chain* file (PEM format), which includes103* not only the leaf (end-entity) server certificate, but also any104* intermediate issuer-CA certificates. The leaf certificate must be the105* first certificate in the file.106*107* In advanced use-cases this can be called multiple times, once per public108* key algorithm for which the server has a corresponding certificate.109* However, the corresponding private key (see below) must be loaded first,110* *before* moving on to the next chain file.111*112* The requisite files "chain.pem" and "pkey.pem" can be generated by running113* "make chain" in this directory. If the server will be executed from some114* other directory, move or copy the files there.115*/116if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) <= 0) {117fprintf(stderr, "couldn't load certificate file: %s\n", cert_path);118goto err;119}120121/*122* Load the corresponding private key, this also checks that the private123* key matches the just loaded end-entity certificate. It does not check124* whether the certificate chain is valid, the certificates could be125* expired, or may otherwise fail to form a chain that a client can validate.126*/127if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0) {128fprintf(stderr, "couldn't load key file: %s\n", key_path);129goto err;130}131132/*133* Clients rarely employ certificate-based authentication, and so we don't134* require "mutual" TLS authentication (indeed there's no way to know135* whether or how the client authenticated the server, so the term "mutual"136* is potentially misleading).137*138* Since we're not soliciting or processing client certificates, we don't139* need to configure a trusted-certificate store, so no call to140* SSL_CTX_set_default_verify_paths() is needed. The server's own141* certificate chain is assumed valid.142*/143SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);144145/* Setup ALPN negotiation callback to decide which ALPN is accepted. */146SSL_CTX_set_alpn_select_cb(ctx, select_alpn, NULL);147148return ctx;149150err:151SSL_CTX_free(ctx);152return NULL;153}154155/* Create UDP socket on the given port. */156static int create_socket(uint16_t port)157{158int fd;159struct sockaddr_in sa = {0};160161/* Retrieve the file descriptor for a new UDP socket */162if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {163fprintf(stderr, "cannot create socket");164return -1;165}166167sa.sin_family = AF_INET;168sa.sin_port = htons(port);169170/* Bind to the new UDP socket on localhost */171if (bind(fd, (const struct sockaddr *)&sa, sizeof(sa)) < 0) {172fprintf(stderr, "cannot bind to %u\n", port);173BIO_closesocket(fd);174return -1;175}176177/* Set port to nonblocking mode */178if (BIO_socket_nbio(fd, 1) <= 0) {179fprintf(stderr, "Unable to set port to nonblocking mode");180BIO_closesocket(fd);181return -1;182}183184return fd;185}186187/**188* @brief Waits for activity on the SSL socket, either for reading or writing.189*190* This function monitors the underlying file descriptor of the given SSL191* connection to determine when it is ready for reading or writing, or both.192* It uses the select function to wait until the socket is either readable193* or writable, depending on what the SSL connection requires.194*195* @param ssl A pointer to the SSL object representing the connection.196*197* @note This function blocks until there is activity on the socket. In a real198* application, you might want to perform other tasks while waiting, such as199* updating a GUI or handling other connections.200*201* @note This function uses select for simplicity and portability. Depending202* on your application's requirements, you might consider using other203* mechanisms like poll or epoll for handling multiple file descriptors.204*/205static void wait_for_activity(SSL *ssl)206{207int sock, isinfinite;208fd_set read_fd, write_fd;209struct timeval tv;210struct timeval *tvp = NULL;211212/* Get hold of the underlying file descriptor for the socket */213if ((sock = SSL_get_fd(ssl)) == -1) {214fprintf(stderr, "Unable to get file descriptor");215return;216}217218/* Initialize the fd_set structure */219FD_ZERO(&read_fd);220FD_ZERO(&write_fd);221222/*223* Determine if we would like to write to the socket, read from it, or both.224*/225if (SSL_net_write_desired(ssl))226FD_SET(sock, &write_fd);227if (SSL_net_read_desired(ssl))228FD_SET(sock, &read_fd);229230/*231* Find out when OpenSSL would next like to be called, regardless of232* whether the state of the underlying socket has changed or not.233*/234if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite)235tvp = &tv;236237/*238* Wait until the socket is writeable or readable. We use select here239* for the sake of simplicity and portability, but you could equally use240* poll/epoll or similar functions241*242* NOTE: For the purposes of this demonstration code this effectively243* makes this demo block until it has something more useful to do. In a244* real application you probably want to go and do other work here (e.g.245* update a GUI, or service other connections).246*247* Let's say for example that you want to update the progress counter on248* a GUI every 100ms. One way to do that would be to use the timeout in249* the last parameter to "select" below. If the tvp value is greater250* than 100ms then use 100ms instead. Then, when select returns, you251* check if it did so because of activity on the file descriptors or252* because of the timeout. If the 100ms GUI timeout has expired but the253* tvp timeout has not then go and update the GUI and then restart the254* "select" (with updated timeouts).255*/256257select(sock + 1, &read_fd, &write_fd, NULL, tvp);258}259260/**261* @brief Handles I/O failures on an SSL connection based on the result code.262*263* This function processes the result of an SSL I/O operation and handles264* different types of errors that may occur during the operation. It takes265* appropriate actions such as retrying the operation, reporting errors, or266* returning specific status codes based on the error type.267*268* @param ssl A pointer to the SSL object representing the connection.269* @param res The result code from the SSL I/O operation.270* @return An integer indicating the outcome:271* - 1: Temporary failure, the operation should be retried.272* - 0: EOF, indicating the connection has been closed.273* - -1: A fatal error occurred or the connection has been reset.274*275* @note This function may block if a temporary failure occurs and276* wait_for_activity() is called.277*278* @note If the failure is due to an SSL verification error, additional279* information will be logged to stderr.280*/281static int handle_io_failure(SSL *ssl, int res)282{283switch (SSL_get_error(ssl, res)) {284case SSL_ERROR_WANT_READ:285case SSL_ERROR_WANT_WRITE:286/* Temporary failure. Wait until we can read/write and try again */287wait_for_activity(ssl);288return 1;289290case SSL_ERROR_ZERO_RETURN:291case SSL_ERROR_NONE:292/* EOF */293return 0;294295case SSL_ERROR_SYSCALL:296return -1;297298case SSL_ERROR_SSL:299/*300* Some stream fatal error occurred. This could be because of a301* stream reset - or some failure occurred on the underlying302* connection.303*/304switch (SSL_get_stream_read_state(ssl)) {305case SSL_STREAM_STATE_RESET_REMOTE:306printf("Stream reset occurred\n");307/*308* The stream has been reset but the connection is still309* healthy.310*/311break;312313case SSL_STREAM_STATE_CONN_CLOSED:314printf("Connection closed\n");315/* Connection is already closed. */316break;317318default:319printf("Unknown stream failure\n");320break;321}322/*323* If the failure is due to a verification error we can get more324* information about it from SSL_get_verify_result().325*/326if (SSL_get_verify_result(ssl) != X509_V_OK)327printf("Verify error: %s\n",328X509_verify_cert_error_string(SSL_get_verify_result(ssl)));329return -1;330331default:332return -1;333}334}335336/*337* Main loop for server to accept QUIC connections.338* Echo every request back to the client.339*/340static int run_quic_server(SSL_CTX *ctx, int fd)341{342int ok = -1;343int ret, eof;344SSL *listener, *conn = NULL;345unsigned char buf[8192];346size_t nread, total_read, total_written;347348/* Create a new QUIC listener */349if ((listener = SSL_new_listener(ctx, 0)) == NULL)350goto err;351352/* Provide the listener with our UDP socket. */353if (!SSL_set_fd(listener, fd))354goto err;355356/*357* Set the listener mode to non-blocking, which is inherited by358* child objects.359*/360if (!SSL_set_blocking_mode(listener, 0))361goto err;362363/*364* Begin listening. Note that is not usually needed as SSL_accept_connection365* will implicitly start listening. It is only needed if a server wishes to366* ensure it has started to accept incoming connections but does not wish to367* actually call SSL_accept_connection yet.368*/369if (!SSL_listen(listener))370goto err;371372/*373* Begin an infinite loop of listening for connections. We will only374* exit this loop if we encounter an error.375*/376for (;;) {377eof = 0;378total_read = 0;379total_written = 0;380381/* Pristine error stack for each new connection */382ERR_clear_error();383384/* Block while waiting for a client connection */385printf("Waiting for connection\n");386while ((conn = SSL_accept_connection(listener, 0)) == NULL)387wait_for_activity(listener);388printf("Accepted new connection\n");389390/* Read from client until the client sends a end of stream packet */391while (!eof) {392ret = SSL_read_ex(conn, buf + total_read, sizeof(buf) - total_read,393&nread);394total_read += nread;395if (total_read >= 8192) {396fprintf(stderr, "Could not fit all data into buffer\n");397goto err;398}399400switch (handle_io_failure(conn, ret)) {401case 1:402continue; /* Retry */403case 0:404/* Reached end of stream */405if (!SSL_has_pending(conn))406eof = 1;407break;408default:409fprintf(stderr, "Failed reading remaining data\n");410goto err;411}412}413414/* Echo client input */415while (!SSL_write_ex2(conn, buf,416total_read,417SSL_WRITE_FLAG_CONCLUDE, &total_written)) {418if (handle_io_failure(conn, 0) == 1)419continue;420fprintf(stderr, "Failed to write data\n");421goto err;422}423424if (total_read != total_written)425fprintf(stderr, "Failed to echo data [read: %lu, written: %lu]\n",426total_read, total_written);427428/*429* Shut down the connection. We may need to call this multiple times430* to ensure the connection is shutdown completely.431*/432while ((ret = SSL_shutdown(conn)) != 1) {433if (ret < 0 && handle_io_failure(conn, ret) == 1)434continue; /* Retry */435}436437SSL_free(conn);438}439440ok = EXIT_SUCCESS;441err:442SSL_free(listener);443return ok;444}445446/* Minimal QUIC HTTP/1.0 server. */447int main(int argc, char *argv[])448{449int res = EXIT_FAILURE;450SSL_CTX *ctx = NULL;451int fd;452unsigned long port;453454#ifdef _WIN32455progname = argv[0];456#endif457458if (argc != 4)459errx(res, "usage: %s <port> <server.crt> <server.key>", argv[0]);460461/* Create SSL_CTX that supports QUIC. */462if ((ctx = create_ctx(argv[2], argv[3])) == NULL) {463ERR_print_errors_fp(stderr);464errx(res, "Failed to create context");465}466467/* Parse port number from command line arguments. */468port = strtoul(argv[1], NULL, 0);469if (port == 0 || port > UINT16_MAX) {470SSL_CTX_free(ctx);471errx(res, "Failed to parse port number");472}473474/* Create and bind a UDP socket. */475if ((fd = create_socket((uint16_t)port)) < 0) {476SSL_CTX_free(ctx);477ERR_print_errors_fp(stderr);478errx(res, "Failed to create socket");479}480481/* QUIC server connection acceptance loop. */482if (run_quic_server(ctx, fd) < 0) {483SSL_CTX_free(ctx);484BIO_closesocket(fd);485ERR_print_errors_fp(stderr);486errx(res, "Error in QUIC server loop");487}488489/* Free resources. */490SSL_CTX_free(ctx);491BIO_closesocket(fd);492res = EXIT_SUCCESS;493return res;494}495496497