Skip to content

Commit

Permalink
fix, socket bind should be only used in passive mode, and don't close…
Browse files Browse the repository at this point in the history
… fd for EINPROGRESS error when connecting
  • Loading branch information
cscps committed May 22, 2022
1 parent 73d9480 commit 483cff9
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
11 changes: 7 additions & 4 deletions internal/socket/tcp_socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ func tcpSocket(proto, addr string, passive bool, sockOpts ...Option) (fd int, ne
return
}
defer func() {
// ignore EINPROGRESS for non-blocking socket connect, should be processed by caller
if t, ok := err.(*os.SyscallError); ok && t.Err == unix.EINPROGRESS {
return
}
if err != nil {
_ = unix.Close(fd)
}
Expand All @@ -140,11 +144,10 @@ func tcpSocket(proto, addr string, passive bool, sockOpts ...Option) (fd int, ne
}
}

if err = os.NewSyscallError("bind", unix.Bind(fd, sa)); err != nil {
return
}

if passive {
if err = os.NewSyscallError("bind", unix.Bind(fd, sa)); err != nil {
return
}
// Set backlog size to the maximum.
err = os.NewSyscallError("listen", unix.Listen(fd, listenerBacklogMaxSize))
} else {
Expand Down
8 changes: 6 additions & 2 deletions internal/socket/udp_socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ func udpSocket(proto, addr string, connect bool, sockOpts ...Option) (fd int, ne
return
}
defer func() {
// ignore EINPROGRESS for non-blocking socket connect, should be processed by caller
if t, ok := err.(*os.SyscallError); ok && t.Err == unix.EINPROGRESS {
return
}
if err != nil {
_ = unix.Close(fd)
}
Expand All @@ -143,10 +147,10 @@ func udpSocket(proto, addr string, connect bool, sockOpts ...Option) (fd int, ne
}
}

err = os.NewSyscallError("bind", unix.Bind(fd, sa))

if connect {
err = os.NewSyscallError("connect", unix.Connect(fd, sa))
} else {
err = os.NewSyscallError("bind", unix.Bind(fd, sa))
}

return
Expand Down
5 changes: 5 additions & 0 deletions internal/socket/unix_socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ func udsSocket(proto, addr string, passive bool, sockOpts ...Option) (fd int, ne
return
}
defer func() {
// ignore EINPROGRESS for non-blocking socket connect, should be processed by caller
// though there is less situation for EINPROGRESS when using unix socket
if t, ok := err.(*os.SyscallError); ok && t.Err == unix.EINPROGRESS {
return
}
if err != nil {
_ = unix.Close(fd)
}
Expand Down

0 comments on commit 483cff9

Please # to comment.