Files
pipelines/internal/discovery/browse.go
T

114 lines
2.9 KiB
Go

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.
type FoundServer struct {
Name string `json:"name"`
Endpoint string `json:"endpoint"`
Auth string `json:"auth"`
Version string `json:"version"`
}
// 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()
return FoundServer{Name: name, Endpoint: endpoint, Auth: auth, Version: fields["v"]}, true
}