2 * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 * NB: Changes to this file should also be reflected in
12 * doc/man7/ossl-guide-quic-client-block.pod
17 /* Include the appropriate header file for SOCK_DGRAM */
18 #ifdef _WIN32 /* Windows */
19 # include <winsock2.h>
20 #else /* Linux/Unix */
21 # include <sys/socket.h>
24 #include <openssl/bio.h>
25 #include <openssl/ssl.h>
26 #include <openssl/err.h>
28 /* Helper function to create a BIO connected to the server */
29 static BIO
*create_socket_bio(const char *hostname
, const char *port
,
30 int family
, BIO_ADDR
**peer_addr
)
34 const BIO_ADDRINFO
*ai
= NULL
;
38 * Lookup IP address info for the server.
40 if (!BIO_lookup_ex(hostname
, port
, BIO_LOOKUP_CLIENT
, family
, SOCK_DGRAM
, 0,
45 * Loop through all the possible addresses for the server and find one
48 for (ai
= res
; ai
!= NULL
; ai
= BIO_ADDRINFO_next(ai
)) {
50 * Create a UDP socket. We could equally use non-OpenSSL calls such
51 * as "socket" here for this and the subsequent connect and close
52 * functions. But for portability reasons and also so that we get
53 * errors on the OpenSSL stack in the event of a failure we use
54 * OpenSSL's versions of these functions.
56 sock
= BIO_socket(BIO_ADDRINFO_family(ai
), SOCK_DGRAM
, 0, 0);
60 /* Connect the socket to the server's address */
61 if (!BIO_connect(sock
, BIO_ADDRINFO_address(ai
), 0)) {
62 BIO_closesocket(sock
);
67 /* Set to nonblocking mode */
68 if (!BIO_socket_nbio(sock
, 1)) {
69 BIO_closesocket(sock
);
78 *peer_addr
= BIO_ADDR_dup(BIO_ADDRINFO_address(ai
));
79 if (*peer_addr
== NULL
) {
80 BIO_closesocket(sock
);
85 /* Free the address information resources we allocated earlier */
86 BIO_ADDRINFO_free(res
);
88 /* If sock is -1 then we've been unable to connect to the server */
92 /* Create a BIO to wrap the socket */
93 bio
= BIO_new(BIO_s_datagram());
95 BIO_closesocket(sock
);
100 * Associate the newly created BIO with the underlying socket. By
101 * passing BIO_CLOSE here the socket will be automatically closed when
102 * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
103 * case you must close the socket explicitly when it is no longer
106 BIO_set_fd(bio
, sock
, BIO_CLOSE
);
112 * Simple application to send a basic HTTP/1.0 request to a server and
113 * print the response on the screen. Note that HTTP/1.0 over QUIC is
114 * non-standard and will not typically be supported by real world servers. This
115 * is for demonstration purposes only.
117 int main(int argc
, char *argv
[])
122 int res
= EXIT_FAILURE
;
124 unsigned char alpn
[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };
125 const char *request_start
= "GET / HTTP/1.0\r\nConnection: close\r\nHost: ";
126 const char *request_end
= "\r\n\r\n";
127 size_t written
, readbytes
;
129 BIO_ADDR
*peer_addr
= NULL
;
130 char *hostname
, *port
;
135 printf("Usage: quic-client-block [-6] hostname port\n");
139 if (!strcmp(argv
[argnext
], "-6")) {
141 printf("Usage: quic-client-block [-6] hostname port\n");
147 hostname
= argv
[argnext
++];
148 port
= argv
[argnext
];
151 * Create an SSL_CTX which we can use to create SSL objects from. We
152 * want an SSL_CTX for creating clients so we use
153 * OSSL_QUIC_client_method() here.
155 ctx
= SSL_CTX_new(OSSL_QUIC_client_method());
157 printf("Failed to create the SSL_CTX\n");
162 * Configure the client to abort the handshake if certificate
163 * verification fails. Virtually all clients should do this unless you
164 * really know what you are doing.
166 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
168 /* Use the default trusted certificate store */
169 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
170 printf("Failed to set the default trusted certificate store\n");
174 /* Create an SSL object to represent the TLS connection */
177 printf("Failed to create the SSL object\n");
182 * Create the underlying transport socket/BIO and associate it with the
185 bio
= create_socket_bio(hostname
, port
, ipv6
? AF_INET6
: AF_INET
, &peer_addr
);
187 printf("Failed to crete the BIO\n");
190 SSL_set_bio(ssl
, bio
, bio
);
193 * Tell the server during the handshake which hostname we are attempting
194 * to connect to in case the server supports multiple hosts.
196 if (!SSL_set_tlsext_host_name(ssl
, hostname
)) {
197 printf("Failed to set the SNI hostname\n");
202 * Ensure we check during certificate verification that the server has
203 * supplied a certificate for the hostname that we were expecting.
204 * Virtually all clients should do this unless you really know what you
207 if (!SSL_set1_host(ssl
, hostname
)) {
208 printf("Failed to set the certificate verification hostname");
212 /* SSL_set_alpn_protos returns 0 for success! */
213 if (SSL_set_alpn_protos(ssl
, alpn
, sizeof(alpn
)) != 0) {
214 printf("Failed to set the ALPN for the connection\n");
218 /* Set the IP address of the remote peer */
219 if (!SSL_set1_initial_peer_addr(ssl
, peer_addr
)) {
220 printf("Failed to set the initial peer address\n");
224 /* Do the handshake with the server */
225 if (SSL_connect(ssl
) < 1) {
226 printf("Failed to connect to the server\n");
228 * If the failure is due to a verification error we can get more
229 * information about it from SSL_get_verify_result().
231 if (SSL_get_verify_result(ssl
) != X509_V_OK
)
232 printf("Verify error: %s\n",
233 X509_verify_cert_error_string(SSL_get_verify_result(ssl
)));
237 /* Write an HTTP GET request to the peer */
238 if (!SSL_write_ex(ssl
, request_start
, strlen(request_start
), &written
)) {
239 printf("Failed to write start of HTTP request\n");
242 if (!SSL_write_ex(ssl
, hostname
, strlen(hostname
), &written
)) {
243 printf("Failed to write hostname in HTTP request\n");
246 if (!SSL_write_ex(ssl
, request_end
, strlen(request_end
), &written
)) {
247 printf("Failed to write end of HTTP request\n");
252 * Get up to sizeof(buf) bytes of the response. We keep reading until the
253 * server closes the connection.
255 while (SSL_read_ex(ssl
, buf
, sizeof(buf
), &readbytes
)) {
257 * OpenSSL does not guarantee that the returned data is a string or
258 * that it is NUL terminated so we use fwrite() to write the exact
259 * number of bytes that we read. The data could be non-printable or
260 * have NUL characters in the middle of it. For this simple example
261 * we're going to print it to stdout anyway.
263 fwrite(buf
, 1, readbytes
, stdout
);
265 /* In case the response didn't finish with a newline we add one now */
269 * Check whether we finished the while loop above normally or as the
270 * result of an error. The 0 argument to SSL_get_error() is the return
271 * code we received from the SSL_read_ex() call. It must be 0 in order
272 * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In
273 * QUIC terms this means that the peer has sent FIN on the stream to
274 * indicate that no further data will be sent.
276 switch (SSL_get_error(ssl
, 0)) {
277 case SSL_ERROR_ZERO_RETURN
:
278 /* Normal completion of the stream */
283 * Some stream fatal error occurred. This could be because of a stream
284 * reset - or some failure occurred on the underlying connection.
286 switch (SSL_get_stream_read_state(ssl
)) {
287 case SSL_STREAM_STATE_RESET_REMOTE
:
288 printf("Stream reset occurred\n");
289 /* The stream has been reset but the connection is still healthy. */
292 case SSL_STREAM_STATE_CONN_CLOSED
:
293 printf("Connection closed\n");
294 /* Connection is already closed. Skip SSL_shutdown() */
298 printf("Unknown stream failure\n");
304 /* Some other unexpected error occurred */
305 printf ("Failed reading remaining data\n");
310 * Repeatedly call SSL_shutdown() until the connection is fully
314 ret
= SSL_shutdown(ssl
);
316 printf("Error shutting down: %d\n", ret
);
325 * If something bad happened then we will dump the contents of the
326 * OpenSSL error stack to stderr. There might be some useful diagnostic
329 if (res
== EXIT_FAILURE
)
330 ERR_print_errors_fp(stderr
);
333 * Free the resources we allocated. We do not free the BIO object here
334 * because ownership of it was immediately transferred to the SSL object
335 * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
339 BIO_ADDR_free(peer_addr
);