tun: windows: serialize write calls

This commit is contained in:
Jason A. Donenfeld 2020-01-07 11:40:45 -05:00
parent 89dd065e53
commit 4fa2ea6a2d

View file

@ -9,6 +9,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"os" "os"
"sync"
"sync/atomic" "sync/atomic"
"time" "time"
"unsafe" "unsafe"
@ -40,6 +41,7 @@ type NativeTun struct {
forcedMTU int forcedMTU int
rate rateJuggler rate rateJuggler
rings *wintun.RingDescriptor rings *wintun.RingDescriptor
writeLock sync.Mutex
} }
const WintunPool = wintun.Pool("WireGuard") const WintunPool = wintun.Pool("WireGuard")
@ -219,6 +221,9 @@ func (tun *NativeTun) Write(buff []byte, offset int) (int, error) {
tun.rate.update(uint64(packetSize)) tun.rate.update(uint64(packetSize))
alignedPacketSize := wintun.PacketAlign(uint32(unsafe.Sizeof(wintun.PacketHeader{})) + packetSize) alignedPacketSize := wintun.PacketAlign(uint32(unsafe.Sizeof(wintun.PacketHeader{})) + packetSize)
tun.writeLock.Lock()
defer tun.writeLock.Unlock()
buffHead := atomic.LoadUint32(&tun.rings.Receive.Ring.Head) buffHead := atomic.LoadUint32(&tun.rings.Receive.Ring.Head)
if buffHead >= wintun.PacketCapacity { if buffHead >= wintun.PacketCapacity {
return 0, os.ErrClosed return 0, os.ErrClosed