net: Introduce red_socket_set_keepalive() helper

This allows to move some low-level code out of reds.c

Signed-off-by: Christophe Fergeau <cfergeau@redhat.com>
Acked-by: Frediano Ziglio <fziglio@redhat.com>
This commit is contained in:
Christophe Fergeau 2017-03-16 16:02:09 +01:00
parent b85ca4b8a9
commit 5ca3d6ca50
3 changed files with 34 additions and 24 deletions

View File

@ -31,6 +31,38 @@
#include "net-utils.h"
/**
* red_socket_set_keepalive:
* @fd: a socket file descriptor
* @keepalive: whether to enable keepalives on @fd
*
* Returns: #true if the operation succeeded, #false otherwise.
*/
bool red_socket_set_keepalive(int fd, bool enable, int timeout)
{
int keepalive = !!enable;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)) == -1) {
if (errno != ENOTSUP) {
spice_printerr("setsockopt for keepalive failed, %s", strerror(errno));
return false;
}
}
if (!enable) {
return true;
}
if (setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &timeout, sizeof(timeout)) == -1) {
if (errno != ENOTSUP) {
spice_printerr("setsockopt for keepalive timeout failed, %s", strerror(errno));
return false;
}
}
return true;
}
/**
* red_socket_set_no_delay:
* @fd: a socket file descriptor

View File

@ -20,6 +20,7 @@
#include <stdbool.h>
bool red_socket_set_keepalive(int fd, bool enable, int timeout);
bool red_socket_set_no_delay(int fd, bool no_delay);
bool red_socket_set_non_blocking(int fd, bool non_blocking);

View File

@ -2378,29 +2378,6 @@ static void reds_handle_ssl_accept(int fd, int event, void *data)
#define KEEPALIVE_TIMEOUT (10*60)
static bool reds_init_keepalive(int socket)
{
int keepalive = 1;
int keepalive_timeout = KEEPALIVE_TIMEOUT;
if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)) == -1) {
if (errno != ENOTSUP) {
spice_printerr("setsockopt for keepalive failed, %s", strerror(errno));
return false;
}
}
if (setsockopt(socket, SOL_TCP, TCP_KEEPIDLE,
&keepalive_timeout, sizeof(keepalive_timeout)) == -1) {
if (errno != ENOTSUP) {
spice_printerr("setsockopt for keepalive timeout failed, %s", strerror(errno));
return false;
}
}
return true;
}
static RedLinkInfo *reds_init_client_connection(RedsState *reds, int socket)
{
RedLinkInfo *link;
@ -2413,7 +2390,7 @@ static RedLinkInfo *reds_init_client_connection(RedsState *reds, int socket)
goto error;
}
reds_init_keepalive(socket);
red_socket_set_keepalive(socket, TRUE, KEEPALIVE_TIMEOUT);
link = spice_new0(RedLinkInfo, 1);
link->reds = reds;