Path: blob/main/crypto/openssl/demos/guide/quic-multi-stream.c
106139 views
/*1* Copyright 2023-2024 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-multi-stream.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#endif2223#include <openssl/bio.h>24#include <openssl/ssl.h>25#include <openssl/err.h>2627/* Helper function to create a BIO connected to the server */28static BIO *create_socket_bio(const char *hostname, const char *port,29int family, BIO_ADDR **peer_addr)30{31int sock = -1;32BIO_ADDRINFO *res;33const BIO_ADDRINFO *ai = NULL;34BIO *bio;3536/*37* Lookup IP address info for the server.38*/39if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_DGRAM, 0,40&res))41return NULL;4243/*44* Loop through all the possible addresses for the server and find one45* we can connect to.46*/47for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {48/*49* Create a UDP socket. We could equally use non-OpenSSL calls such50* as "socket" here for this and the subsequent connect and close51* functions. But for portability reasons and also so that we get52* errors on the OpenSSL stack in the event of a failure we use53* OpenSSL's versions of these functions.54*/55sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0);56if (sock == -1)57continue;5859/* Connect the socket to the server's address */60if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) {61BIO_closesocket(sock);62sock = -1;63continue;64}6566/* Set to nonblocking mode */67if (!BIO_socket_nbio(sock, 1)) {68BIO_closesocket(sock);69sock = -1;70continue;71}7273break;74}7576if (sock != -1) {77*peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));78if (*peer_addr == NULL) {79BIO_closesocket(sock);80return NULL;81}82}8384/* Free the address information resources we allocated earlier */85BIO_ADDRINFO_free(res);8687/* If sock is -1 then we've been unable to connect to the server */88if (sock == -1)89return NULL;9091/* Create a BIO to wrap the socket */92bio = BIO_new(BIO_s_datagram());93if (bio == NULL) {94BIO_closesocket(sock);95return NULL;96}9798/*99* Associate the newly created BIO with the underlying socket. By100* passing BIO_CLOSE here the socket will be automatically closed when101* the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which102* case you must close the socket explicitly when it is no longer103* needed.104*/105BIO_set_fd(bio, sock, BIO_CLOSE);106107return bio;108}109110static int write_a_request(SSL *stream, const char *request_start,111const char *hostname)112{113const char *request_end = "\r\n\r\n";114size_t written;115116if (!SSL_write_ex(stream, request_start, strlen(request_start),117&written))118return 0;119if (!SSL_write_ex(stream, hostname, strlen(hostname), &written))120return 0;121if (!SSL_write_ex(stream, request_end, strlen(request_end), &written))122return 0;123124return 1;125}126127/*128* Simple application to send basic HTTP/1.0 requests to a server and print the129* response on the screen. Note that HTTP/1.0 over QUIC is not a real protocol130* and will not be supported by real world servers. This is for demonstration131* purposes only.132*/133int main(int argc, char *argv[])134{135SSL_CTX *ctx = NULL;136SSL *ssl = NULL;137SSL *stream1 = NULL, *stream2 = NULL, *stream3 = NULL;138BIO *bio = NULL;139int res = EXIT_FAILURE;140int ret;141unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };142const char *request1_start = "GET /request1.html HTTP/1.0\r\nConnection: close\r\nHost: ";143const char *request2_start = "GET /request2.html HTTP/1.0\r\nConnection: close\r\nHost: ";144size_t readbytes;145char buf[160];146BIO_ADDR *peer_addr = NULL;147char *hostname, *port;148int argnext = 1;149int ipv6 = 0;150151if (argc < 3) {152printf("Usage: quic-client-non-block [-6] hostname port\n");153goto end;154}155156if (!strcmp(argv[argnext], "-6")) {157if (argc < 4) {158printf("Usage: quic-client-non-block [-6] hostname port\n");159goto end;160}161ipv6 = 1;162argnext++;163}164hostname = argv[argnext++];165port = argv[argnext];166167/*168* Create an SSL_CTX which we can use to create SSL objects from. We169* want an SSL_CTX for creating clients so we use170* OSSL_QUIC_client_method() here.171*/172ctx = SSL_CTX_new(OSSL_QUIC_client_method());173if (ctx == NULL) {174printf("Failed to create the SSL_CTX\n");175goto end;176}177178/*179* Configure the client to abort the handshake if certificate180* verification fails. Virtually all clients should do this unless you181* really know what you are doing.182*/183SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);184185/* Use the default trusted certificate store */186if (!SSL_CTX_set_default_verify_paths(ctx)) {187printf("Failed to set the default trusted certificate store\n");188goto end;189}190191/* Create an SSL object to represent the TLS connection */192ssl = SSL_new(ctx);193if (ssl == NULL) {194printf("Failed to create the SSL object\n");195goto end;196}197198/*199* We will use multiple streams so we will disable the default stream mode.200* This is not a requirement for using multiple streams but is recommended.201*/202if (!SSL_set_default_stream_mode(ssl, SSL_DEFAULT_STREAM_MODE_NONE)) {203printf("Failed to disable the default stream mode\n");204goto end;205}206207/*208* Create the underlying transport socket/BIO and associate it with the209* connection.210*/211bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET, &peer_addr);212if (bio == NULL) {213printf("Failed to crete the BIO\n");214goto end;215}216SSL_set_bio(ssl, bio, bio);217218/*219* Tell the server during the handshake which hostname we are attempting220* to connect to in case the server supports multiple hosts.221*/222if (!SSL_set_tlsext_host_name(ssl, hostname)) {223printf("Failed to set the SNI hostname\n");224goto end;225}226227/*228* Ensure we check during certificate verification that the server has229* supplied a certificate for the hostname that we were expecting.230* Virtually all clients should do this unless you really know what you231* are doing.232*/233if (!SSL_set1_host(ssl, hostname)) {234printf("Failed to set the certificate verification hostname");235goto end;236}237238/* SSL_set_alpn_protos returns 0 for success! */239if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {240printf("Failed to set the ALPN for the connection\n");241goto end;242}243244/* Set the IP address of the remote peer */245if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {246printf("Failed to set the initial peer address\n");247goto end;248}249250/* Do the handshake with the server */251if (SSL_connect(ssl) < 1) {252printf("Failed to connect to the server\n");253/*254* If the failure is due to a verification error we can get more255* information about it from SSL_get_verify_result().256*/257if (SSL_get_verify_result(ssl) != X509_V_OK)258printf("Verify error: %s\n",259X509_verify_cert_error_string(SSL_get_verify_result(ssl)));260goto end;261}262263/*264* We create two new client initiated streams. The first will be265* bi-directional, and the second will be uni-directional.266*/267stream1 = SSL_new_stream(ssl, 0);268stream2 = SSL_new_stream(ssl, SSL_STREAM_FLAG_UNI);269if (stream1 == NULL || stream2 == NULL) {270printf("Failed to create streams\n");271goto end;272}273274/* Write an HTTP GET request on each of our streams to the peer */275if (!write_a_request(stream1, request1_start, hostname)) {276printf("Failed to write HTTP request on stream 1\n");277goto end;278}279280if (!write_a_request(stream2, request2_start, hostname)) {281printf("Failed to write HTTP request on stream 2\n");282goto end;283}284285/*286* In this demo we read all the data from one stream before reading all the287* data from the next stream for simplicity. In practice there is no need to288* do this. We can interleave IO on the different streams if we wish, or289* manage the streams entirely separately on different threads.290*/291292printf("Stream 1 data:\n");293/*294* Get up to sizeof(buf) bytes of the response from stream 1 (which is a295* bidirectional stream). We keep reading until the server closes the296* connection.297*/298while (SSL_read_ex(stream1, buf, sizeof(buf), &readbytes)) {299/*300* OpenSSL does not guarantee that the returned data is a string or301* that it is NUL terminated so we use fwrite() to write the exact302* number of bytes that we read. The data could be non-printable or303* have NUL characters in the middle of it. For this simple example304* we're going to print it to stdout anyway.305*/306fwrite(buf, 1, readbytes, stdout);307}308/* In case the response didn't finish with a newline we add one now */309printf("\n");310311/*312* Check whether we finished the while loop above normally or as the313* result of an error. The 0 argument to SSL_get_error() is the return314* code we received from the SSL_read_ex() call. It must be 0 in order315* to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In316* QUIC terms this means that the peer has sent FIN on the stream to317* indicate that no further data will be sent.318*/319switch (SSL_get_error(stream1, 0)) {320case SSL_ERROR_ZERO_RETURN:321/* Normal completion of the stream */322break;323324case SSL_ERROR_SSL:325/*326* Some stream fatal error occurred. This could be because of a stream327* reset - or some failure occurred on the underlying connection.328*/329switch (SSL_get_stream_read_state(stream1)) {330case SSL_STREAM_STATE_RESET_REMOTE:331printf("Stream reset occurred\n");332/* The stream has been reset but the connection is still healthy. */333break;334335case SSL_STREAM_STATE_CONN_CLOSED:336printf("Connection closed\n");337/* Connection is already closed. Skip SSL_shutdown() */338goto end;339340default:341printf("Unknown stream failure\n");342break;343}344break;345346default:347/* Some other unexpected error occurred */348printf("Failed reading remaining data\n");349break;350}351352/*353* In our hypothetical HTTP/1.0 over QUIC protocol that we are using we354* assume that the server will respond with a server initiated stream355* containing the data requested in our uni-directional stream. This doesn't356* really make sense to do in a real protocol, but its just for357* demonstration purposes.358*359* We're using blocking mode so this will block until a stream becomes360* available. We could override this behaviour if we wanted to by setting361* the SSL_ACCEPT_STREAM_NO_BLOCK flag in the second argument below.362*/363stream3 = SSL_accept_stream(ssl, 0);364if (stream3 == NULL) {365printf("Failed to accept a new stream\n");366goto end;367}368369printf("Stream 3 data:\n");370/*371* Read the data from stream 3 like we did for stream 1 above. Note that372* stream 2 was uni-directional so there is no data to be read from that373* one.374*/375while (SSL_read_ex(stream3, buf, sizeof(buf), &readbytes))376fwrite(buf, 1, readbytes, stdout);377printf("\n");378379/* Check for errors on the stream */380switch (SSL_get_error(stream3, 0)) {381case SSL_ERROR_ZERO_RETURN:382/* Normal completion of the stream */383break;384385case SSL_ERROR_SSL:386switch (SSL_get_stream_read_state(stream3)) {387case SSL_STREAM_STATE_RESET_REMOTE:388printf("Stream reset occurred\n");389break;390391case SSL_STREAM_STATE_CONN_CLOSED:392printf("Connection closed\n");393goto end;394395default:396printf("Unknown stream failure\n");397break;398}399break;400401default:402printf("Failed reading remaining data\n");403break;404}405406/*407* Repeatedly call SSL_shutdown() until the connection is fully408* closed.409*/410do {411ret = SSL_shutdown(ssl);412if (ret < 0) {413printf("Error shutting down: %d\n", ret);414goto end;415}416} while (ret != 1);417418/* Success! */419res = EXIT_SUCCESS;420end:421/*422* If something bad happened then we will dump the contents of the423* OpenSSL error stack to stderr. There might be some useful diagnostic424* information there.425*/426if (res == EXIT_FAILURE)427ERR_print_errors_fp(stderr);428429/*430* Free the resources we allocated. We do not free the BIO object here431* because ownership of it was immediately transferred to the SSL object432* via SSL_set_bio(). The BIO will be freed when we free the SSL object.433*/434SSL_free(ssl);435SSL_free(stream1);436SSL_free(stream2);437SSL_free(stream3);438SSL_CTX_free(ctx);439BIO_ADDR_free(peer_addr);440return res;441}442443444