From 4205121689490befed4c41b8f55ba22f9015b889 Mon Sep 17 00:00:00 2001 From: WofWca Date: Sun, 2 Mar 2025 15:38:23 +0400 Subject: [PATCH] fix: make NATPolicy thread-safe Although it does not look like that there are situations where it is critical to use a mutex, because it's only used when performing rendezvous with a proxy, which doesn't happen too frequently, let's still do it just to be sure. --- client/lib/rendezvous.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/client/lib/rendezvous.go b/client/lib/rendezvous.go index da06027..76209ee 100644 --- a/client/lib/rendezvous.go +++ b/client/lib/rendezvous.go @@ -11,6 +11,7 @@ import ( "net/http" "net/url" "sync" + "sync/atomic" "time" "github.com/pion/webrtc/v4" @@ -186,8 +187,9 @@ func (bc *BrokerChannel) GetNATType() string { return bc.natType } +// All of the methods of the struct are thread-safe. type NATPolicy struct { - assumedUnrestrictedNATAndFailedToConnect bool + assumedUnrestrictedNATAndFailedToConnect atomic.Bool } // When our NAT type is unknown, we want to try to connect to a @@ -199,7 +201,8 @@ type NATPolicy struct { // This is useful when our STUN servers are blocked or don't support // the NAT discovery feature, or if they're just slow. func (p *NATPolicy) NATTypeToSend(actualNatType string) string { - if !p.assumedUnrestrictedNATAndFailedToConnect && actualNatType == nat.NATUnknown { + if !p.assumedUnrestrictedNATAndFailedToConnect.Load() && + actualNatType == nat.NATUnknown { // If our NAT type is unknown, and we haven't failed to connect // with a spoofed NAT type yet, then spoof a NATUnrestricted // type. @@ -236,7 +239,7 @@ func (p *NATPolicy) Failure(actualNATType, sentNATType string) { "is \"%v\", and failed. Let's not do that again.", actualNATType, ) - p.assumedUnrestrictedNATAndFailedToConnect = true + p.assumedUnrestrictedNATAndFailedToConnect.Store(true) } }