Path: blob/main/crypto/openssl/demos/guide/quic-multi-stream.c
34876 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 =143"GET /request1.html HTTP/1.0\r\nConnection: close\r\nHost: ";144const char *request2_start =145"GET /request2.html HTTP/1.0\r\nConnection: close\r\nHost: ";146size_t readbytes;147char buf[160];148BIO_ADDR *peer_addr = NULL;149char *hostname, *port;150int argnext = 1;151int ipv6 = 0;152153if (argc < 3) {154printf("Usage: quic-client-non-block [-6] hostname port\n");155goto end;156}157158if (!strcmp(argv[argnext], "-6")) {159if (argc < 4) {160printf("Usage: quic-client-non-block [-6] hostname port\n");161goto end;162}163ipv6 = 1;164argnext++;165}166hostname = argv[argnext++];167port = argv[argnext];168169/*170* Create an SSL_CTX which we can use to create SSL objects from. We171* want an SSL_CTX for creating clients so we use172* OSSL_QUIC_client_method() here.173*/174ctx = SSL_CTX_new(OSSL_QUIC_client_method());175if (ctx == NULL) {176printf("Failed to create the SSL_CTX\n");177goto end;178}179180/*181* Configure the client to abort the handshake if certificate182* verification fails. Virtually all clients should do this unless you183* really know what you are doing.184*/185SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);186187/* Use the default trusted certificate store */188if (!SSL_CTX_set_default_verify_paths(ctx)) {189printf("Failed to set the default trusted certificate store\n");190goto end;191}192193/* Create an SSL object to represent the TLS connection */194ssl = SSL_new(ctx);195if (ssl == NULL) {196printf("Failed to create the SSL object\n");197goto end;198}199200/*201* We will use multiple streams so we will disable the default stream mode.202* This is not a requirement for using multiple streams but is recommended.203*/204if (!SSL_set_default_stream_mode(ssl, SSL_DEFAULT_STREAM_MODE_NONE)) {205printf("Failed to disable the default stream mode\n");206goto end;207}208209/*210* Create the underlying transport socket/BIO and associate it with the211* connection.212*/213bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET, &peer_addr);214if (bio == NULL) {215printf("Failed to crete the BIO\n");216goto end;217}218SSL_set_bio(ssl, bio, bio);219220/*221* Tell the server during the handshake which hostname we are attempting222* to connect to in case the server supports multiple hosts.223*/224if (!SSL_set_tlsext_host_name(ssl, hostname)) {225printf("Failed to set the SNI hostname\n");226goto end;227}228229/*230* Ensure we check during certificate verification that the server has231* supplied a certificate for the hostname that we were expecting.232* Virtually all clients should do this unless you really know what you233* are doing.234*/235if (!SSL_set1_host(ssl, hostname)) {236printf("Failed to set the certificate verification hostname");237goto end;238}239240/* SSL_set_alpn_protos returns 0 for success! */241if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {242printf("Failed to set the ALPN for the connection\n");243goto end;244}245246/* Set the IP address of the remote peer */247if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {248printf("Failed to set the initial peer address\n");249goto end;250}251252/* Do the handshake with the server */253if (SSL_connect(ssl) < 1) {254printf("Failed to connect to the server\n");255/*256* If the failure is due to a verification error we can get more257* information about it from SSL_get_verify_result().258*/259if (SSL_get_verify_result(ssl) != X509_V_OK)260printf("Verify error: %s\n",261X509_verify_cert_error_string(SSL_get_verify_result(ssl)));262goto end;263}264265/*266* We create two new client initiated streams. The first will be267* bi-directional, and the second will be uni-directional.268*/269stream1 = SSL_new_stream(ssl, 0);270stream2 = SSL_new_stream(ssl, SSL_STREAM_FLAG_UNI);271if (stream1 == NULL || stream2 == NULL) {272printf("Failed to create streams\n");273goto end;274}275276/* Write an HTTP GET request on each of our streams to the peer */277if (!write_a_request(stream1, request1_start, hostname)) {278printf("Failed to write HTTP request on stream 1\n");279goto end;280}281282if (!write_a_request(stream2, request2_start, hostname)) {283printf("Failed to write HTTP request on stream 2\n");284goto end;285}286287/*288* In this demo we read all the data from one stream before reading all the289* data from the next stream for simplicity. In practice there is no need to290* do this. We can interleave IO on the different streams if we wish, or291* manage the streams entirely separately on different threads.292*/293294printf("Stream 1 data:\n");295/*296* Get up to sizeof(buf) bytes of the response from stream 1 (which is a297* bidirectional stream). We keep reading until the server closes the298* connection.299*/300while (SSL_read_ex(stream1, buf, sizeof(buf), &readbytes)) {301/*302* OpenSSL does not guarantee that the returned data is a string or303* that it is NUL terminated so we use fwrite() to write the exact304* number of bytes that we read. The data could be non-printable or305* have NUL characters in the middle of it. For this simple example306* we're going to print it to stdout anyway.307*/308fwrite(buf, 1, readbytes, stdout);309}310/* In case the response didn't finish with a newline we add one now */311printf("\n");312313/*314* Check whether we finished the while loop above normally or as the315* result of an error. The 0 argument to SSL_get_error() is the return316* code we received from the SSL_read_ex() call. It must be 0 in order317* to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In318* QUIC terms this means that the peer has sent FIN on the stream to319* indicate that no further data will be sent.320*/321switch (SSL_get_error(stream1, 0)) {322case SSL_ERROR_ZERO_RETURN:323/* Normal completion of the stream */324break;325326case SSL_ERROR_SSL:327/*328* Some stream fatal error occurred. This could be because of a stream329* reset - or some failure occurred on the underlying connection.330*/331switch (SSL_get_stream_read_state(stream1)) {332case SSL_STREAM_STATE_RESET_REMOTE:333printf("Stream reset occurred\n");334/* The stream has been reset but the connection is still healthy. */335break;336337case SSL_STREAM_STATE_CONN_CLOSED:338printf("Connection closed\n");339/* Connection is already closed. Skip SSL_shutdown() */340goto end;341342default:343printf("Unknown stream failure\n");344break;345}346break;347348default:349/* Some other unexpected error occurred */350printf ("Failed reading remaining data\n");351break;352}353354/*355* In our hypothetical HTTP/1.0 over QUIC protocol that we are using we356* assume that the server will respond with a server initiated stream357* containing the data requested in our uni-directional stream. This doesn't358* really make sense to do in a real protocol, but its just for359* demonstration purposes.360*361* We're using blocking mode so this will block until a stream becomes362* available. We could override this behaviour if we wanted to by setting363* the SSL_ACCEPT_STREAM_NO_BLOCK flag in the second argument below.364*/365stream3 = SSL_accept_stream(ssl, 0);366if (stream3 == NULL) {367printf("Failed to accept a new stream\n");368goto end;369}370371printf("Stream 3 data:\n");372/*373* Read the data from stream 3 like we did for stream 1 above. Note that374* stream 2 was uni-directional so there is no data to be read from that375* one.376*/377while (SSL_read_ex(stream3, buf, sizeof(buf), &readbytes))378fwrite(buf, 1, readbytes, stdout);379printf("\n");380381/* Check for errors on the stream */382switch (SSL_get_error(stream3, 0)) {383case SSL_ERROR_ZERO_RETURN:384/* Normal completion of the stream */385break;386387case SSL_ERROR_SSL:388switch (SSL_get_stream_read_state(stream3)) {389case SSL_STREAM_STATE_RESET_REMOTE:390printf("Stream reset occurred\n");391break;392393case SSL_STREAM_STATE_CONN_CLOSED:394printf("Connection closed\n");395goto end;396397default:398printf("Unknown stream failure\n");399break;400}401break;402403default:404printf ("Failed reading remaining data\n");405break;406}407408/*409* Repeatedly call SSL_shutdown() until the connection is fully410* closed.411*/412do {413ret = SSL_shutdown(ssl);414if (ret < 0) {415printf("Error shutting down: %d\n", ret);416goto end;417}418} while (ret != 1);419420/* Success! */421res = EXIT_SUCCESS;422end:423/*424* If something bad happened then we will dump the contents of the425* OpenSSL error stack to stderr. There might be some useful diagnostic426* information there.427*/428if (res == EXIT_FAILURE)429ERR_print_errors_fp(stderr);430431/*432* Free the resources we allocated. We do not free the BIO object here433* because ownership of it was immediately transferred to the SSL object434* via SSL_set_bio(). The BIO will be freed when we free the SSL object.435*/436SSL_free(ssl);437SSL_free(stream1);438SSL_free(stream2);439SSL_free(stream3);440SSL_CTX_free(ctx);441BIO_ADDR_free(peer_addr);442return res;443}444445446