p2p/discover: fix timeout loop early exit when removing expired matchers (#34743)

Save `el.Next()` before calling `plist.Remove(el)` so iteration
continues correctly. Previously the loop exited after removing the first
expired matcher because `Remove` invalidates the element's links.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
This commit is contained in:
Rahman 2026-04-28 02:57:58 -06:00 committed by GitHub
parent 822e7c6486
commit 51c97216c5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 19 additions and 7 deletions

View file

@ -17,9 +17,11 @@
package discover
import (
"container/list"
"crypto/ecdsa"
crand "crypto/rand"
"encoding/binary"
"iter"
"math/rand"
"net"
"net/netip"
@ -143,3 +145,16 @@ func (r *reseedingRandom) Shuffle(n int, swap func(i, j int)) {
defer r.mu.Unlock()
r.cur.Shuffle(n, swap)
}
// iterList iterates over the elements of the given list.
func iterList[T any](l *list.List) iter.Seq2[T, *list.Element] {
return func(yield func(T, *list.Element) bool) {
for el := l.Front(); el != nil; {
next := el.Next()
if !yield(el.Value.(T), el) {
return
}
el = next
}
}
}

View file

@ -446,9 +446,8 @@ func (t *UDPv4) loop() {
}
// Start the timer so it fires when the next pending reply has expired.
now := time.Now()
for el := plist.Front(); el != nil; el = el.Next() {
nextTimeout = el.Value.(*replyMatcher)
if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout {
for p, el := range iterList[*replyMatcher](plist) {
if dist := p.deadline.Sub(now); dist < 2*respTimeout {
timeout.Reset(dist)
return
}
@ -478,8 +477,7 @@ func (t *UDPv4) loop() {
case r := <-t.gotreply:
var matched bool // whether any replyMatcher considered the reply acceptable.
for el := plist.Front(); el != nil; el = el.Next() {
p := el.Value.(*replyMatcher)
for p, el := range iterList[*replyMatcher](plist) {
if p.from == r.from && p.ptype == r.data.Kind() && p.ip == r.ip {
ok, requestDone := p.callback(r.data)
matched = matched || ok
@ -499,8 +497,7 @@ func (t *UDPv4) loop() {
nextTimeout = nil
// Notify and remove callbacks whose deadline is in the past.
for el := plist.Front(); el != nil; el = el.Next() {
p := el.Value.(*replyMatcher)
for p, el := range iterList[*replyMatcher](plist) {
if now.After(p.deadline) || now.Equal(p.deadline) {
p.errc <- errTimeout
plist.Remove(el)