Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tun/netstack: fix race during (*netTun).Close() #85

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions tun/netstack/tun.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"

Expand All @@ -42,7 +43,10 @@ import (
type netTun struct {
ep *channel.Endpoint
stack *stack.Stack
notifyHandle *channel.NotificationHandle
events chan tun.Event
pktMu sync.RWMutex
pktClosed bool
incomingPacket chan *bufferv2.View
mtu int
dnsServers []netip.Addr
Expand Down Expand Up @@ -70,7 +74,7 @@ func CreateNetTUN(localAddresses, dnsServers []netip.Addr, mtu int) (tun.Device,
if tcpipErr != nil {
return nil, nil, fmt.Errorf("could not enable TCP SACK: %v", tcpipErr)
}
dev.ep.AddNotify(dev)
dev.notifyHandle = dev.ep.AddNotify(dev)
tcpipErr = dev.stack.CreateNIC(1, dev.ep)
if tcpipErr != nil {
return nil, nil, fmt.Errorf("CreateNIC: %v", tcpipErr)
Expand Down Expand Up @@ -162,21 +166,27 @@ func (tun *netTun) WriteNotify() {
view := pkt.ToView()
pkt.DecRef()

tun.incomingPacket <- view
tun.pktMu.RLock()
if !tun.pktClosed {
tun.incomingPacket <- view
}
tun.pktMu.RUnlock()
}

func (tun *netTun) Close() error {
tun.stack.RemoveNIC(1)
tun.ep.RemoveNotify(tun.notifyHandle)

if tun.events != nil {
close(tun.events)
}

tun.ep.Close()

if tun.incomingPacket != nil {
close(tun.incomingPacket)
}
tun.pktMu.Lock()
tun.pktClosed = true
close(tun.incomingPacket)
tun.pktMu.Unlock()

return nil
}
Expand Down