| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 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 |
|
| 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 |
|
| 139 |
func NewPinger(addr string) (*Pinger, error) { |
| 140 |
p := New(addr) |
| 141 |
return p, p.Resolve() |
| 142 |
} |
| 143 |
|
| 144 |
|
| 145 |
type Pinger struct { |
| 146 |
|
| 147 |
Interval time.Duration |
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
Timeout time.Duration |
| 152 |
|
| 153 |
|
| 154 |
ResolveTimeout time.Duration |
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
Count int |
| 160 |
|
| 161 |
|
| 162 |
Debug bool |
| 163 |
|
| 164 |
|
| 165 |
PacketsSent int |
| 166 |
|
| 167 |
|
| 168 |
PacketsRecv int |
| 169 |
|
| 170 |
|
| 171 |
PacketsRecvDuplicates int |
| 172 |
|
| 173 |
|
| 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 |
|
| 182 |
|
| 183 |
RecordRtts bool |
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
RecordTTLs bool |
| 188 |
|
| 189 |
|
| 190 |
rtts []time.Duration |
| 191 |
|
| 192 |
|
| 193 |
ttls []uint8 |
| 194 |
|
| 195 |
|
| 196 |
OnSetup func() |
| 197 |
|
| 198 |
|
| 199 |
OnSend func(*Packet) |
| 200 |
|
| 201 |
|
| 202 |
OnRecv func(*Packet) |
| 203 |
|
| 204 |
|
| 205 |
OnFinish func(*Statistics) |
| 206 |
|
| 207 |
|
| 208 |
OnDuplicateRecv func(*Packet) |
| 209 |
|
| 210 |
|
| 211 |
OnSendError func(*Packet, error) |
| 212 |
|
| 213 |
|
| 214 |
OnRecvError func(error) |
| 215 |
|
| 216 |
|
| 217 |
Size int |
| 218 |
|
| 219 |
|
| 220 |
Tracker uint64 |
| 221 |
|
| 222 |
|
| 223 |
Source string |
| 224 |
|
| 225 |
|
| 226 |
InterfaceName string |
| 227 |
|
| 228 |
|
| 229 |
done chan any |
| 230 |
lock sync.Mutex |
| 231 |
|
| 232 |
ipaddr *net.IPAddr |
| 233 |
addr string |
| 234 |
|
| 235 |
|
| 236 |
mark uint |
| 237 |
|
| 238 |
|
| 239 |
df bool |
| 240 |
|
| 241 |
|
| 242 |
trackerUUIDs []uuid.UUID |
| 243 |
|
| 244 |
ipv4 bool |
| 245 |
id int |
| 246 |
sequence int |
| 247 |
|
| 248 |
awaitingSequences map[uuid.UUID]map[int]struct{} |
| 249 |
|
| 250 |
network string |
| 251 |
|
| 252 |
protocol string |
| 253 |
|
| 254 |
logger Logger |
| 255 |
|
| 256 |
TTL int |
| 257 |
|
| 258 |
|
| 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 |
|
| 270 |
type Packet struct { |
| 271 |
|
| 272 |
Rtt time.Duration |
| 273 |
|
| 274 |
|
| 275 |
IPAddr *net.IPAddr |
| 276 |
|
| 277 |
|
| 278 |
Addr string |
| 279 |
|
| 280 |
|
| 281 |
Nbytes int |
| 282 |
|
| 283 |
|
| 284 |
Seq int |
| 285 |
|
| 286 |
|
| 287 |
TTL int |
| 288 |
|
| 289 |
|
| 290 |
ID int |
| 291 |
} |
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
type Statistics struct { |
| 296 |
|
| 297 |
PacketsRecv int |
| 298 |
|
| 299 |
|
| 300 |
PacketsSent int |
| 301 |
|
| 302 |
|
| 303 |
PacketsRecvDuplicates int |
| 304 |
|
| 305 |
|
| 306 |
PacketLoss float64 |
| 307 |
|
| 308 |
|
| 309 |
IPAddr *net.IPAddr |
| 310 |
|
| 311 |
|
| 312 |
Addr string |
| 313 |
|
| 314 |
|
| 315 |
Rtts []time.Duration |
| 316 |
|
| 317 |
|
| 318 |
TTLs []uint8 |
| 319 |
|
| 320 |
|
| 321 |
MinRtt time.Duration |
| 322 |
|
| 323 |
|
| 324 |
MaxRtt time.Duration |
| 325 |
|
| 326 |
|
| 327 |
AvgRtt time.Duration |
| 328 |
|
| 329 |
|
| 330 |
|
| 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 |
|
| 357 |
|
| 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 |
|
| 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 |
|
| 377 |
func (p *Pinger) IPAddr() *net.IPAddr { |
| 378 |
return p.ipaddr |
| 379 |
} |
| 380 |
|
| 381 |
|
| 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 |
|
| 434 |
|
| 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 |
|
| 451 |
func (p *Pinger) Addr() string { |
| 452 |
return p.addr |
| 453 |
} |
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
|
| 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 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
func (p *Pinger) SetPrivileged(privileged bool) { |
| 475 |
if privileged { |
| 476 |
p.protocol = "icmp" |
| 477 |
} else { |
| 478 |
p.protocol = "udp" |
| 479 |
} |
| 480 |
} |
| 481 |
|
| 482 |
|
| 483 |
func (p *Pinger) Privileged() bool { |
| 484 |
return p.protocol == "icmp" |
| 485 |
} |
| 486 |
|
| 487 |
|
| 488 |
func (p *Pinger) SetLogger(logger Logger) { |
| 489 |
p.logger = logger |
| 490 |
} |
| 491 |
|
| 492 |
|
| 493 |
func (p *Pinger) SetID(id int) { |
| 494 |
p.id = id |
| 495 |
} |
| 496 |
|
| 497 |
|
| 498 |
func (p *Pinger) ID() int { |
| 499 |
return p.id |
| 500 |
} |
| 501 |
|
| 502 |
|
| 503 |
func (p *Pinger) SetMark(m uint) { |
| 504 |
p.mark = m |
| 505 |
} |
| 506 |
|
| 507 |
|
| 508 |
func (p *Pinger) Mark() uint { |
| 509 |
return p.mark |
| 510 |
} |
| 511 |
|
| 512 |
|
| 513 |
func (p *Pinger) SetDoNotFragment(df bool) { |
| 514 |
p.df = df |
| 515 |
} |
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
func (p *Pinger) SetTrafficClass(tc uint8) { |
| 520 |
p.tclass = tc |
| 521 |
} |
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
func (p *Pinger) TrafficClass() uint8 { |
| 526 |
return p.tclass |
| 527 |
} |
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
func (p *Pinger) Run() error { |
| 533 |
return p.RunWithContext(context.Background()) |
| 534 |
} |
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 706 |
|
| 707 |
|
| 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 |
. |
| 758 |
expBackoff := newExpBackoff(50*time.Microsecond, 11) |
| 759 |
delay := expBackoff.Get() |
| 760 |
|
| 761 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 838 |
return nil |
| 839 |
} |
| 840 |
|
| 841 |
|
| 842 |
|
| 843 |
var realIP *net.IPAddr |
| 844 |
|
| 845 |
switch v := recv.addr.(type) { |
| 846 |
case *net.IPAddr: |
| 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 |
|
| 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 |
|
| 893 |
delete(p.awaitingSequences[*pktUUID], pkt.Seq) |
| 894 |
p.updateStatistics(inPkt) |
| 895 |
default: |
| 896 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1049 |
func getSeed() int64 { |
| 1050 |
return atomic.AddInt64(&seed, 1) |
| 1051 |
} |
| 1052 |
|
| 1053 |
|
| 1054 |
|
| 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 |
} |