196 lines
5.1 KiB
Go
196 lines
5.1 KiB
Go
package scanner
|
|
|
|
import (
|
|
"context"
|
|
"net"
|
|
"net/netip"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"golang.org/x/net/dns/dnsmessage"
|
|
"golang.org/x/net/ipv4"
|
|
)
|
|
|
|
// Service is a Bonjour (DNS-SD) service announced by a device.
|
|
type Service struct {
|
|
Type string `json:"type"` // e.g. "_airplay._tcp"
|
|
Instance string `json:"instance"`
|
|
Port uint16 `json:"port"`
|
|
}
|
|
|
|
// Short returns the service type without underscores and protocol ("airplay").
|
|
func (s Service) Short() string {
|
|
t, _, _ := strings.Cut(s.Type, ".")
|
|
return strings.TrimPrefix(t, "_")
|
|
}
|
|
|
|
type bonjourResult struct {
|
|
services map[netip.Addr][]Service
|
|
hostnames map[netip.Addr]string
|
|
}
|
|
|
|
type bonjourInstance struct {
|
|
name, typ string
|
|
target string
|
|
port uint16
|
|
src netip.Addr
|
|
askedSRV bool
|
|
}
|
|
|
|
var mdnsGroup = &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251), Port: 5353}
|
|
|
|
// browseBonjour enumerates all DNS-SD service types on the link, then their
|
|
// instances, and resolves each to an address. Queries are sent from an
|
|
// ephemeral port, so responders answer by unicast (RFC 6762, 6.7) and we do
|
|
// not compete with the system's mDNS daemon for port 5353.
|
|
func browseBonjour(ctx context.Context, iface *net.Interface, wait time.Duration) bonjourResult {
|
|
res := bonjourResult{services: map[netip.Addr][]Service{}, hostnames: map[netip.Addr]string{}}
|
|
conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero})
|
|
if err != nil {
|
|
return res
|
|
}
|
|
defer conn.Close()
|
|
context.AfterFunc(ctx, func() { conn.Close() })
|
|
pc := ipv4.NewPacketConn(conn)
|
|
if iface != nil {
|
|
pc.SetMulticastInterface(iface)
|
|
}
|
|
pc.SetMulticastTTL(255)
|
|
|
|
send := func(name string, t dnsmessage.Type) {
|
|
q, err := question(name, t)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if b, err := buildQuery(0, q); err == nil {
|
|
pc.WriteTo(b, nil, mdnsGroup)
|
|
}
|
|
}
|
|
|
|
const metaQuery = "_services._dns-sd._udp.local."
|
|
types := map[string]bool{}
|
|
instances := map[string]*bonjourInstance{}
|
|
addrs := map[string]netip.Addr{}
|
|
askedA := map[string]bool{}
|
|
instance := func(name string) *bonjourInstance {
|
|
key := strings.ToLower(name)
|
|
in := instances[key]
|
|
if in == nil {
|
|
in = &bonjourInstance{name: name, typ: serviceTypeOf(name)}
|
|
instances[key] = in
|
|
}
|
|
return in
|
|
}
|
|
|
|
send(metaQuery, dnsmessage.TypePTR)
|
|
deadline := time.Now().Add(wait)
|
|
lastFollowUp := time.Now()
|
|
buf := make([]byte, 9000)
|
|
for time.Now().Before(deadline) && ctx.Err() == nil {
|
|
conn.SetReadDeadline(minTime(deadline, time.Now().Add(250*time.Millisecond)))
|
|
if n, src, err := conn.ReadFromUDPAddrPort(buf); err == nil {
|
|
for _, rr := range parseRecords(buf[:n]) {
|
|
name := rr.Header.Name.String()
|
|
switch body := rr.Body.(type) {
|
|
case *dnsmessage.PTRResource:
|
|
target := body.PTR.String()
|
|
if strings.EqualFold(name, metaQuery) {
|
|
if t := strings.ToLower(target); !types[t] {
|
|
types[t] = true
|
|
send(target, dnsmessage.TypePTR)
|
|
}
|
|
} else if strings.HasPrefix(name, "_") {
|
|
in := instance(target)
|
|
if !in.src.IsValid() {
|
|
in.src = src.Addr().Unmap()
|
|
}
|
|
}
|
|
case *dnsmessage.SRVResource:
|
|
in := instance(name)
|
|
in.target, in.port = body.Target.String(), body.Port
|
|
in.src = src.Addr().Unmap()
|
|
case *dnsmessage.AResource:
|
|
addrs[strings.ToLower(name)] = netip.AddrFrom4(body.A)
|
|
}
|
|
}
|
|
}
|
|
// Ask for whatever the responders did not include on their own.
|
|
if time.Since(lastFollowUp) > 300*time.Millisecond {
|
|
lastFollowUp = time.Now()
|
|
for _, in := range instances {
|
|
switch {
|
|
case in.target == "" && !in.askedSRV:
|
|
in.askedSRV = true
|
|
send(in.name, dnsmessage.TypeSRV)
|
|
case in.target != "":
|
|
t := strings.ToLower(in.target)
|
|
if _, ok := addrs[t]; !ok && !askedA[t] {
|
|
askedA[t] = true
|
|
send(in.target, dnsmessage.TypeA)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for _, in := range instances {
|
|
if in.target == "" {
|
|
continue
|
|
}
|
|
ip, ok := addrs[strings.ToLower(in.target)]
|
|
if !ok {
|
|
ip = in.src
|
|
}
|
|
if !ip.Is4() {
|
|
continue
|
|
}
|
|
res.services[ip] = append(res.services[ip], Service{
|
|
Type: strings.TrimSuffix(in.typ, ".local."),
|
|
Instance: instanceLabel(in.name, in.typ),
|
|
Port: in.port,
|
|
})
|
|
if res.hostnames[ip] == "" {
|
|
res.hostnames[ip] = cleanHostname(in.target)
|
|
}
|
|
}
|
|
for host, ip := range addrs {
|
|
if res.hostnames[ip] == "" {
|
|
res.hostnames[ip] = cleanHostname(host)
|
|
}
|
|
}
|
|
for _, svcs := range res.services {
|
|
sort.Slice(svcs, func(i, j int) bool {
|
|
if svcs[i].Type != svcs[j].Type {
|
|
return svcs[i].Type < svcs[j].Type
|
|
}
|
|
return svcs[i].Instance < svcs[j].Instance
|
|
})
|
|
}
|
|
return res
|
|
}
|
|
|
|
// serviceTypeOf derives "_airplay._tcp.local." from an instance name such as
|
|
// "Living Room._airplay._tcp.local.".
|
|
func serviceTypeOf(instance string) string {
|
|
labels := strings.Split(strings.TrimSuffix(instance, "."), ".")
|
|
if len(labels) < 3 {
|
|
return instance
|
|
}
|
|
return strings.Join(labels[len(labels)-3:], ".") + "."
|
|
}
|
|
|
|
func instanceLabel(instance, typ string) string {
|
|
if len(instance) > len(typ) && strings.EqualFold(instance[len(instance)-len(typ):], typ) {
|
|
return strings.TrimSuffix(instance[:len(instance)-len(typ)], ".")
|
|
}
|
|
return instance
|
|
}
|
|
|
|
func minTime(a, b time.Time) time.Time {
|
|
if a.Before(b) {
|
|
return a
|
|
}
|
|
return b
|
|
}
|