Skip to content

Commit 2964360

Browse files
committed
ssh: add func DialContext
DialContext starts a client connection to the given SSH server using the supplied Context. The supplied Context affects the dial and handshake. If it expires after the connection is opened, it has no effect on the resulting Client.
1 parent 4e5a261 commit 2964360

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

ssh/client.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package ssh
66

77
import (
88
"bytes"
9+
"context"
910
"errors"
1011
"fmt"
1112
"net"
@@ -168,6 +169,50 @@ func (c *Client) handleChannelOpens(in <-chan NewChannel) {
168169
c.mu.Unlock()
169170
}
170171

172+
// DialContext starts a client connection to the given SSH server. It is a
173+
// convenience function that connects to the given network address,
174+
// initiates the SSH handshake, and then sets up a Client.
175+
//
176+
// The provided Context must be non-nil. If the context expires before the
177+
// connection is complete, an error is returned. Once successfully connected,
178+
// any expiration of the context will not affect the connection.
179+
//
180+
// See [Dial] for additional information.
181+
func DialContext(ctx context.Context, network, addr string, config *ClientConfig) (*Client, error) {
182+
d := net.Dialer{
183+
Timeout: config.Timeout,
184+
}
185+
conn, err := d.DialContext(ctx, network, addr)
186+
if err != nil {
187+
return nil, err
188+
}
189+
type result struct {
190+
client *Client
191+
err error
192+
}
193+
ch := make(chan result)
194+
go func() {
195+
var client *Client
196+
c, chans, reqs, err := NewClientConn(conn, addr, config)
197+
if err == nil {
198+
client = NewClient(c, chans, reqs)
199+
}
200+
select {
201+
case ch <- result{client, err}:
202+
case <-ctx.Done():
203+
if client != nil {
204+
client.Close()
205+
}
206+
}
207+
}()
208+
select {
209+
case res := <-ch:
210+
return res.client, res.err
211+
case <-ctx.Done():
212+
return nil, context.Cause(ctx)
213+
}
214+
}
215+
171216
// Dial starts a client connection to the given SSH server. It is a
172217
// convenience function that connects to the given network address,
173218
// initiates the SSH handshake, and then sets up a Client. For access

0 commit comments

Comments
 (0)