浏览文件
probe.go
62 行 · 1.9 KB历史下载| 1 | // SPDX-FileCopyrightText: Copyright The Lima Authors |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| 4 | package portfwd |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "fmt" |
| 9 | "net" |
| 10 | "path/filepath" |
| 11 | "strconv" |
| 12 | ) |
| 13 | |
| 14 | // probeAddrs are the addresses a host program can serve a port on, such that a |
| 15 | // client of the host's loopback reaches it. |
| 16 | var probeAddrs = []string{"127.0.0.1", "::1", "0.0.0.0", "::"} |
| 17 | |
| 18 | // inUse reports whether a program of the host already serves the port of |
| 19 | // hostAddress, on any of probeAddrs. The listener of a forward binds with |
| 20 | // SO_REUSEADDR, which BSD (macOS) lets bind 127.0.0.1:port next to a program |
| 21 | // listening on 0.0.0.0:port: the guest would take the host's loopback clients |
| 22 | // of that program. Each address is bound and closed at once, with the same |
| 23 | // options as the forward (Control), so that only a socket bound to that exact |
| 24 | // address, not one in TIME_WAIT, counts. The wildcard addresses are bound too, |
| 25 | // as a listener on them is not seen from the loopback ones: this may make |
| 26 | // macOS's firewall ask once whether to accept incoming connections. |
| 27 | func inUse(ctx context.Context, protocol, hostAddress string) error { |
| 28 | if filepath.IsAbs(hostAddress) { |
| 29 | return nil |
| 30 | } |
| 31 | _, portStr, err := net.SplitHostPort(hostAddress) |
| 32 | if err != nil { |
| 33 | return nil |
| 34 | } |
| 35 | if port, err := strconv.Atoi(portStr); err != nil || port == 0 { |
| 36 | return nil |
| 37 | } |
| 38 | lc := net.ListenConfig{Control: Control} |
| 39 | for _, ip := range probeAddrs { |
| 40 | addr := net.JoinHostPort(ip, portStr) |
| 41 | var err error |
| 42 | switch protocol { |
| 43 | case "tcp": |
| 44 | var l net.Listener |
| 45 | if l, err = lc.Listen(ctx, "tcp", addr); err == nil { |
| 46 | l.Close() |
| 47 | } |
| 48 | case "udp": |
| 49 | var c net.PacketConn |
| 50 | if c, err = lc.ListenPacket(ctx, "udp", addr); err == nil { |
| 51 | c.Close() |
| 52 | } |
| 53 | default: |
| 54 | return nil |
| 55 | } |
| 56 | // Other errors (no IPv6, a privileged port) say nothing of the port. |
| 57 | if err != nil && addrInUse(err) { |
| 58 | return fmt.Errorf("%s port %s is in use on the host (%s)", protocol, portStr, addr) |
| 59 | } |
| 60 | } |
| 61 | return nil |
| 62 | } |

