File: client.go

package info (click to toggle)
golang-github-microsoft-dev-tunnels 0.0.25-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,988 kB
  • sloc: cs: 9,969; java: 2,767; javascript: 328; xml: 186; makefile: 5
file content (310 lines) | stat: -rw-r--r-- 8,904 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

package tunnels

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"strings"

	"net/http"

	tunnelssh "github.com/microsoft/dev-tunnels/go/tunnels/ssh"
	"github.com/microsoft/dev-tunnels/go/tunnels/ssh/messages"
	"golang.org/x/crypto/ssh"
)

const (
	clientWebSocketSubProtocol = "tunnel-relay-client"
)

// Client is a client for a tunnel. It is used to connect to a tunnel.
type Client struct {
	logger *log.Logger

	hostID    string
	tunnel    *Tunnel
	endpoints []TunnelEndpoint

	ssh                  *tunnelssh.ClientSSHSession
	remoteForwardedPorts *remoteForwardedPorts

	acceptLocalConnectionsForForwardedPorts bool
}

var (
	// ErrNoTunnel is returned when no tunnel is provided.
	ErrNoTunnel = errors.New("tunnel cannot be nil")

	// ErrNoTunnelEndpoints is returned when no tunnel endpoints are provided.
	ErrNoTunnelEndpoints = errors.New("tunnel endpoints cannot be nil or empty")

	// ErrNoConnections is returned when no tunnel endpoints are provided for the given host ID.
	ErrNoConnections = errors.New("the specified host is not currently accepting connections to the tunnel")

	// ErrMultipleHosts is returned when multiple tunnel endpoints for different hosts are provided.
	ErrMultipleHosts = errors.New("there are multiple hosts for the tunnel, specify the host ID to connect to")

	// ErrNoRelayConnections is returned when no relay connections are available.
	ErrNoRelayConnections = errors.New("the host is not currently accepting tunnel relay connections")

	// ErrSSHConnectionClosed is returned when the ssh connection is closed.
	ErrSSHConnectionClosed = errors.New("the ssh connection is closed")

	// ErrPortNotForwarded is returned when the specified port is not forwarded.
	ErrPortNotForwarded = errors.New("the port is not forwarded")
)

// Connect connects to a tunnel and returns a connected client.
func NewClient(logger *log.Logger, tunnel *Tunnel, acceptLocalConnectionsForForwardedPorts bool) (*Client, error) {
	if tunnel == nil {
		return nil, ErrNoTunnel
	}

	if len(tunnel.Endpoints) == 0 {
		return nil, ErrNoTunnelEndpoints
	}

	c := &Client{
		logger:                                  logger,
		tunnel:                                  tunnel,
		endpoints:                               tunnel.Endpoints,
		remoteForwardedPorts:                    newRemoteForwardedPorts(),
		acceptLocalConnectionsForForwardedPorts: acceptLocalConnectionsForForwardedPorts,
	}
	return c, nil
}

func (c *Client) Connect(ctx context.Context, hostID string) error {
	endpointGroups := make(map[string][]TunnelEndpoint)
	for _, endpoint := range c.tunnel.Endpoints {
		endpointGroups[endpoint.HostID] = append(endpointGroups[endpoint.HostID], endpoint)
	}

	var endpointGroup []TunnelEndpoint
	c.hostID = hostID
	if hostID != "" {
		g, ok := endpointGroups[hostID]
		if !ok {
			return ErrNoConnections
		}
		endpointGroup = g
	} else if len(endpointGroups) > 1 {
		return ErrMultipleHosts
	} else {
		endpointGroup = endpointGroups[c.tunnel.Endpoints[0].HostID]
	}

	if len(c.endpoints) != 1 {
		return ErrNoRelayConnections
	}
	tunnelEndpoint := endpointGroup[0]
	clientRelayURI := tunnelEndpoint.ClientRelayURI

	accessToken := c.tunnel.AccessTokens[TunnelAccessScopeConnect]

	c.logger.Printf(fmt.Sprintf("Connecting to client tunnel relay %s", clientRelayURI))
	c.logger.Printf(fmt.Sprintf("Sec-Websocket-Protocol: %s", clientWebSocketSubProtocol))
	protocols := []string{clientWebSocketSubProtocol}

	var headers http.Header
	if accessToken != "" {
		headers = make(http.Header)
		if !strings.Contains(accessToken, "Tunnel") && !strings.Contains(accessToken, "tunnel") {
			accessToken = fmt.Sprintf("Tunnel %s", accessToken)
		}
		headers.Add("Authorization", accessToken)
		c.logger.Printf(fmt.Sprintf("Authorization: %s", accessToken))

	}

	sock := newSocket(clientRelayURI, protocols, headers, nil)
	if err := sock.connect(ctx); err != nil {
		return fmt.Errorf("failed to connect to client relay: %w", err)
	}

	c.ssh = tunnelssh.NewClientSSHSession(sock, c.remoteForwardedPorts, c.acceptLocalConnectionsForForwardedPorts, c.logger)
	if err := c.ssh.Connect(ctx); err != nil {
		return fmt.Errorf("failed to create ssh session: %w", err)
	}

	return nil
}

