Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add DialTimeout and cleanup ResolveEndpoint #372

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,9 @@ func (c *Client) Dial(ctx context.Context) error {
ctx = context.Background()
}

ctx, cancel := context.WithTimeout(ctx, c.cfg.DialTimeout)
defer cancel()

c.once.Do(func() { c.session.Store((*Session)(nil)) })
if c.sechan != nil {
return errors.Errorf("secure channel already connected")
Expand Down
8 changes: 8 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func DefaultClientConfig() *uasc.Config {
SecurityMode: ua.MessageSecurityModeNone,
Lifetime: uint32(time.Hour / time.Millisecond),
RequestTimeout: 10 * time.Second,
DialTimeout: 10 * time.Second,
}
}

Expand Down Expand Up @@ -416,3 +417,10 @@ func RequestTimeout(t time.Duration) Option {
c.RequestTimeout = t
}
}

// DialTimeout sets the timeout for name resolution and establishment of a network connection
func DialTimeout(t time.Duration) Option {
return func(c *uasc.Config, sc *uasc.SessionConfig) {
c.DialTimeout = t
}
}
2 changes: 1 addition & 1 deletion examples/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func main() {
ctx := context.Background()

log.Printf("Listening on %s", *endpoint)
l, err := uacp.Listen(*endpoint, nil)
l, err := uacp.Listen(ctx, *endpoint, nil)
if err != nil {
log.Fatal(err)
}
Expand Down
19 changes: 13 additions & 6 deletions uacp/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"net"
"sync/atomic"
"time"

"github.com/gopcua/opcua/debug"
"github.com/gopcua/opcua/errors"
Expand All @@ -23,6 +24,7 @@ const (
DefaultSendBufSize = 0xffff
DefaultMaxChunkCount = 512
DefaultMaxMessageSize = 2 * MB
DefaultDialTimeout = time.Second * 10
)

// connid stores the current connection id. updated with atomic.AddUint32
Expand All @@ -35,12 +37,15 @@ func nextid() uint32 {

func Dial(ctx context.Context, endpoint string) (*Conn, error) {
debug.Printf("Connect to %s", endpoint)
_, raddr, err := ResolveEndpoint(endpoint)

_, raddr, err := ResolveEndpoint(ctx, endpoint)
if err != nil {
return nil, err
}

var dialer net.Dialer
c, err := dialer.DialContext(ctx, "tcp", raddr.String())

c, err := dialer.DialContext(ctx, "tcp", raddr.Host)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -79,7 +84,7 @@ type Listener struct {
// If the IP field of laddr is nil or an unspecified IP address, Listen listens
// on all available unicast and anycast IP addresses of the local system.
// If the Port field of laddr is 0, a port number is automatically chosen.
func Listen(endpoint string, ack *Acknowledge) (*Listener, error) {
func Listen(ctx context.Context, endpoint string, ack *Acknowledge) (*Listener, error) {
if ack == nil {
ack = &Acknowledge{
ReceiveBufSize: DefaultReceiveBufSize,
Expand All @@ -89,16 +94,18 @@ func Listen(endpoint string, ack *Acknowledge) (*Listener, error) {
}
}

network, laddr, err := ResolveEndpoint(endpoint)
_, laddr, err := ResolveEndpoint(ctx, endpoint)
if err != nil {
return nil, err
}
l, err := net.ListenTCP(network, laddr)

var lc net.ListenConfig
l, err := lc.Listen(ctx, "tcp", laddr.Host)
if err != nil {
return nil, err
}
return &Listener{
l: l,
l: l.(*net.TCPListener),
ack: ack,
endpoint: endpoint,
}, nil
Expand Down
6 changes: 3 additions & 3 deletions uacp/conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
func TestConn(t *testing.T) {
t.Run("server exists ", func(t *testing.T) {
ep := "opc.tcp://127.0.0.1:4840/foo/bar"
ln, err := Listen(ep, nil)
ln, err := Listen(context.Background(), ep, nil)
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -64,7 +64,7 @@ func TestConn(t *testing.T) {

func TestClientWrite(t *testing.T) {
ep := "opc.tcp://127.0.0.1:4840/foo/bar"
ln, err := Listen(ep, nil)
ln, err := Listen(context.Background(), ep, nil)
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -127,7 +127,7 @@ NEXT:

func TestServerWrite(t *testing.T) {
ep := "opc.tcp://127.0.0.1:4840/foo/bar"
ln, err := Listen(ep, nil)
ln, err := Listen(context.Background(), ep, nil)
if err != nil {
t.Fatal(err)
}
Expand Down
44 changes: 31 additions & 13 deletions uacp/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,49 @@
package uacp

import (
"context"
"net"
"strings"
"net/url"

"github.com/gopcua/opcua/errors"
)

// ResolveEndpoint returns network type, address, and error splitted from EndpointURL.
const defaultPort = "4840"

// ResolveEndpoint returns network type, address, and error split from EndpointURL.
//
// Expected format of input is "opc.tcp://<addr[:port]/path/to/somewhere"
func ResolveEndpoint(endpoint string) (network string, addr *net.TCPAddr, err error) {
elems := strings.Split(endpoint, "/")
if elems[0] != "opc.tcp:" {
return "", nil, errors.Errorf("invalid endpoint %s", endpoint)
func ResolveEndpoint(ctx context.Context, endpoint string) (network string, u *url.URL, err error) {
u, err = url.Parse(endpoint)
if err != nil {
return
}

addrString := elems[2]
if !strings.Contains(addrString, ":") {
addrString += ":4840"
if u.Scheme != "opc.tcp" {
err = errors.Errorf("unsupported scheme %s", u.Scheme)
return
}

network = "tcp"
addr, err = net.ResolveTCPAddr(network, addrString)
switch err.(type) {
case *net.DNSError:
return "", nil, errors.Errorf("could not resolve address %s", addrString)

port := u.Port()
if port == "" {
port = defaultPort
}

var resolver net.Resolver

addrs, err := resolver.LookupIPAddr(ctx, u.Hostname())
if err != nil {
return
}

if len(addrs) == 0 {
err = errors.Errorf("could not resolve address %s", u.Hostname())
return
}

u.Host = net.JoinHostPort(addrs[0].String(), port)

return
}
54 changes: 30 additions & 24 deletions uacp/endpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,72 +5,78 @@
package uacp

import (
"net"
"context"
"net/url"
"testing"
)

func TestResolveEndpoint(t *testing.T) {
cases := []struct {
input string
network string
addr *net.TCPAddr
u *url.URL
errStr string
}{
{ // Valid, full EndpointURL
"opc.tcp://10.0.0.1:4840/foo/bar",
"tcp",
&net.TCPAddr{
IP: net.IP([]byte{0x0a, 0x00, 0x00, 0x01}),
Port: 4840,
&url.URL{
Scheme: "opc.tcp",
Host: "10.0.0.1:4840",
Path: "/foo/bar",
},
"",
},
{ // Valid, port number omitted
"opc.tcp://10.0.0.1/foo/bar",
"tcp",
&net.TCPAddr{
IP: net.IP([]byte{0x0a, 0x00, 0x00, 0x01}),
Port: 4840,
&url.URL{
Scheme: "opc.tcp",
Host: "10.0.0.1:4840",
Path: "/foo/bar",
},
"",
},
{ // Valid, hostname resolved
"opc.tcp://localhost:4840/foo/bar",
// note: xip.io is hosted by Basecamp (see: https://github.com/basecamp/xip-pdns)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is awesome. I never knew.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose this should be in an integration test rather than a normal unit test since it requires a mostly working network stack. 🤷

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

xip is dead. long live https://sslip.io/

"opc.tcp://www.1.1.1.1.xip.io:4840/foo/bar",
"tcp",
&net.TCPAddr{
IP: net.IP([]byte{0x7f, 0x00, 0x00, 0x01}),
Port: 4840,
&url.URL{
Scheme: "opc.tcp",
Host: "1.1.1.1:4840",
Path: "/foo/bar",
},
"",
},
{ // Invalid, schema is not "opc.tcp://"
"tcp://10.0.0.1:4840/foo/bar",
"",
nil,
"opcua: invalid endpoint tcp://10.0.0.1:4840/foo/bar",
"opcua: unsupported scheme tcp",
},
{ // Invalid, bad formatted schema
"opc.tcp:/10.0.0.1:4840/foo1337bar/baz",
"",
nil,
"opcua: could not resolve address foo1337bar:4840",
"lookup : no such host",
},
}

for _, c := range cases {
var errStr string
network, addr, err := ResolveEndpoint(c.input)
network, u, err := ResolveEndpoint(context.Background(), c.input)
if err != nil {
errStr = err.Error()
}
if got, want := network, c.network; got != want {
t.Fatalf("got network %q want %q", got, want)
}
if got, want := addr.String(), c.addr.String(); got != want {
t.Fatalf("got addr %q want %q", got, want)
}
if got, want := errStr, c.errStr; got != want {
t.Fatalf("got error %q want %q", got, want)
if got, want := errStr, c.errStr; got != want {
t.Fatalf("got error %q want %q", got, want)
}
} else {
if got, want := network, c.network; got != want {
t.Fatalf("got network %q want %q", got, want)
}
if got, want := u.String(), c.u.String(); got != want {
t.Fatalf("got addr %q want %q", got, want)
}
}
}
}
3 changes: 3 additions & 0 deletions uasc/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ type Config struct {
// RequestTimeout is timeout duration for all synchronous requests over SecureChannel.
// If the Server doesn't respond within RequestTimeout time, Client returns StatusBadTimeout
RequestTimeout time.Duration

// DialTimeout is the timeout for name resolution and establishment of a network connection
DialTimeout time.Duration
}

// SessionConfig is a set of common configurations used in Session.
Expand Down