LAN discovery: server advertises _pipelines._tcp over mDNS; app finds servers on the connect screen
Server: internal/discovery publishes a DNS-SD record (hashicorp/mdns) with the port LAN clients dial (the web proxy via -mdns-port, which the supervisor passes, or a non-loopback -addr) and TXT v, name, path, tls, auth. On by default; -mdns=false or PIPELINES_MDNS=off disables it. Failures are logged and never block startup; the advert is withdrawn on shutdown. App: the Connect to Pipelines screen gets 'Find servers on this network' behind a ServerDiscovery interface (Bonsoir: Android NSD with multicast lock, iOS Bonjour with NSLocalNetworkUsageDescription and NSBonjourServices). Tapping a server fills the address and connects; manual entry stays. Web has no scan.
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
// Package discovery advertises the Pipelines server on the local network with
|
||||
// mDNS/DNS-SD (Bonjour), so a phone on the same LAN can find it without typing
|
||||
// an address.
|
||||
//
|
||||
// The advertised port is the one a LAN client dials. The installed server binds
|
||||
// loopback behind the authenticated web proxy, so the installer passes the
|
||||
// proxy's port (-mdns-port); a server bound to a LAN address with no proxy
|
||||
// advertises its own listen port and no authentication.
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/mdns"
|
||||
)
|
||||
|
||||
// ServiceType is the DNS-SD service type clients browse for.
|
||||
const ServiceType = "_pipelines._tcp"
|
||||
|
||||
// Config is what the server knows about how LAN clients reach it.
|
||||
type Config struct {
|
||||
// ListenAddr is the server's own -addr.
|
||||
ListenAddr string
|
||||
// ProxyPort, when non-zero, is the port of the authenticated web proxy on
|
||||
// this host that fronts the server for LAN clients.
|
||||
ProxyPort int
|
||||
// Version is the server build version.
|
||||
Version string
|
||||
// Hostname is this machine's host name (os.Hostname).
|
||||
Hostname string
|
||||
// IPs are the LAN addresses clients may dial.
|
||||
IPs []net.IP
|
||||
}
|
||||
|
||||
// Advert is the record set the server publishes.
|
||||
type Advert struct {
|
||||
Instance string
|
||||
Host string // fully qualified, e.g. "box.local."
|
||||
Port int
|
||||
IPs []net.IP
|
||||
TXT []string
|
||||
}
|
||||
|
||||
// ErrNotReachable means no LAN client could dial what the server would
|
||||
// advertise (loopback-only listener without a proxy, or no LAN address).
|
||||
var ErrNotReachable = errors.New("not reachable from the LAN")
|
||||
|
||||
// Plan decides what to advertise. It is pure, so tests check record content
|
||||
// without touching the network.
|
||||
func Plan(cfg Config) (Advert, error) {
|
||||
port, auth := cfg.ProxyPort, "password"
|
||||
if port == 0 {
|
||||
host, value, err := net.SplitHostPort(cfg.ListenAddr)
|
||||
if err != nil {
|
||||
return Advert{}, fmt.Errorf("listen address %q: %w", cfg.ListenAddr, err)
|
||||
}
|
||||
if ip := net.ParseIP(host); host == "localhost" || (ip != nil && ip.IsLoopback()) {
|
||||
return Advert{}, fmt.Errorf("server listens on loopback %s and no -mdns-port names its LAN proxy: %w", cfg.ListenAddr, ErrNotReachable)
|
||||
}
|
||||
if port, err = strconv.Atoi(value); err != nil || port <= 0 {
|
||||
return Advert{}, fmt.Errorf("listen address %q has no usable port: %w", cfg.ListenAddr, ErrNotReachable)
|
||||
}
|
||||
auth = "none"
|
||||
}
|
||||
if port <= 0 || port > 65535 {
|
||||
return Advert{}, fmt.Errorf("advertised port %d is out of range", port)
|
||||
}
|
||||
if len(cfg.IPs) == 0 {
|
||||
return Advert{}, fmt.Errorf("no LAN IPv4 address: %w", ErrNotReachable)
|
||||
}
|
||||
label := hostLabel(cfg.Hostname)
|
||||
version := cfg.Version
|
||||
if version == "" {
|
||||
version = "dev"
|
||||
}
|
||||
return Advert{
|
||||
Instance: "Pipelines-" + label,
|
||||
Host: label + ".local.",
|
||||
Port: port,
|
||||
IPs: cfg.IPs,
|
||||
// TXT keys follow RFC 6763 (short, lower case). The scheme and path are
|
||||
// what the client puts in its ws(s):// URL.
|
||||
TXT: []string{
|
||||
"v=" + version,
|
||||
"name=" + label,
|
||||
"path=/connect",
|
||||
"tls=0",
|
||||
"auth=" + auth,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// hostLabel reduces a host name to one DNS label: the first dotted part, with
|
||||
// anything other than letters, digits and hyphens replaced, so instance and
|
||||
// host names never need escaping on the wire.
|
||||
func hostLabel(hostname string) string {
|
||||
first, _, _ := strings.Cut(strings.TrimSpace(hostname), ".")
|
||||
var b strings.Builder
|
||||
for _, r := range first {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-':
|
||||
b.WriteRune(r)
|
||||
default:
|
||||
b.WriteRune('-')
|
||||
}
|
||||
}
|
||||
label := strings.Trim(b.String(), "-")
|
||||
if label == "" {
|
||||
return "pipelines"
|
||||
}
|
||||
if len(label) > 50 {
|
||||
label = label[:50]
|
||||
}
|
||||
return label
|
||||
}
|
||||
|
||||
// Zone builds the DNS-SD zone that answers queries for the advert.
|
||||
func (a Advert) Zone() (*mdns.MDNSService, error) {
|
||||
return mdns.NewMDNSService(a.Instance, ServiceType, "local.", a.Host, a.Port, a.IPs, a.TXT)
|
||||
}
|
||||
|
||||
// Start publishes the advert until the returned stop is called. Failure is an
|
||||
// error for the caller to log; it never blocks startup.
|
||||
func Start(a Advert, logger *log.Logger) (stop func(), err error) {
|
||||
zone, err := a.Zone()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
server, err := mdns.NewServer(&mdns.Config{Zone: zone, Logger: logger})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return func() { _ = server.Shutdown() }, nil
|
||||
}
|
||||
|
||||
// LANAddresses lists the up, multicast-capable, physical interfaces' IPv4
|
||||
// addresses. VPN, tunnel, container and loopback interfaces are skipped: a LAN
|
||||
// client cannot dial them (the tailnet address is reached by name instead).
|
||||
func LANAddresses() []net.IP {
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var ips []net.IP
|
||||
for _, iface := range interfaces {
|
||||
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagMulticast == 0 || iface.Flags&net.FlagLoopback != 0 || virtual(iface.Name) {
|
||||
continue
|
||||
}
|
||||
addrs, err := iface.Addrs()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, addr := range addrs {
|
||||
network, ok := addr.(*net.IPNet)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if ip4 := network.IP.To4(); ip4 != nil && !ip4.IsLinkLocalUnicast() && !ip4.IsLoopback() {
|
||||
ips = append(ips, ip4)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
func virtual(name string) bool {
|
||||
for _, prefix := range []string{"lo", "docker", "veth", "br-", "virbr", "tun", "tap", "utun", "wg", "tailscale", "zt", "vpn", "bridge", "awdl", "llw", "anpi", "ap"} {
|
||||
if strings.HasPrefix(name, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
var lan = []net.IP{net.ParseIP("192.168.1.20").To4()}
|
||||
|
||||
func TestPlanAdvertisesTheWebProxyWithPasswordAuth(t *testing.T) {
|
||||
advert, err := Plan(Config{ListenAddr: "127.0.0.1:8080", ProxyPort: 8083, Version: "v1.4.0", Hostname: "Alans-Mac.local", IPs: lan})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if advert.Port != 8083 || advert.Instance != "Pipelines-Alans-Mac" || advert.Host != "Alans-Mac.local." {
|
||||
t.Fatalf("advert = %+v", advert)
|
||||
}
|
||||
want := []string{"v=v1.4.0", "name=Alans-Mac", "path=/connect", "tls=0", "auth=password"}
|
||||
if !slices.Equal(advert.TXT, want) {
|
||||
t.Fatalf("TXT = %q, want %q", advert.TXT, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanAdvertisesADirectLANListenerWithoutAuth(t *testing.T) {
|
||||
advert, err := Plan(Config{ListenAddr: "0.0.0.0:8080", Hostname: "box", IPs: lan})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if advert.Port != 8080 || !slices.Contains(advert.TXT, "auth=none") || !slices.Contains(advert.TXT, "v=dev") {
|
||||
t.Fatalf("advert = %+v", advert)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanRefusesWhatALANClientCannotDial(t *testing.T) {
|
||||
for name, cfg := range map[string]Config{
|
||||
"loopback only": {ListenAddr: "127.0.0.1:8080", Hostname: "box", IPs: lan},
|
||||
"localhost only": {ListenAddr: "localhost:8080", Hostname: "box", IPs: lan},
|
||||
"no LAN address": {ListenAddr: "127.0.0.1:8080", ProxyPort: 8083, Hostname: "box"},
|
||||
} {
|
||||
if _, err := Plan(cfg); !errors.Is(err, ErrNotReachable) {
|
||||
t.Errorf("%s: err = %v, want ErrNotReachable", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := Plan(Config{ListenAddr: "127.0.0.1:8080", ProxyPort: 70000, IPs: lan}); err == nil {
|
||||
t.Error("out-of-range port accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostLabelIsOneSafeDNSLabel(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"Alans-MacBook-Pro.local": "Alans-MacBook-Pro",
|
||||
"my box_2": "my-box-2",
|
||||
"": "pipelines",
|
||||
"...": "pipelines",
|
||||
} {
|
||||
if got := hostLabel(in); got != want {
|
||||
t.Errorf("hostLabel(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The zone answers a DNS-SD browse (PTR), resolve (SRV + TXT) and address
|
||||
// lookup (A) with the advertised content.
|
||||
func TestZoneAnswersBrowseResolveAndAddressQueries(t *testing.T) {
|
||||
advert, err := Plan(Config{ListenAddr: "127.0.0.1:8080", ProxyPort: 8083, Version: "v2", Hostname: "box", IPs: lan})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zone, err := advert.Zone()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
instance := "Pipelines-box._pipelines._tcp.local."
|
||||
|
||||
ptr := zone.Records(dns.Question{Name: "_pipelines._tcp.local.", Qtype: dns.TypePTR, Qclass: dns.ClassINET})
|
||||
if len(ptr) == 0 || ptr[0].(*dns.PTR).Ptr != instance {
|
||||
t.Fatalf("PTR = %v", ptr)
|
||||
}
|
||||
srv := zone.Records(dns.Question{Name: instance, Qtype: dns.TypeSRV, Qclass: dns.ClassINET})
|
||||
if len(srv) == 0 || srv[0].(*dns.SRV).Port != 8083 || srv[0].(*dns.SRV).Target != "box.local." {
|
||||
t.Fatalf("SRV = %v", srv)
|
||||
}
|
||||
txt := zone.Records(dns.Question{Name: instance, Qtype: dns.TypeTXT, Qclass: dns.ClassINET})
|
||||
if len(txt) != 1 || !slices.Equal(txt[0].(*dns.TXT).Txt, advert.TXT) {
|
||||
t.Fatalf("TXT = %v", txt)
|
||||
}
|
||||
a := zone.Records(dns.Question{Name: "box.local.", Qtype: dns.TypeA, Qclass: dns.ClassINET})
|
||||
if len(a) != 1 || !a[0].(*dns.A).A.Equal(lan[0]) {
|
||||
t.Fatalf("A = %v", a)
|
||||
}
|
||||
// The records survive a wire round trip unescaped.
|
||||
msg := new(dns.Msg)
|
||||
msg.Answer = append(append(ptr, srv...), txt...)
|
||||
packed, err := msg.Pack()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var back dns.Msg
|
||||
if err := back.Unpack(packed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if back.Answer[0].(*dns.PTR).Ptr != instance {
|
||||
t.Fatalf("round trip PTR = %v", back.Answer[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestVirtualInterfacesAreSkipped(t *testing.T) {
|
||||
for _, name := range []string{"utun3", "tailscale0", "docker0", "lo0", "awdl0", "bridge100"} {
|
||||
if !virtual(name) {
|
||||
t.Errorf("%s treated as LAN", name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"en0", "eth0", "wlan0", "enp3s0"} {
|
||||
if virtual(name) {
|
||||
t.Errorf("%s treated as virtual", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user