]> git.ipfire.org Git - thirdparty/openssl.git/blame - demos/guide/quic-client-block.c
Expand the explanation of how to go and do useful work in non-blocking
[thirdparty/openssl.git] / demos / guide / quic-client-block.c
CommitLineData
23fe02e5
MC
1/*
2 * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
3 *
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
8 */
9
10/*
11 * NB: Changes to this file should also be reflected in
12 * doc/man7/ossl-guide-quic-client-block.pod
13 */
14
15#include <string.h>
16
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>
22#endif
23
24#include <openssl/bio.h>
25#include <openssl/ssl.h>
26#include <openssl/err.h>
27
28/* Helper function to create a BIO connected to the server */
29static BIO *create_socket_bio(const char *hostname, const char *port,
30 BIO_ADDR **peer_addr)
31{
32 int sock = -1;
33 BIO_ADDRINFO *res;
34 const BIO_ADDRINFO *ai = NULL;
35 BIO *bio;
36
37 /*
38 * Lookup IP address info for the server.
39 */
40 if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, 0, SOCK_DGRAM, 0,
41 &res))
42 return NULL;
43
44 /*
45 * Loop through all the possible addresses for the server and find one
46 * we can connect to.
47 */
48 for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
49 /*
38c3c1db 50 * Create a UDP socket. We could equally use non-OpenSSL calls such
23fe02e5
MC
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.
55 */
56 sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0);
57 if (sock == -1)
58 continue;
59
60 /* Connect the socket to the server's address */
61 if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) {
62 BIO_closesocket(sock);
63 sock = -1;
64 continue;
65 }
66
67 /* Set to nonblocking mode */
68 if (!BIO_socket_nbio(sock, 1)) {
69 sock = -1;
70 continue;
71 }
72
73 break;
74 }
75
76 if (sock != -1) {
77 *peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
78 if (*peer_addr == NULL) {
79 BIO_closesocket(sock);
80 return NULL;
81 }
82 }
83
23fe02e5
MC
84 /* Free the address information resources we allocated earlier */
85 BIO_ADDRINFO_free(res);
86
87 /* If sock is -1 then we've been unable to connect to the server */
88 if (sock == -1)
89 return NULL;
90
91 /* Create a BIO to wrap the socket*/
92 bio = BIO_new(BIO_s_datagram());
93 if (bio == NULL)
94 BIO_closesocket(sock);
95
96 /*
97 * Associate the newly created BIO with the underlying socket. By
98 * passing BIO_CLOSE here the socket will be automatically closed when
99 * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
100 * case you must close the socket explicitly when it is no longer
101 * needed.
102 */
103 BIO_set_fd(bio, sock, BIO_CLOSE);
104
105 return bio;
106}
107
108/* Server hostname and port details. Must be in quotes */
109#ifndef HOSTNAME
110# define HOSTNAME "www.example.com"
111#endif
112#ifndef PORT
113# define PORT "443"
114#endif
115
116/*
117 * Simple application to send a basic HTTP/1.0 request to a server and
118 * print the response on the screen. Note that HTTP/1.0 over QUIC is
119 * non-standard and will not typically be supported by real world servers. This
120 * is for demonstration purposes only.
121 */
122int main(void)
123{
124 SSL_CTX *ctx = NULL;
584140fa 125 SSL *ssl = NULL;
23fe02e5
MC
126 BIO *bio = NULL;
127 int res = EXIT_FAILURE;
128 int ret;
129 unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };
130 const char *request =
131 "GET / HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
132 size_t written, readbytes;
133 char buf[160];
134 BIO_ADDR *peer_addr = NULL;
135
136 /*
137 * Create an SSL_CTX which we can use to create SSL objects from. We
138 * want an SSL_CTX for creating clients so we use
139 * OSSL_QUIC_client_method() here.
140 */
141 ctx = SSL_CTX_new(OSSL_QUIC_client_method());
142 if (ctx == NULL) {
143 printf("Failed to create the SSL_CTX\n");
144 goto end;
145 }
146
147 /*
148 * Configure the client to abort the handshake if certificate
149 * verification fails. Virtually all clients should do this unless you
150 * really know what you are doing.
151 */
152 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
153
154 /* Use the default trusted certificate store */
155 if (!SSL_CTX_set_default_verify_paths(ctx)) {
156 printf("Failed to set the default trusted certificate store\n");
157 goto end;
158 }
159
160 /* Create an SSL object to represent the TLS connection */
161 ssl = SSL_new(ctx);
162 if (ssl == NULL) {
163 printf("Failed to create the SSL object\n");
164 goto end;
165 }
166
167 /*
168 * Create the underlying transport socket/BIO and associate it with the
169 * connection.
170 */
171 bio = create_socket_bio(HOSTNAME, PORT, &peer_addr);
172 if (bio == NULL) {
173 printf("Failed to crete the BIO\n");
174 goto end;
175 }
176 SSL_set_bio(ssl, bio, bio);
177
178 /*
179 * Tell the server during the handshake which hostname we are attempting
180 * to connect to in case the server supports multiple hosts.
181 */
182 if (!SSL_set_tlsext_host_name(ssl, HOSTNAME)) {
183 printf("Failed to set the SNI hostname\n");
184 goto end;
185 }
186
187 /*
188 * Ensure we check during certificate verification that the server has
189 * supplied a certificate for the hostname that we were expecting.
190 * Virtually all clients should do this unless you really know what you
191 * are doing.
192 */
193 if (!SSL_set1_host(ssl, HOSTNAME)) {
194 printf("Failed to set the certificate verification hostname");
195 goto end;
196 }
197
198 /* SSL_set_alpn_protos returns 0 for success! */
199 if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {
200 printf("Failed to set the ALPN for the connection\n");
201 goto end;
202 }
203
8d74a131 204 /* Set the IP address of the remote peer */
ce7a9e23 205 if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {
4409e152 206 printf("Failed to set the initial peer address\n");
23fe02e5
MC
207 goto end;
208 }
209
8d74a131 210 /* Connect to the server and perform the TLS handshake */
23fe02e5
MC
211 if ((ret = SSL_connect(ssl)) < 1) {
212 /*
213 * If the failure is due to a verification error we can get more
214 * information about it from SSL_get_verify_result().
215 */
216 if (SSL_get_verify_result(ssl) != X509_V_OK)
217 printf("Verify error: %s\n",
218 X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
219 goto end;
220 }
221
222 /* Write an HTTP GET request to the peer */
223 if (!SSL_write_ex(ssl, request, strlen(request), &written)) {
224 printf("Failed to write HTTP request\n");
225 goto end;
226 }
227
228 /*
229 * Get up to sizeof(buf) bytes of the response. We keep reading until the
230 * server closes the connection.
231 */
232 while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
233 /*
234 * OpenSSL does not guarantee that the returned data is a string or
235 * that it is NUL terminated so we use fwrite() to write the exact
236 * number of bytes that we read. The data could be non-printable or
237 * have NUL characters in the middle of it. For this simple example
238 * we're going to print it to stdout anyway.
239 */
240 fwrite(buf, 1, readbytes, stdout);
241 }
242 /* In case the response didn't finish with a newline we add one now */
243 printf("\n");
244
245 /*
246 * Check whether we finished the while loop above normally or as the
247 * result of an error. The 0 argument to SSL_get_error() is the return
248 * code we received from the SSL_read_ex() call. It must be 0 in order
b7f3d5d6
MC
249 * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In
250 * QUIC terms this means that the peer has sent FIN on the stream to
251 * indicate that no further data will be sent.
23fe02e5 252 */
02e36ed3
MC
253 switch (SSL_get_error(ssl, 0)) {
254 case SSL_ERROR_ZERO_RETURN:
255 /* Normal completion of the stream */
256 break;
257
258 case SSL_ERROR_SSL:
23fe02e5 259 /*
02e36ed3
MC
260 * Some stream fatal error occurred. This could be because of a stream
261 * reset - or some failure occurred on the underlying connection.
23fe02e5 262 */
02e36ed3
MC
263 switch (SSL_get_stream_read_state(ssl)) {
264 case SSL_STREAM_STATE_RESET_REMOTE:
265 printf("Stream reset occurred\n");
266 /* The stream has been reset but the connection is still healthy. */
267 break;
268
269 case SSL_STREAM_STATE_CONN_CLOSED:
270 printf("Connection closed\n");
271 /* Connection is already closed. Skip SSL_shutdown() */
272 goto end;
273
274 default:
275 printf("Unknown stream failure\n");
276 break;
277 }
278 break;
279
280 default:
281 /* Some other unexpected error occurred */
23fe02e5 282 printf ("Failed reading remaining data\n");
02e36ed3 283 break;
23fe02e5
MC
284 }
285
286 /*
287 * Repeatedly call SSL_shutdown() until the connection is fully
288 * closed.
289 */
290 do {
291 ret = SSL_shutdown(ssl);
292 if (ret < 0) {
4409e152 293 printf("Error shutting down: %d\n", ret);
23fe02e5
MC
294 goto end;
295 }
296 } while (ret != 1);
297
298 /* Success! */
299 res = EXIT_SUCCESS;
300 end:
301 /*
302 * If something bad happened then we will dump the contents of the
303 * OpenSSL error stack to stderr. There might be some useful diagnostic
304 * information there.
305 */
306 if (res == EXIT_FAILURE)
307 ERR_print_errors_fp(stderr);
308
309 /*
310 * Free the resources we allocated. We do not free the BIO object here
311 * because ownership of it was immediately transferred to the SSL object
312 * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
313 */
314 SSL_free(ssl);
315 SSL_CTX_free(ctx);
316 BIO_ADDR_free(peer_addr);
317 return res;
318}