-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
port_forward.go
132 lines (116 loc) · 3.82 KB
/
port_forward.go
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
/*
Copyright 2023 Avi Zimmerman <avi.zimmerman@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ctlcmd
import (
"context"
"fmt"
"net"
"net/netip"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/spf13/cobra"
v1 "github.com/webmeshproj/api/v1"
"github.com/webmeshproj/webmesh/pkg/cmd/ctlcmd/portforward"
"github.com/webmeshproj/webmesh/pkg/meshnet/transport"
"github.com/webmeshproj/webmesh/pkg/meshnet/transport/datachannels"
"github.com/webmeshproj/webmesh/pkg/meshnet/transport/tcp"
)
var (
portForwardProtocol string
portForwardAddress string
)
func init() {
portForwardCmd.Flags().StringVar(&portForwardProtocol, "protocol", "tcp", "Protocol to forward")
portForwardCmd.Flags().StringVar(&portForwardAddress, "address", "127.0.0.1", "Address to listen on")
rootCmd.AddCommand(portForwardCmd)
}
var portForwardCmd = &cobra.Command{
Use: "port-forward NODE_ID [LOCAL_PORT:[REMOTE_ADDRESS]:]REMOTE_PORT",
Short: "Forward ports to services running in the mesh",
Args: cobra.ExactArgs(2),
ValidArgsFunction: completeNodes(1),
RunE: func(cmd *cobra.Command, args []string) error {
nodeID, portForwardSpec := args[0], args[1]
return portForward(cmd, nodeID, portForwardSpec)
},
}
func portForward(cmd *cobra.Command, nodeID string, portForwardSpec string) error {
spec, err := portforward.ParsePortForwardSpec(portForwardSpec)
if err != nil {
return fmt.Errorf("failed to parse port forward spec: %w", err)
}
creds, err := cliConfig.GetDialOptions()
if err != nil {
return fmt.Errorf("failed to get dial options: %w", err)
}
pc, err := datachannels.NewPeerConnectionClient(cmd.Context(), portForwardProtocol, tcp.NewSignalTransport(tcp.WebRTCSignalOptions{
Resolver: transport.FeatureResolverFunc(func(ctx context.Context, lookup v1.Feature) ([]netip.AddrPort, error) {
// Return the server address from our config
addrport, err := netip.ParseAddrPort(cliConfig.GetCurrentCluster().Server)
if err != nil {
return nil, err
}
return []netip.AddrPort{addrport}, nil
}),
Credentials: creds,
NodeID: nodeID,
TargetProto: portForwardProtocol,
TargetAddr: netip.MustParseAddrPort(net.JoinHostPort(portForwardAddress, strconv.Itoa(int(spec.RemotePort)))),
}))
if err != nil {
return fmt.Errorf("failed to create peer connection: %w", err)
}
defer pc.Close()
// Handle errors from the peer connection
go func() {
for err := range pc.Errors() {
cmd.Printf("Peer connection error: %v\n", err)
select {
case <-pc.Ready():
continue
default:
os.Exit(1)
}
}
}()
// Block until the connection is ready or fails
select {
case <-pc.Ready():
case <-pc.Closed():
cmd.Println("Peer connection failed to become ready")
os.Exit(1)
}
portForwardAddr := net.JoinHostPort(portForwardAddress, strconv.Itoa(int(spec.LocalPort)))
// Start the listener
go func() {
cmd.Println("Forwarding connections",
"from", portForwardAddr,
"via", nodeID,
"to", spec.RemoteString(),
)
if err := pc.ListenAndServe(cmd.Context(), portForwardProtocol, portForwardAddr); err != nil {
cmd.Printf("Failed to serve: %v\n", err)
}
}()
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
select {
case <-pc.Closed():
cmd.Println("Peer connection closed")
case <-sig:
cmd.Println("Received interrupt, shutting down")
}
return nil
}