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