If SSL_write returns a negative value, you may need to handle the error accordingly, which could involve retrying the write after a read if SSL_ERROR_WANT_READ is returned, or retrying the write if SSL_ERROR_WANT_WRITE is returned.
To make a socket non-blocking when working with OpenSSL, you need to directly set the non-blocking property on the underlying socket file descriptor before using it with the OpenSSL I/O functions. You can do this by using standard POSIX system calls. Here's a general example of how you might set a socket to non-blocking in a POSIX-compliant system:
#include <fcntl.h>
#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
int make_socket_non_blocking(int sockfd) {
int flags, s;
// Get current flags for the socket
flags = fcntl(sockfd, F_GETFL, 0);
if (flags == -1)
{
perror("fcntl");
return -1;
}
// Update the flags with non-blocking mode (O_NONBLOCK)
flags |= O_NONBLOCK;
s = fcntl(sockfd, F_SETFL, flags);
if (s == -1)
{
perror("fcntl");
return -1;
}
return 0; // Success
}
// Use this function on your socket before SSL operations
After calling this function on a socket file descriptor, any I/O operations on the socket will be non-blocking. This means that functions like SSL_read, SSL_write, accept, connect, read, and write will return immediately if they would block waiting for data to be sent or received.
When working with non-blocking I/O and OpenSSL, you’ll have to handle the cases where SSL_read or SSL_write return due to a SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE error. These errors indicate that the operation could not proceed because the socket would block, and you should try the operation again later.
Here's an example of how to use SSL_write in a non-blocking manner:
int ssl_nonblocking_write(SSL *ssl, const void *buf, int num) {
int ret;
do {
ret = SSL_write(ssl, buf, num);
if (ret <= 0) {
// Non-blocking operation could not proceed
int err = SSL_get_error(ssl, ret);
switch (err) {
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
// Operation should be retried later
break;
default:
// Handle other errors
return -1;
}
}
} while (ret <= 0 && (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE));
return ret; // Bytes successfully written
}
Keep in mind that this is a simple example and that proper error handling and the logic to retry the operation (perhaps using select, poll, or epoll mechanisms) should be included for a production-level application.