]> git.ipfire.org Git - thirdparty/openssl.git/blob - demos/guide/tls-client-non-block.c
05db0f529e66b9036832e20261240cd964e46c9f
[thirdparty/openssl.git] / demos / guide / tls-client-non-block.c
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-tls-client-non-block.pod
13 */
14
15 #include <string.h>
16
17 /* Include the appropriate header file for SOCK_STREAM */
18 #ifdef _WIN32 /* Windows */
19 # include <winsock2.h>
20 #else /* Linux/Unix */
21 # include <sys/socket.h>
22 # include <sys/select.h>
23 #endif
24
25 #include <openssl/bio.h>
26 #include <openssl/ssl.h>
27 #include <openssl/err.h>
28
29 /* Helper function to create a BIO connected to the server */
30 static BIO *create_socket_bio(const char *hostname, const char *port)
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_STREAM, 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_STREAM, 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), BIO_SOCK_NODELAY)) {
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 /* We have a connected socket so break out of the loop */
74 break;
75 }
76
77 /* Free the address information resources we allocated earlier */
78 BIO_ADDRINFO_free(res);
79
80 /* If sock is -1 then we've been unable to connect to the server */
81 if (sock == -1)
82 return NULL;
83
84 /* Create a BIO to wrap the socket*/
85 bio = BIO_new(BIO_s_socket());
86 if (bio == NULL)
87 BIO_closesocket(sock);
88
89 /*
90 * Associate the newly created BIO with the underlying socket. By
91 * passing BIO_CLOSE here the socket will be automatically closed when
92 * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
93 * case you must close the socket explicitly when it is no longer
94 * needed.
95 */
96 BIO_set_fd(bio, sock, BIO_CLOSE);
97
98 return bio;
99 }
100
101 static void wait_for_activity(SSL *ssl, int write)
102 {
103 fd_set fds;
104 int width, sock;
105
106 /* Get hold of the underlying file descriptor for the socket */
107 sock = SSL_get_fd(ssl);
108
109 FD_ZERO(&fds);
110 FD_SET(sock, &fds);
111 width = sock + 1;
112
113 /*
114 * Wait until the socket is writeable or readable. We use select here for
115 * the sake of simplicity and portability, but you could equally use
116 * poll/epoll or similar functions
117 */
118 if (write)
119 select(width, NULL, &fds, NULL, NULL);
120 else
121 select(width, &fds, NULL, NULL, NULL);
122 }
123
124 static int handle_io_failure(SSL *ssl, int res)
125 {
126 switch (SSL_get_error(ssl, res)) {
127 case SSL_ERROR_WANT_READ:
128 /* Temporary failure. Wait until we can read and try again */
129 wait_for_activity(ssl, 0);
130 return 1;
131
132 case SSL_ERROR_WANT_WRITE:
133 /* Temporary failure. Wait until we can write and try again */
134 wait_for_activity(ssl, 1);
135 return 1;
136
137 case SSL_ERROR_ZERO_RETURN:
138 /* EOF */
139 return 0;
140
141 case SSL_ERROR_SYSCALL:
142 return -1;
143
144 case SSL_ERROR_SSL:
145 /*
146 * If the failure is due to a verification error we can get more
147 * information about it from SSL_get_verify_result().
148 */
149 if (SSL_get_verify_result(ssl) != X509_V_OK)
150 printf("Verify error: %s\n",
151 X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
152 return -1;
153
154 default:
155 return -1;
156 }
157 }
158
159 /* Server hostname and port details. Must be in quotes */
160 #ifndef HOSTNAME
161 # define HOSTNAME "www.example.com"
162 #endif
163 #ifndef PORT
164 # define PORT "443"
165 #endif
166
167 /*
168 * Simple application to send a basic HTTP/1.0 request to a server and
169 * print the response on the screen.
170 */
171 int main(void)
172 {
173 SSL_CTX *ctx = NULL;
174 SSL *ssl = NULL;
175 BIO *bio = NULL;
176 int res = EXIT_FAILURE;
177 int ret;
178 const char *request =
179 "GET / HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
180 size_t written, readbytes;
181 char buf[160];
182 int eof = 0;
183
184 /*
185 * Create an SSL_CTX which we can use to create SSL objects from. We
186 * want an SSL_CTX for creating clients so we use TLS_client_method()
187 * here.
188 */
189 ctx = SSL_CTX_new(TLS_client_method());
190 if (ctx == NULL) {
191 printf("Failed to create the SSL_CTX\n");
192 goto end;
193 }
194
195 /*
196 * Configure the client to abort the handshake if certificate
197 * verification fails. Virtually all clients should do this unless you
198 * really know what you are doing.
199 */
200 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
201
202 /* Use the default trusted certificate store */
203 if (!SSL_CTX_set_default_verify_paths(ctx)) {
204 printf("Failed to set the default trusted certificate store\n");
205 goto end;
206 }
207
208 /*
209 * TLSv1.1 or earlier are deprecated by IETF and are generally to be
210 * avoided if possible. We require a minimum TLS version of TLSv1.2.
211 */
212 if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) {
213 printf("Failed to set the minimum TLS protocol version\n");
214 goto end;
215 }
216
217 /* Create an SSL object to represent the TLS connection */
218 ssl = SSL_new(ctx);
219 if (ssl == NULL) {
220 printf("Failed to create the SSL object\n");
221 goto end;
222 }
223
224 /*
225 * Create the underlying transport socket/BIO and associate it with the
226 * connection.
227 */
228 bio = create_socket_bio(HOSTNAME, PORT);
229 if (bio == NULL) {
230 printf("Failed to crete the BIO\n");
231 goto end;
232 }
233 SSL_set_bio(ssl, bio, bio);
234
235 /*
236 * Tell the server during the handshake which hostname we are attempting
237 * to connect to in case the server supports multiple hosts.
238 */
239 if (!SSL_set_tlsext_host_name(ssl, HOSTNAME)) {
240 printf("Failed to set the SNI hostname\n");
241 goto end;
242 }
243
244 /*
245 * Ensure we check during certificate verification that the server has
246 * supplied a certificate for the hostname that we were expecting.
247 * Virtually all clients should do this unless you really know what you
248 * are doing.
249 */
250 if (!SSL_set1_host(ssl, HOSTNAME)) {
251 printf("Failed to set the certificate verification hostname");
252 goto end;
253 }
254
255 /* Do the handshake with the server */
256 while ((ret = SSL_connect(ssl)) != 1) {
257 if (handle_io_failure(ssl, ret) == 1)
258 continue; /* Retry */
259 printf("Failed to connect to server\n");
260 goto end; /* Cannot retry: error */
261 }
262
263 /* Write an HTTP GET request to the peer */
264 while (!SSL_write_ex(ssl, request, strlen(request), &written)) {
265 if (handle_io_failure(ssl, 0) == 1)
266 continue; /* Retry */
267 printf("Failed to write HTTP request\n");
268 goto end; /* Cannot retry: error */
269 }
270
271 do {
272 /*
273 * Get up to sizeof(buf) bytes of the response. We keep reading until
274 * the server closes the connection.
275 */
276 while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
277 switch (handle_io_failure(ssl, 0)) {
278 case 1:
279 continue; /* Retry */
280 case 0:
281 eof = 1;
282 continue;
283 case -1:
284 default:
285 printf("Failed reading remaining data\n");
286 goto end; /* Cannot retry: error */
287 }
288 }
289 /*
290 * OpenSSL does not guarantee that the returned data is a string or
291 * that it is NUL terminated so we use fwrite() to write the exact
292 * number of bytes that we read. The data could be non-printable or
293 * have NUL characters in the middle of it. For this simple example
294 * we're going to print it to stdout anyway.
295 */
296 if (!eof)
297 fwrite(buf, 1, readbytes, stdout);
298 } while (!eof);
299 /* In case the response didn't finish with a newline we add one now */
300 printf("\n");
301
302 /*
303 * The peer already shutdown gracefully (we know this because of the
304 * SSL_ERROR_ZERO_RETURN (i.e. EOF) above). We should do the same back.
305 */
306 while ((ret = SSL_shutdown(ssl)) != 1) {
307 if (ret < 0 && handle_io_failure(ssl, ret) == 1)
308 continue; /* Retry */
309 /*
310 * ret == 0 is unexpected here because that means "we've sent a
311 * close_notify and we're waiting for one back". But we already know
312 * we got one from the peer because of the SSL_ERROR_ZERO_RETURN
313 * (i.e. EOF) above.
314 */
315 printf("Error shutting down\n");
316 goto end; /* Cannot retry: error */
317 }
318
319 /* Success! */
320 res = EXIT_SUCCESS;
321 end:
322 /*
323 * If something bad happened then we will dump the contents of the
324 * OpenSSL error stack to stderr. There might be some useful diagnostic
325 * information there.
326 */
327 if (res == EXIT_FAILURE)
328 ERR_print_errors_fp(stderr);
329
330 /*
331 * Free the resources we allocated. We do not free the BIO object here
332 * because ownership of it was immediately transferred to the SSL object
333 * via SSL_set_bio(). The BIO will be freed when we free the SSL object.
334 */
335 SSL_free(ssl);
336 SSL_CTX_free(ctx);
337 return res;
338 }