OSSL-GUIDE-T...ENT-NON-BLOCK(7ossl)
π NAME π
ossl-guide-tls-client-non-block β the OpenSSL Guide: Writing a simple nonblocking TLS client, live from the 7ossl section of the manual. Bestie, we're leveling up from the blocking era and honestly? It's giving glow-up β¨
πΈ SIMPLE NONBLOCKING TLS CLIENT EXAMPLE πΈ
Okay so this page builds on the example from ossl-guide-tls-client-block(7) β that one showed you how to write a simple blocking TLS client. Here we're amending that demo code so the socket is nonblocking. Same energy, new vibe check π
The complete source code for this example 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>.
Real talk about what "blocking" even means: a blocking socket is one that waits (blocks) until data is available to read if you attempt to read from it when there's no data yet. Same deal when writing β it waits if the socket can't write right now. Lowkey convenient, because you don't have to worry about what to do in those cases: the code just stops executing until it can continue. But in many cases you do not want this behaviour. Instead of stopping and waiting, your app might need to go do other tasks while the socket can't read/write β like updating a GUI, or doing operations on some other socket π
With a nonblocking socket, attempting to read or write to a socket that's currently unable to read or write returns immediately with a non-fatal error. And even though it's OpenSSL doing the reading/writing to the socket, this nonblocking behaviour gets propagated up to the application, so OpenSSL I/O functions like SSL_read_ex(3) or SSL_write_ex(3) will not block π«Ά
Since this whole page builds on the example from ossl-guide-tls-client-block(7), we're assuming you already know that one, and we're only explaining how this example differs.
π¦ Setting the socket to be nonblocking
First step of any nonblocking app: put the socket into nonblocking mode. A socket is blocking by default. The exact details of how to do this can differ from one platform to another β but 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 don't have to use OpenSSL's function for this, obviously. You can absolutely just 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 need work to perform when we want to read or write to the socket but currently can't. That's literally the whole point of a nonblocking socket: giving the application the chance to do something else. Whatever that something is, the app must also be prepared to come back and retry the operation it previously attempted, periodically, to see if it can now complete. Ideally it only does this when the state of the underlying socket has actually changed (e.g. it became readable where it wasn't before) β but that doesn't have to be the case. It can retry at any time.
β οΈ Bestie, this is important: you have to retry exactly the same operation you tried last time. You can't 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 can't just attempt to write some other text when you retry. Periodt.
In this demo application we create a helper function that simulates doing other work. For the sake of simplicity it actually does 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);
}
We're using the select function here because it's super simple to use and it's available on most Operating Systems. But you could use any other similar function to do the same thing, no cap. 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 use that to periodically wake up and perform work while waiting for the socket state to change. We just don't use that timeout capability in this example, for the sake of simplicity π
π Handling errors from OpenSSL I/O functions
An app that uses a nonblocking socket needs 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 (like, because the underlying connection has failed) or non-fatal (like, because we're trying to read from the underlying socket but the data hasn't arrived from the peer yet).
Here's the receipts:
SSL_read_ex(3)andSSL_write_ex(3)return0to indicate an error.SSL_read(3)andSSL_write(3)return0or a negative value to indicate an error.SSL_shutdown(3)returns a negative value to indicate an error.
When an error happens, the application should call SSL_get_error(3) to find out what type of error occurred. If the error is non-fatal and can be retried, then SSL_get_error(3) returns SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE β depending on whether OpenSSL wanted to read from or write to the socket but couldn't. And heads up π«’: 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 non-fatal error that may occur is SSL_ERROR_ZERO_RETURN. That one indicates an EOF (End-Of-File), which can happen if you attempt to read data from an SSL object but the peer has indicated it won't send any more data on it. In that case you may still want to write data to the connection β but you will not receive any more data π
The fatal errors that may occur are SSL_ERROR_SYSCALL and SSL_ERROR_SSL. These indicate the underlying connection has failed. You should not attempt to shut it down with SSL_shutdown(3). SSL_ERROR_SYSCALL means OpenSSL attempted to make a syscall that failed β consult errno for further details. SSL_ERROR_SSL means some OpenSSL error occurred β 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 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, plus 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 (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
To connect to a server we gotta create SSL_CTX and SSL objects. The steps for this are the same as for a blocking client and are explained on the ossl-guide-tls-client-block(7) page β so we're not repeating that info here, go read it, it's iconic π
β Performing the handshake
Same as in the demo for a blocking TLS client: we use the SSL_connect(3) function to perform the TLS handshake with the server. But 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 that 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 keep calling SSL_connect(3) until it gives us a success response β like, the loop literally will not let us move on until that happens. If it doesn't succeed, we use handle_io_failure() (the little helper we built earlier) to figure out what we should do next. Important vibe check: we are not expecting an EOF at this stage, so if one shows up, it gets treated in the same way as a fatal error. No cap.
Sending and receiving data π
Just like in the blocking TLS client demo, we use SSL_write_ex(3) to send data to the server. And just like with SSL_connect(3) above, because we're using a nonblocking socket, this call could fail with a non-fatal error. When that happens, we retry exactly the same SSL_write_ex(3) call again.
Bestie, the parameters must be exactly the same: same pointer to the buffer you're writing from, same length. You must not attempt to send different data on a retry. Periodt.
There is an optional mode, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, which configures OpenSSL to allow the buffer being written to change from one retry to the next. But even in that case, you must still retry exactly the same data β even though the buffer that contains that data may change location. See SSL_CTX_set_mode(3) for further details.
As 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 we treat that case in the same way as a fatal error. Do not shrug it off, bestie β it's giving fatal.
Reading a response back from the server is 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 main difference this time is that it is valid for us to receive an EOF response when trying to read data from the server. This will occur when the server closes down the connection after sending all the data in its response. Like, that's the server saying "k bye" after it's done.
In this demo we just print out all the data we've received back in the response from the server. We continue going around the loop until we either encounter a fatal error, or we receive an EOF (indicating a graceful finish). Very demure, very mindful.
Shutting down the connection π
As in the TLS blocking example, we must shutdown the connection when we are finished with it.
If our application was initiating the shutdown, then we would expect to see SSL_shutdown(3) give a return value of 0, and then we would continue to call it until we received a return value of 1 (meaning we have successfully completed the shutdown). In this particular example, we don't expect SSL_shutdown() to return 0 because we have already received EOF from the server, indicating that it has shutdown already. So we just keep calling it until SSL_shutdown() returns 1.
Since we are using a nonblocking socket, we might 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. We use our handle_io_failure() function that we developed earlier for this:
/*
* 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 π§Ή
As with the blocking TLS client example, once our connection is finished with, we must free it. The steps to do this for this example are the same as for the blocking example, so we won't repeat it here.
FURTHER READING π
See ossl-guide-tls-client-block(7) to read a tutorial on how to write a blocking TLS client. See ossl-guide-quic-client-block(7) to see how to do the same thing 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>.
That's the whole nonblocking TLS client glow-up, bestie. Source/version: OpenSSL 3.5.0 Β· date: 2026-09-2. Go off and make those sockets slay π
β¨
π¦ where this page comes from
- opensuse-leap 16.0: openssl-3 3.5.0-160000.11.1 Β· Apache-2.0
- opensuse-leap 16.0: openssl-3 3.5.0-160000.11.1 Β· Apache-2.0
- opensuse-leap 16.0: openssl-3 3.5.0-160000.11.1 Β· Apache-2.0
- opensuse-leap 16.0: openssl-3 3.5.0-160000.11.1 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms