Skip to content

Commit

Permalink
Try setting the socket to be blocking
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Dec 4, 2024
1 parent 0e1d9c2 commit 44df03b
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions p2p/transport/tcpreuse/internal/sampledconn/sampledconn_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,45 @@ import (
"errors"
"io"
"syscall"
"unsafe"

"golang.org/x/sys/windows"
)

const fionbio = 0x8004667e

// updateBlocking updates the blocking mode of the file descriptor.
// It returns true if the blocking mode was changed, and false if it was already in the desired mode.
// If an error occurs, it returns the error.
func updateBlocking(fd windows.Handle, blocking bool) (bool, error) {
// Determine the desired mode
var desiredMode uint32
if !blocking {
desiredMode = 1
} else {
desiredMode = 0
}

// Query the current mode
var currentMode uint32
err := windows.WSAIoctl(fd, fionbio, (*byte)(unsafe.Pointer(&currentMode)), 4, nil, 0, nil, nil, 0)
if err != nil {
return false, err
}

if currentMode == desiredMode {
return false, nil
}

// Update to the desired mode
err = windows.WSAIoctl(fd, fionbio, (*byte)(unsafe.Pointer(&desiredMode)), 4, nil, 0, nil, nil, 0)
if err != nil {
return false, err
}

return true, nil
}

func OSPeekConn(conn syscall.Conn) (PeekedBytes, error) {
s := PeekedBytes{}

Expand All @@ -18,6 +53,24 @@ func OSPeekConn(conn syscall.Conn) (PeekedBytes, error) {
return s, err
}

var updatedBlocking bool
ctlErr := rawConn.Control(func(fd uintptr) {
updatedBlocking, err = updateBlocking(windows.Handle(fd), true)
})
if ctlErr != nil {
return s, ctlErr
}
if err != nil {
return s, err
}
if updatedBlocking {
defer func() {
_ = rawConn.Control(func(fd uintptr) {
_, _ = updateBlocking(windows.Handle(fd), false)
})
}()
}

var readErr error
var n uint32
err = rawConn.Read(func(fd uintptr) bool {
Expand Down

0 comments on commit 44df03b

Please sign in to comment.