Skip to content

Commit e47a858

Browse files
Eric Wonggitster
authored andcommitted
enable SO_KEEPALIVE for connected TCP sockets
Sockets may never receive notification of some link errors, causing "git fetch" or similar processes to hang forever. Enabling keepalive messages allows hung processes to error out after a few minutes/hours depending on the keepalive settings of the system. This is a problem noticed when running non-interactive cronjobs to mirror repositories using "git fetch". Signed-off-by: Eric Wong <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent c2857fb commit e47a858

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

connect.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,15 @@ static void get_host_and_port(char **host, const char **port)
175175
}
176176
}
177177

178+
static void enable_keepalive(int sockfd)
179+
{
180+
int ka = 1;
181+
182+
if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
183+
fprintf(stderr, "unable to set SO_KEEPALIVE on socket: %s\n",
184+
strerror(errno));
185+
}
186+
178187
#ifndef NO_IPV6
179188

180189
static const char *ai_name(const struct addrinfo *ai)
@@ -239,6 +248,8 @@ static int git_tcp_connect_sock(char *host, int flags)
239248
if (sockfd < 0)
240249
die("unable to connect to %s:\n%s", host, error_message.buf);
241250

251+
enable_keepalive(sockfd);
252+
242253
if (flags & CONNECT_VERBOSE)
243254
fprintf(stderr, "done.\n");
244255

@@ -315,6 +326,8 @@ static int git_tcp_connect_sock(char *host, int flags)
315326
if (sockfd < 0)
316327
die("unable to connect a socket (%s)", strerror(saved_errno));
317328

329+
enable_keepalive(sockfd);
330+
318331
if (flags & CONNECT_VERBOSE)
319332
fprintf(stderr, "done.\n");
320333

0 commit comments

Comments
 (0)