Debian Codegraph @

ping.go

raw symbols SCIP
1 // Copyright The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package probing is a simple but powerful ICMP echo (ping) library.
15 //
16 // Here is a very simple example that sends and receives three packets:
17 //
18 // pinger, err := probing.NewPinger("www.google.com")
19 // if err != nil {
20 // panic(err)
21 // }
22 // pinger.Count = 3
23 // err = pinger.Run() // blocks until finished
24 // if err != nil {
25 // panic(err)
26 // }
27 // stats := pinger.Statistics() // get send/receive/rtt stats
28 //
29 // Here is an example that emulates the traditional UNIX ping command:
30 //
31 // pinger, err := probing.NewPinger("www.google.com")
32 // if err != nil {
33 // panic(err)
34 // }
35 // // Listen for Ctrl-C.
36 // c := make(chan os.Signal, 1)
37 // signal.Notify(c, os.Interrupt)
38 // go func() {
39 // for _ = range c {
40 // pinger.Stop()
41 // }
42 // }()
43 // pinger.OnRecv = func(pkt *probing.Packet) {
44 // fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
45 // pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
46 // }
47 // pinger.OnFinish = func(stats *probing.Statistics) {
48 // fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr)
49 // fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n",
50 // stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
51 // fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
52 // stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
53 // }
54 // fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr())
55 // err = pinger.Run()
56 // if err != nil {
57 // panic(err)
58 // }
59 //
60 // It sends ICMP Echo Request packet(s) and waits for an Echo Reply in response.
61 // If it receives a response, it calls the OnRecv callback. When it's finished,
62 // it calls the OnFinish callback.
63 //
64 // For a full ping example, see "cmd/ping/ping.go".
65 package probing
66
67 import (
68 "bytes"
69 "context"
70 "errors"
71 "fmt"
72 "log"
73 "math"
74 "math/rand"
75 "net"
76 "runtime"
77 "slices"
78 "sync"
79 "sync/atomic"
80 "syscall"
81 "time"
82
83 "github.com/google/uuid"
84 "golang.org/x/net/icmp"
85 "golang.org/x/net/ipv4"
86 "golang.org/x/net/ipv6"
87 "golang.org/x/sync/errgroup"
88 )
89
90 const (
91 timeSliceLength = 8
92 trackerLength = len(uuid.UUID{})
93 protocolICMP = 1
94 protocolIPv6ICMP = 58
95
96 networkIP = "ip"
97 networkIPv4 = "ip4"
98 networkIPv6 = "ip6"
99 )
100
101 var (
102 ipv4Proto = map[string]string{"icmp": "ip4:icmp", "udp": "udp4"}
103 ipv6Proto = map[string]string{"icmp": "ip6:ipv6-icmp", "udp": "udp6"}
104
105 ErrMarkNotSupported = errors.New("setting SO_MARK socket option is not supported on this platform")
106 ErrDFNotSupported = errors.New("setting do-not-fragment bit is not supported on this platform")
107 )
108
109 // New returns a new Pinger struct pointer.
110 func New(addr string) *Pinger {
111 r := rand.New(rand.NewSource(getSeed()))
112 firstUUID := uuid.New()
113 var firstSequence = map[uuid.UUID]map[int]struct{}{}
114 firstSequence[firstUUID] = make(map[int]struct{})
115 return &Pinger{
116 Count: -1,
117 Interval: time.Second,
118 RecordRtts: true,
119 RecordTTLs: true,
120 Size: timeSliceLength + trackerLength,
121 Timeout: time.Duration(math.MaxInt64),
122
123 addr: addr,
124 done: make(chan any),
125 id: r.Intn(math.MaxUint16),
126 trackerUUIDs: []uuid.UUID{firstUUID},
127 ipaddr: nil,
128 ipv4: false,
129 network: networkIP,
130 protocol: "udp",
131 awaitingSequences: firstSequence,
132 TTL: 64,
133 tclass: 0,
134 logger: StdLogger{Logger: log.New(log.Writer(), log.Prefix(), log.Flags())},
135 }
136 }
137
138 // NewPinger returns a new Pinger and resolves the address.
139 func NewPinger(addr string) (*Pinger, error) {
140 p := New(addr)
141 return p, p.Resolve()
142 }
143
144 // Pinger represents a packet sender/receiver.
145 type Pinger struct {
146 // Interval is the wait time between each packet send. Default is 1s.
147 Interval time.Duration
148
149 // Timeout specifies a timeout before ping exits, regardless of how many
150 // packets have been received.
151 Timeout time.Duration
152
153 // ResolveTimeout specifies a timeout to resolve an IP address or domain name
154 ResolveTimeout time.Duration
155
156 // Count tells pinger to stop after sending (and receiving) Count echo
157 // packets. If this option is not specified, pinger will operate until
158 // interrupted.
159 Count int
160
161 // Debug runs in debug mode
162 Debug bool
163
164 // Number of packets sent
165 PacketsSent int
166
167 // Number of packets received
168 PacketsRecv int
169
170 // Number of duplicate packets received
171 PacketsRecvDuplicates int
172
173 // Round trip time statistics
174 minRtt time.Duration
175 maxRtt time.Duration
176 avgRtt time.Duration
177 stdDevRtt time.Duration
178 stddevm2 float64
179 statsMu sync.RWMutex
180
181 // If true, keep a record of rtts of all received packets.
182 // Set to false to avoid memory bloat for long running pings.
183 RecordRtts bool
184
185 // If true, keep a record of TTLs of all received packets.
186 // Set to false to avoid memory bloat for long running pings.
187 RecordTTLs bool
188
189 // rtts is all of the Rtts
190 rtts []time.Duration
191
192 // ttls is all of the TTLs
193 ttls []uint8
194
195 // OnSetup is called when Pinger has finished setting up the listening socket
196 OnSetup func()
197
198 // OnSend is called when Pinger sends a packet
199 OnSend func(*Packet)
200
201 // OnRecv is called when Pinger receives and processes a packet
202 OnRecv func(*Packet)
203
204 // OnFinish is called when Pinger exits
205 OnFinish func(*Statistics)
206
207 // OnDuplicateRecv is called when a packet is received that has already been received.
208 OnDuplicateRecv func(*Packet)
209
210 // OnSendError is called when an error occurs while Pinger attempts to send a packet
211 OnSendError func(*Packet, error)
212
213 // OnRecvError is called when an error occurs while Pinger attempts to receive a packet
214 OnRecvError func(error)
215
216 // Size of packet being sent
217 Size int
218
219 // Tracker: Used to uniquely identify packets - Deprecated
220 Tracker uint64
221
222 // Source is the source IP address
223 Source string
224
225 // Interface used to send/recv ICMP messages
226 InterfaceName string
227
228 // Channel and mutex used to communicate when the Pinger should stop between goroutines.
229 done chan any
230 lock sync.Mutex
231
232 ipaddr *net.IPAddr
233 addr string
234
235 // mark is a SO_MARK (fwmark) set on outgoing icmp packets
236 mark uint
237
238 // df when true sets the do-not-fragment bit in the outer IP or IPv6 header
239 df bool
240
241 // trackerUUIDs is the list of UUIDs being used for sending packets.
242 trackerUUIDs []uuid.UUID
243
244 ipv4 bool
245 id int
246 sequence int
247 // awaitingSequences are in-flight sequence numbers we keep track of to help remove duplicate receipts
248 awaitingSequences map[uuid.UUID]map[int]struct{}
249 // network is one of "ip", "ip4", or "ip6".
250 network string
251 // protocol is "icmp" or "udp".
252 protocol string
253
254 logger Logger
255
256 TTL int
257
258 // tclass defines the traffic class (ToS for IPv4) set on outgoing icmp packets
259 tclass uint8
260 }
261
262 type packet struct {
263 bytes []byte
264 nbytes int
265 ttl int
266 addr net.Addr
267 }
268
269 // Packet represents a received and processed ICMP echo packet.
270 type Packet struct {
271 // Rtt is the round-trip time it took to ping.
272 Rtt time.Duration
273
274 // IPAddr is the address of the host being pinged.
275 IPAddr *net.IPAddr
276
277 // Addr is the string address of the host being pinged.
278 Addr string
279
280 // NBytes is the number of bytes in the message.
281 Nbytes int
282
283 // Seq is the ICMP sequence number.
284 Seq int
285
286 // TTL is the Time To Live on the packet.
287 TTL int
288
289 // ID is the ICMP identifier.
290 ID int
291 }
292
293 // Statistics represent the stats of a currently running or finished
294 // pinger operation.
295 type Statistics struct {
296 // PacketsRecv is the number of packets received.
297 PacketsRecv int
298
299 // PacketsSent is the number of packets sent.
300 PacketsSent int
301
302 // PacketsRecvDuplicates is the number of duplicate responses there were to a sent packet.
303 PacketsRecvDuplicates int
304
305 // PacketLoss is the percentage of packets lost.
306 PacketLoss float64
307
308 // IPAddr is the address of the host being pinged.
309 IPAddr *net.IPAddr
310
311 // Addr is the string address of the host being pinged.
312 Addr string
313
314 // Rtts is all of the round-trip times sent via this pinger.
315 Rtts []time.Duration
316
317 // TTLs is all of the TTLs received via this pinger.
318 TTLs []uint8
319
320 // MinRtt is the minimum round-trip time sent via this pinger.
321 MinRtt time.Duration
322
323 // MaxRtt is the maximum round-trip time sent via this pinger.
324 MaxRtt time.Duration
325
326 // AvgRtt is the average round-trip time sent via this pinger.
327 AvgRtt time.Duration
328
329 // StdDevRtt is the standard deviation of the round-trip times sent via
330 // this pinger.
331 StdDevRtt time.Duration
332 }
333
334 func (p *Pinger) updateStatistics(pkt *Packet) {
335 p.statsMu.Lock()
336 defer p.statsMu.Unlock()
337
338 p.PacketsRecv++
339 if p.RecordRtts {
340 p.rtts = append(p.rtts, pkt.Rtt)
341 }
342
343 if p.RecordTTLs {
344 p.ttls = append(p.ttls, uint8(pkt.TTL))
345 }
346
347 if p.PacketsRecv == 1 || pkt.Rtt < p.minRtt {
348 p.minRtt = pkt.Rtt
349 }
350
351 if pkt.Rtt > p.maxRtt {
352 p.maxRtt = pkt.Rtt
353 }
354
355 pktCount := time.Duration(p.PacketsRecv)
356 // welford's online method for stddev
357 // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
358 delta := pkt.Rtt - p.avgRtt
359 p.avgRtt += delta / pktCount
360 delta2 := pkt.Rtt - p.avgRtt
361 p.stddevm2 += float64(delta) * float64(delta2)
362
363 p.stdDevRtt = time.Duration(math.Sqrt(p.stddevm2 / float64(pktCount)))
364 }
365
366 // SetIPAddr sets the ip address of the target host.
367 func (p *Pinger) SetIPAddr(ipaddr *net.IPAddr) {
368 p.ipv4 = isIPv4(ipaddr.IP)
369
370 p.statsMu.Lock()
371 p.ipaddr = ipaddr
372 p.addr = ipaddr.String()
373 p.statsMu.Unlock()
374 }
375
376 // IPAddr returns the ip address of the target host.
377 func (p *Pinger) IPAddr() *net.IPAddr {
378 return p.ipaddr
379 }
380
381 // Resolve does the DNS lookup for the Pinger address and sets IP protocol.
382 func (p *Pinger) Resolve() error {
383 if len(p.addr) == 0 {
384 return errors.New("addr cannot be empty")
385 }
386 var (
387 ipaddr *net.IPAddr
388 err error
389 )
390 if p.ResolveTimeout > time.Duration(0) {
391 var (
392 ctx = context.Background()
393 ips []net.IP
394 )
395 ctx, cancel := context.WithTimeout(ctx, p.ResolveTimeout)
396 defer cancel()
397 ips, err = net.DefaultResolver.LookupIP(ctx, p.network, p.addr)
398 if err != nil {
399 return err
400 }
401 if len(ips) == 0 {
402 return fmt.Errorf("lookup %s failed: no addresses found", p.addr)
403 }
404 ipaddr = &net.IPAddr{IP: ips[0]}
405 for _, ip := range ips {
406 if p.network == networkIPv6 {
407 if ip.To4() == nil && ip.To16() != nil {
408 ipaddr = &net.IPAddr{IP: ip}
409 break
410 }
411 continue
412 }
413 if ip.To4() != nil {
414 ipaddr = &net.IPAddr{IP: ip}
415 }
416 }
417 } else {
418 ipaddr, err = net.ResolveIPAddr(p.network, p.addr)
419 if err != nil {
420 return err
421 }
422 }
423
424 p.ipv4 = isIPv4(ipaddr.IP)
425
426 p.statsMu.Lock()
427 p.ipaddr = ipaddr
428 p.statsMu.Unlock()
429
430 return nil
431 }
432
433 // SetAddr resolves and sets the ip address of the target host, addr can be a
434 // DNS name like "www.google.com" or IP like "127.0.0.1".
435 func (p *Pinger) SetAddr(addr string) error {
436 oldAddr := p.addr
437 p.statsMu.Lock()
438 p.addr = addr
439 p.statsMu.Unlock()
440 err := p.Resolve()
441 if err != nil {
442 p.statsMu.Lock()
443 p.addr = oldAddr
444 p.statsMu.Unlock()
445 return err
446 }
447 return nil
448 }
449
450 // Addr returns the string ip address of the target host.
451 func (p *Pinger) Addr() string {
452 return p.addr
453 }
454
455 // SetNetwork allows configuration of DNS resolution.
456 // * "ip" will automatically select IPv4 or IPv6.
457 // * "ip4" will select IPv4.
458 // * "ip6" will select IPv6.
459 func (p *Pinger) SetNetwork(n string) {
460 switch n {
461 case networkIPv4:
462 p.network = networkIPv4
463 case networkIPv6:
464 p.network = networkIPv6
465 default:
466 p.network = networkIP
467 }
468 }
469
470 // SetPrivileged sets the type of ping pinger will send.
471 // false means pinger will send an "unprivileged" UDP ping.
472 // true means pinger will send a "privileged" raw ICMP ping.
473 // NOTE: setting to true requires that it be run with super-user privileges.
474 func (p *Pinger) SetPrivileged(privileged bool) {
475 if privileged {
476 p.protocol = "icmp"
477 } else {
478 p.protocol = "udp"
479 }
480 }
481
482 // Privileged returns whether pinger is running in privileged mode.
483 func (p *Pinger) Privileged() bool {
484 return p.protocol == "icmp"
485 }
486
487 // SetLogger sets the logger to be used to log events from the pinger.
488 func (p *Pinger) SetLogger(logger Logger) {
489 p.logger = logger
490 }
491
492 // SetID sets the ICMP identifier.
493 func (p *Pinger) SetID(id int) {
494 p.id = id
495 }
496
497 // ID returns the ICMP identifier.
498 func (p *Pinger) ID() int {
499 return p.id
500 }
501
502 // SetMark sets a mark intended to be set on outgoing ICMP packets.
503 func (p *Pinger) SetMark(m uint) {
504 p.mark = m
505 }
506
507 // Mark returns the mark to be set on outgoing ICMP packets.
508 func (p *Pinger) Mark() uint {
509 return p.mark
510 }
511
512 // SetDoNotFragment sets the do-not-fragment bit in the outer IP header to the desired value.
513 func (p *Pinger) SetDoNotFragment(df bool) {
514 p.df = df
515 }
516
517 // SetTrafficClass sets the traffic class (type-of-service field for IPv4) field
518 // value for future outgoing packets.
519 func (p *Pinger) SetTrafficClass(tc uint8) {
520 p.tclass = tc
521 }
522
523 // TrafficClass returns the traffic class field (type-of-service field for IPv4)
524 // value for outgoing packets.
525 func (p *Pinger) TrafficClass() uint8 {
526 return p.tclass
527 }
528
529 // Run runs the pinger. This is a blocking function that will exit when it's
530 // done. If Count or Interval are not specified, it will run continuously until
531 // it is interrupted.
532 func (p *Pinger) Run() error {
533 return p.RunWithContext(context.Background())
534 }
535
536 // RunWithContext runs the pinger with a context. This is a blocking function that will exit when it's
537 // done or if the context is canceled. If Count or Interval are not specified, it will run continuously until
538 // it is interrupted.
539 func (p *Pinger) RunWithContext(ctx context.Context) error {
540 var conn packetConn
541 var err error
542 if p.Size < timeSliceLength+trackerLength {
543 return fmt.Errorf("size %d is less than minimum required size %d", p.Size, timeSliceLength+trackerLength)
544 }
545 if p.ipaddr == nil {
546 err = p.Resolve()
547 }
548 if err != nil {
549 return err
550 }
551 if conn, err = p.listen(); err != nil {
552 return err
553 }
554 defer conn.Close()
555
556 if p.mark != 0 {
557 if err := conn.SetMark(p.mark); err != nil {
558 return fmt.Errorf("error setting mark: %v", err)
559 }
560 }
561
562 if p.df {
563 if err := conn.SetDoNotFragment(); err != nil {
564 return fmt.Errorf("error setting do-not-fragment: %v", err)
565 }
566 }
567
568 if p.tclass != 0 {
569 if err := conn.SetTrafficClass(p.tclass); err != nil {
570 return fmt.Errorf("error setting traffic class: %v", err)
571 }
572 }
573
574 conn.SetTTL(p.TTL)
575 if p.InterfaceName != "" {
576 iface, err := net.InterfaceByName(p.InterfaceName)
577 if err != nil {
578 return err
579 }
580 conn.SetIfIndex(iface.Index)
581 }
582
583 if p.Source != "" {
584 ip := net.ParseIP(p.Source)
585 if ip == nil {
586 return fmt.Errorf("invalid source address: %s", p.Source)
587 }
588 conn.SetSource(ip)
589 }
590
591 return p.run(ctx, conn)
592 }
593
594 func (p *Pinger) run(ctx context.Context, conn packetConn) error {
595 if err := conn.SetFlagTTL(); err != nil {
596 return err
597 }
598 defer p.finish()
599
600 recv := make(chan *packet, 5)
601 defer close(recv)
602
603 if p.OnSetup != nil {
604 p.OnSetup()
605 }
606
607 g, ctx := errgroup.WithContext(ctx)
608
609 g.Go(func() error {
610 select {
611 case <-ctx.Done():
612 p.Stop()
613 return ctx.Err()
614 case <-p.done:
615 }
616 return nil
617 })
618
619 g.Go(func() error {
620 defer p.Stop()
621 return p.recvICMP(conn, recv)
622 })
623
624 g.Go(func() error {
625 defer p.Stop()
626 return p.runLoop(conn, recv)
627 })
628
629 return g.Wait()
630 }
631
632 func (p *Pinger) runLoop(
633 conn packetConn,
634 recvCh <-chan *packet,
635 ) error {
636 logger := p.logger
637 if logger == nil {
638 logger = NoopLogger{}
639 }
640
641 timeout := time.NewTicker(p.Timeout)
642 interval := time.NewTicker(p.Interval)
643 defer func() {
644 interval.Stop()
645 timeout.Stop()
646 }()
647
648 if err := p.sendICMP(conn); err != nil {
649 return err
650 }
651
652 for {
653 select {
654 case <-p.done:
655 return nil
656
657 case <-timeout.C:
658 return nil
659
660 case r := <-recvCh:
661 err := p.processPacket(r)
662 if err != nil {
663 // FIXME: this logs as FATAL but continues
664 logger.Fatalf("processing received packet: %s", err)
665 }
666
667 case <-interval.C:
668 if p.Count > 0 && p.PacketsSent >= p.Count {
669 interval.Stop()
670 continue
671 }
672 err := p.sendICMP(conn)
673 if err != nil {
674 // FIXME: this logs as FATAL but continues
675 logger.Fatalf("sending packet: %s", err)
676 }
677 }
678 if p.Count > 0 && p.PacketsRecv >= p.Count {
679 return nil
680 }
681 }
682 }
683
684 func (p *Pinger) Stop() {
685 p.lock.Lock()
686 defer p.lock.Unlock()
687
688 open := true
689 select {
690 case _, open = <-p.done:
691 default:
692 }
693
694 if open {
695 close(p.done)
696 }
697 }
698
699 func (p *Pinger) finish() {
700 if p.OnFinish != nil {
701 p.OnFinish(p.Statistics())
702 }
703 }
704
705 // Statistics returns the statistics of the pinger. This can be run while the
706 // pinger is running or after it is finished. OnFinish calls this function to
707 // get it's finished statistics.
708 func (p *Pinger) Statistics() *Statistics {
709 p.statsMu.RLock()
710 defer p.statsMu.RUnlock()
711 sent := p.PacketsSent
712
713 var loss float64
714 if sent > 0 {
715 loss = float64(sent-p.PacketsRecv) / float64(sent) * 100
716 }
717
718 s := Statistics{
719 PacketsSent: sent,
720 PacketsRecv: p.PacketsRecv,
721 PacketsRecvDuplicates: p.PacketsRecvDuplicates,
722 PacketLoss: loss,
723 Rtts: p.rtts,
724 TTLs: p.ttls,
725 Addr: p.addr,
726 IPAddr: p.ipaddr,
727 MaxRtt: p.maxRtt,
728 MinRtt: p.minRtt,
729 AvgRtt: p.avgRtt,
730 StdDevRtt: p.stdDevRtt,
731 }
732 return &s
733 }
734
735 type expBackoff struct {
736 baseDelay time.Duration
737 maxExp int64
738 c int64
739 }
740
741 func (b *expBackoff) Get() time.Duration {
742 if b.c < b.maxExp {
743 b.c++
744 }
745
746 return b.baseDelay * time.Duration(rand.Int63n(1<<b.c))
747 }
748
749 func newExpBackoff(baseDelay time.Duration, maxExp int64) expBackoff {
750 return expBackoff{baseDelay: baseDelay, maxExp: maxExp}
751 }
752
753 func (p *Pinger) recvICMP(
754 conn packetConn,
755 recv chan<- *packet,
756 ) error {
757 // Start by waiting for 50 µs and increase to a possible maximum of ~ 100 ms.
758 expBackoff := newExpBackoff(50*time.Microsecond, 11)
759 delay := expBackoff.Get()
760
761 // Workaround for https://github.com/golang/go/issues/47369
762 offset := 0
763 if p.ipv4 && !p.Privileged() && runtime.GOOS == "darwin" {
764 offset = 20
765 }
766
767 for {
768 select {
769 case <-p.done:
770 return nil
771 default:
772 bytes := make([]byte, p.getMessageLength()+offset)
773 if err := conn.SetReadDeadline(time.Now().Add(delay)); err != nil {
774 return err
775 }
776 n, ttl, addr, err := conn.ReadFrom(bytes)
777 if err != nil {
778 if p.OnRecvError != nil {
779 p.OnRecvError(err)
780 }
781 if neterr, ok := err.(*net.OpError); ok {
782 if neterr.Timeout() {
783 // Read timeout
784 delay = expBackoff.Get()
785 continue
786 }
787 }
788 return err
789 }
790
791 select {
792 case <-p.done:
793 return nil
794 case recv <- &packet{bytes: bytes, nbytes: n, ttl: ttl, addr: addr}:
795 }
796 }
797 }
798 }
799
800 // getPacketUUID scans the tracking slice for matches.
801 func (p *Pinger) getPacketUUID(pkt []byte) (*uuid.UUID, error) {
802 var packetUUID uuid.UUID
803 err := packetUUID.UnmarshalBinary(pkt[timeSliceLength : timeSliceLength+trackerLength])
804 if err != nil {
805 return nil, fmt.Errorf("error decoding tracking UUID: %w", err)
806 }
807
808 if slices.Contains(p.trackerUUIDs, packetUUID) {
809 return &packetUUID, nil
810 }
811 return nil, nil
812 }
813
814 // getCurrentTrackerUUID grabs the latest tracker UUID.
815 func (p *Pinger) getCurrentTrackerUUID() uuid.UUID {
816 return p.trackerUUIDs[len(p.trackerUUIDs)-1]
817 }
818
819 func (p *Pinger) processPacket(recv *packet) error {
820 receivedAt := time.Now()
821 var proto int
822 if p.ipv4 {
823 proto = protocolICMP
824 // Workaround for https://github.com/golang/go/issues/47369
825 recv.nbytes = stripIPv4Header(recv.nbytes, recv.bytes)
826 } else {
827 proto = protocolIPv6ICMP
828 }
829
830 var m *icmp.Message
831 var err error
832 if m, err = icmp.ParseMessage(proto, recv.bytes); err != nil {
833 return fmt.Errorf("error parsing icmp message: %w", err)
834 }
835
836 if m.Type != ipv4.ICMPTypeEchoReply && m.Type != ipv6.ICMPTypeEchoReply {
837 // Not an echo reply, ignore it
838 return nil
839 }
840
841 // If initial ip is a broadcast ip, ping responses will come from machines' in the
842 // subnet, thus ip will differ. Below gets real ip from received package.
843 var realIP *net.IPAddr
844
845 switch v := recv.addr.(type) {
846 case *net.IPAddr: // For ICMP
847 realIP = v
848 case *net.UDPAddr:
849 realIP = &net.IPAddr{IP: v.IP}
850 default:
851 p.logger.Infof("received address: %s it neither an Ip address (ICMP) nor UDP address, shouldn't happen. using initial address", recv.addr)
852 realIP = p.ipaddr
853 }
854
855 inPkt := &Packet{
856 Nbytes: recv.nbytes,
857 IPAddr: realIP,
858 Addr: realIP.String(),
859 TTL: recv.ttl,
860 ID: p.id,
861 }
862
863 switch pkt := m.Body.(type) {
864 case *icmp.Echo:
865 if !p.matchID(pkt.ID) {
866 return nil
867 }
868
869 if len(pkt.Data) < timeSliceLength+trackerLength {
870 return fmt.Errorf("insufficient data received; got: %d %v",
871 len(pkt.Data), pkt.Data)
872 }
873
874 pktUUID, err := p.getPacketUUID(pkt.Data)
875 if err != nil || pktUUID == nil {
876 return err
877 }
878
879 timestamp := bytesToTime(pkt.Data[:timeSliceLength])
880 inPkt.Rtt = receivedAt.Sub(timestamp)
881 inPkt.Seq = pkt.Seq
882 // If we've already received this sequence, ignore it.
883 if _, inflight := p.awaitingSequences[*pktUUID][pkt.Seq]; !inflight {
884 p.statsMu.Lock()
885 p.PacketsRecvDuplicates++
886 p.statsMu.Unlock()
887 if p.OnDuplicateRecv != nil {
888 p.OnDuplicateRecv(inPkt)
889 }
890 return nil
891 }
892 // remove it from the list of sequences we're waiting for so we don't get duplicates.
893 delete(p.awaitingSequences[*pktUUID], pkt.Seq)
894 p.updateStatistics(inPkt)
895 default:
896 // Very bad, not sure how this can happen
897 return fmt.Errorf("invalid ICMP echo reply; type: '%T', '%v'", pkt, pkt)
898 }
899
900 if p.OnRecv != nil {
901 p.OnRecv(inPkt)
902 }
903
904 return nil
905 }
906
907 func (p *Pinger) sendICMP(conn packetConn) error {
908 var dst net.Addr = p.ipaddr
909 if p.protocol == "udp" {
910 dst = &net.UDPAddr{IP: p.ipaddr.IP, Zone: p.ipaddr.Zone}
911 }
912
913 currentUUID := p.getCurrentTrackerUUID()
914 uuidEncoded, err := currentUUID.MarshalBinary()
915 if err != nil {
916 return fmt.Errorf("unable to marshal UUID binary: %w", err)
917 }
918 t := append(timeToBytes(time.Now()), uuidEncoded...)
919 if remainSize := p.Size - timeSliceLength - trackerLength; remainSize > 0 {
920 t = append(t, bytes.Repeat([]byte{1}, remainSize)...)
921 }
922
923 body := &icmp.Echo{
924 ID: p.id,
925 Seq: p.sequence,
926 Data: t,
927 }
928
929 msg := &icmp.Message{
930 Type: conn.ICMPRequestType(),
931 Code: 0,
932 Body: body,
933 }
934
935 msgBytes, err := msg.Marshal(nil)
936 if err != nil {
937 return err
938 }
939
940 for {
941 if _, err := conn.WriteTo(msgBytes, dst); err != nil {
942 // Try to set broadcast flag
943 if errors.Is(err, syscall.EACCES) && runtime.GOOS == "linux" {
944 if e := conn.SetBroadcastFlag(); e != nil {
945 p.logger.Warnf("had EACCES syscall error, check your local firewall")
946 }
947 p.logger.Infof("Pinging a broadcast address")
948 continue
949 }
950 if p.OnSendError != nil {
951 outPkt := &Packet{
952 Nbytes: len(msgBytes),
953 IPAddr: p.ipaddr,
954 Addr: p.addr,
955 Seq: p.sequence,
956 ID: p.id,
957 }
958 p.OnSendError(outPkt, err)
959 }
960 if neterr, ok := err.(*net.OpError); ok {
961 if neterr.Err == syscall.ENOBUFS {
962 continue
963 }
964 }
965 return err
966 }
967 if p.OnSend != nil {
968 outPkt := &Packet{
969 Nbytes: len(msgBytes),
970 IPAddr: p.ipaddr,
971 Addr: p.addr,
972 Seq: p.sequence,
973 ID: p.id,
974 }
975 p.OnSend(outPkt)
976 }
977 // mark this sequence as in-flight
978 p.awaitingSequences[currentUUID][p.sequence] = struct{}{}
979 p.statsMu.Lock()
980 p.PacketsSent++
981 p.statsMu.Unlock()
982 p.sequence++
983 if p.sequence > 65535 {
984 newUUID := uuid.New()
985 p.trackerUUIDs = append(p.trackerUUIDs, newUUID)
986 p.awaitingSequences[newUUID] = make(map[int]struct{})
987 p.sequence = 0
988 }
989 break
990 }
991
992 return nil
993 }
994
995 func (p *Pinger) listen() (packetConn, error) {
996 var (
997 conn packetConn
998 err error
999 )
1000
1001 if p.ipv4 {
1002 var c icmpv4Conn
1003 c.c, err = icmp.ListenPacket(ipv4Proto[p.protocol], p.Source)
1004 conn = &c
1005 } else {
1006 var c icmpV6Conn
1007 c.c, err = icmp.ListenPacket(ipv6Proto[p.protocol], p.Source)
1008 conn = &c
1009 }
1010
1011 if err != nil {
1012 p.Stop()
1013 return nil, err
1014 }
1015
1016 if p.Privileged() {
1017 if err := conn.InstallICMPIDFilter(p.id); err != nil {
1018 p.logger.Warnf("error installing icmp filter, %v", err)
1019 }
1020 }
1021
1022 return conn, nil
1023 }
1024
1025 func bytesToTime(b []byte) time.Time {
1026 var nsec int64
1027 for i := range uint8(8) {
1028 nsec += int64(b[i]) << ((7 - i) * 8)
1029 }
1030 return time.Unix(nsec/1000000000, nsec%1000000000)
1031 }
1032
1033 func isIPv4(ip net.IP) bool {
1034 return len(ip.To4()) == net.IPv4len
1035 }
1036
1037 func timeToBytes(t time.Time) []byte {
1038 nsec := t.UnixNano()
1039 b := make([]byte, 8)
1040 for i := range uint8(8) {
1041 b[i] = byte((nsec >> ((7 - i) * 8)) & 0xff)
1042 }
1043 return b
1044 }
1045
1046 var seed = time.Now().UnixNano()
1047
1048 // getSeed returns a goroutine-safe unique seed
1049 func getSeed() int64 {
1050 return atomic.AddInt64(&seed, 1)
1051 }
1052
1053 // stripIPv4Header strips IPv4 header bytes if present
1054 // https://github.com/golang/go/commit/3b5be4522a21df8ce52a06a0c4ba005c89a8590f
1055 func stripIPv4Header(n int, b []byte) int {
1056 if len(b) < 20 {
1057 return n
1058 }
1059 l := int(b[0]&0x0f) << 2
1060 if 20 > l || l > len(b) {
1061 return n
1062 }
1063 if b[0]>>4 != 4 {
1064 return n
1065 }
1066 copy(b, b[l:])
1067 return n - l
1068 }