Skip to content

Commit

Permalink
fix(measurexlite): add robust RemoteAddr accessors (#1551)
Browse files Browse the repository at this point in the history
  • Loading branch information
bassosimone committed Apr 12, 2024
1 parent a3f04af commit 81169f0
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 4 deletions.
26 changes: 22 additions & 4 deletions internal/measurexlite/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,29 @@ type connTrace struct {

var _ net.Conn = &connTrace{}

type remoteAddrProvider interface {
RemoteAddr() net.Addr
}

func safeRemoteAddrNetwork(rap remoteAddrProvider) (result string) {
if addr := rap.RemoteAddr(); addr != nil {
result = addr.Network()
}
return result
}

func safeRemoteAddrString(rap remoteAddrProvider) (result string) {
if addr := rap.RemoteAddr(); addr != nil {
result = addr.String()
}
return result
}

// Read implements net.Conn.Read and saves network events.
func (c *connTrace) Read(b []byte) (int, error) {
// collect preliminary stats when the connection is surely active
network := c.RemoteAddr().Network()
addr := c.RemoteAddr().String()
network := safeRemoteAddrNetwork(c)
addr := safeRemoteAddrString(c)
started := c.tx.TimeSince(c.tx.ZeroTime())

// perform the underlying network operation
Expand Down Expand Up @@ -99,8 +117,8 @@ func (tx *Trace) CloneBytesReceivedMap() (out map[string]int64) {

// Write implements net.Conn.Write and saves network events.
func (c *connTrace) Write(b []byte) (int, error) {
network := c.RemoteAddr().Network()
addr := c.RemoteAddr().String()
network := safeRemoteAddrNetwork(c)
addr := safeRemoteAddrString(c)
started := c.tx.TimeSince(c.tx.ZeroTime())

count, err := c.Conn.Write(b)
Expand Down
37 changes: 37 additions & 0 deletions internal/measurexlite/conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,43 @@ import (
"github.com/ooni/probe-cli/v3/internal/testingx"
)

func TestRemoteAddrProvider(t *testing.T) {
t.Run("for nil address", func(t *testing.T) {
conn := &mocks.Conn{
MockRemoteAddr: func() net.Addr {
return nil
},
}
if safeRemoteAddrNetwork(conn) != "" {
t.Fatal("expected empty network")
}
if safeRemoteAddrString(conn) != "" {
t.Fatal("expected empty string")
}
})

t.Run("for common case", func(t *testing.T) {
conn := &mocks.Conn{
MockRemoteAddr: func() net.Addr {
return &mocks.Addr{
MockString: func() string {
return "1.1.1.1:443"
},
MockNetwork: func() string {
return "tcp"
},
}
},
}
if safeRemoteAddrNetwork(conn) != "tcp" {
t.Fatal("unexpected network")
}
if safeRemoteAddrString(conn) != "1.1.1.1:443" {
t.Fatal("unexpected string")
}
})
}

func TestMaybeClose(t *testing.T) {
t.Run("with nil conn", func(t *testing.T) {
var conn net.Conn = nil
Expand Down

0 comments on commit 81169f0

Please sign in to comment.