// Package tailnet lists the machines on this device's tailnet, from the // local Tailscale daemon, and checks one for a Rex server, as rex-rune's // host picker does. package tailnet import ( "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "os" "os/exec" "sort" "strings" "time" "100gex/internal/rex" ) // Machine is a machine on the tailnet. type Machine struct { // Name is the first part of its MagicDNS name, such as studio, or what // it calls itself when the tailnet has no MagicDNS. Name string // Address reaches it: its MagicDNS name without the final dot, such as // studio.tail1234.ts.net, or its Tailscale IP. Address string // OS is linux, macOS, windows, android, iOS, or "" if unknown. OS string Online bool // SSH is true if it runs Tailscale SSH. SSH bool // ThisMachine is the device this program runs on. ThisMachine bool } // OSName spells the machine's operating system for people. func (m Machine) OSName() string { switch m.OS { case "linux": return "Linux" case "windows": return "Windows" case "android": return "Android" } return m.OS } // node is a machine as Tailscale's status describes it. type node struct { HostName string `json:"HostName"` DNSName string `json:"DNSName"` OS string `json:"OS"` Online bool `json:"Online"` TailscaleIPs []string `json:"TailscaleIPs"` SSHHostKeys []string `json:"sshHostKeys"` Location json.RawMessage `json:"Location"` } type status struct { Self *node `json:"Self"` Peer map[string]node `json:"Peer"` } // Parse reads Tailscale's status, as `tailscale status --json` and the // daemon's local API give it, and returns this machine, then the others by // name. It leaves out machines that can't run a Rex server: a VPN provider's // exit nodes, such as Mullvad's, which have a location, and iPhones and // iPads. func Parse(data []byte) ([]Machine, error) { var st status if err := json.Unmarshal(data, &st); err != nil { return nil, fmt.Errorf("tailscale status: %w", err) } var machines []Machine if st.Self != nil { if m, ok := st.Self.machine(true); ok { machines = append(machines, m) } } var peers []Machine for _, n := range st.Peer { if len(n.Location) > 0 && string(n.Location) != "null" { continue // a VPN provider's exit node } if n.OS == "iOS" { continue } if m, ok := n.machine(false); ok { peers = append(peers, m) } } sort.Slice(peers, func(i, j int) bool { a, b := strings.ToLower(peers[i].Name), strings.ToLower(peers[j].Name) if a != b { return a < b } return peers[i].Address < peers[j].Address }) return append(machines, peers...), nil } func (n node) machine(self bool) (Machine, bool) { m := Machine{OS: n.OS, Online: self || n.Online, SSH: len(n.SSHHostKeys) > 0, ThisMachine: self} if dns := strings.TrimSuffix(n.DNSName, "."); dns != "" { m.Address = dns m.Name, _, _ = strings.Cut(dns, ".") return m, true } // Without MagicDNS a machine has no name on the tailnet; its IP // reaches it, IPv4 first. for _, ip := range n.TailscaleIPs { if !strings.Contains(ip, ":") { m.Address = ip break } } if m.Address == "" && len(n.TailscaleIPs) > 0 { m.Address = n.TailscaleIPs[0] } if m.Address == "" { return Machine{}, false } m.Name = n.HostName if m.Name == "" || m.Name == "localhost" { m.Name = m.Address } return m, true } // sockets are where the Tailscale daemon's local API listens on Linux. var sockets = []string{"/run/tailscale/tailscaled.sock", "/var/run/tailscale/tailscaled.sock"} // ErrNoTailscale means Tailscale isn't installed or isn't running here. var ErrNoTailscale = errors.New("Tailscale isn't running on this machine") // Machines asks the local Tailscale daemon for the tailnet's machines: over // its local API, or failing that, with the tailscale command. func Machines(ctx context.Context) ([]Machine, error) { data, err := localAPIStatus(ctx) if err != nil { data, err = cliStatus(ctx) } if err != nil { return nil, err } return Parse(data) } func localAPIStatus(ctx context.Context) ([]byte, error) { path := os.Getenv("TS_SOCKET") if path == "" { for _, p := range sockets { if _, err := os.Stat(p); err == nil { path = p break } } } if path == "" { return nil, ErrNoTailscale } var d net.Dialer client := &http.Client{Transport: &http.Transport{ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return d.DialContext(ctx, "unix", path) }, }} req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://local-tailscaled.sock/localapi/v0/status", nil) if err != nil { return nil, err } resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("tailscale: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("tailscale: status %s", resp.Status) } return io.ReadAll(io.LimitReader(resp.Body, 64<<20)) } func cliStatus(ctx context.Context) ([]byte, error) { out, err := exec.CommandContext(ctx, "tailscale", "status", "--json").Output() if errors.Is(err, exec.ErrNotFound) { return nil, ErrNoTailscale } if err != nil { var exit *exec.ExitError if errors.As(err, &exit) && len(exit.Stderr) > 0 { return nil, fmt.Errorf("tailscale: %s", strings.TrimSpace(string(exit.Stderr))) } return nil, fmt.Errorf("tailscale: %w", err) } return out, nil } // ErrNoRex means nothing answered as a Rex server at any address a machine // might serve one on. var ErrNoRex = errors.New("no Rex server answered") // Probe looks for a Rex server at an address, trying the endpoints a bare // host name means to the rex CLI: HTTPS on 443, as built-in Tailscale // serves, then HTTPS and plain HTTP on 7297. It only says hello, and closes // the connection, so the server isn't changed. It returns the endpoint that // answered. func Probe(ctx context.Context, address string) (rex.Endpoint, error) { eps, err := rex.Candidates(address) if err != nil { return rex.Endpoint{}, err } ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() c, ep, err := rex.DialAny(ctx, eps, rex.ClientInfo{Kind: "app", Name: "100gex (looking for Rex)"}) var forbidden *rex.ForbiddenError if errors.As(err, &forbidden) { return rex.Endpoint{}, err // a server, which said no } if err != nil { return rex.Endpoint{}, fmt.Errorf("%w at %s: %v", ErrNoRex, address, err) } c.Close() return ep, nil }