OSSL-GUIDE-T...ENT-NON-BLOCK(7ossl)
π NAME π
ossl-guide-tls-client-non-block(7ossl) β OpenSSL Guide: Writing a simple nonblocking TLS client π¦
πΈ SIMPLE NONBLOCKING TLS CLIENT EXAMPLE πΈ
Okay so bestie, this page builds on the example from ossl-guide-tls-client-block(7) β that one shows you how to write a simple blocking TLS client. Here, weβre gonna amend that demo code so it supports a nonblocking socket. β¨
The complete source code for this example nonblocking TLS client lives in the demos/guide directory of the OpenSSL source distribution, in the file tls-client-non-block.c. Itβs also online at <https://github.com/openssl/openssl/blob/master/demos/guide/tls-client-non-block.c>. π
As we saw in the previous example, a blocking socket is one that waits (blocks) until data is available to read if you try to read from it when thereβs no data yet. Similarly, it waits when writing if the socket is currently unable to write at that moment. This can simplify development because you donβt have to worry about what to do in those cases β execution just stops until it can continue. But in lots of cases you do not want that behaviour. Instead of stopping and waiting, your application may need to go do other tasks while the socket is unable to read/write β for example, updating a GUI or performing operations on some other socket. π
With a nonblocking socket, trying to read or write to a socket thatβs currently unable to read or write will return immediately with a non-fatal error. OpenSSL still does the reading/writing to the socket, but this nonblocking behaviour gets propagated up to the application, so OpenSSL I/O functions such as SSL_read_ex(3) or SSL_write_ex(3) will not block. π
Since this page builds on the example from ossl-guide-tls-client-block(7), we assume youβre familiar with it, and we only explain how this example differs. π«Ά
π Setting the socket to be nonblocking π
The first step in writing an application that supports nonblocking is to set the socket into nonblocking mode. A socket is blocking by default. The exact details on how to do this can differ from one platform to another. Fortunately, OpenSSL offers a portable function that does it for you:
/* Set to nonblocking mode */
if (!BIO_socket_nbio(sock, 1)) {
sock = -1;
continue;
}
You do not have to use OpenSSLβs function for this. You can of course directly call whatever functions your Operating System provides for this purpose on your platform. β¨
π¦ Performing work while waiting for the socket π¦
In a nonblocking application, youβll need work to perform in the event that we want to read or write to the socket but currently canβt. Honestly, thatβs the whole point of using a nonblocking socket: giving the application the opportunity to do something else. Whatever the application has to do, it must also be prepared to come back and retry the operation it previously attempted β periodically β to see if it can now complete. Ideally it would only do this in the event that the state of the underlying socket has actually changed (e.g. become readable where it wasnβt before), but that doesnβt have to be the case. It can retry at any time. π
Note that itβs important that you retry exactly the same operation you tried last time. You cannot start something new. For example, if you were attempting to write the text "Hello World" and the operation failed because the socket is currently unable to write, then you cannot then attempt to write some other text when you retry the operation. π
In this demo application, weβll create a helper function that simulates doing other work. In fact, for the sake of simplicity, it will do nothing except wait for the state of the socket to change.
We call our function wait_for_activity() because all it does is wait until the underlying socket has become readable or writeable when it wasnβt before.
static void wait_for_activity(SSL *ssl, int write)
{
fd_set fds;
int width, sock;
/* Get hold of the underlying file descriptor for the socket */
sock = SSL_get_fd(ssl);
FD_ZERO(&fds);
FD_SET(sock, &fds);
width = sock + 1;
/*
* Wait until the socket is writeable or readable. We use select here
* for the sake of simplicity and portability, but you could equally use
* poll/epoll or similar functions
*
* NOTE: For the purposes of this demonstration code this effectively
* makes this demo block until it has something more useful to do. In a
* real application you probably want to go and do other work here (e.g.
* update a GUI, or service other connections).
*
* Let's say for example that you want to update the progress counter on
* a GUI every 100ms. One way to do that would be to add a 100ms timeout
* in the last parameter to "select" below. Then, when select returns,
* you check if it did so because of activity on the file descriptors or
* because of the timeout. If it is due to the timeout then update the
* GUI and then restart the "select".
*/
if (write)
select(width, NULL, &fds, NULL, NULL);
else
select(width, &fds, NULL, NULL, NULL);
}
In this example weβre using the select function because itβs very simple to use and is available on most Operating Systems. However, you could use any other similar function to do the same thing. select waits for the state of the underlying socket(s) to become readable/writeable before returning. It also supports a timeout (as do most other similar functions), so in your own applications you can make use of this to periodically wake up and perform work while waiting for the socket state to change. But we donβt use that timeout capability in this example, for the sake of simplicity. π
π Handling errors from OpenSSL I/O functions π
An application that uses a nonblocking socket will need to be prepared to handle errors returned from OpenSSL I/O functions such as SSL_read_ex(3) or SSL_write_ex(3). Errors may be fatal (for example, because the underlying connection has failed), or non-fatal (for example, because weβre trying to read from the underlying socket but the data has not yet arrived from the peer). π
SSL_read_ex(3) and SSL_write_ex(3) will return 0 to indicate an error, and SSL_read(3) and SSL_write(3) will return 0 or a negative value to indicate an error. SSL_shutdown(3) will return a negative value to indicate an error.
In the event of an error, an application should call SSL_get_error(3) to find out what type of error has occurred. If the error is non-fatal and can be retried, then SSL_get_error(3) will return SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, depending on whether OpenSSL wanted to read to or write from the socket but was unable to. Note that a call to SSL_read_ex(3) or SSL_read(3) can still generate SSL_ERROR_WANT_WRITE because OpenSSL may need to write protocol messages (such as to update cryptographic keys) even if the application is only trying to read data. Similarly, calls to SSL_write_ex(3) or SSL_write(3) might generate SSL_ERROR_WANT_READ. π
Another type of non-fatal error that may occur is SSL_ERROR_ZERO_RETURN. This indicates an EOF (End-Of-File), which can occur if you attempt to read data from an SSL object but the peer has indicated that it will not send any more data on it. In this case you may still want to write data to the connection, but you will not receive any more data. π
Fatal errors that may occur are SSL_ERROR_SYSCALL and SSL_ERROR_SSL. These indicate that the underlying connection has failed. You should not attempt to shut it down with SSL_shutdown(3). SSL_ERROR_SYSCALL indicates that OpenSSL attempted to make a syscall that failed. You can consult errno for further details. SSL_ERROR_SSL indicates that some OpenSSL error occurred. You can consult the OpenSSL error stack for further details (for example, by calling ERR_print_errors(3) to print out details of errors that have occurred). π₯
In our demo application, weβll write a function to handle these errors from OpenSSL I/O functions:
static int handle_io_failure(SSL *ssl, int res)
{
switch (SSL_get_error(ssl, res)) {
case SSL_ERROR_WANT_READ:
/* Temporary failure. Wait until we can read and try again */
wait_for_activity(ssl, 0);
return 1;
case SSL_ERROR_WANT_WRITE:
/* Temporary failure. Wait until we can write and try again */
wait_for_activity(ssl, 1);
return 1;
case SSL_ERROR_ZERO_RETURN:
/* EOF */
return 0;
case SSL_ERROR_SYSCALL:
return -1;
case SSL_ERROR_SSL:
/*
* If the failure is due to a verification error we can get more
* information about it from SSL_get_verify_result().
*/
if (SSL_get_verify_result(ssl) != X509_V_OK)
printf("Verify error: %s\n",
X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
return -1;
default:
return -1;
}
}
This function takes as arguments the SSL object that represents the connection, as well as the return code from the I/O function that failed. In the event of a non-fatal failure, it waits until a retry of the I/O operation might succeed (by using the wait_for_activity() function we developed in the previous section). It returns 1 in the event of a non-fatal error (except EOF), 0 in the event of EOF, or -1 if a fatal error occurred. π§
β Creating the SSL_CTX and SSL objects β
In order to connect to a server, we must create SSL_CTX and SSL objects for this. The steps to do this are the same as for a blocking client and are explained on the ossl-guide-tls-client-block(7) page. We wonβt repeat that information here. π
π Performing the handshake π
As in the demo for a blocking TLS client, we use the SSL_connect(3) function to perform the TLS handshake with the server. Since weβre using a nonblocking socket, itβs very likely that calls to this function will fail with a non-fatal error while weβre waiting for the server to respond to our handshake messages. In such a case, we must retry the same SSL_connect(3) call at a later time. In this demo we do this in a loop:
/* Do the handshake with the server */
while ((ret = SSL_connect(ssl)) != 1) {
if (handle_io_failure(ssl, ret) == 1)
continue; /* Retry */
printf("Failed to connect to server\n");
goto end; /* Cannot retry: error */
}
So we just keep calling SSL_connect(3) over and over until it blesses us with a 1 π« and if it doesn't, handle_io_failure() β our little bestie from earlier β tells us what to do next. One thing tho: at this stage we are not expecting an EOF, so if one shows up it gets treated exactly like a fatal error. No grace, no vibes, just goto end. π
π¦ Sending and receiving data π¦
Same as the blocking TLS client demo, we're using SSL_write_ex(3) to yeet data at the server. And same as SSL_connect(3) up above, because our socket is nonblocking, this call can fail with a non-fatal error. When that happens? You retry exactly the same SSL_write_ex(3) call. Same parameters. Same pointer to the buffer, same length. Not a single byte different.
β οΈ Bestie listen to me: you must NOT try to send different data on a retry. Like, ever. There is an optional mode βSSL_MODE_ACCEPT_MOVING_WRITE_BUFFERβ that configures OpenSSL to let the buffer being written change between retries. But even then you still have to retry exactly the same data, it's just that the buffer holding that data is allowed to move. PeepSSL_CTX_set_mode(3)for the full tea. π΅
And just like in the TLS client blocking tutorial (ossl-guide-tls-client-block(7)), we write the request in three chunks:
/* Write an HTTP GET request to the peer */
while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {
if (handle_io_failure(ssl, 0) == 1)
continue; /* Retry */
printf("Failed to write start of HTTP request\n");
goto end; /* Cannot retry: error */
}
while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {
if (handle_io_failure(ssl, 0) == 1)
continue; /* Retry */
printf("Failed to write hostname in HTTP request\n");
goto end; /* Cannot retry: error */
}
while (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) {
if (handle_io_failure(ssl, 0) == 1)
continue; /* Retry */
printf("Failed to write end of HTTP request\n");
goto end; /* Cannot retry: error */
}
On a write we do not expect to see an EOF response, so that case gets handled the same way as a fatal error. Periodt. π
Reading a response back from the server is lowkey similar:
do {
/*
* Get up to sizeof(buf) bytes of the response. We keep reading until
* the server closes the connection.
*/
while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
switch (handle_io_failure(ssl, 0)) {
case 1:
continue; /* Retry */
case 0:
eof = 1;
continue;
case -1:
default:
printf("Failed reading remaining data\n");
goto end; /* Cannot retry: error */
}
}
/*
* OpenSSL does not guarantee that the returned data is a string or
* that it is NUL terminated so we use fwrite() to write the exact
* number of bytes that we read. The data could be non-printable or
* have NUL characters in the middle of it. For this simple example
* we're going to print it to stdout anyway.
*/
if (!eof)
fwrite(buf, 1, readbytes, stdout);
} while (!eof);
/* In case the response didn't finish with a newline we add one now */
printf("\n");
The big main character difference this time β¨ is that it is valid for us to receive an EOF response while trying to read data from the server. That's just what happens when the server closes down the connection after sending all the data in its response. Totally normal, no red flags. πΈ
In this demo we just print out all the data we've gotten back in the response from the server, and we keep going around the loop until we either hit a fatal error or receive an EOF (which means a graceful finish). π
π Shutting down the connection π
As in the TLS blocking example, we have to shut the connection down when we're done with it. Rude not to. π«Ά
If our application was the one initiating the shutdown, we'd expect SSL_shutdown(3) to give us a return value of 0, and then we'd keep calling it until we got a 1 back (that 1 means we successfully completed the shutdown, slay). In this particular example though, we don't expect SSL_shutdown() to return 0 β because we already received EOF from the server, which tells us it's already shut down. So we just keep calling it until SSL_shutdown() returns 1.
And since our socket is nonblocking, expect to have to retry this operation several times. π If SSL_shutdown(3) returns a negative result then we must call SSL_get_error(3) to work out what to do next β and we use our handle_io_failure() function from earlier for that:
/*
* The peer already shutdown gracefully (we know this because of the
* SSL_ERROR_ZERO_RETURN (i.e. EOF) above). We should do the same back.
*/
while ((ret = SSL_shutdown(ssl)) != 1) {
if (ret < 0 && handle_io_failure(ssl, ret) == 1)
continue; /* Retry */
/*
* ret == 0 is unexpected here because that means "we've sent a
* close_notify and we're waiting for one back". But we already know
* we got one from the peer because of the SSL_ERROR_ZERO_RETURN
* (i.e. EOF) above.
*/
printf("Error shutting down\n");
goto end; /* Cannot retry: error */
}
π§ Final clean up π§
Same as the blocking TLS client example: once we're finished with our connection we must free it. The steps for this example are identical to the blocking one, so we're not repeating them here. Go read that page, it's iconic. π
π FURTHER READING π
- Peep
ossl-guide-tls-client-block(7)for a whole tutorial on writing a blocking TLS client. - Peep
ossl-guide-quic-client-block(7)to see how to do the exact same thing but for a QUIC client. π¦
π SEE ALSO π
ossl-guide-introduction(7)ossl-guide-libraries-introduction(7)ossl-guide-libssl-introduction(7)ossl-guide-tls-introduction(7)ossl-guide-tls-client-block(7)ossl-guide-quic-client-block(7)
π COPYRIGHT π
Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at <https://www.openssl.org/source/license.html>.
β¨ and that's the whole page bestie β¨ β sourced from OpenSSL 3.5.6, dated 2026-04-0, and rewritten with love, SSL_ERROR_WANT_READ energy, and zero skipped options. mwah ππ
π¦ where this page comes from
- freebsd 15.1: base 15.1
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms