Repository navigation
Description
What happened?
Data race in strelaypoolsrv: unsynchronized read of knownRelays while it is being mutated
Summary
cmd/infra/strelaypoolsrv/main.go contains a data race on the global slice
knownRelays. After mut.Unlock() in handleRelayTest, the slice is passed
by value to saveRelays, which then iterates over it without holding the
lock. Meanwhile:
- other
requestProcessorgoroutines may enter the critical section and
mutate the same backing array (append, in-place swap-and-shrink), and - the
time.AfterFunc-scheduledevictcallback may also mutate the same
backing array (swap-and-shrink), and handleEndpointFull/handleEndpointShortmay concurrently read the
slice undermut.RLock()(which does not synchronize with the unlocked
read insidesaveRelays).
This has been confirmed with Go's built-in race detector: running a plain
-race build against a small local cluster of strelaysrv instances
produces WARNING: DATA RACE reports within seconds.
Root cause
1) Write path A — handleRelayTest (main.go L534-L548)
func handleRelayTest(request request, geoip *geoip.Provider) {
...
mut.Lock()
...
for i, current := range knownRelays {
if current.uri.Host == request.relay.uri.Host {
...
last := len(knownRelays) - 1
knownRelays[i] = knownRelays[last] // in-place swap
knownRelays = knownRelays[:last] // shrink
goto found
}
}
...
found:
knownRelays = append(knownRelays, request.relay) // L542
evictionTimers[request.relay.uri.Host] = time.AfterFunc(evictionTime, evict(request.relay))
mut.Unlock() // L545 – lock released
if err := saveRelays(knownRelaysFile, knownRelays); err != nil { // L547 – UNSYNCHRONIZED READ
log.Println("Failed to write known relays: " + err.Error())
}
...
}2) Write path B — evict (main.go L554-L575)
func evict(relay *relay) func() {
return func() {
mut.Lock()
defer mut.Unlock()
...
for i, current := range knownRelays {
if current.uri.Host == relay.uri.Host {
...
last := len(knownRelays) - 1
knownRelays[i] = knownRelays[last] // L567 – in-place swap
knownRelays = knownRelays[:last] // shrink
...
}
}
...
}
}3) Unsynchronized reader — saveRelays (main.go L610-L616)
func saveRelays(file string, relays []*relay) error {
var content string
for _, relay := range relays { // iterates over shared backing array
content += relay.uri.String() + "\n"
}
return os.WriteFile(file, []byte(content), 0o666)
}Why passing the slice "by value" does not save it
A Go slice header is {ptr, len, cap}. Passing knownRelays to
saveRelays copies the header but not the backing array. The
for _, relay := range relays loop inside saveRelays therefore reads
the same memory that:
- the current goroutine's
append(L542) may have relocated / grown, - other
requestProcessorgoroutines' swap-and-shrink (L529) may overwrite, - the
evictcallback's swap-and-shrink (L567) may overwrite, - and
handleEndpointFull/handleEndpointShortmay also be iterating
under a read lock.
None of these are ordered with respect to saveRelays because the write
lock has already been dropped on L545.
Runtime consequences
Because []*relay is a slice of pointers and Go's runtime does not panic
on unsynchronized slice access, the bug is silent by default. Observable
effects include:
- the on-disk cache file (
known-relays) may contain duplicate URLs
(the same relay written twice via the swap position and the tail
position), or stale URLs that have just been evicted, or skip a
freshly appended entry whose header was captured before the append. - under a slow filesystem (NFS, contended disk) the reader window widens
from milliseconds to seconds, and the corruption probability grows
proportionally. - per the Go memory model, a program with a data race is undefined
behavior — future compilers / runtimes are free to make it worse.
Reproduction
Full scripted reproduction (starts a race-instrumented pool + 8 real
strelaysrv peers + concurrent readers):
Minimal one-liner reproducer
# 1. Build with the race detector
go build -race -o /tmp/strelaypoolsrv-race ./cmd/infra/strelaypoolsrv
# 2. Start the pool with an aggressive eviction interval so the race
# window opens frequently.
GORACE="halt_on_error=0 log_path=/tmp/race_report history_size=4" \
/tmp/strelaypoolsrv-race \
-listen=127.0.0.1:18080 \
-eviction=5s \
-request-processors=16 \
-known-relays=/tmp/known_relays_race \
-debug &
# 3. Point several real strelaysrv instances at the local pool
for i in 1 2 3 4 5 6 7 8; do
mkdir -p /tmp/relay-$i
./bin/strelaysrv \
-listen=127.0.0.1:$((22066+i)) \
-ext-address=127.0.0.1:$((22066+i)) \
-status-srv=127.0.0.1:$((22069+i)) \
-keys=/tmp/relay-$i \
-pools=http://127.0.0.1:18080/endpoint &
done
# 4. Add read pressure
end=$(( $(date +%s) + 60 ))
for _ in $(seq 1 20); do
while [ $(date +%s) -lt $end ]; do
curl -s -o /dev/null http://127.0.0.1:18080/endpoint/full
done &
done
wait
ls /tmp/race_report.* # -> race report filesNote: the pool server calls geoip.NewGeoLite2CityProvider early in
main() which does log.Fatalln on failure. To run without a MaxMind
license key locally, either export GEOIP_ACCOUNT_ID/GEOIP_LICENSE_KEY
or degrade that error to a warning temporarily. This is orthogonal to the
race — it just prevents the server from starting.
Race detector output
Representative excerpt. The line numbers below come from a locally-patched
build that adds ~5 lines to degrade a GeoIP fatal error into a warning
(unrelated to this race — see the note in Reproduction). Subtract 5 to
map them back to c904140b3 — i.e. reported 547 → upstream 542,
reported 552 → upstream 547, reported 617 → upstream 612, reported
490 → upstream 485, reported 173 → upstream 168:
==================
WARNING: DATA RACE
Write at 0x00c0001d4d10 by goroutine 65:
main.handleRelayTest()
cmd/infra/strelaypoolsrv/main.go:547 +0xafc # upstream: L542 (append)
main.requestProcessor()
cmd/infra/strelaypoolsrv/main.go:490 +0xf8 # upstream: L485
main.main.gowrap2()
cmd/infra/strelaypoolsrv/main.go:173 +0x2c
Previous read at 0x00c0001d4d10 by goroutine 61:
main.saveRelays()
cmd/infra/strelaypoolsrv/main.go:617 +0x54 # upstream: L612 (range over slice)
main.handleRelayTest()
cmd/infra/strelaypoolsrv/main.go:552 +0xce4 # upstream: L547 (saveRelays call after Unlock)
main.requestProcessor()
cmd/infra/strelaypoolsrv/main.go:490 +0xf8
main.main.gowrap2()
cmd/infra/strelaypoolsrv/main.go:173 +0x2c
==================
Additional distinct warnings observed in the same run include:
handleEndpointFull(L323,for _, r := range append(permanentRelays, knownRelays...))
reading concurrently with the writes above;handleRelayTest(append) racing withhandleRelayTest(saveRelays) on
different goroutines.
The full report (67 KB, multiple distinct warnings) can be attached if
useful.
Suggested fix
Take a snapshot of the slice while still holding the write lock, then
release the lock before doing I/O. This keeps the disk write outside the
critical section (good for throughput) while guaranteeing saveRelays
iterates over memory it exclusively owns.
--- a/cmd/infra/strelaypoolsrv/main.go
+++ b/cmd/infra/strelaypoolsrv/main.go
@@ -539,11 +539,15 @@ found:
knownRelays = append(knownRelays, request.relay)
evictionTimers[request.relay.uri.Host] = time.AfterFunc(evictionTime, evict(request.relay))
- mut.Unlock()
+ // Snapshot the slice under the lock so that saveRelays iterates over
+ // memory that cannot be mutated concurrently by evict() or by other
+ // requestProcessors.
+ relaysSnapshot := make([]*relay, len(knownRelays))
+ copy(relaysSnapshot, knownRelays)
+ mut.Unlock()
- if err := saveRelays(knownRelaysFile, knownRelays); err != nil {
+ if err := saveRelays(knownRelaysFile, relaysSnapshot); err != nil {
log.Println("Failed to write known relays: " + err.Error())
}The snapshot is O(N) pointer copies (N is the number of known relays,
typically a few hundred to low thousands on relays.syncthing.net), which
is negligible compared to the subsequent os.WriteFile I/O. The
*relay pointer values themselves are already effectively immutable after
they enter knownRelays for the purposes of saveRelays (only .uri is
read, and .uri is not mutated post-insertion).
Alternative (stricter): capture only the URL strings
If you prefer minimizing field-level exposure — e.g. in case someone later
adds mutable fields that saveRelays starts reading — capture the URL
strings directly:
urls := make([]string, len(knownRelays))
for i, r := range knownRelays {
urls[i] = r.uri.String()
}
mut.Unlock()
// change saveRelays to accept []stringAlso worth reviewing
The similar unlocked read of permanentRelays on L462
(for _, current := range permanentRelays) is only safe in practice
because permanentRelays is currently written once at startup and never
mutated afterwards. Adding a comment (or an explicit lock) would prevent
regressions if that invariant ever changes.
Verification of the fix
After applying the diff above, rerun the reproducer. Under the same
workload (-eviction=5s, -request-processors=16, 8 real strelaysrv
peers, 20 concurrent readers for 60 s), the race detector produces no
race_report.* files, whereas the unpatched build produces one within
seconds.
Happy to submit a PR with the fix if it looks reasonable.
Syncthing version
Latest main HEAD tested: [c904140b3]
Platform & operating system
darwin-arm64
Browser version
No response
Activity
fix(strelaypoolsrv): locking correctness (syncthing#10801)