RTSP: data race in `APISessionsKick` — map write under `RLock` causes `fatal error: concurrent map iteration and map write`
Which version are you using?
v1.18.2 (Docker image bluenviron/mediamtx:1.18.2, linux/amd64). The code path is unchanged in v1.21.1.
Which operating system are you using?
Linux amd64 Docker
Describe the issue
Server.APISessionsKick in internal/servers/rtsp/server.go acquires a read
lock and then performs a write on the sessions map inside that section:
func (s *Server) APISessionsKick(uuid uuid.UUID) error {
// ...
s.mutex.RLock()
defer s.mutex.RUnlock()
key, sx := s.findSessionByUUID(uuid) // iterates s.sessions
if sx == nil {
return ErrSessionNotFound
}
sx.Close()
delete(s.sessions, key) // <-- map write under RLock
sx.onClose(liberrors.ErrServerTerminated{})
return nil
}sync.RWMutex allows several readers to hold RLock simultaneously. Two
concurrent calls to POST /v3/rtspsessions/kick/{id} — or one kick concurrent
with GET /v3/rtspsessions/list, which iterates the same map under RLock —
can therefore run at the same time, with one goroutine iterating in
findSessionByUUID while the other deletes. That is an unsynchronised map
iteration/write, and the Go runtime aborts the process.
This is fatal, not recoverable: the whole server dies, dropping every ingest and every viewer.
Suggested fix
APISessionsKick mutates the map, so it should take the write lock:
s.mutex.Lock()
defer s.mutex.Unlock()One caveat we cannot settle ourselves: with the write lock held, sx.Close() and
sx.onClose() would run inside the critical section, and OnSessionClose takes
s.mutex.Lock() to remove the session from the map. If Close() ever invoked
that callback synchronously, the write lock would self-deadlock (Go's RWMutex
is not reentrant). As far as we can tell that hazard already exists identically
under the current RLock, so the change looks safe — but we have not built or
run the test suite, so we are reporting rather than proposing a patch. You are
better placed to judge.
Worth noting that the WebRTC and RTMP servers do not have this problem: they
funnel every access to their session/connection maps through their run() loop
over a channel (chAPIConnsKick), so the mutation is serialised by construction.
The RTSP server is the one that uses an RWMutex instead — and its kick path
writes under the read lock.
Workaround for other users
Until this is fixed, serialise your calls to /v3/rtspsessions/* so that no two
are ever in flight at once. That removes the trigger entirely on the caller side.
Describe how to replicate the issue
The race window is narrow, so the fatal error is not the fastest way to see it — the Go race detector confirms it immediately.
1. Build the server with the race detector enabled and start it with the config below (defaults + control API):
go build -race && ./mediamtx2. Publish a few RTSP streams so several sessions exist:
for i in 1 2 3 4; do
ffmpeg -re -f lavfi -i testsrc=size=640x480:rate=25 -c:v libx264 \
-f rtsp rtsp://localhost:8554/test$i &
done3. Hit the control API with a read and a kick at the same time, in a loop:
while true; do
ids=$(curl -s localhost:9997/v3/rtspsessions/list | jq -r '.items[].id')
for id in $ids; do
curl -s -X POST localhost:9997/v3/rtspsessions/kick/$id >/dev/null &
curl -s localhost:9997/v3/rtspsessions/list >/dev/null &
done
wait
doneAny two concurrent handlers touching the sessions map are enough: both
APISessionsList and APISessionsKick hold only a read lock, while
APISessionsKick deletes from the map. The race detector reports the write in
APISessionsKick against the iteration in findSessionByUUID.
4. Relaunch the publishers as they get kicked, so the map keeps being written to while it is being iterated.
Without -race this is a matter of luck: in our case it took weeks of ordinary
production traffic before a burst of simultaneous kicks hit it, and two
deliberate attempts to reproduce it by closing many sessions at once did not
fire.
MediaMTX configuration
# Defaults, plus the control API. Nothing else is needed to trigger this —
# the race is in the API handlers, not in the media path.
api: yes
apiAddress: :9997MediaMTX logs
fatal error: concurrent map iteration and map write
goroutine 412541 [running]:
internal/runtime/maps.fatal({0x18336ae?, 0x48d9cf?})
/usr/local/go/src/runtime/panic.go:1181 +0x18
internal/runtime/maps.(*Iter).Next(...)
/usr/local/go/src/internal/runtime/maps/table.go:819 +0x86
github.com/bluenviron/mediamtx/internal/servers/rtsp.(*Server).findSessionByUUID(...)
/s/internal/servers/rtsp/server.go:408
github.com/bluenviron/mediamtx/internal/servers/rtsp.(*Server).APISessionsKick(...)
/s/internal/servers/rtsp/server.go:525 +0x165
github.com/bluenviron/mediamtx/internal/api.(*API).onRTSPSessionsKick(...)
/s/internal/api/api_rtsp.go:95 +0x99
github.com/gin-gonic/gin.(*Context).Next(...)
/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:192 +0x5f
...
net/http.(*conn).serve(...)
/usr/local/go/src/net/http/server.go:2073 +0x650Debug logging is not relevant here: this is a Go runtime fatal error, not an
application-level log. The line immediately before the panic was an ordinary
[RTSP] [session ...] destroyed: terminated, from three kicks landing in the
same millisecond.
Packet dump
Not applicable: this is a race in the control API handlers, no media packets are involved.
Source: bluenviron/mediamtx