Skip to content

Commit

Permalink
Add timeouts to syscall retries
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxMaeder committed Dec 13, 2024
1 parent d50cc6f commit 6da8a23
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions internal/socket_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,20 +130,27 @@ func connect(fd int, remoteAddr net.Addr, timeout time.Duration, opts ...sonicop
return err
}

startTime := time.Now()

for {
// Prevent an infinite connect() loop, time out eventually
if time.Since(startTime) > 5 * timeout {
return sonicerrors.ErrTimeout
}

// Try to connect, if it succeeds we're done!
err := syscall.Connect(fd, ToSockaddr(remoteAddr))
if err == nil {
return nil
}

// Retry the connect syscall if interrupted
if err == syscall.EINTR {
if errors.Is(err, syscall.EINTR) {
continue
}

// Handle errors
if err != syscall.EINPROGRESS && err != syscall.EAGAIN {
if !errors.Is(err, syscall.EINPROGRESS) && !errors.Is(err, syscall.EAGAIN) {
return os.NewSyscallError("connect", err)
}

Expand All @@ -158,8 +165,14 @@ func connect(fd int, remoteAddr net.Addr, timeout time.Duration, opts ...sonicop
fds.Set(fd)

t := unix.NsecToTimeval(timeout.Nanoseconds())
startTime = time.Now()

for {
// Prevent an infinite select() loop, time out eventually
if time.Since(startTime) > 5 * timeout {
return sonicerrors.ErrTimeout
}

n, err := unix.Select(fd+1, nil, &fds, nil, &t)
if err == nil {
// Handle timeout
Expand All @@ -172,7 +185,7 @@ func connect(fd int, remoteAddr net.Addr, timeout time.Duration, opts ...sonicop
}

// Handle errors
if err != syscall.EINTR {
if !errors.Is(err, syscall.EINTR) {
return os.NewSyscallError("select", err)
}

Expand Down

0 comments on commit 6da8a23

Please sign in to comment.