Path: blob/main/crypto/openssl/demos/guide/quic-server-block.c
106175 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,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");183goto err;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);193goto err;194}195196return fd;197198err:199BIO_closesocket(fd);200return -1;201}202203/*204* Main loop for server to accept QUIC connections.205* Echo every request back to the client.206*/207static int run_quic_server(SSL_CTX *ctx, int fd)208{209int ok = 0;210SSL *listener, *conn;211unsigned char buf[8192];212size_t nread;213size_t nwritten;214215/*216* Create a new QUIC listener. Listeners, and other QUIC objects, default217* to operating in blocking mode. The configured behaviour is inherited by218* child objects.219*/220if ((listener = SSL_new_listener(ctx, 0)) == NULL)221goto err;222223/* Provide the listener with our UDP socket. */224if (!SSL_set_fd(listener, fd))225goto err;226227/* Begin listening. */228if (!SSL_listen(listener))229goto err;230231/*232* Begin an infinite loop of listening for connections. We will only233* exit this loop if we encounter an error.234*/235for (;;) {236/* Pristine error stack for each new connection */237ERR_clear_error();238239/* Block while waiting for a client connection */240printf("Waiting for connection\n");241conn = SSL_accept_connection(listener, 0);242if (conn == NULL) {243fprintf(stderr, "error while accepting connection\n");244goto err;245}246printf("Accepted new connection\n");247248/* Echo client input */249while (SSL_read_ex(conn, buf, sizeof(buf), &nread) > 0) {250if (SSL_write_ex(conn, buf, nread, &nwritten) > 0251&& nwritten == nread)252continue;253fprintf(stderr, "Error echoing client input");254break;255}256257/* Signal the end of the stream. */258if (SSL_stream_conclude(conn, 0) != 1) {259fprintf(stderr, "Unable to conclude stream\n");260SSL_free(conn);261goto err;262}263264/*265* Shut down the connection. We may need to call this multiple times266* to ensure the connection is shutdown completely.267*/268while (SSL_shutdown(conn) != 1)269continue;270271SSL_free(conn);272}273274err:275SSL_free(listener);276return ok;277}278279/* Minimal QUIC HTTP/1.0 server. */280int main(int argc, char *argv[])281{282int res = EXIT_FAILURE;283SSL_CTX *ctx = NULL;284int fd;285unsigned long port;286#ifdef _WIN32287static const char *progname;288289progname = argv[0];290#endif291292if (argc != 4)293errx(res, "usage: %s <port> <server.crt> <server.key>", argv[0]);294295/* Create SSL_CTX that supports QUIC. */296if ((ctx = create_ctx(argv[2], argv[3])) == NULL) {297ERR_print_errors_fp(stderr);298errx(res, "Failed to create context");299}300301/* Parse port number from command line arguments. */302port = strtoul(argv[1], NULL, 0);303if (port == 0 || port > UINT16_MAX) {304SSL_CTX_free(ctx);305errx(res, "Failed to parse port number");306}307308/* Create and bind a UDP socket. */309if ((fd = create_socket((uint16_t)port)) < 0) {310SSL_CTX_free(ctx);311ERR_print_errors_fp(stderr);312errx(res, "Failed to create socket");313}314315/* QUIC server connection acceptance loop. */316if (!run_quic_server(ctx, fd)) {317SSL_CTX_free(ctx);318BIO_closesocket(fd);319ERR_print_errors_fp(stderr);320errx(res, "Error in QUIC server loop");321}322323/* Free resources. */324SSL_CTX_free(ctx);325BIO_closesocket(fd);326res = EXIT_SUCCESS;327return res;328}329330331