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 } }