Path: blob/main/crypto/openssl/demos/guide/quic-server-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-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");164goto err;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);174goto err;175}176177return fd;178179err:180BIO_closesocket(fd);181return -1;182}183184/*185* Main loop for server to accept QUIC connections.186* Echo every request back to the client.187*/188static int run_quic_server(SSL_CTX *ctx, int fd)189{190int ok = 0;191SSL *listener, *conn;192unsigned char buf[8192];193size_t nread;194size_t nwritten;195196/*197* Create a new QUIC listener. Listeners, and other QUIC objects, default198* to operating in blocking mode. The configured behaviour is inherited by199* child objects.200*/201if ((listener = SSL_new_listener(ctx, 0)) == NULL)202goto err;203204/* Provide the listener with our UDP socket. */205if (!SSL_set_fd(listener, fd))206goto err;207208/* Begin listening. */209if (!SSL_listen(listener))210goto err;211212/*213* Begin an infinite loop of listening for connections. We will only214* exit this loop if we encounter an error.215*/216for (;;) {217/* Pristine error stack for each new connection */218ERR_clear_error();219220/* Block while waiting for a client connection */221printf("Waiting for connection\n");222conn = SSL_accept_connection(listener, 0);223if (conn == NULL) {224fprintf(stderr, "error while accepting connection\n");225goto err;226}227printf("Accepted new connection\n");228229/* Echo client input */230while (SSL_read_ex(conn, buf, sizeof(buf), &nread) > 0) {231if (SSL_write_ex(conn, buf, nread, &nwritten) > 0232&& nwritten == nread)233continue;234fprintf(stderr, "Error echoing client input");235break;236}237238/* Signal the end of the stream. */239if (SSL_stream_conclude(conn, 0) != 1) {240fprintf(stderr, "Unable to conclude stream\n");241SSL_free(conn);242goto err;243}244245/*246* Shut down the connection. We may need to call this multiple times247* to ensure the connection is shutdown completely.248*/249while (SSL_shutdown(conn) != 1)250continue;251252SSL_free(conn);253}254255err:256SSL_free(listener);257return ok;258}259260/* Minimal QUIC HTTP/1.0 server. */261int main(int argc, char *argv[])262{263int res = EXIT_FAILURE;264SSL_CTX *ctx = NULL;265int fd;266unsigned long port;267#ifdef _WIN32268static const char *progname;269270progname = argv[0];271#endif272273if (argc != 4)274errx(res, "usage: %s <port> <server.crt> <server.key>", argv[0]);275276/* Create SSL_CTX that supports QUIC. */277if ((ctx = create_ctx(argv[2], argv[3])) == NULL) {278ERR_print_errors_fp(stderr);279errx(res, "Failed to create context");280}281282/* Parse port number from command line arguments. */283port = strtoul(argv[1], NULL, 0);284if (port == 0 || port > UINT16_MAX) {285SSL_CTX_free(ctx);286errx(res, "Failed to parse port number");287}288289/* Create and bind a UDP socket. */290if ((fd = create_socket((uint16_t)port)) < 0) {291SSL_CTX_free(ctx);292ERR_print_errors_fp(stderr);293errx(res, "Failed to create socket");294}295296/* QUIC server connection acceptance loop. */297if (!run_quic_server(ctx, fd)) {298SSL_CTX_free(ctx);299BIO_closesocket(fd);300ERR_print_errors_fp(stderr);301errx(res, "Error in QUIC server loop");302}303304/* Free resources. */305SSL_CTX_free(ctx);306BIO_closesocket(fd);307res = EXIT_SUCCESS;308return res;309}310311312