]> git.ipfire.org Git - thirdparty/openssl.git/blame - demos/guide/quic-multi-stream.c
Add a missing call to BIO_closesocket()
[thirdparty/openssl.git] / demos / guide / quic-multi-stream.c
CommitLineData
584140fa
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-multi-stream.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 /*
50 * Create a TCP 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.
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)) {
cdedecd5 69 BIO_closesocket(sock);
584140fa
MC
70 sock = -1;
71 continue;
72 }
73
74 break;
75 }
76
77 if (sock != -1) {
78 *peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
79 if (*peer_addr == NULL) {
80 BIO_closesocket(sock);
81 return NULL;
82 }
83 }
84
85
86 /* Free the address information resources we allocated earlier */
87 BIO_ADDRINFO_free(res);
88
89 /* If sock is -1 then we've been unable to connect to the server */
90 if (sock == -1)
91 return NULL;
92
93 /* Create a BIO to wrap the socket*/
94 bio = BIO_new(BIO_s_datagram());
95 if (bio == NULL)
96 BIO_closesocket(sock);
97
98 /*
99 * Associate the newly created BIO with the underlying socket. By
100 * passing BIO_CLOSE here the socket will be automatically closed when
101 * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
102 * case you must close the socket explicitly when it is no longer
103 * needed.
104 */
105 BIO_set_fd(bio, sock, BIO_CLOSE);
106
107 return bio;
108}
109
110/* Server hostname and port details. Must be in quotes */
111#ifndef HOSTNAME
112# define HOSTNAME "www.example.com"
113#endif
114#ifndef PORT
115# define PORT "443"
116#endif
117
118/*
119 * Simple application to send basic HTTP/1.0 requests to a server and print the
120 * response on the screen. Note that HTTP/1.0 over QUIC is not a real protocol
121 * and will not be supported by real world servers. This is for demonstration
122 * purposes only.
123 */
124int main(void)
125{
126 SSL_CTX *ctx = NULL;
127 SSL *ssl = NULL;
128 SSL *stream1 = NULL, *stream2 = NULL, *stream3 = NULL;
129 BIO *bio = NULL;
130 int res = EXIT_FAILURE;
131 int ret;
132 unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };
133 const char *request1 =
134 "GET /request1.html HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
135 const char *request2 =
136 "GET /request2.html HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
137 size_t written, readbytes;
138 char buf[160];
139 BIO_ADDR *peer_addr = NULL;
140
141 /*
142 * Create an SSL_CTX which we can use to create SSL objects from. We
143 * want an SSL_CTX for creating clients so we use
144 * OSSL_QUIC_client_method() here.
145 */
146 ctx = SSL_CTX_new(OSSL_QUIC_client_method());
147 if (ctx == NULL) {
148 printf("Failed to create the SSL_CTX\n");
149 goto end;
150 }
151
152 /*
153 * Configure the client to abort the handshake if certificate
154 * verification fails. Virtually all clients should do this unless you
155 * really know what you are doing.
156 */
157 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
158
159 /* Use the default trusted certificate store */
160 if (!SSL_CTX_set_default_verify_paths(ctx)) {
161 printf("Failed to set the default trusted certificate store\n");
162 goto end;
163 }
164
165 /* Create an SSL object to represent the TLS connection */
166 ssl = SSL_new(ctx);
167 if (ssl == NULL) {
168 printf("Failed to create the SSL object\n");
169 goto end;
170 }
171
172 /*
173 * We will use multiple streams so we will disable the default stream mode.
174 * This is not a requirement for using multiple streams but is recommended.
175 */
176 if (!SSL_set_default_stream_mode(ssl, SSL_DEFAULT_STREAM_MODE_NONE)) {
177 printf("Failed to disable the default stream mode\n");
178 goto end;
179 }
180
181 /*
182 * Create the underlying transport socket/BIO and associate it with the
183 * connection.
184 */
185 bio = create_socket_bio(HOSTNAME, PORT, &peer_addr);
186 if (bio == NULL) {
187 printf("Failed to crete the BIO\n");
188 goto end;
189 }
190 SSL_set_bio(ssl, bio, bio);
191
192 /*
193 * Tell the server during the handshake which hostname we are attempting
194 * to connect to in case the server supports multiple hosts.
195 */
196 if (!SSL_set_tlsext_host_name(ssl, HOSTNAME)) {
197 printf("Failed to set the SNI hostname\n");
198 goto end;
199 }
200
201 /*
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
205 * are doing.
206 */
207 if (!SSL_set1_host(ssl, HOSTNAME)) {
208 printf("Failed to set the certificate verification hostname");
209 goto end;
210 }
211
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");
215 goto end;
216 }
217
8d74a131 218 /* Set the IP address of the remote peer */
dac42bdc 219 if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {
584140fa
MC
220 printf("Failed to set the initial peer address\n");
221 goto end;
222 }
223
8d74a131 224 /* Connect to the server and perform the TLS handshake */
584140fa
MC
225 if ((ret = SSL_connect(ssl)) < 1) {
226 /*
227 * If the failure is due to a verification error we can get more
228 * information about it from SSL_get_verify_result().
229 */
230 if (SSL_get_verify_result(ssl) != X509_V_OK)
231 printf("Verify error: %s\n",
232 X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
233 goto end;
234 }
235
236 /*
237 * We create two new client initiated streams. The first will be
238 * bi-directional, and the second will be uni-directional.
239 */
240 stream1 = SSL_new_stream(ssl, 0);
241 stream2 = SSL_new_stream(ssl, SSL_STREAM_FLAG_UNI);
242 if (stream1 == NULL || stream2 == NULL) {
243 printf("Failed to create streams\n");
244 goto end;
245 }
246
247 /* Write an HTTP GET request on each of our streams to the peer */
248 if (!SSL_write_ex(stream1, request1, strlen(request1), &written)) {
249 printf("Failed to write HTTP request on stream 1\n");
250 goto end;
251 }
252
253 if (!SSL_write_ex(stream2, request2, strlen(request2), &written)) {
254 printf("Failed to write HTTP request on stream 2\n");
255 goto end;
256 }
257
258 /*
259 * In this demo we read all the data from one stream before reading all the
260 * data from the next stream for simplicity. In practice there is no need to
261 * do this. We can interleave IO on the different streams if we wish, or
262 * manage the streams entirely separately on different threads.
263 */
264
265 printf("Stream 1 data:\n");
266 /*
267 * Get up to sizeof(buf) bytes of the response from stream 1 (which is a
268 * bidirectional stream). We keep reading until the server closes the
269 * connection.
270 */
271 while (SSL_read_ex(stream1, buf, sizeof(buf), &readbytes)) {
272 /*
273 * OpenSSL does not guarantee that the returned data is a string or
274 * that it is NUL terminated so we use fwrite() to write the exact
275 * number of bytes that we read. The data could be non-printable or
276 * have NUL characters in the middle of it. For this simple example
277 * we're going to print it to stdout anyway.
278 */
279 fwrite(buf, 1, readbytes, stdout);
280 }
281 /* In case the response didn't finish with a newline we add one now */
282 printf("\n");
283
284 /*
285 * Check whether we finished the while loop above normally or as the
286 * result of an error. The 0 argument to SSL_get_error() is the return
287 * code we received from the SSL_read_ex() call. It must be 0 in order
288 * to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN. In
289 * QUIC terms this means that the peer has sent FIN on the stream to
290 * indicate that no further data will be sent.
291 */
02e36ed3
MC
292 switch (SSL_get_error(stream1, 0)) {
293 case SSL_ERROR_ZERO_RETURN:
294 /* Normal completion of the stream */
295 break;
296
297 case SSL_ERROR_SSL:
584140fa 298 /*
02e36ed3
MC
299 * Some stream fatal error occurred. This could be because of a stream
300 * reset - or some failure occurred on the underlying connection.
584140fa 301 */
02e36ed3
MC
302 switch (SSL_get_stream_read_state(stream1)) {
303 case SSL_STREAM_STATE_RESET_REMOTE:
304 printf("Stream reset occurred\n");
305 /* The stream has been reset but the connection is still healthy. */
306 break;
307
308 case SSL_STREAM_STATE_CONN_CLOSED:
309 printf("Connection closed\n");
310 /* Connection is already closed. Skip SSL_shutdown() */
311 goto end;
312
313 default:
314 printf("Unknown stream failure\n");
315 break;
316 }
317 break;
318
319 default:
320 /* Some other unexpected error occurred */
321 printf ("Failed reading remaining data\n");
322 break;
584140fa
MC
323 }
324
325 /*
326 * In our hypothetical HTTP/1.0 over QUIC protocol that we are using we
327 * assume that the server will respond with a server initiated stream
328 * containing the data requested in our uni-directional stream. This doesn't
329 * really make sense to do in a real protocol, but its just for
330 * demonstration purposes.
331 *
332 * We're using blocking mode so this will block until a stream becomes
333 * available. We could override this behaviour if we wanted to by setting
334 * the SSL_ACCEPT_STREAM_NO_BLOCK flag in the second argument below.
335 */
336 stream3 = SSL_accept_stream(ssl, 0);
337 if (stream3 == NULL) {
338 printf("Failed to accept a new stream\n");
339 goto end;
340 }
341
342 printf("Stream 3 data:\n");
343 /*
344 * Read the data from stream 3 like we did for stream 1 above. Note that
345 * stream 2 was uni-directional so there is no data to be read from that
346 * one.
347 */
348 while (SSL_read_ex(stream3, buf, sizeof(buf), &readbytes))
349 fwrite(buf, 1, readbytes, stdout);
350 printf("\n");
351
352 /* Check for errors on the stream */
02e36ed3
MC
353 switch (SSL_get_error(stream3, 0)) {
354 case SSL_ERROR_ZERO_RETURN:
355 /* Normal completion of the stream */
356 break;
357
358 case SSL_ERROR_SSL:
359 switch (SSL_get_stream_read_state(stream3)) {
360 case SSL_STREAM_STATE_RESET_REMOTE:
361 printf("Stream reset occurred\n");
362 break;
363
364 case SSL_STREAM_STATE_CONN_CLOSED:
365 printf("Connection closed\n");
366 goto end;
367
368 default:
369 printf("Unknown stream failure\n");
370 break;
371 }
372 break;
373
374 default:
375 printf ("Failed reading remaining data\n");
376 break;
584140fa
MC
377 }
378
379 /*
380 * Repeatedly call SSL_shutdown() until the connection is fully
381 * closed.
382 */
383 do {
384 ret = SSL_shutdown(ssl);
385 if (ret < 0) {
386 printf("Error shutting down: %d\n", ret);
387 goto end;
388 }
389 } while (ret != 1);
390
391 /* Success! */
392 res = EXIT_SUCCESS;
393 end:
394 /*
395 * If something bad happened then we will dump the contents of the
396 * OpenSSL error stack to stderr. There might be some useful diagnostic
397 * information there.
398 */
399 if (res == EXIT_FAILURE)
400 ERR_print_errors_fp(stderr);
401
402 /*
403 * Free the resources we allocated. We do not free the BIO object here
404 * because ownership of it was immediately transferred to the SSL object
405 * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
406 */
407 SSL_free(ssl);
408 SSL_free(stream1);
409 SSL_free(stream2);
410 SSL_free(stream3);
411 SSL_CTX_free(ctx);
412 BIO_ADDR_free(peer_addr);
413 return res;
414}