// ConnectListenerToForwardedPort opens a stream to a remote port and connects it to a given listener.
//
// Ensure that the port is already forwarded before calling this function
// by calling WaitForForwardedPort. Otherwise, this will return an error.
//
// Set acceptLocalConnectionsForForwardedPorts to false when creating the client to ensure
// TCP listeners are not created for all ports automatically when the client connects.
func (c *Client) ConnectListenerToForwardedPort(ctx context.Context, listenerIn net.Listener, port uint16) error {
	errc := make(chan error, 1)
	go func() {
		for {
			conn, err := listenerIn.Accept()
			if err != nil {
				sendError(err, errc)
				return
			}

			go func() {
				if err := c.ConnectToForwardedPort(ctx, conn, port); err != nil {
					sendError(err, errc)
				}
			}()
		}
	}()

	return awaitError(ctx, errc)
}

// ConnectToForwardedPort opens a stream to a remote port and connects it to a given connection.
//
// Ensure that the port is already forwarded before calling this function
// by calling WaitForForwardedPort. Otherwise, this will return an error.
//
// Set acceptLocalConnectionsForForwardedPorts to false when creating the client to ensure
// TCP listeners are not created for all ports automatically when the client connects.
func (c *Client) ConnectToForwardedPort(ctx context.Context, conn io.ReadWriteCloser, port uint16) error {
	errc := make(chan error, 1)
	go func() {
		if err := c.handleConnection(ctx, conn, port); err != nil {
			sendError(err, errc)
		}
	}()

	return awaitError(ctx, errc)
}

// WaitForForwardedPort waits for the specified port to be forwarded.
// It is common practice to call this function before ConnectToForwardedPort.
func (c *Client) WaitForForwardedPort(ctx context.Context, port uint16) error {
	// It's already forwarded there's no need to wait.
	if c.remoteForwardedPorts.hasPort(port) {
		return nil
	}

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case n := <-c.remoteForwardedPorts.notify:
			if n.port == port && n.notificationType == remoteForwardedPortNotificationTypeAdd {
				return nil
			}
		}
	}
}

func (c *Client) RefreshPorts(ctx context.Context) error {
	if c.ssh == nil {
		return fmt.Errorf("not Connected")
	}

	res, _, err := c.ssh.SendSessionRequest("RefreshPorts", true, make([]byte, 0))
	if err != nil {
		return fmt.Errorf("failed to send port refresh message: %w", err)
	}
	if !res {
		return fmt.Errorf("failed to refresh ports: %w", err)
	}

	return err
}

func sendError(err error, errc chan error) {
	// Use non-blocking send, to avoid goroutines getting
	// stuck in case of concurrent or sequential errors.
	select {
	case errc <- err:
	default:
	}
}

func awaitError(ctx context.Context, errc chan error) error {
	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
		return ctx.Err()
	}
}

func (c *Client) handleConnection(ctx context.Context, conn io.ReadWriteCloser, port uint16) (err error) {
	defer safeClose(conn, &err)

	channel, err := c.openStreamingChannel(ctx, port)
	if err != nil {
		return fmt.Errorf("failed to open streaming channel: %w", err)
	}

	// Ideally we would call safeClose again, but (*ssh.channel).Close
	// appears to have a bug that causes it return io.EOF spuriously
	// if its peer closed first; see github.com/golang/go/issues/38115.
	defer func() {
		closeErr := channel.Close()
		if err == nil && closeErr != io.EOF {
			err = closeErr
		}
	}()

	errs := make(chan error, 2)
	copyConn := func(w io.Writer, r io.Reader) {
		_, err := io.Copy(w, r)
		errs <- err
	}

	go copyConn(conn, channel)
	go copyConn(channel, conn)

	// Wait until context is cancelled or both copies are done.
	// Discard errors from io.Copy; they should not cause (e.g.) failures.
	for i := 0; ; {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-errs:
			i++
			if i == 2 {
				return nil
			}
		}
	}
}

func safeClose(c io.Closer, err *error) {
	if closerErr := c.Close(); *err == nil {
		*err = closerErr
	}
}

func (c *Client) openStreamingChannel(ctx context.Context, port uint16) (ssh.Channel, error) {
	portForwardChannel := messages.NewPortForwardChannel(
		c.ssh.NextChannelID(),
		"127.0.0.1",
		uint32(port),
		"",
		0,
	)
	data, err := portForwardChannel.Marshal()
	if err != nil {
		return nil, fmt.Errorf("failed to marshal port forward channel open message: %w", err)
	}

	channel, err := c.ssh.OpenChannel(ctx, portForwardChannel.Type(), data)
	if err != nil {
		return nil, fmt.Errorf("failed to open port forward channel: %w", err)
	}

	return channel, nil
}

func (c *Client) Close() error {
	return c.ssh.Close()
}