Path: blob/main/crypto/openssl/demos/guide/quic-client-block.c
34876 views
/*1* Copyright 2023-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-client-block.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}109110/*111* Simple application to send a basic HTTP/1.0 request to a server and112* print the response on the screen. Note that HTTP/1.0 over QUIC is113* non-standard and will not typically be supported by real world servers. This114* is for demonstration purposes only.115*/116int main(int argc, char *argv[])117{118SSL_CTX *ctx = NULL;119SSL *ssl = NULL;120BIO *bio = NULL;121int res = EXIT_FAILURE;122int ret;123unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };124const char *request_start = "GET / HTTP/1.0\r\nConnection: close\r\nHost: ";125const char *request_end = "\r\n\r\n";126size_t written, readbytes;127char buf[160];128BIO_ADDR *peer_addr = NULL;129char *hostname, *port;130int argnext = 1;131int ipv6 = 0;132133if (argc < 3) {134printf("Usage: quic-client-block [-6] hostname port\n");135goto end;136}137138if (!strcmp(argv[argnext], "-6")) {139if (argc < 4) {140printf("Usage: quic-client-block [-6] hostname port\n");141goto end;142}143ipv6 = 1;144argnext++;145}146hostname = argv[argnext++];147port = argv[argnext];148149/*150* Create an SSL_CTX which we can use to create SSL objects from. We151* want an SSL_CTX for creating clients so we use152* OSSL_QUIC_client_method() here.153*/154ctx = SSL_CTX_new(OSSL_QUIC_client_method());155if (ctx == NULL) {156printf("Failed to create the SSL_CTX\n");157goto end;158}159160/*161* Configure the client to abort the handshake if certificate162* verification fails. Virtually all clients should do this unless you163* really know what you are doing.164*/165SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);166167/* Use the default trusted certificate store */168if (!SSL_CTX_set_default_verify_paths(ctx)) {169printf("Failed to set the default trusted certificate store\n");170goto end;171}172173/* Create an SSL object to represent the TLS connection */174ssl = SSL_new(ctx);175if (ssl == NULL) {176printf("Failed to create the SSL object\n");177goto end;178}179180/*181* Create the underlying transport socket/BIO and associate it with the182* connection.183*/184bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET, &peer_addr);185if (bio == NULL) {186printf("Failed to crete the BIO\n");187goto end;188}189SSL_set_bio(ssl, bio, bio);190191/*192* Tell the server during the handshake which hostname we are attempting193* to connect to in case the server supports multiple hosts.194*/195if (!SSL_set_tlsext_host_name(ssl, hostname)) {196printf("Failed to set the SNI hostname\n");197goto end;198}199200/*201* Ensure we check during certificate verification that the server has202* supplied a certificate for the hostname that we were expecting.203* Virtually all clients should do this unless you really know what you204* are doing.205*/206if (!SSL_set1_host(ssl, hostname)) {207printf("Failed to set the certificate verification hostname");208goto end;209}210211/* SSL_set_alpn_protos returns 0 for success! */212if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {213printf("Failed to set the ALPN for the connection\n");214goto end;215}216217/* Set the IP address of the remote peer */218if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {219printf("Failed to set the initial peer address\n");220goto end;221}222223/* Do the handshake with the server */224if (SSL_connect(ssl) < 1) {225printf("Failed to connect to the server\n");226/*227* If the failure is due to a verification error we can get more228* information about it from SSL_get_verify_result().229*/230if (SSL_get_verify_result(ssl) != X509_V_OK)231printf("Verify error: %s\n",232X509_verify_cert_error_string(SSL_get_verify_result(ssl)));233goto end;234}235236/* Write an HTTP GET request to the peer */237if (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {238printf("Failed to write start of HTTP request\n");239goto end;240}241if (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {242printf("Failed to write hostname in HTTP request\n");243goto end;244}245if (!SSL_write_ex2(ssl, request_end, strlen(request_end),246SSL_WRITE_FLAG_CONCLUDE, &written)) {247printf("Failed to write end of HTTP request\n");248goto end;249}250251/*252* Get up to sizeof(buf) bytes of the response. We keep reading until the253* server closes the connection.254*/255while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {256/*257* OpenSSL does not guarantee that the returned data is a string or258* that it is NUL terminated so we use fwrite() to write the exact259* number of bytes that we read. The data could be non-printable or260* have NUL characters in the middle of it. For this simple example261* we're going to print it to stdout anyway.262*/263fwrite(buf, 1, readbytes, stdout);264}265/* In case the response didn't finish with a newline we add one now */266printf("\n");267268/*269* Check whether we finished the while loop above normally or as the270* result of an error. The 0 argument to SSL_get_error() is the return271* code we received from the SSL_read_ex() call. It must be 0 in order272* to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In273* QUIC terms this means that the peer has sent FIN on the stream to274* indicate that no further data will be sent.275*/276switch (SSL_get_error(ssl, 0)) {277case SSL_ERROR_ZERO_RETURN:278/* Normal completion of the stream */279break;280281case SSL_ERROR_SSL:282/*283* Some stream fatal error occurred. This could be because of a stream284* reset - or some failure occurred on the underlying connection.285*/286switch (SSL_get_stream_read_state(ssl)) {287case SSL_STREAM_STATE_RESET_REMOTE:288printf("Stream reset occurred\n");289/* The stream has been reset but the connection is still healthy. */290break;291292case SSL_STREAM_STATE_CONN_CLOSED:293printf("Connection closed\n");294/* Connection is already closed. Skip SSL_shutdown() */295goto end;296297default:298printf("Unknown stream failure\n");299break;300}301break;302303default:304/* Some other unexpected error occurred */305printf ("Failed reading remaining data\n");306break;307}308309/*310* Repeatedly call SSL_shutdown() until the connection is fully311* closed.312*/313do {314ret = SSL_shutdown(ssl);315if (ret < 0) {316printf("Error shutting down: %d\n", ret);317goto end;318}319} while (ret != 1);320321/* Success! */322res = EXIT_SUCCESS;323end:324/*325* If something bad happened then we will dump the contents of the326* OpenSSL error stack to stderr. There might be some useful diagnostic327* information there.328*/329if (res == EXIT_FAILURE)330ERR_print_errors_fp(stderr);331332/*333* Free the resources we allocated. We do not free the BIO object here334* because ownership of it was immediately transferred to the SSL object335* via SSL_set_bio(). The BIO will be freed when we free the SSL object.336*/337SSL_free(ssl);338SSL_CTX_free(ctx);339BIO_ADDR_free(peer_addr);340return res;341}342343344