| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | @@ -6,11 +6,14 @@ |
| 6 | package portfwd |
| 7 | |
| 8 | import ( |
| 9 | + "errors" |
| 10 | "syscall" |
| 11 | |
| 12 | "golang.org/x/sys/unix" |
| 13 | ) |
| 14 | |
| 15 | +func addrInUse(err error) bool { return errors.Is(err, unix.EADDRINUSE) } |
| 16 | + |
| 17 | func Control(_, _ string, c syscall.RawConn) (err error) { |
| 18 | controlErr := c.Control(func(fd uintptr) { |
| 19 | err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | @@ -4,20 +4,28 @@ |
| 25 | package portfwd |
| 26 | |
| 27 | import ( |
| 28 | + "errors" |
| 29 | "syscall" |
| 30 | |
| 31 | "golang.org/x/sys/windows" |
| 32 | ) |
| 33 | |
| 34 | +// soExclusiveAddrUse is SO_EXCLUSIVEADDRUSE, ~SO_REUSEADDR in winsock2.h. On |
| 35 | +// Windows, SO_REUSEADDR lets a socket bind an address another program is |
| 36 | +// listening on, and take its connections: exclusive use is what other systems |
| 37 | +// do by default. |
| 38 | +const soExclusiveAddrUse = ^windows.SO_REUSEADDR |
| 39 | + |
| 40 | func Control(_, _ string, c syscall.RawConn) (err error) { |
| 41 | controlErr := c.Control(func(fd uintptr) { |
| 42 | - err = windows.SetsockoptInt(windows.Handle(int(fd)), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1) |
| 43 | - if err != nil { |
| 44 | - return |
| 45 | - } |
| 46 | + err = windows.SetsockoptInt(windows.Handle(int(fd)), windows.SOL_SOCKET, soExclusiveAddrUse, 1) |
| 47 | }) |
| 48 | if controlErr != nil { |
| 49 | err = controlErr |
| 50 | } |
| 51 | return err |
| 52 | } |
| 53 | + |
| 54 | +func addrInUse(err error) bool { |
| 55 | + return errors.Is(err, windows.WSAEADDRINUSE) || errors.Is(err, windows.WSAEACCES) |
| 56 | +} |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | @@ -72,6 +72,20 @@ func (fw *Forwarder) OnEvent(ctx context.Context, dialContext func(ctx context.C |
| 62 | } |
| 63 | continue |
| 64 | } |
| 65 | + // Never next to a program of the host on the same port (see inUse). |
| 66 | + if !fw.closableListeners.has(f.Protocol, local, remote) { |
| 67 | + if err := inUse(ctx, f.Protocol, local); err != nil { |
| 68 | + logrus.Warnf("Not forwarding %s from %s to %s: %v", strings.ToUpper(f.Protocol), remote, local, err) |
| 69 | + fw.emitEvent(&events.PortForwardEvent{ |
| 70 | + Type: events.PortForwardEventFailed, |
| 71 | + Protocol: f.Protocol, |
| 72 | + GuestAddr: remote, |
| 73 | + HostAddr: local, |
| 74 | + Error: err.Error(), |
| 75 | + }) |
| 76 | + continue |
| 77 | + } |
| 78 | + } |
| 79 | logrus.Infof("Forwarding %s from %s to %s", strings.ToUpper(f.Protocol), remote, local) |
| 80 | fw.emitEvent(&events.PortForwardEvent{ |
| 81 | Type: events.PortForwardEventForwarding, |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | @@ -70,6 +70,21 @@ func (p *ClosableListeners) Forward(ctx context.Context, dialContext func(ctx co |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | +// has reports whether the forward of hostAddress to guestAddress is open. |
| 91 | +func (p *ClosableListeners) has(protocol, hostAddress, guestAddress string) bool { |
| 92 | + k := key(protocol, hostAddress, guestAddress) |
| 93 | + if protocol == "udp" { |
| 94 | + p.udpListenersRW.Lock() |
| 95 | + defer p.udpListenersRW.Unlock() |
| 96 | + _, ok := p.udpListeners[k] |
| 97 | + return ok |
| 98 | + } |
| 99 | + p.listenersRW.Lock() |
| 100 | + defer p.listenersRW.Unlock() |
| 101 | + _, ok := p.listeners[k] |
| 102 | + return ok |
| 103 | +} |
| 104 | + |
| 105 | func (p *ClosableListeners) Remove(_ context.Context, protocol, hostAddress, guestAddress string) { |
| 106 | logrus.Debugf("removing listener for hostAddress: %s, guestAddress: %s", hostAddress, guestAddress) |
| 107 | key := key(protocol, hostAddress, guestAddress) |
| 108 | |
| 109 | new file mode 100644 |
| 110 | |
| 111 | |
| 112 | |
| 113 | @@ -0,0 +1,62 @@ |
| 114 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 115 | +// SPDX-License-Identifier: Apache-2.0 |
| 116 | + |
| 117 | +package portfwd |
| 118 | + |
| 119 | +import ( |
| 120 | + "context" |
| 121 | + "fmt" |
| 122 | + "net" |
| 123 | + "path/filepath" |
| 124 | + "strconv" |
| 125 | +) |
| 126 | + |
| 127 | +// probeAddrs are the addresses a host program can serve a port on, such that a |
| 128 | +// client of the host's loopback reaches it. |
| 129 | +var probeAddrs = []string{"127.0.0.1", "::1", "0.0.0.0", "::"} |
| 130 | + |
| 131 | +// inUse reports whether a program of the host already serves the port of |
| 132 | +// hostAddress, on any of probeAddrs. The listener of a forward binds with |
| 133 | +// SO_REUSEADDR, which BSD (macOS) lets bind 127.0.0.1:port next to a program |
| 134 | +// listening on 0.0.0.0:port: the guest would take the host's loopback clients |
| 135 | +// of that program. Each address is bound and closed at once, with the same |
| 136 | +// options as the forward (Control), so that only a socket bound to that exact |
| 137 | +// address, not one in TIME_WAIT, counts. The wildcard addresses are bound too, |
| 138 | +// as a listener on them is not seen from the loopback ones: this may make |
| 139 | +// macOS's firewall ask once whether to accept incoming connections. |
| 140 | +func inUse(ctx context.Context, protocol, hostAddress string) error { |
| 141 | + if filepath.IsAbs(hostAddress) { |
| 142 | + return nil |
| 143 | + } |
| 144 | + _, portStr, err := net.SplitHostPort(hostAddress) |
| 145 | + if err != nil { |
| 146 | + return nil |
| 147 | + } |
| 148 | + if port, err := strconv.Atoi(portStr); err != nil || port == 0 { |
| 149 | + return nil |
| 150 | + } |
| 151 | + lc := net.ListenConfig{Control: Control} |
| 152 | + for _, ip := range probeAddrs { |
| 153 | + addr := net.JoinHostPort(ip, portStr) |
| 154 | + var err error |
| 155 | + switch protocol { |
| 156 | + case "tcp": |
| 157 | + var l net.Listener |
| 158 | + if l, err = lc.Listen(ctx, "tcp", addr); err == nil { |
| 159 | + l.Close() |
| 160 | + } |
| 161 | + case "udp": |
| 162 | + var c net.PacketConn |
| 163 | + if c, err = lc.ListenPacket(ctx, "udp", addr); err == nil { |
| 164 | + c.Close() |
| 165 | + } |
| 166 | + default: |
| 167 | + return nil |
| 168 | + } |
| 169 | + // Other errors (no IPv6, a privileged port) say nothing of the port. |
| 170 | + if err != nil && addrInUse(err) { |
| 171 | + return fmt.Errorf("%s port %s is in use on the host (%s)", protocol, portStr, addr) |
| 172 | + } |
| 173 | + } |
| 174 | + return nil |
| 175 | +} |
| 176 | |
| 177 | new file mode 100644 |
| 178 | |
| 179 | |
| 180 | |
| 181 | @@ -0,0 +1,66 @@ |
| 182 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 183 | +// SPDX-License-Identifier: Apache-2.0 |
| 184 | + |
| 185 | +package portfwd |
| 186 | + |
| 187 | +import ( |
| 188 | + "context" |
| 189 | + "net" |
| 190 | + "strconv" |
| 191 | + "testing" |
| 192 | + |
| 193 | + "gotest.tools/v3/assert" |
| 194 | + |
| 195 | + "github.com/lima-vm/lima/v2/pkg/guestagent/api" |
| 196 | + "github.com/lima-vm/lima/v2/pkg/hostagent/events" |
| 197 | + "github.com/lima-vm/lima/v2/pkg/limatype" |
| 198 | + "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 199 | +) |
| 200 | + |
| 201 | +// A port a program of the host serves, on any address its loopback clients |
| 202 | +// reach, is not forwarded: the guest would take those clients. |
| 203 | +func TestForwardNotNextToHostProgram(t *testing.T) { |
| 204 | + for _, hostIP := range []string{"0.0.0.0", "127.0.0.1", "::1"} { |
| 205 | + t.Run(hostIP, func(t *testing.T) { |
| 206 | + host, err := net.Listen("tcp", net.JoinHostPort(hostIP, "0")) |
| 207 | + if err != nil { |
| 208 | + t.Skipf("cannot listen on %s: %v", hostIP, err) |
| 209 | + } |
| 210 | + defer host.Close() |
| 211 | + port := host.Addr().(*net.TCPAddr).Port |
| 212 | + |
| 213 | + rule := limatype.PortForward{} |
| 214 | + limayaml.FillPortForwardDefaults(&rule, "", limatype.User{}, nil) |
| 215 | + var got []*events.PortForwardEvent |
| 216 | + fw := NewPortForwarder([]limatype.PortForward{rule}, false, false, func(ev *events.PortForwardEvent) { got = append(got, ev) }) |
| 217 | + defer fw.Close() |
| 218 | + fw.OnEvent(context.Background(), nil, &api.Event{AddedLocalPorts: []*api.IPPort{{Ip: "127.0.0.1", Port: int32(port), Protocol: "tcp"}}}) |
| 219 | + |
| 220 | + assert.Equal(t, len(got), 1) |
| 221 | + assert.Equal(t, got[0].Type, events.PortForwardEventFailed) |
| 222 | + assert.Assert(t, !fw.closableListeners.has("tcp", got[0].HostAddr, got[0].GuestAddr)) |
| 223 | + // The host's program still has its port. |
| 224 | + c, err := net.Dial("tcp", host.Addr().String()) |
| 225 | + assert.NilError(t, err) |
| 226 | + c.Close() |
| 227 | + }) |
| 228 | + } |
| 229 | +} |
| 230 | + |
| 231 | +// A free port is forwarded as before. |
| 232 | +func TestForwardFreePort(t *testing.T) { |
| 233 | + l, err := net.Listen("tcp", "127.0.0.1:0") |
| 234 | + assert.NilError(t, err) |
| 235 | + port := l.Addr().(*net.TCPAddr).Port |
| 236 | + l.Close() |
| 237 | + |
| 238 | + rule := limatype.PortForward{} |
| 239 | + limayaml.FillPortForwardDefaults(&rule, "", limatype.User{}, nil) |
| 240 | + var got []*events.PortForwardEvent |
| 241 | + fw := NewPortForwarder([]limatype.PortForward{rule}, false, false, func(ev *events.PortForwardEvent) { got = append(got, ev) }) |
| 242 | + defer fw.Close() |
| 243 | + fw.OnEvent(context.Background(), nil, &api.Event{AddedLocalPorts: []*api.IPPort{{Ip: "127.0.0.1", Port: int32(port), Protocol: "tcp"}}}) |
| 244 | + assert.Equal(t, len(got), 1) |
| 245 | + assert.Equal(t, got[0].Type, events.PortForwardEventForwarding) |
| 246 | + assert.Equal(t, got[0].HostAddr, net.JoinHostPort("127.0.0.1", strconv.Itoa(port))) |
| 247 | +} |