Path: blob/main/crypto/openssl/demos/guide/quic-server-non-block.c
107605 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,70'h',71't',72't',73'p',74'/',75'1',76'.',77'0',7810,79'h',80'q',81'-',82'i',83'n',84't',85'e',86'r',87'o',88'p',89};9091/*92* This callback validates and negotiates the desired ALPN on the server side.93*/94static int select_alpn(SSL *ssl, const unsigned char **out,95unsigned char *out_len, const unsigned char *in,96unsigned int in_len, void *arg)97{98if (SSL_select_next_proto((unsigned char **)out, out_len, alpn_ossltest,99sizeof(alpn_ossltest), in,100in_len)101== OPENSSL_NPN_NEGOTIATED)102return SSL_TLSEXT_ERR_OK;103return SSL_TLSEXT_ERR_ALERT_FATAL;104}105106/* Create SSL_CTX. */107static SSL_CTX *create_ctx(const char *cert_path, const char *key_path)108{109SSL_CTX *ctx;110111/*112* An SSL_CTX holds shared configuration information for multiple113* subsequent per-client connections. We specifically load a QUIC114* server method here.115*/116ctx = SSL_CTX_new(OSSL_QUIC_server_method());117if (ctx == NULL)118goto err;119120/*121* Load the server's certificate *chain* file (PEM format), which includes122* not only the leaf (end-entity) server certificate, but also any123* intermediate issuer-CA certificates. The leaf certificate must be the124* first certificate in the file.125*126* In advanced use-cases this can be called multiple times, once per public127* key algorithm for which the server has a corresponding certificate.128* However, the corresponding private key (see below) must be loaded first,129* *before* moving on to the next chain file.130*131* The requisite files "chain.pem" and "pkey.pem" can be generated by running132* "make chain" in this directory. If the server will be executed from some133* other directory, move or copy the files there.134*/135if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) <= 0) {136fprintf(stderr, "couldn't load certificate file: %s\n", cert_path);137goto err;138}139140/*141* Load the corresponding private key, this also checks that the private142* key matches the just loaded end-entity certificate. It does not check143* whether the certificate chain is valid, the certificates could be144* expired, or may otherwise fail to form a chain that a client can validate.145*/146if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0) {147fprintf(stderr, "couldn't load key file: %s\n", key_path);148goto err;149}150151/*152* Clients rarely employ certificate-based authentication, and so we don't153* require "mutual" TLS authentication (indeed there's no way to know154* whether or how the client authenticated the server, so the term "mutual"155* is potentially misleading).156*157* Since we're not soliciting or processing client certificates, we don't158* need to configure a trusted-certificate store, so no call to159* SSL_CTX_set_default_verify_paths() is needed. The server's own160* certificate chain is assumed valid.161*/162SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);163164/* Setup ALPN negotiation callback to decide which ALPN is accepted. */165SSL_CTX_set_alpn_select_cb(ctx, select_alpn, NULL);166167return ctx;168169err:170SSL_CTX_free(ctx);171return NULL;172}173174/* Create UDP socket on the given port. */175static int create_socket(uint16_t port)176{177int fd;178struct sockaddr_in sa = { 0 };179180/* Retrieve the file descriptor for a new UDP socket */181if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {182fprintf(stderr, "cannot create socket");183return -1;184}185186sa.sin_family = AF_INET;187sa.sin_port = htons(port);188189/* Bind to the new UDP socket on localhost */190if (bind(fd, (const struct sockaddr *)&sa, sizeof(sa)) < 0) {191fprintf(stderr, "cannot bind to %u\n", port);192BIO_closesocket(fd);193return -1;194}195196/* Set port to nonblocking mode */197if (BIO_socket_nbio(fd, 1) <= 0) {198fprintf(stderr, "Unable to set port to nonblocking mode");199BIO_closesocket(fd);200return -1;201}202203return fd;204}205206/**207* @brief Waits for activity on the SSL socket, either for reading or writing.208*209* This function monitors the underlying file descriptor of the given SSL210* connection to determine when it is ready for reading or writing, or both.211* It uses the select function to wait until the socket is either readable212* or writable, depending on what the SSL connection requires.213*214* @param ssl A pointer to the SSL object representing the connection.215*216* @note This function blocks until there is activity on the socket. In a real217* application, you might want to perform other tasks while waiting, such as218* updating a GUI or handling other connections.219*220* @note This function uses select for simplicity and portability. Depending221* on your application's requirements, you might consider using other222* mechanisms like poll or epoll for handling multiple file descriptors.223*/224static void wait_for_activity(SSL *ssl)225{226int sock, isinfinite;227fd_set read_fd, write_fd;228struct timeval tv;229struct timeval *tvp = NULL;230231/* Get hold of the underlying file descriptor for the socket */232if ((sock = SSL_get_fd(ssl)) == -1) {233fprintf(stderr, "Unable to get file descriptor");234return;235}236237/* Initialize the fd_set structure */238FD_ZERO(&read_fd);239FD_ZERO(&write_fd);240241/*242* Determine if we would like to write to the socket, read from it, or both.243*/244if (SSL_net_write_desired(ssl))245FD_SET(sock, &write_fd);246if (SSL_net_read_desired(ssl))247FD_SET(sock, &read_fd);248249/*250* Find out when OpenSSL would next like to be called, regardless of251* whether the state of the underlying socket has changed or not.252*/253if (SSL_get_event_timeout(ssl, &tv, &isinfinite) && !isinfinite)254tvp = &tv;255256/*257* Wait until the socket is writeable or readable. We use select here258* for the sake of simplicity and portability, but you could equally use259* poll/epoll or similar functions260*261* NOTE: For the purposes of this demonstration code this effectively262* makes this demo block until it has something more useful to do. In a263* real application you probably want to go and do other work here (e.g.264* update a GUI, or service other connections).265*266* Let's say for example that you want to update the progress counter on267* a GUI every 100ms. One way to do that would be to use the timeout in268* the last parameter to "select" below. If the tvp value is greater269* than 100ms then use 100ms instead. Then, when select returns, you270* check if it did so because of activity on the file descriptors or271* because of the timeout. If the 100ms GUI timeout has expired but the272* tvp timeout has not then go and update the GUI and then restart the273* "select" (with updated timeouts).274*/275276select(sock + 1, &read_fd, &write_fd, NULL, tvp);277}278279/**280* @brief Handles I/O failures on an SSL connection based on the result code.281*282* This function processes the result of an SSL I/O operation and handles283* different types of errors that may occur during the operation. It takes284* appropriate actions such as retrying the operation, reporting errors, or285* returning specific status codes based on the error type.286*287* @param ssl A pointer to the SSL object representing the connection.288* @param res The result code from the SSL I/O operation.289* @return An integer indicating the outcome:290* - 1: Temporary failure, the operation should be retried.291* - 0: EOF, indicating the connection has been closed.292* - -1: A fatal error occurred or the connection has been reset.293*294* @note This function may block if a temporary failure occurs and295* wait_for_activity() is called.296*297* @note If the failure is due to an SSL verification error, additional298* information will be logged to stderr.299*/300static int handle_io_failure(SSL *ssl, int res)301{302switch (SSL_get_error(ssl, res)) {303case SSL_ERROR_WANT_READ:304case SSL_ERROR_WANT_WRITE:305/* Temporary failure. Wait until we can read/write and try again */306wait_for_activity(ssl);307return 1;308309case SSL_ERROR_ZERO_RETURN:310case SSL_ERROR_NONE:311/* EOF */312return 0;313314case SSL_ERROR_SYSCALL:315return -1;316317case SSL_ERROR_SSL:318/*319* Some stream fatal error occurred. This could be because of a320* stream reset - or some failure occurred on the underlying321* connection.322*/323switch (SSL_get_stream_read_state(ssl)) {324case SSL_STREAM_STATE_RESET_REMOTE:325printf("Stream reset occurred\n");326/*327* The stream has been reset but the connection is still328* healthy.329*/330break;331332case SSL_STREAM_STATE_CONN_CLOSED:333printf("Connection closed\n");334/* Connection is already closed. */335break;336337default:338printf("Unknown stream failure\n");339break;340}341/*342* If the failure is due to a verification error we can get more343* information about it from SSL_get_verify_result().344*/345if (SSL_get_verify_result(ssl) != X509_V_OK)346printf("Verify error: %s\n",347X509_verify_cert_error_string(SSL_get_verify_result(ssl)));348return -1;349350default:351return -1;352}353}354355/*356* Main loop for server to accept QUIC connections.357* Echo every request back to the client.358*/359static int run_quic_server(SSL_CTX *ctx, int fd)360{361int ok = -1;362int ret, eof;363SSL *listener, *conn = NULL;364unsigned char buf[8192];365size_t nread, total_read, total_written;366367/* Create a new QUIC listener */368if ((listener = SSL_new_listener(ctx, 0)) == NULL)369goto err;370371/* Provide the listener with our UDP socket. */372if (!SSL_set_fd(listener, fd))373goto err;374375/*376* Set the listener mode to non-blocking, which is inherited by377* child objects.378*/379if (!SSL_set_blocking_mode(listener, 0))380goto err;381382/*383* Begin listening. Note that is not usually needed as SSL_accept_connection384* will implicitly start listening. It is only needed if a server wishes to385* ensure it has started to accept incoming connections but does not wish to386* actually call SSL_accept_connection yet.387*/388if (!SSL_listen(listener))389goto err;390391/*392* Begin an infinite loop of listening for connections. We will only393* exit this loop if we encounter an error.394*/395for (;;) {396eof = 0;397total_read = 0;398total_written = 0;399400/* Pristine error stack for each new connection */401ERR_clear_error();402403/* Block while waiting for a client connection */404printf("Waiting for connection\n");405while ((conn = SSL_accept_connection(listener, 0)) == NULL)406wait_for_activity(listener);407printf("Accepted new connection\n");408409/* Read from client until the client sends a end of stream packet */410while (!eof) {411ret = SSL_read_ex(conn, buf + total_read, sizeof(buf) - total_read,412&nread);413total_read += nread;414if (total_read >= 8192) {415fprintf(stderr, "Could not fit all data into buffer\n");416goto err;417}418419switch (handle_io_failure(conn, ret)) {420case 1:421continue; /* Retry */422case 0:423/* Reached end of stream */424if (!SSL_has_pending(conn))425eof = 1;426break;427default:428fprintf(stderr, "Failed reading remaining data\n");429goto err;430}431}432433/* Echo client input */434while (!SSL_write_ex2(conn, buf,435total_read,436SSL_WRITE_FLAG_CONCLUDE, &total_written)) {437if (handle_io_failure(conn, 0) == 1)438continue;439fprintf(stderr, "Failed to write data\n");440goto err;441}442443if (total_read != total_written)444fprintf(stderr, "Failed to echo data [read: %lu, written: %lu]\n",445total_read, total_written);446447/*448* Shut down the connection. We may need to call this multiple times449* to ensure the connection is shutdown completely.450*/451while ((ret = SSL_shutdown(conn)) != 1) {452if (ret < 0 && handle_io_failure(conn, ret) == 1)453continue; /* Retry */454}455456SSL_free(conn);457}458459ok = EXIT_SUCCESS;460err:461SSL_free(listener);462return ok;463}464465/* Minimal QUIC HTTP/1.0 server. */466int main(int argc, char *argv[])467{468int res = EXIT_FAILURE;469SSL_CTX *ctx = NULL;470int fd;471unsigned long port;472473#ifdef _WIN32474progname = argv[0];475#endif476477if (argc != 4)478errx(res, "usage: %s <port> <server.crt> <server.key>", argv[0]);479480/* Create SSL_CTX that supports QUIC. */481if ((ctx = create_ctx(argv[2], argv[3])) == NULL) {482ERR_print_errors_fp(stderr);483errx(res, "Failed to create context");484}485486/* Parse port number from command line arguments. */487port = strtoul(argv[1], NULL, 0);488if (port == 0 || port > UINT16_MAX) {489SSL_CTX_free(ctx);490errx(res, "Failed to parse port number");491}492493/* Create and bind a UDP socket. */494if ((fd = create_socket((uint16_t)port)) < 0) {495SSL_CTX_free(ctx);496ERR_print_errors_fp(stderr);497errx(res, "Failed to create socket");498}499500/* QUIC server connection acceptance loop. */501if (run_quic_server(ctx, fd) < 0) {502SSL_CTX_free(ctx);503BIO_closesocket(fd);504ERR_print_errors_fp(stderr);505errx(res, "Error in QUIC server loop");506}507508/* Free resources. */509SSL_CTX_free(ctx);510BIO_closesocket(fd);511res = EXIT_SUCCESS;512return res;513}514515516