From 7bd5eb7a1f260d504b8235968dc793abb6b023eb Mon Sep 17 00:00:00 2001 From: Nate Straz Date: Thu, 3 Jan 2008 14:35:45 +0000 Subject: Switch to using a select with a timeout instead of a loop of recvfroms and sleeps in btime(). This makes it easier to tune how long to wait for a heartbeat. Now I can get heartbeats over my vpn connection. --- btime.c | 36 +++++++++++++++++++++--------------- btime_int.h | 1 - 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/btime.c b/btime.c index 4b4c474..6bd36c0 100644 --- a/btime.c +++ b/btime.c @@ -59,6 +59,8 @@ btime(const char *host) unsigned int btime = 0; ssize_t nbytes; int retry; + fd_set sdset; + struct timeval timeout; if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { fprintf(stderr, "Could not create socket: %s\n", @@ -107,24 +109,26 @@ btime(const char *host) } } + FD_ZERO(&sdset); + FD_SET(sd, &sdset); + do { + retry = 0; - memset(&resp_addr, 0, sizeof resp_addr); - memset(response, 0, BTIME_MSGLEN); - for (retry = 0; retry < MAX_RETRY; retry++) { - resp_addr_len = sizeof resp_addr; - if ((nbytes = recvfrom(sd, &response, BTIME_MSGLEN, MSG_DONTWAIT, - (struct sockaddr *)&resp_addr, &resp_addr_len)) < 0) { - if (errno == EAGAIN) { - usleep(RETRY_SLEEP); - continue; - } else { - /* Non EAGAIN error... */ - break; - } + timeout.tv_sec = 0; + timeout.tv_usec = 250000; + + if (select(sd + 1, &sdset, NULL, NULL, &timeout) != 1) { + /* Either an error or a timeout, we don't need to retry */ + break; } + memset(&resp_addr, 0, sizeof resp_addr); + memset(response, 0, BTIME_MSGLEN); + resp_addr_len = sizeof resp_addr; + nbytes = recvfrom(sd, &response, BTIME_MSGLEN, MSG_DONTWAIT, + (struct sockaddr *)&resp_addr, &resp_addr_len); if (nbytes == 0) { - /* Nothing received, try again */ + /* Nothing received */ continue; } else if (response[0] == 'B' && response[1] == 'T') { /* Check for new style cookie */ @@ -133,6 +137,7 @@ btime(const char *host) break; } else { /* ignore the invalid btime cookie */ + retry = 1; continue; } } else if (!same_addr(&serv_addr, &resp_addr)) { @@ -143,13 +148,14 @@ btime(const char *host) rstr, sstr); free(rstr); free(sstr); + retry = 1; continue; } else { /* If peer matches, accept the bare btime */ btime = strtoul(response, (char **)NULL, 10); break; } - } + } while (retry); close(sd); diff --git a/btime_int.h b/btime_int.h index b4d34ba..6872fce 100644 --- a/btime_int.h +++ b/btime_int.h @@ -26,7 +26,6 @@ #define BTIME_PORT 23456 #define BTIME_MSGLEN 128 #define MAX_RETRY 40 -#define RETRY_SLEEP 1000 #define COOKIE_RANDOM_PARTS 4 #define COOKIE_LEN (3 + (COOKIE_RANDOM_PARTS * sizeof(int32_t))) -- cgit