initial commit [141.14.140.180,mike]
This commit is contained in:
commit
e34ba75b7b
33 files changed
+6267
No files matched your search
@@ -0,0 +1,39 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var arpLine = regexp.MustCompile(`(\d+\.\d+\.\d+\.\d+)\D+?((?:[0-9a-fA-F]{1,2}[:-]){5}[0-9a-fA-F]{1,2})`)
|
||||
|
||||
// readARPExec parses the output of arp(8), which looks similar enough on
|
||||
// macOS, the BSDs and Windows.
|
||||
func readARPExec() (map[netip.Addr]net.HardwareAddr, error) {
|
||||
args := []string{"-an"}
|
||||
if runtime.GOOS == "windows" {
|
||||
args = []string{"-a"}
|
||||
}
|
||||
out, err := exec.Command("arp", args...).Output()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return parseARPOutput(string(out)), nil
|
||||
}
|
||||
|
||||
func parseARPOutput(out string) map[netip.Addr]net.HardwareAddr {
|
||||
table := make(map[netip.Addr]net.HardwareAddr)
|
||||
for _, m := range arpLine.FindAllStringSubmatch(out, -1) {
|
||||
ip, err := netip.ParseAddr(m[1])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if mac, ok := parseLooseMAC(m[2]); ok {
|
||||
table[ip] = mac
|
||||
}
|
||||
}
|
||||
return table
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand/v2"
|
||||
"net"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/dns/dnsmessage"
|
||||
)
|
||||
|
||||
// appleModel matches the model identifiers Apple devices announce, such as
|
||||
// "MacBookAir10,1", "Mac16,10", "iPhone15,3" or "AudioAccessory5,1" (HomePod).
|
||||
var appleModel = regexp.MustCompile(`^(Mac|MacBook|MacBookAir|MacBookPro|Macmini|MacPro|iMac|iMacPro|iPhone|iPad|iPod|AppleTV|AudioAccessory|Watch|RealityDevice|AirPort)\d+,\d+$`)
|
||||
|
||||
// PrivateMAC reports whether mac is locally administered, as the randomized
|
||||
// addresses phones and laptops use per network are. Such addresses carry no
|
||||
// vendor.
|
||||
func PrivateMAC(mac net.HardwareAddr) bool { return len(mac) > 0 && mac[0]&0x02 != 0 }
|
||||
|
||||
// Maker returns who made the device: the vendor registered for its MAC
|
||||
// address or, for private addresses, the maker implied by the announced model.
|
||||
func (h *Host) Maker() string {
|
||||
if h.Model != "" && (h.Vendor == "" || PrivateMAC(h.MAC)) && appleModel.MatchString(h.Model) {
|
||||
return "Apple"
|
||||
}
|
||||
return h.Vendor
|
||||
}
|
||||
|
||||
// VendorLabel is the maker followed by the model, e.g. "Apple Mac16,10".
|
||||
func (h *Host) VendorLabel() string {
|
||||
maker := h.Maker()
|
||||
switch {
|
||||
case h.Model == "":
|
||||
return maker
|
||||
case maker == "" || PrivateMAC(h.MAC) && maker == h.Vendor:
|
||||
return h.Model
|
||||
}
|
||||
return maker + " " + h.Model
|
||||
}
|
||||
|
||||
// deviceModels asks hosts for their "<name>._device-info._tcp.local." TXT
|
||||
// record, in which Apple devices announce their model identifier. Each host
|
||||
// is asked under all names it may use: its host name and its service names.
|
||||
func deviceModels(ctx context.Context, names map[netip.Addr][]string, timeout time.Duration) map[netip.Addr]string {
|
||||
conn, err := net.ListenUDP("udp4", nil)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer conn.Close()
|
||||
context.AfterFunc(ctx, func() { conn.Close() })
|
||||
|
||||
asked := map[string]netip.Addr{}
|
||||
for ip, ns := range names {
|
||||
for _, n := range ns {
|
||||
fq := n + "._device-info._tcp.local."
|
||||
q, err := question(fq, dnsmessage.TypeTXT)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if b, err := buildQuery(uint16(rand.N(0xffff)+1), q); err == nil {
|
||||
asked[strings.ToLower(fq)] = ip
|
||||
conn.WriteToUDPAddrPort(b, netip.AddrPortFrom(ip, 5353))
|
||||
}
|
||||
}
|
||||
}
|
||||
res := make(map[netip.Addr]string)
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
buf := make([]byte, 9000)
|
||||
for len(res) < len(names) {
|
||||
n, _, err := conn.ReadFromUDPAddrPort(buf)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
for _, rr := range parseRecords(buf[:n]) {
|
||||
txt, ok := rr.Body.(*dnsmessage.TXTResource)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ip, ok := asked[strings.ToLower(rr.Header.Name.String())]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if model := txtValue(txt.TXT, "model"); model != "" {
|
||||
res[ip] = model
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func txtValue(txt []string, key string) string {
|
||||
for _, kv := range txt {
|
||||
if v, ok := strings.CutPrefix(kv, key+"="); ok {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/dns/dnsmessage"
|
||||
)
|
||||
|
||||
func buildQuery(id uint16, qs ...dnsmessage.Question) ([]byte, error) {
|
||||
b := dnsmessage.NewBuilder(make([]byte, 0, 512), dnsmessage.Header{ID: id})
|
||||
b.EnableCompression()
|
||||
if err := b.StartQuestions(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, q := range qs {
|
||||
if err := b.Question(q); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return b.Finish()
|
||||
}
|
||||
|
||||
func question(name string, t dnsmessage.Type) (dnsmessage.Question, error) {
|
||||
n, err := dnsmessage.NewName(name)
|
||||
if err != nil {
|
||||
return dnsmessage.Question{}, err
|
||||
}
|
||||
return dnsmessage.Question{Name: n, Type: t, Class: dnsmessage.ClassINET}, nil
|
||||
}
|
||||
|
||||
// parseRecords returns the answer and additional records of a DNS response.
|
||||
// Parsing stops quietly at the first malformed record.
|
||||
func parseRecords(b []byte) []dnsmessage.Resource {
|
||||
var p dnsmessage.Parser
|
||||
h, err := p.Start(b)
|
||||
if err != nil || !h.Response {
|
||||
return nil
|
||||
}
|
||||
if err := p.SkipAllQuestions(); err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []dnsmessage.Resource
|
||||
for {
|
||||
r, err := p.Answer()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
if err := p.SkipAllAuthorities(); err != nil {
|
||||
return out
|
||||
}
|
||||
for {
|
||||
r, err := p.Additional()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// reverseName returns the in-addr.arpa name used for PTR lookups of ip.
|
||||
func reverseName(ip netip.Addr) string {
|
||||
b := ip.As4()
|
||||
return fmt.Sprintf("%d.%d.%d.%d.in-addr.arpa.", b[3], b[2], b[1], b[0])
|
||||
}
|
||||
|
||||
func parseReverseName(name string) (netip.Addr, bool) {
|
||||
rest, ok := strings.CutSuffix(strings.ToLower(name), ".in-addr.arpa.")
|
||||
if !ok {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
parts := strings.Split(rest, ".")
|
||||
if len(parts) != 4 {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
ip, err := netip.ParseAddr(parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0])
|
||||
return ip, err == nil
|
||||
}
|
||||
|
||||
// localSuffixes are domains that add no information in a LAN listing.
|
||||
var localSuffixes = []string{".local", ".lan", ".home", ".home.arpa", ".localdomain", ".fritz.box", ".internal"}
|
||||
|
||||
// cleanHostname trims the trailing dot and well-known local domains.
|
||||
func cleanHostname(s string) string {
|
||||
s = strings.TrimSuffix(s, ".")
|
||||
lower := strings.ToLower(s)
|
||||
for _, suf := range localSuffixes {
|
||||
if strings.HasSuffix(lower, suf) && len(s) > len(suf) {
|
||||
return s[:len(s)-len(suf)]
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
)
|
||||
|
||||
// icmpToken marks our echo requests so replies to other ping processes on the
|
||||
// same machine are ignored.
|
||||
var icmpToken = []byte("nscan\x00\x4e\x53")
|
||||
|
||||
type icmpSocket struct {
|
||||
conn *icmp.PacketConn
|
||||
privileged bool
|
||||
}
|
||||
|
||||
// openICMP prefers unprivileged ICMP sockets (macOS, most Linux distros) and
|
||||
// falls back to raw sockets, which need root.
|
||||
func openICMP() (*icmpSocket, error) {
|
||||
if c, err := icmp.ListenPacket("udp4", "0.0.0.0"); err == nil {
|
||||
return &icmpSocket{conn: c}, nil
|
||||
}
|
||||
c, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &icmpSocket{conn: c, privileged: true}, nil
|
||||
}
|
||||
|
||||
func (s *icmpSocket) Close() error { return s.conn.Close() }
|
||||
|
||||
func (s *icmpSocket) sendEcho(dst netip.Addr, id, seq int) error {
|
||||
data := make([]byte, 16)
|
||||
copy(data, icmpToken)
|
||||
binary.BigEndian.PutUint64(data[8:], uint64(time.Now().UnixNano()))
|
||||
msg := icmp.Message{
|
||||
Type: ipv4.ICMPTypeEcho,
|
||||
Body: &icmp.Echo{ID: id, Seq: seq, Data: data},
|
||||
}
|
||||
b, err := msg.Marshal(nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var to net.Addr = &net.UDPAddr{IP: dst.AsSlice()}
|
||||
if s.privileged {
|
||||
to = &net.IPAddr{IP: dst.AsSlice()}
|
||||
}
|
||||
_, err = s.conn.WriteTo(b, to)
|
||||
return err
|
||||
}
|
||||
|
||||
type echoReply struct {
|
||||
From netip.Addr
|
||||
Seq int
|
||||
RTT time.Duration
|
||||
}
|
||||
|
||||
// readEcho blocks until one of our echo replies arrives or reading fails.
|
||||
func (s *icmpSocket) readEcho(buf []byte) (echoReply, error) {
|
||||
for {
|
||||
n, peer, err := s.conn.ReadFrom(buf)
|
||||
if err != nil {
|
||||
return echoReply{}, err
|
||||
}
|
||||
m, err := icmp.ParseMessage(1, buf[:n])
|
||||
if err != nil || m.Type != ipv4.ICMPTypeEchoReply {
|
||||
continue
|
||||
}
|
||||
e, ok := m.Body.(*icmp.Echo)
|
||||
if !ok || len(e.Data) < 16 || !bytes.Equal(e.Data[:8], icmpToken) {
|
||||
continue
|
||||
}
|
||||
sent := time.Unix(0, int64(binary.BigEndian.Uint64(e.Data[8:16])))
|
||||
return echoReply{From: addrOf(peer), Seq: e.Seq, RTT: time.Since(sent)}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func addrOf(a net.Addr) netip.Addr {
|
||||
var ip net.IP
|
||||
switch a := a.(type) {
|
||||
case *net.UDPAddr:
|
||||
ip = a.IP
|
||||
case *net.IPAddr:
|
||||
ip = a.IP
|
||||
}
|
||||
addr, _ := netip.AddrFromSlice(ip)
|
||||
return addr.Unmap()
|
||||
}
|
||||
|
||||
// PingResult is the outcome of a single echo request.
|
||||
type PingResult struct {
|
||||
Seq int
|
||||
RTT time.Duration
|
||||
Timeout bool
|
||||
Err error
|
||||
Method string
|
||||
}
|
||||
|
||||
// Ping sends count echo requests (0 = until ctx is cancelled) and reports each
|
||||
// result. Without ICMP permission it falls back to timing TCP connects.
|
||||
func Ping(ctx context.Context, dst netip.Addr, count int, interval, timeout time.Duration, onResult func(PingResult)) error {
|
||||
sock, err := openICMP()
|
||||
if err != nil {
|
||||
return tcpPing(ctx, dst, count, interval, timeout, onResult)
|
||||
}
|
||||
defer sock.Close()
|
||||
context.AfterFunc(ctx, func() { sock.Close() })
|
||||
|
||||
replies := make(chan echoReply, 16)
|
||||
go func() {
|
||||
buf := make([]byte, 1500)
|
||||
for {
|
||||
r, err := sock.readEcho(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if r.From == dst {
|
||||
select {
|
||||
case replies <- r:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
id := os.Getpid() & 0xffff
|
||||
for seq := 1; count == 0 || seq <= count; seq++ {
|
||||
start := time.Now()
|
||||
res := PingResult{Seq: seq, Method: "ICMP"}
|
||||
if err := sock.sendEcho(dst, id, seq); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
res.Err = err
|
||||
} else {
|
||||
res.Timeout = true
|
||||
timer := time.NewTimer(timeout)
|
||||
wait:
|
||||
for {
|
||||
select {
|
||||
case r := <-replies:
|
||||
if r.Seq == seq {
|
||||
res.Timeout, res.RTT = false, r.RTT
|
||||
break wait
|
||||
}
|
||||
case <-timer.C:
|
||||
break wait
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
timer.Stop()
|
||||
}
|
||||
onResult(res)
|
||||
if count != 0 && seq == count {
|
||||
break
|
||||
}
|
||||
if !sleepCtx(ctx, interval-time.Since(start)) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func tcpPing(ctx context.Context, dst netip.Addr, count int, interval, timeout time.Duration, onResult func(PingResult)) error {
|
||||
for seq := 1; count == 0 || seq <= count; seq++ {
|
||||
start := time.Now()
|
||||
rtt, ok := tcpAlive(ctx, dst, probePorts, timeout)
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
onResult(PingResult{Seq: seq, RTT: rtt, Timeout: !ok, Method: "TCP"})
|
||||
if count != 0 && seq == count {
|
||||
break
|
||||
}
|
||||
if !sleepCtx(ctx, interval-time.Since(start)) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// probePorts are tried when ICMP is unavailable or blocked. A refused
|
||||
// connection proves the host is up just as well as an accepted one.
|
||||
var probePorts = []int{80, 443, 22, 445, 139, 62078}
|
||||
|
||||
func tcpAlive(ctx context.Context, ip netip.Addr, ports []int, timeout time.Duration) (time.Duration, bool) {
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
type result struct {
|
||||
rtt time.Duration
|
||||
ok bool
|
||||
}
|
||||
ch := make(chan result, len(ports))
|
||||
start := time.Now()
|
||||
for _, p := range ports {
|
||||
go func(p int) {
|
||||
var d net.Dialer
|
||||
c, err := d.DialContext(ctx, "tcp4", netip.AddrPortFrom(ip, uint16(p)).String())
|
||||
if err == nil {
|
||||
c.Close()
|
||||
}
|
||||
ch <- result{time.Since(start), err == nil || errors.Is(err, syscall.ECONNREFUSED)}
|
||||
}(p)
|
||||
}
|
||||
for range ports {
|
||||
if r := <-ch; r.ok {
|
||||
return r.rtt, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// sleepCtx waits for d and reports false if ctx was cancelled meanwhile.
|
||||
func sleepCtx(ctx context.Context, d time.Duration) bool {
|
||||
if d <= 0 {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"math/rand/v2"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/dns/dnsmessage"
|
||||
)
|
||||
|
||||
// reverseDNS looks up PTR records via the system resolver.
|
||||
func reverseDNS(ctx context.Context, ips []netip.Addr, timeout time.Duration) map[netip.Addr]string {
|
||||
var mu sync.Mutex
|
||||
res := make(map[netip.Addr]string)
|
||||
sem := make(chan struct{}, 32)
|
||||
var wg sync.WaitGroup
|
||||
for _, ip := range ips {
|
||||
sem <- struct{}{}
|
||||
wg.Add(1)
|
||||
go func(ip netip.Addr) {
|
||||
defer func() { <-sem; wg.Done() }()
|
||||
lctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
names, err := net.DefaultResolver.LookupAddr(lctx, ip.String())
|
||||
if err != nil || len(names) == 0 {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
res[ip] = cleanHostname(names[0])
|
||||
mu.Unlock()
|
||||
}(ip)
|
||||
}
|
||||
wg.Wait()
|
||||
return res
|
||||
}
|
||||
|
||||
// mdnsReverse asks every host directly (unicast to port 5353) for its own
|
||||
// name. Apple devices and Linux machines running Avahi answer these queries.
|
||||
func mdnsReverse(ctx context.Context, ips []netip.Addr, timeout time.Duration) map[netip.Addr]string {
|
||||
conn, err := net.ListenUDP("udp4", nil)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer conn.Close()
|
||||
context.AfterFunc(ctx, func() { conn.Close() })
|
||||
|
||||
for _, ip := range ips {
|
||||
q, err := question(reverseName(ip), dnsmessage.TypePTR)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if b, err := buildQuery(uint16(rand.N(0xffff)+1), q); err == nil {
|
||||
conn.WriteToUDPAddrPort(b, netip.AddrPortFrom(ip, 5353))
|
||||
}
|
||||
}
|
||||
res := make(map[netip.Addr]string)
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
buf := make([]byte, 9000)
|
||||
for len(res) < len(ips) {
|
||||
n, from, err := conn.ReadFromUDPAddrPort(buf)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
for _, rr := range parseRecords(buf[:n]) {
|
||||
ptr, ok := rr.Body.(*dnsmessage.PTRResource)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ip, ok := parseReverseName(rr.Header.Name.String())
|
||||
if !ok {
|
||||
ip = from.Addr().Unmap()
|
||||
}
|
||||
res[ip] = cleanHostname(ptr.PTR.String())
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// netbiosNames sends NetBIOS node status requests (UDP 137), which Windows
|
||||
// machines and Samba servers answer with their computer name.
|
||||
func netbiosNames(ctx context.Context, ips []netip.Addr, timeout time.Duration) map[netip.Addr]string {
|
||||
conn, err := net.ListenUDP("udp4", nil)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer conn.Close()
|
||||
context.AfterFunc(ctx, func() { conn.Close() })
|
||||
|
||||
for _, ip := range ips {
|
||||
conn.WriteToUDPAddrPort(nbstatRequest(uint16(rand.N(0xffff))), netip.AddrPortFrom(ip, 137))
|
||||
}
|
||||
res := make(map[netip.Addr]string)
|
||||
conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
buf := make([]byte, 1500)
|
||||
for len(res) < len(ips) {
|
||||
n, from, err := conn.ReadFromUDPAddrPort(buf)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if name, ok := parseNBStat(buf[:n]); ok {
|
||||
res[from.Addr().Unmap()] = name
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func nbstatRequest(id uint16) []byte {
|
||||
b := []byte{byte(id >> 8), byte(id), 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}
|
||||
// The wildcard name "*" padded to 16 bytes, first-level encoded.
|
||||
b = append(b, 0x20)
|
||||
name := [16]byte{'*'}
|
||||
for _, c := range name {
|
||||
b = append(b, 'A'+c>>4, 'A'+c&0x0f)
|
||||
}
|
||||
return append(b, 0, 0x00, 0x21, 0x00, 0x01) // NBSTAT, IN
|
||||
}
|
||||
|
||||
// parseNBStat extracts the unique workstation name from a node status response.
|
||||
func parseNBStat(b []byte) (string, bool) {
|
||||
if len(b) < 12 || b[2]&0x80 == 0 {
|
||||
return "", false
|
||||
}
|
||||
qd := int(binary.BigEndian.Uint16(b[4:6]))
|
||||
an := int(binary.BigEndian.Uint16(b[6:8]))
|
||||
off := 12
|
||||
for range qd {
|
||||
off = skipDNSName(b, off) + 4
|
||||
}
|
||||
if an == 0 {
|
||||
return "", false
|
||||
}
|
||||
off = skipDNSName(b, off)
|
||||
if off+10 > len(b) || binary.BigEndian.Uint16(b[off:]) != 0x21 {
|
||||
return "", false
|
||||
}
|
||||
off += 10
|
||||
if off >= len(b) {
|
||||
return "", false
|
||||
}
|
||||
num := int(b[off])
|
||||
off++
|
||||
for i := 0; i < num && off+18 <= len(b); i++ {
|
||||
name := strings.TrimRight(string(b[off:off+15]), " \x00")
|
||||
suffix := b[off+15]
|
||||
group := binary.BigEndian.Uint16(b[off+16:])&0x8000 != 0
|
||||
off += 18
|
||||
if suffix == 0x00 && !group && name != "" {
|
||||
return name, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func skipDNSName(b []byte, off int) int {
|
||||
for off < len(b) {
|
||||
l := int(b[off])
|
||||
switch {
|
||||
case l == 0:
|
||||
return off + 1
|
||||
case l&0xc0 == 0xc0:
|
||||
return off + 2
|
||||
}
|
||||
off += 1 + l
|
||||
}
|
||||
return len(b)
|
||||
}
|
||||
|
||||
func localHostname() string {
|
||||
h, err := os.Hostname()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return cleanHostname(h)
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// maxTargets limits how many addresses a single scan may cover.
|
||||
const maxTargets = 65536
|
||||
|
||||
// Network describes the local network segment a scan runs on.
|
||||
type Network struct {
|
||||
Iface *net.Interface
|
||||
LocalIP netip.Addr
|
||||
LocalMAC net.HardwareAddr
|
||||
Prefix netip.Prefix
|
||||
Gateway netip.Addr
|
||||
}
|
||||
|
||||
// OnLink reports whether ip is on the local segment, i.e. reachable via ARP.
|
||||
func (n *Network) OnLink(ip netip.Addr) bool {
|
||||
return n.Prefix.IsValid() && n.Prefix.Contains(ip)
|
||||
}
|
||||
|
||||
// Broadcast returns the directed broadcast address of the network.
|
||||
func (n *Network) Broadcast() netip.Addr {
|
||||
if !n.Prefix.IsValid() || !n.Prefix.Addr().Is4() || n.Prefix.Bits() >= 31 {
|
||||
return netip.AddrFrom4([4]byte{255, 255, 255, 255})
|
||||
}
|
||||
a := n.Prefix.Masked().Addr().As4()
|
||||
v := binary.BigEndian.Uint32(a[:]) | ^uint32(0)>>n.Prefix.Bits()
|
||||
binary.BigEndian.PutUint32(a[:], v)
|
||||
return netip.AddrFrom4(a)
|
||||
}
|
||||
|
||||
// DefaultRange returns the prefix scanned when no range is given. Very large
|
||||
// networks are narrowed to the /24 around the local address.
|
||||
func (n *Network) DefaultRange() netip.Prefix {
|
||||
if n.Prefix.Bits() < 20 {
|
||||
p, _ := n.LocalIP.Prefix(24)
|
||||
return p
|
||||
}
|
||||
return n.Prefix.Masked()
|
||||
}
|
||||
|
||||
// DetectNetwork finds the interface to scan. With an empty name it picks the
|
||||
// interface that carries the default route.
|
||||
func DetectNetwork(ifaceName string) (*Network, error) {
|
||||
var iface *net.Interface
|
||||
var err error
|
||||
if ifaceName != "" {
|
||||
iface, err = net.InterfaceByName(ifaceName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("interface %q: %w", ifaceName, err)
|
||||
}
|
||||
} else if iface, err = defaultInterface(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ip, prefix, ok := ipv4Of(iface)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("interface %s has no IPv4 address", iface.Name)
|
||||
}
|
||||
return &Network{
|
||||
Iface: iface,
|
||||
LocalIP: ip,
|
||||
LocalMAC: iface.HardwareAddr,
|
||||
Prefix: prefix,
|
||||
Gateway: defaultGateway(iface),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Interfaces returns all interfaces that are up and have an IPv4 address.
|
||||
func Interfaces() []*Network {
|
||||
ifaces, _ := net.Interfaces()
|
||||
var out []*Network
|
||||
for i := range ifaces {
|
||||
iface := &ifaces[i]
|
||||
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
|
||||
continue
|
||||
}
|
||||
if ip, prefix, ok := ipv4Of(iface); ok {
|
||||
out = append(out, &Network{Iface: iface, LocalIP: ip, LocalMAC: iface.HardwareAddr, Prefix: prefix})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func defaultInterface() (*net.Interface, error) {
|
||||
// Connecting a UDP socket sends nothing, but makes the kernel pick the
|
||||
// source address of the default route.
|
||||
if c, err := net.Dial("udp4", "192.0.2.1:9"); err == nil {
|
||||
local, _ := netip.AddrFromSlice(c.LocalAddr().(*net.UDPAddr).IP)
|
||||
c.Close()
|
||||
for _, n := range Interfaces() {
|
||||
if n.LocalIP == local.Unmap() {
|
||||
return n.Iface, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, n := range Interfaces() {
|
||||
if n.LocalIP.IsPrivate() {
|
||||
return n.Iface, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("no active network interface found (use -i)")
|
||||
}
|
||||
|
||||
func ipv4Of(iface *net.Interface) (netip.Addr, netip.Prefix, bool) {
|
||||
addrs, err := iface.Addrs()
|
||||
if err != nil {
|
||||
return netip.Addr{}, netip.Prefix{}, false
|
||||
}
|
||||
for _, a := range addrs {
|
||||
ipn, ok := a.(*net.IPNet)
|
||||
if !ok || ipn.IP.To4() == nil {
|
||||
continue
|
||||
}
|
||||
ip := netip.AddrFrom4([4]byte(ipn.IP.To4()))
|
||||
if ip.IsLinkLocalUnicast() {
|
||||
continue
|
||||
}
|
||||
bits, _ := ipn.Mask.Size()
|
||||
return ip, netip.PrefixFrom(ip, bits), true
|
||||
}
|
||||
return netip.Addr{}, netip.Prefix{}, false
|
||||
}
|
||||
|
||||
// ParseRange accepts a CIDR prefix ("192.168.1.0/24"), a single address or an
|
||||
// address range ("192.168.1.10-50", "192.168.1.10-192.168.1.80"). Several
|
||||
// specs can be separated by commas.
|
||||
func ParseRange(spec string) ([]netip.Addr, error) {
|
||||
seen := make(map[netip.Addr]bool)
|
||||
var out []netip.Addr
|
||||
add := func(a netip.Addr) error {
|
||||
if !seen[a] {
|
||||
if len(out) >= maxTargets {
|
||||
return fmt.Errorf("range too large (max. %d addresses)", maxTargets)
|
||||
}
|
||||
seen[a] = true
|
||||
out = append(out, a)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, part := range strings.Split(spec, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
addrs, err := parseRangePart(part)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, a := range addrs {
|
||||
if err := add(a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, errors.New("empty address range")
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Less(out[j]) })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func parseRangePart(part string) ([]netip.Addr, error) {
|
||||
if strings.Contains(part, "/") {
|
||||
p, err := netip.ParsePrefix(part)
|
||||
if err != nil || !p.Addr().Is4() {
|
||||
return nil, fmt.Errorf("invalid network %q", part)
|
||||
}
|
||||
return PrefixHosts(p)
|
||||
}
|
||||
from, to, isRange := strings.Cut(part, "-")
|
||||
start, err := netip.ParseAddr(strings.TrimSpace(from))
|
||||
if err != nil || !start.Is4() {
|
||||
return nil, fmt.Errorf("invalid address %q", from)
|
||||
}
|
||||
if !isRange {
|
||||
return []netip.Addr{start}, nil
|
||||
}
|
||||
to = strings.TrimSpace(to)
|
||||
end, err := netip.ParseAddr(to)
|
||||
if err != nil {
|
||||
// Short form: only the last octet is given.
|
||||
n, convErr := strconv.Atoi(to)
|
||||
if convErr != nil || n < 0 || n > 255 {
|
||||
return nil, fmt.Errorf("invalid range end %q", to)
|
||||
}
|
||||
b := start.As4()
|
||||
b[3] = byte(n)
|
||||
end = netip.AddrFrom4(b)
|
||||
}
|
||||
if !end.Is4() || end.Less(start) {
|
||||
return nil, fmt.Errorf("invalid range %q", part)
|
||||
}
|
||||
var out []netip.Addr
|
||||
for a := start; a.Compare(end) <= 0 && a.IsValid(); a = a.Next() {
|
||||
if len(out) >= maxTargets {
|
||||
return nil, fmt.Errorf("range too large (max. %d addresses)", maxTargets)
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PrefixHosts lists the usable host addresses of an IPv4 prefix.
|
||||
func PrefixHosts(p netip.Prefix) ([]netip.Addr, error) {
|
||||
p = p.Masked()
|
||||
if p.Bits() < 16 {
|
||||
return nil, fmt.Errorf("network %s too large (at most /16)", p)
|
||||
}
|
||||
var out []netip.Addr
|
||||
for a := p.Addr(); p.Contains(a); a = a.Next() {
|
||||
out = append(out, a)
|
||||
}
|
||||
if p.Bits() < 31 && len(out) > 2 {
|
||||
out = out[1 : len(out)-1] // network and broadcast address
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// validMAC filters out empty, broadcast and multicast link-layer addresses.
|
||||
func validMAC(b []byte) bool {
|
||||
if len(b) != 6 || b[0]&1 == 1 {
|
||||
return false
|
||||
}
|
||||
for _, x := range b {
|
||||
if x != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// parseLooseMAC parses MACs whose octets may lack leading zeros ("0:1a:2:...")
|
||||
// as printed by BSD arp(8).
|
||||
func parseLooseMAC(s string) (net.HardwareAddr, bool) {
|
||||
parts := strings.FieldsFunc(s, func(r rune) bool { return r == ':' || r == '-' })
|
||||
if len(parts) != 6 {
|
||||
return nil, false
|
||||
}
|
||||
mac := make(net.HardwareAddr, 6)
|
||||
for i, p := range parts {
|
||||
v, err := strconv.ParseUint(p, 16, 8)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
mac[i] = byte(v)
|
||||
}
|
||||
return mac, validMAC(mac)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PortResult describes an open TCP port.
|
||||
type PortResult struct {
|
||||
Port int `json:"port"`
|
||||
Service string `json:"service,omitempty"`
|
||||
RTT time.Duration `json:"-"`
|
||||
}
|
||||
|
||||
var wellKnownPorts = map[int]string{
|
||||
20: "ftp-data", 21: "ftp", 22: "ssh", 23: "telnet", 25: "smtp", 53: "dns",
|
||||
80: "http", 81: "http-alt", 88: "kerberos", 110: "pop3", 111: "rpcbind",
|
||||
135: "msrpc", 139: "netbios-ssn", 143: "imap", 179: "bgp", 389: "ldap",
|
||||
443: "https", 445: "smb", 465: "smtps", 515: "lpd", 548: "afp", 554: "rtsp",
|
||||
587: "submission", 631: "ipp", 636: "ldaps", 873: "rsync", 902: "vmware",
|
||||
993: "imaps", 995: "pop3s", 1080: "socks", 1194: "openvpn", 1400: "sonos",
|
||||
1433: "mssql", 1521: "oracle", 1723: "pptp", 1883: "mqtt", 2049: "nfs",
|
||||
2375: "docker", 2376: "docker-tls", 3000: "http-dev", 3128: "squid",
|
||||
3306: "mysql", 3389: "rdp", 3689: "daap", 4443: "https-alt", 5000: "upnp",
|
||||
5001: "synology", 5060: "sip", 5222: "xmpp", 5357: "wsd", 5432: "postgresql",
|
||||
5900: "vnc", 5985: "winrm", 6379: "redis", 6443: "kubernetes", 6881: "bittorrent",
|
||||
7000: "airplay", 7547: "tr-069", 8000: "http-alt", 8008: "http-alt",
|
||||
8009: "chromecast", 8080: "http-proxy", 8081: "http-alt", 8123: "home-assistant",
|
||||
8200: "dlna", 8443: "https-alt", 8554: "rtsp-alt", 8883: "mqtt-tls",
|
||||
8888: "http-alt", 9000: "http-alt", 9090: "http-alt", 9091: "transmission",
|
||||
9100: "jetdirect", 9200: "elasticsearch", 10000: "webmin", 11211: "memcached",
|
||||
27017: "mongodb", 32400: "plex", 49000: "tr-064", 62078: "iphone-sync",
|
||||
}
|
||||
|
||||
// ServiceName returns the conventional service on a TCP port, if known.
|
||||
func ServiceName(port int) string { return wellKnownPorts[port] }
|
||||
|
||||
// TopPorts returns the commonly used ports nscan knows by name.
|
||||
func TopPorts() []int {
|
||||
ports := make([]int, 0, len(wellKnownPorts))
|
||||
for p := range wellKnownPorts {
|
||||
ports = append(ports, p)
|
||||
}
|
||||
sort.Ints(ports)
|
||||
return ports
|
||||
}
|
||||
|
||||
// ParsePorts understands "top", "all" and lists like "22,80,8000-8100".
|
||||
func ParsePorts(spec string) ([]int, error) {
|
||||
switch strings.TrimSpace(spec) {
|
||||
case "", "top":
|
||||
return TopPorts(), nil
|
||||
case "all":
|
||||
spec = "1-65535"
|
||||
}
|
||||
seen := map[int]bool{}
|
||||
var ports []int
|
||||
for _, part := range strings.Split(spec, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
lo, hi, isRange := strings.Cut(part, "-")
|
||||
a, err := strconv.Atoi(lo)
|
||||
b := a
|
||||
if err == nil && isRange {
|
||||
b, err = strconv.Atoi(hi)
|
||||
}
|
||||
if err != nil || a < 1 || b > 65535 || b < a {
|
||||
return nil, fmt.Errorf("invalid port spec %q", part)
|
||||
}
|
||||
for p := a; p <= b; p++ {
|
||||
if !seen[p] {
|
||||
seen[p] = true
|
||||
ports = append(ports, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(ports) == 0 {
|
||||
return nil, fmt.Errorf("no ports given")
|
||||
}
|
||||
sort.Ints(ports)
|
||||
return ports, nil
|
||||
}
|
||||
|
||||
// ScanPorts probes ports with TCP connects. onOpen is called for every open
|
||||
// port, onProgress roughly every percent; both may be called concurrently.
|
||||
func ScanPorts(ctx context.Context, ip netip.Addr, ports []int, timeout time.Duration, workers int,
|
||||
onOpen func(PortResult), onProgress func(done, total int)) {
|
||||
if workers <= 0 {
|
||||
workers = 200
|
||||
}
|
||||
total := len(ports)
|
||||
step := max(1, total/100)
|
||||
var done atomic.Int64
|
||||
jobs := make(chan int)
|
||||
var wg sync.WaitGroup
|
||||
for range min(workers, total) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
var d net.Dialer
|
||||
for p := range jobs {
|
||||
dctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
start := time.Now()
|
||||
c, err := d.DialContext(dctx, "tcp4", netip.AddrPortFrom(ip, uint16(p)).String())
|
||||
cancel()
|
||||
if err == nil {
|
||||
c.Close()
|
||||
onOpen(PortResult{Port: p, Service: ServiceName(p), RTT: time.Since(start)})
|
||||
}
|
||||
if n := int(done.Add(1)); onProgress != nil && (n%step == 0 || n == total) {
|
||||
onProgress(n, total)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
feed:
|
||||
for _, p := range ports {
|
||||
select {
|
||||
case jobs <- p:
|
||||
case <-ctx.Done():
|
||||
break feed
|
||||
}
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//go:build darwin
|
||||
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/net/route"
|
||||
)
|
||||
|
||||
// arpViaExec is set once the routing sysctl came back empty while arp(8)
|
||||
// returned entries; from then on arp(8) is asked directly.
|
||||
var arpViaExec atomic.Bool
|
||||
|
||||
// readARPTable returns the complete entries of the kernel's ARP cache.
|
||||
func readARPTable() (map[netip.Addr]net.HardwareAddr, error) {
|
||||
if !arpViaExec.Load() {
|
||||
if table, err := readARPSysctl(); err == nil && len(table) > 0 {
|
||||
return table, nil
|
||||
}
|
||||
}
|
||||
table, err := readARPExec()
|
||||
if err == nil && len(table) > 0 {
|
||||
arpViaExec.Store(true)
|
||||
}
|
||||
return table, err
|
||||
}
|
||||
|
||||
func readARPSysctl() (map[netip.Addr]net.HardwareAddr, error) {
|
||||
b, err := route.FetchRIB(syscall.AF_INET, syscall.NET_RT_FLAGS, syscall.RTF_LLINFO)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msgs, err := route.ParseRIB(syscall.NET_RT_FLAGS, b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
table := make(map[netip.Addr]net.HardwareAddr)
|
||||
for _, m := range msgs {
|
||||
rm, ok := m.(*route.RouteMessage)
|
||||
if !ok || len(rm.Addrs) <= syscall.RTAX_GATEWAY {
|
||||
continue
|
||||
}
|
||||
dst, ok1 := rm.Addrs[syscall.RTAX_DST].(*route.Inet4Addr)
|
||||
ll, ok2 := rm.Addrs[syscall.RTAX_GATEWAY].(*route.LinkAddr)
|
||||
if !ok1 || !ok2 || !validMAC(ll.Addr) {
|
||||
continue
|
||||
}
|
||||
table[netip.AddrFrom4(dst.IP)] = net.HardwareAddr(slices.Clone(ll.Addr))
|
||||
}
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// defaultGateway returns the IPv4 default gateway reached via iface.
|
||||
func defaultGateway(iface *net.Interface) netip.Addr {
|
||||
b, err := route.FetchRIB(syscall.AF_INET, route.RIBTypeRoute, 0)
|
||||
if err != nil {
|
||||
return netip.Addr{}
|
||||
}
|
||||
msgs, err := route.ParseRIB(route.RIBTypeRoute, b)
|
||||
if err != nil {
|
||||
return netip.Addr{}
|
||||
}
|
||||
for _, m := range msgs {
|
||||
rm, ok := m.(*route.RouteMessage)
|
||||
if !ok || rm.Flags&syscall.RTF_GATEWAY == 0 || len(rm.Addrs) <= syscall.RTAX_NETMASK {
|
||||
continue
|
||||
}
|
||||
if iface != nil && rm.Index != iface.Index {
|
||||
continue
|
||||
}
|
||||
dst, ok := rm.Addrs[syscall.RTAX_DST].(*route.Inet4Addr)
|
||||
if !ok || dst.IP != [4]byte{} {
|
||||
continue
|
||||
}
|
||||
if mask, ok := rm.Addrs[syscall.RTAX_NETMASK].(*route.Inet4Addr); ok && mask.IP != [4]byte{} {
|
||||
continue
|
||||
}
|
||||
if gw, ok := rm.Addrs[syscall.RTAX_GATEWAY].(*route.Inet4Addr); ok {
|
||||
return netip.AddrFrom4(gw.IP)
|
||||
}
|
||||
}
|
||||
return netip.Addr{}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//go:build linux
|
||||
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// readARPTable returns the complete entries of the kernel's ARP cache.
|
||||
func readARPTable() (map[netip.Addr]net.HardwareAddr, error) {
|
||||
f, err := os.Open("/proc/net/arp")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
table := make(map[netip.Addr]net.HardwareAddr)
|
||||
sc := bufio.NewScanner(f)
|
||||
sc.Scan() // header
|
||||
for sc.Scan() {
|
||||
fields := strings.Fields(sc.Text())
|
||||
if len(fields) < 4 {
|
||||
continue
|
||||
}
|
||||
flags, _ := strconv.ParseUint(strings.TrimPrefix(fields[2], "0x"), 16, 32)
|
||||
if flags&0x2 == 0 { // ATF_COM: entry is complete
|
||||
continue
|
||||
}
|
||||
ip, err := netip.ParseAddr(fields[0])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if mac, err := net.ParseMAC(fields[3]); err == nil && validMAC(mac) {
|
||||
table[ip] = mac
|
||||
}
|
||||
}
|
||||
return table, sc.Err()
|
||||
}
|
||||
|
||||
// defaultGateway returns the IPv4 default gateway reached via iface.
|
||||
func defaultGateway(iface *net.Interface) netip.Addr {
|
||||
f, err := os.Open("/proc/net/route")
|
||||
if err != nil {
|
||||
return netip.Addr{}
|
||||
}
|
||||
defer f.Close()
|
||||
sc := bufio.NewScanner(f)
|
||||
sc.Scan() // header
|
||||
for sc.Scan() {
|
||||
fields := strings.Fields(sc.Text())
|
||||
if len(fields) < 3 || fields[1] != "00000000" {
|
||||
continue
|
||||
}
|
||||
if iface != nil && fields[0] != iface.Name {
|
||||
continue
|
||||
}
|
||||
v, err := strconv.ParseUint(fields[2], 16, 32)
|
||||
if err != nil || v == 0 {
|
||||
continue
|
||||
}
|
||||
var b [4]byte
|
||||
binary.LittleEndian.PutUint32(b[:], uint32(v))
|
||||
return netip.AddrFrom4(b)
|
||||
}
|
||||
return netip.Addr{}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !darwin && !linux
|
||||
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
func readARPTable() (map[netip.Addr]net.HardwareAddr, error) { return readARPExec() }
|
||||
|
||||
func defaultGateway(*net.Interface) netip.Addr { return netip.Addr{} }
|
||||
@@ -0,0 +1,458 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"slices"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Host is a device discovered on the network.
|
||||
type Host struct {
|
||||
IP netip.Addr
|
||||
MAC net.HardwareAddr
|
||||
Vendor string
|
||||
MDNSName string
|
||||
NetBIOSName string
|
||||
DNSName string
|
||||
Services []Service
|
||||
Model string // announced via Bonjour device-info, e.g. "MacBookAir10,1"
|
||||
RTT time.Duration
|
||||
Via string // how the host was found: self, icmp, arp, tcp, mdns
|
||||
Self bool
|
||||
Gateway bool
|
||||
}
|
||||
|
||||
// Name returns the most descriptive name discovered for the host.
|
||||
func (h *Host) Name() string {
|
||||
for _, n := range []string{h.MDNSName, h.NetBIOSName, h.DNSName} {
|
||||
if n != "" {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (h *Host) clone() Host {
|
||||
c := *h
|
||||
c.MAC = slices.Clone(h.MAC)
|
||||
c.Services = slices.Clone(h.Services)
|
||||
return c
|
||||
}
|
||||
|
||||
// Progress reports which phase a scan is in.
|
||||
type Progress struct {
|
||||
Phase string
|
||||
Done int
|
||||
Total int
|
||||
}
|
||||
|
||||
// Options configure a scan.
|
||||
type Options struct {
|
||||
Network *Network
|
||||
Targets []netip.Addr
|
||||
// Wait is how long to wait for late replies after the ping sweep.
|
||||
Wait time.Duration
|
||||
Names bool
|
||||
Bonjour bool
|
||||
Vendor func(net.HardwareAddr) string
|
||||
|
||||
// OnHost is called whenever a host is found or learns new details.
|
||||
OnHost func(Host)
|
||||
OnProgress func(Progress)
|
||||
}
|
||||
|
||||
type scan struct {
|
||||
opt Options
|
||||
net *Network
|
||||
targets map[netip.Addr]bool
|
||||
|
||||
mu sync.Mutex
|
||||
hosts map[netip.Addr]*Host
|
||||
}
|
||||
|
||||
// Scan discovers the hosts in opt.Targets. Discovery combines an ICMP echo
|
||||
// sweep with the kernel's ARP cache, so devices that ignore pings are still
|
||||
// found on the local segment; outside of it, TCP connects are tried instead.
|
||||
func Scan(ctx context.Context, opt Options) ([]Host, error) {
|
||||
if opt.Wait <= 0 {
|
||||
opt.Wait = 1500 * time.Millisecond
|
||||
}
|
||||
s := &scan{
|
||||
opt: opt,
|
||||
net: opt.Network,
|
||||
targets: make(map[netip.Addr]bool, len(opt.Targets)),
|
||||
hosts: make(map[netip.Addr]*Host),
|
||||
}
|
||||
for _, ip := range opt.Targets {
|
||||
s.targets[ip] = true
|
||||
}
|
||||
|
||||
var bonjour bonjourResult
|
||||
var bwg sync.WaitGroup
|
||||
if opt.Bonjour && s.net.Iface != nil {
|
||||
bwg.Add(1)
|
||||
go func() {
|
||||
defer bwg.Done()
|
||||
bonjour = browseBonjour(ctx, s.net.Iface, opt.Wait+2*time.Second)
|
||||
}()
|
||||
}
|
||||
|
||||
if s.targets[s.net.LocalIP] {
|
||||
s.found(s.net.LocalIP, func(h *Host) bool {
|
||||
h.Via, h.MDNSName = "self", localHostname()
|
||||
s.setMAC(h, s.net.LocalMAC)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
s.sweep(ctx)
|
||||
s.tcpSweep(ctx)
|
||||
s.arpPass()
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if opt.Names {
|
||||
s.resolveNames(ctx)
|
||||
}
|
||||
if opt.Bonjour {
|
||||
s.progress("Bonjour", 0, 0)
|
||||
}
|
||||
bwg.Wait()
|
||||
s.mergeBonjour(bonjour)
|
||||
if opt.Names {
|
||||
s.resolveModels(ctx)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]Host, 0, len(s.hosts))
|
||||
for _, h := range s.hosts {
|
||||
out = append(out, h.clone())
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].IP.Less(out[j].IP) })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// found creates or updates the host for ip. update reports whether it changed
|
||||
// anything; only then (or for new hosts) OnHost fires.
|
||||
func (s *scan) found(ip netip.Addr, update func(h *Host) bool) {
|
||||
s.mu.Lock()
|
||||
h, ok := s.hosts[ip]
|
||||
if !ok {
|
||||
h = &Host{IP: ip, Self: ip == s.net.LocalIP, Gateway: ip == s.net.Gateway}
|
||||
s.hosts[ip] = h
|
||||
}
|
||||
changed := update(h) || !ok
|
||||
snap := h.clone()
|
||||
s.mu.Unlock()
|
||||
if changed && s.opt.OnHost != nil {
|
||||
s.opt.OnHost(snap)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *scan) has(ip netip.Addr) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, ok := s.hosts[ip]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *scan) alive() []netip.Addr {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
ips := make([]netip.Addr, 0, len(s.hosts))
|
||||
for ip := range s.hosts {
|
||||
ips = append(ips, ip)
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
func (s *scan) setMAC(h *Host, mac net.HardwareAddr) bool {
|
||||
if len(mac) == 0 || bytes.Equal(h.MAC, mac) {
|
||||
return false
|
||||
}
|
||||
h.MAC = slices.Clone(mac)
|
||||
if s.opt.Vendor != nil {
|
||||
h.Vendor = s.opt.Vendor(mac)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *scan) progress(phase string, done, total int) {
|
||||
if s.opt.OnProgress != nil {
|
||||
s.opt.OnProgress(Progress{Phase: phase, Done: done, Total: total})
|
||||
}
|
||||
}
|
||||
|
||||
// sweep sends two rounds of echo requests. Each request also makes the kernel
|
||||
// resolve the target via ARP, so the ARP cache is polled in parallel.
|
||||
func (s *scan) sweep(ctx context.Context) {
|
||||
sock, err := openICMP()
|
||||
var nudge *net.UDPConn
|
||||
if err != nil {
|
||||
// Without ICMP, any UDP datagram still triggers ARP resolution.
|
||||
nudge, _ = net.ListenUDP("udp4", nil)
|
||||
if nudge != nil {
|
||||
defer nudge.Close()
|
||||
}
|
||||
}
|
||||
|
||||
var rwg sync.WaitGroup
|
||||
if sock != nil {
|
||||
rwg.Add(1)
|
||||
go func() {
|
||||
defer rwg.Done()
|
||||
buf := make([]byte, 1500)
|
||||
for {
|
||||
r, err := sock.readEcho(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if !s.targets[r.From] {
|
||||
continue
|
||||
}
|
||||
s.found(r.From, func(h *Host) bool {
|
||||
changed := false
|
||||
if h.RTT == 0 || r.RTT < h.RTT {
|
||||
h.RTT, changed = r.RTT, true
|
||||
}
|
||||
if h.Via == "" || h.Via == "arp" {
|
||||
h.Via, changed = "icmp", true
|
||||
}
|
||||
return changed
|
||||
})
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
arpDone := make(chan struct{})
|
||||
var awg sync.WaitGroup
|
||||
awg.Add(1)
|
||||
go func() {
|
||||
defer awg.Done()
|
||||
t := time.NewTicker(600 * time.Millisecond)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-arpDone:
|
||||
return
|
||||
case <-t.C:
|
||||
s.arpPass()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
id := os.Getpid() & 0xffff
|
||||
total := len(s.opt.Targets)
|
||||
for round := 1; round <= 2 && ctx.Err() == nil; round++ {
|
||||
for i, ip := range s.opt.Targets {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if round == 1 && (i%32 == 0 || i == total-1) {
|
||||
s.progress("Ping", i+1, total)
|
||||
}
|
||||
if ip == s.net.LocalIP || (round == 2 && s.has(ip)) {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case sock != nil:
|
||||
sock.sendEcho(ip, id, round)
|
||||
case nudge != nil && s.net.OnLink(ip):
|
||||
nudge.WriteToUDPAddrPort([]byte{0}, netip.AddrPortFrom(ip, 9))
|
||||
}
|
||||
if i%8 == 7 {
|
||||
time.Sleep(3 * time.Millisecond) // ~2500 pps keeps ARP queues happy
|
||||
}
|
||||
}
|
||||
if round == 1 {
|
||||
s.progress("Waiting for replies", 0, 0)
|
||||
sleepCtx(ctx, s.opt.Wait/2)
|
||||
}
|
||||
}
|
||||
sleepCtx(ctx, s.opt.Wait)
|
||||
|
||||
close(arpDone)
|
||||
awg.Wait()
|
||||
if sock != nil {
|
||||
sock.Close()
|
||||
rwg.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// tcpSweep probes targets outside the local segment that stayed silent,
|
||||
// since neither ARP nor (often) ICMP gets through routers and firewalls.
|
||||
func (s *scan) tcpSweep(ctx context.Context) {
|
||||
var pending []netip.Addr
|
||||
for _, ip := range s.opt.Targets {
|
||||
if !s.net.OnLink(ip) && !s.has(ip) {
|
||||
pending = append(pending, ip)
|
||||
}
|
||||
}
|
||||
if len(pending) == 0 {
|
||||
return
|
||||
}
|
||||
sem := make(chan struct{}, 256)
|
||||
var wg sync.WaitGroup
|
||||
for i, ip := range pending {
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
wg.Wait()
|
||||
return
|
||||
}
|
||||
if i%16 == 0 || i == len(pending)-1 {
|
||||
s.progress("TCP probe", i+1, len(pending))
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(ip netip.Addr) {
|
||||
defer func() { <-sem; wg.Done() }()
|
||||
if rtt, ok := tcpAlive(ctx, ip, probePorts, 800*time.Millisecond); ok {
|
||||
s.found(ip, func(h *Host) bool {
|
||||
h.RTT, h.Via = rtt, "tcp"
|
||||
return true
|
||||
})
|
||||
}
|
||||
}(ip)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// arpPass adds every complete ARP cache entry within the target set.
|
||||
func (s *scan) arpPass() {
|
||||
table, err := readARPTable()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for ip, mac := range table {
|
||||
if !s.targets[ip] || !s.net.OnLink(ip) {
|
||||
continue
|
||||
}
|
||||
s.found(ip, func(h *Host) bool {
|
||||
changed := s.setMAC(h, mac)
|
||||
if h.Via == "" {
|
||||
h.Via, changed = "arp", true
|
||||
}
|
||||
return changed
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *scan) resolveNames(ctx context.Context) {
|
||||
ips := s.alive()
|
||||
s.progress("Names", 0, len(ips))
|
||||
const timeout = 1500 * time.Millisecond
|
||||
var wg sync.WaitGroup
|
||||
apply := func(names map[netip.Addr]string, set func(h *Host, name string) bool) {
|
||||
for ip, name := range names {
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
s.found(ip, func(h *Host) bool { return set(h, name) })
|
||||
}
|
||||
}
|
||||
wg.Add(3)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
apply(mdnsReverse(ctx, ips, timeout), func(h *Host, n string) bool {
|
||||
if h.MDNSName == n || h.Self {
|
||||
return false
|
||||
}
|
||||
h.MDNSName = n
|
||||
return true
|
||||
})
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
apply(netbiosNames(ctx, ips, timeout), func(h *Host, n string) bool {
|
||||
if h.NetBIOSName == n {
|
||||
return false
|
||||
}
|
||||
h.NetBIOSName = n
|
||||
return true
|
||||
})
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
apply(reverseDNS(ctx, ips, 2*timeout), func(h *Host, n string) bool {
|
||||
if h.DNSName == n {
|
||||
return false
|
||||
}
|
||||
h.DNSName = n
|
||||
return true
|
||||
})
|
||||
}()
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// resolveModels asks every host with a known mDNS or service name for the
|
||||
// model it announces; devices with private MAC addresses are otherwise
|
||||
// anonymous.
|
||||
func (s *scan) resolveModels(ctx context.Context) {
|
||||
names := map[netip.Addr][]string{}
|
||||
s.mu.Lock()
|
||||
for ip, h := range s.hosts {
|
||||
var ns []string
|
||||
if h.MDNSName != "" {
|
||||
ns = append(ns, h.MDNSName)
|
||||
}
|
||||
for _, svc := range h.Services {
|
||||
if svc.Instance != "" && !slices.Contains(ns, svc.Instance) {
|
||||
ns = append(ns, svc.Instance)
|
||||
}
|
||||
}
|
||||
if len(ns) > 0 {
|
||||
names[ip] = ns
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if len(names) == 0 {
|
||||
return
|
||||
}
|
||||
s.progress("Models", 0, 0)
|
||||
for ip, model := range deviceModels(ctx, names, time.Second) {
|
||||
s.found(ip, func(h *Host) bool {
|
||||
if h.Model == model {
|
||||
return false
|
||||
}
|
||||
h.Model = model
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *scan) mergeBonjour(b bonjourResult) {
|
||||
for ip, svcs := range b.services {
|
||||
if !s.targets[ip] {
|
||||
continue
|
||||
}
|
||||
s.found(ip, func(h *Host) bool {
|
||||
h.Services = svcs
|
||||
if h.Via == "" {
|
||||
h.Via = "mdns"
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
for ip, name := range b.hostnames {
|
||||
if !s.targets[ip] || !s.has(ip) {
|
||||
continue
|
||||
}
|
||||
s.found(ip, func(h *Host) bool {
|
||||
if h.MDNSName != "" {
|
||||
return false
|
||||
}
|
||||
h.MDNSName = name
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/dns/dnsmessage"
|
||||
)
|
||||
|
||||
func TestParseRange(t *testing.T) {
|
||||
tests := []struct {
|
||||
spec string
|
||||
n int
|
||||
first, end string
|
||||
}{
|
||||
{"192.168.1.0/24", 254, "192.168.1.1", "192.168.1.254"},
|
||||
{"192.168.1.77/30", 2, "192.168.1.77", "192.168.1.78"},
|
||||
{"10.0.0.5", 1, "10.0.0.5", "10.0.0.5"},
|
||||
{"10.0.0.10-20", 11, "10.0.0.10", "10.0.0.20"},
|
||||
{"10.0.0.250-10.0.1.3", 10, "10.0.0.250", "10.0.1.3"},
|
||||
{"10.0.0.3, 10.0.0.1-3", 3, "10.0.0.1", "10.0.0.3"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got, err := ParseRange(tt.spec)
|
||||
if err != nil {
|
||||
t.Errorf("ParseRange(%q): %v", tt.spec, err)
|
||||
continue
|
||||
}
|
||||
if len(got) != tt.n || got[0].String() != tt.first || got[len(got)-1].String() != tt.end {
|
||||
t.Errorf("ParseRange(%q) = %d addrs %v…%v, want %d %s…%s", tt.spec, len(got), got[0], got[len(got)-1], tt.n, tt.first, tt.end)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "foo", "10.0.0.20-10", "10.0.0.0/8", "10.0.0.1-300", "::1"} {
|
||||
if _, err := ParseRange(bad); err == nil {
|
||||
t.Errorf("ParseRange(%q) succeeded, want error", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkHelpers(t *testing.T) {
|
||||
n := &Network{Prefix: netip.MustParsePrefix("192.168.178.23/24"), LocalIP: netip.MustParseAddr("192.168.178.23")}
|
||||
if got := n.Broadcast().String(); got != "192.168.178.255" {
|
||||
t.Errorf("Broadcast = %s", got)
|
||||
}
|
||||
if !n.OnLink(netip.MustParseAddr("192.168.178.1")) || n.OnLink(netip.MustParseAddr("192.168.179.1")) {
|
||||
t.Error("OnLink wrong")
|
||||
}
|
||||
big := &Network{Prefix: netip.MustParsePrefix("10.20.30.40/16"), LocalIP: netip.MustParseAddr("10.20.30.40")}
|
||||
if got := big.DefaultRange().String(); got != "10.20.30.0/24" {
|
||||
t.Errorf("DefaultRange of /16 = %s, want the local /24", got)
|
||||
}
|
||||
mid := &Network{Prefix: netip.MustParsePrefix("172.16.40.180/20"), LocalIP: netip.MustParseAddr("172.16.40.180")}
|
||||
if got := mid.DefaultRange().String(); got != "172.16.32.0/20" {
|
||||
t.Errorf("DefaultRange of /20 = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLooseMAC(t *testing.T) {
|
||||
mac, ok := parseLooseMAC("0:1a:2:b3:4:5")
|
||||
if !ok || mac.String() != "00:1a:02:b3:04:05" {
|
||||
t.Errorf("got %v %v", mac, ok)
|
||||
}
|
||||
if _, ok := parseLooseMAC("ff-ff-ff-ff-ff-ff"); ok {
|
||||
t.Error("broadcast accepted")
|
||||
}
|
||||
if _, ok := parseLooseMAC("01:00:5e:00:00:fb"); ok {
|
||||
t.Error("multicast accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseARPOutput(t *testing.T) {
|
||||
out := `? (10.0.1.1) at 3c:22:fb:12:34:56 on en1 ifscope [ethernet]
|
||||
? (10.0.1.2) at (incomplete) on en1 ifscope [ethernet]
|
||||
? (10.0.1.205) at e:4f:6b:00:00:21 on en1 ifscope [ethernet]
|
||||
? (10.0.1.255) at ff:ff:ff:ff:ff:ff on en1 ifscope [ethernet]
|
||||
? (224.0.0.251) at 1:0:5e:0:0:fb on en1 ifscope permanent [ethernet]
|
||||
192.168.0.1 00-11-22-33-44-55 dynamic
|
||||
`
|
||||
table := parseARPOutput(out)
|
||||
want := map[string]string{
|
||||
"10.0.1.1": "3c:22:fb:12:34:56",
|
||||
"10.0.1.205": "0e:4f:6b:00:00:21",
|
||||
"192.168.0.1": "00:11:22:33:44:55",
|
||||
}
|
||||
if len(table) != len(want) {
|
||||
t.Fatalf("got %v", table)
|
||||
}
|
||||
for ip, mac := range want {
|
||||
if got := table[netip.MustParseAddr(ip)].String(); got != mac {
|
||||
t.Errorf("%s = %s, want %s", ip, got, mac)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePorts(t *testing.T) {
|
||||
got, err := ParsePorts("443, 22,8000-8002,22")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []int{22, 443, 8000, 8001, 8002}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("got %v, want %v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
if all, _ := ParsePorts("all"); len(all) != 65535 {
|
||||
t.Errorf("all = %d ports", len(all))
|
||||
}
|
||||
for _, bad := range []string{"0", "70000", "20-10", "abc"} {
|
||||
if _, err := ParsePorts(bad); err == nil {
|
||||
t.Errorf("ParsePorts(%q) succeeded", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReverseName(t *testing.T) {
|
||||
ip := netip.MustParseAddr("192.168.1.42")
|
||||
name := reverseName(ip)
|
||||
if name != "42.1.168.192.in-addr.arpa." {
|
||||
t.Fatalf("reverseName = %s", name)
|
||||
}
|
||||
if back, ok := parseReverseName(name); !ok || back != ip {
|
||||
t.Errorf("parseReverseName = %v %v", back, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanHostname(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"Mikes-MacBook-Pro.local.": "Mikes-MacBook-Pro",
|
||||
"fritz.box.": "fritz.box",
|
||||
"nas.fritz.box": "nas",
|
||||
"host.example.org.": "host.example.org",
|
||||
"printer.lan": "printer",
|
||||
} {
|
||||
if got := cleanHostname(in); got != want {
|
||||
t.Errorf("cleanHostname(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBonjourNames(t *testing.T) {
|
||||
inst := "Living Room TV._airplay._tcp.local."
|
||||
if got := serviceTypeOf(inst); got != "_airplay._tcp.local." {
|
||||
t.Errorf("serviceTypeOf = %q", got)
|
||||
}
|
||||
if got := instanceLabel(inst, "_airplay._tcp.local."); got != "Living Room TV" {
|
||||
t.Errorf("instanceLabel = %q", got)
|
||||
}
|
||||
if got := (Service{Type: "_googlecast._tcp"}).Short(); got != "googlecast" {
|
||||
t.Errorf("Short = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMDNSRoundTrip(t *testing.T) {
|
||||
// A responder's answer to our reverse query must yield the host name.
|
||||
name := dnsmessage.MustNewName(reverseName(netip.MustParseAddr("10.0.0.7")))
|
||||
b := dnsmessage.NewBuilder(nil, dnsmessage.Header{Response: true, Authoritative: true})
|
||||
b.StartAnswers()
|
||||
b.PTRResource(dnsmessage.ResourceHeader{Name: name, Type: dnsmessage.TypePTR, Class: dnsmessage.ClassINET, TTL: 120},
|
||||
dnsmessage.PTRResource{PTR: dnsmessage.MustNewName("Apple-TV.local.")})
|
||||
msg, err := b.Finish()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rrs := parseRecords(msg)
|
||||
if len(rrs) != 1 {
|
||||
t.Fatalf("got %d records", len(rrs))
|
||||
}
|
||||
ptr := rrs[0].Body.(*dnsmessage.PTRResource)
|
||||
if got := cleanHostname(ptr.PTR.String()); got != "Apple-TV" {
|
||||
t.Errorf("name = %q", got)
|
||||
}
|
||||
|
||||
q, err := question("_services._dns-sd._udp.local.", dnsmessage.TypePTR)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := buildQuery(0, q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNBStat(t *testing.T) {
|
||||
req := nbstatRequest(0x1234)
|
||||
if len(req) != 50 || req[12] != 0x20 || string(req[13:15]) != "CK" {
|
||||
t.Fatalf("bad request % x", req)
|
||||
}
|
||||
|
||||
// Response: header, the queried name, NBSTAT RR with a group name first.
|
||||
resp := []byte{0x12, 0x34, 0x84, 0x00, 0, 0, 0, 1, 0, 0, 0, 0}
|
||||
resp = append(resp, req[12:46]...)
|
||||
resp = append(resp, 0x00, 0x21, 0x00, 0x01, 0, 0, 0, 0)
|
||||
entry := func(name string, suffix byte, flags uint16) []byte {
|
||||
e := bytes.Repeat([]byte(" "), 15)
|
||||
copy(e, name)
|
||||
return append(e, suffix, byte(flags>>8), byte(flags))
|
||||
}
|
||||
rdata := []byte{2}
|
||||
rdata = append(rdata, entry("WORKGROUP", 0x00, 0x8400)...)
|
||||
rdata = append(rdata, entry("DESKTOP-ABC", 0x00, 0x0400)...)
|
||||
rdata = append(rdata, make([]byte, 6)...)
|
||||
resp = append(resp, byte(len(rdata)>>8), byte(len(rdata)))
|
||||
resp = append(resp, rdata...)
|
||||
|
||||
name, ok := parseNBStat(resp)
|
||||
if !ok || name != "DESKTOP-ABC" {
|
||||
t.Errorf("parseNBStat = %q %v", name, ok)
|
||||
}
|
||||
if _, ok := parseNBStat(resp[:20]); ok {
|
||||
t.Error("truncated response accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMagicPacket(t *testing.T) {
|
||||
mac, _ := net.ParseMAC("aa:bb:cc:dd:ee:ff")
|
||||
p, err := MagicPacket(mac)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(p) != 102 || !bytes.Equal(p[:6], bytes.Repeat([]byte{0xff}, 6)) || !bytes.Equal(p[96:], mac) {
|
||||
t.Errorf("bad packet % x", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVendorLabel(t *testing.T) {
|
||||
private, _ := net.ParseMAC("02:5a:7c:11:22:33")
|
||||
apple, _ := net.ParseMAC("d0:11:e5:12:34:56")
|
||||
tests := []struct {
|
||||
h Host
|
||||
maker, want string
|
||||
}{
|
||||
{Host{MAC: private, Vendor: "Private address", Model: "MacBookAir10,1"}, "Apple", "Apple MacBookAir10,1"},
|
||||
{Host{MAC: private, Vendor: "Private address"}, "Private address", "Private address"},
|
||||
{Host{MAC: private, Vendor: "Private address", Model: "VMware7,1"}, "Private address", "VMware7,1"},
|
||||
{Host{MAC: apple, Vendor: "Apple", Model: "Mac16,10"}, "Apple", "Apple Mac16,10"},
|
||||
{Host{MAC: apple, Vendor: "Apple"}, "Apple", "Apple"},
|
||||
{Host{Model: "iPhone15,3"}, "Apple", "Apple iPhone15,3"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := tt.h.Maker(); got != tt.maker {
|
||||
t.Errorf("Maker(%v) = %q, want %q", tt.h.Model, got, tt.maker)
|
||||
}
|
||||
if got := tt.h.VendorLabel(); got != tt.want {
|
||||
t.Errorf("VendorLabel(%v) = %q, want %q", tt.h.Model, got, tt.want)
|
||||
}
|
||||
}
|
||||
if txtValue([]string{"model=Mac16,10", "osxvers=26"}, "model") != "Mac16,10" {
|
||||
t.Error("txtValue")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeviceModelsLoopback(t *testing.T) {
|
||||
// The local mDNS responder answers for this machine, if there is one.
|
||||
got := deviceModels(t.Context(), map[netip.Addr][]string{netip.MustParseAddr("127.0.0.1"): {localHostname()}}, 500*time.Millisecond)
|
||||
t.Logf("loopback model: %q", got[netip.MustParseAddr("127.0.0.1")])
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
// MagicPacket builds a Wake-on-LAN packet: six 0xff bytes followed by the
|
||||
// MAC address repeated 16 times.
|
||||
func MagicPacket(mac net.HardwareAddr) ([]byte, error) {
|
||||
if len(mac) != 6 {
|
||||
return nil, fmt.Errorf("invalid MAC address %s", mac)
|
||||
}
|
||||
return append(bytes.Repeat([]byte{0xff}, 6), bytes.Repeat(mac, 16)...), nil
|
||||
}
|
||||
|
||||
// WakeOnLAN sends a magic packet to the limited broadcast address and, if
|
||||
// given, to the directed broadcast address of the network.
|
||||
func WakeOnLAN(mac net.HardwareAddr, broadcast netip.Addr) error {
|
||||
pkt, err := MagicPacket(mac)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
conn, err := net.ListenUDP("udp4", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
targets := []netip.Addr{netip.AddrFrom4([4]byte{255, 255, 255, 255})}
|
||||
if broadcast.IsValid() && broadcast != targets[0] {
|
||||
targets = append(targets, broadcast)
|
||||
}
|
||||
var lastErr error
|
||||
sent := 0
|
||||
for _, t := range targets {
|
||||
if _, err := conn.WriteToUDPAddrPort(pkt, netip.AddrPortFrom(t, 9)); err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
sent++
|
||||
}
|
||||
if sent == 0 {
|
||||
return lastErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user