package discovery import ( "context" "io" "log" "net" "net/url" "sort" "strconv" "strings" "time" "github.com/hashicorp/mdns" ) // FoundServer is a validated service advertised on the serving host's LAN. // Endpoint is its LAN route; Addresses lists every route to this same // machine (LAN first), so a client can offer the choice. type FoundServer struct { Name string `json:"name"` Endpoint string `json:"endpoint"` Auth string `json:"auth"` Version string `json:"version"` Addresses []FoundAddress `json:"addresses"` } // FoundAddress is one way to dial a discovered machine. Kind is "lan", // "tailscale" (a tailnet IP, same port as the LAN) or "public" (an HTTPS // origin fronting the same proxy, usually the machine's tailnet DNS name). type FoundAddress struct { Kind string `json:"kind"` Endpoint string `json:"endpoint"` } // Browse sends one bounded DNS-SD query, never a network port scan. func Browse(ctx context.Context) ([]FoundServer, error) { return browse(ctx, mdns.QueryContext) } func browse(ctx context.Context, query func(context.Context, *mdns.QueryParam) error) ([]FoundServer, error) { ctx, cancel := context.WithTimeout(ctx, 4*time.Second) defer cancel() entries := make(chan *mdns.ServiceEntry, 128) result := make(chan error, 1) go func() { result <- query(ctx, &mdns.QueryParam{Service: ServiceType, Domain: "local", Timeout: 3 * time.Second, Entries: entries, WantUnicastResponse: true, Logger: log.New(io.Discard, "", 0)}) }() found := map[string]FoundServer{} consume := func(entry *mdns.ServiceEntry) { if item, ok := discovered(entry); ok && len(found) < 128 { found[item.Endpoint] = item } } for { select { case entry := <-entries: consume(entry) case err := <-result: for { select { case entry := <-entries: consume(entry) default: values := make([]FoundServer, 0, len(found)) for _, item := range found { values = append(values, item) } sort.Slice(values, func(i, j int) bool { return values[i].Endpoint < values[j].Endpoint }) return values, err } } case <-ctx.Done(): return nil, ctx.Err() } } } func discovered(entry *mdns.ServiceEntry) (FoundServer, bool) { if entry == nil || entry.Port < 1 || entry.Port > 65535 { return FoundServer{}, false } fields := map[string]string{} for _, value := range entry.InfoFields { if key, text, ok := strings.Cut(value, "="); ok { fields[key] = text } } path := fields["path"] if path != "/connect" { return FoundServer{}, false } ip := entry.AddrV4 if ip == nil { ip = entry.AddrV6 } if ip == nil && entry.AddrV6IPAddr != nil { ip = entry.AddrV6IPAddr.IP } if ip == nil || ip.IsUnspecified() || ip.IsMulticast() || ip.IsLoopback() || ip.IsLinkLocalUnicast() { return FoundServer{}, false } if fields["tls"] != "0" && fields["tls"] != "1" { return FoundServer{}, false } scheme := "ws" if fields["tls"] == "1" { scheme = "wss" } auth := fields["auth"] if auth != "password" && auth != "none" { return FoundServer{}, false } name := strings.TrimSpace(fields["name"]) if name == "" { name = strings.TrimSuffix(entry.Host, ".") } if name == "" || len(name) > 200 { return FoundServer{}, false } endpoint := (&url.URL{Scheme: scheme, Host: net.JoinHostPort(ip.String(), strconv.Itoa(entry.Port)), Path: path}).String() addresses := []FoundAddress{{Kind: "lan", Endpoint: endpoint}} if fields["lan"] == "0" { // The proxy refuses LAN connections; the address record is a tailnet IP. addresses = nil } for _, value := range strings.Split(fields["ts"], ",") { ts := net.ParseIP(strings.TrimSpace(value)) if ts == nil || !IsTailscaleIP(ts) || len(addresses) > 5 { continue } addresses = append(addresses, FoundAddress{Kind: "tailscale", Endpoint: (&url.URL{Scheme: scheme, Host: net.JoinHostPort(ts.String(), strconv.Itoa(entry.Port)), Path: path}).String()}) } if public, ok := PublicOrigin(fields["public"]); ok { u, _ := url.Parse(public) wsScheme := "ws" if u.Scheme == "https" { wsScheme = "wss" } addresses = append(addresses, FoundAddress{Kind: "public", Endpoint: (&url.URL{Scheme: wsScheme, Host: u.Host, Path: path}).String()}) } if len(addresses) == 0 { return FoundServer{}, false } return FoundServer{Name: name, Endpoint: addresses[0].Endpoint, Auth: auth, Version: fields["v"], Addresses: addresses}, true }