From 18f43705ecbc8751bcf5ed05cd65cf93c36798b0 Mon Sep 17 00:00:00 2001 From: "Jason A. Donenfeld" Date: Sun, 20 May 2018 06:38:39 +0200 Subject: [PATCH] Fix race with closing event channel There's still a tiny race on Linux, since the tun channel is written to from two places. --- tun_darwin.go | 3 ++- tun_linux.go | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/tun_darwin.go b/tun_darwin.go index 23c0b54..d2cdcd5 100644 --- a/tun_darwin.go +++ b/tun_darwin.go @@ -53,6 +53,8 @@ func (tun *NativeTun) RoutineRouteListener(tunIfindex int) { statusMTU int ) + defer close(tun.events) + data := make([]byte, os.Getpagesize()) for { n, err := unix.Read(tun.routeSocket, data) @@ -302,7 +304,6 @@ func (tun *NativeTun) Close() error { // We don't even need to call shutdown, or use a rwcancel. err3 = unix.Close(tun.routeSocket) } - close(tun.events) if err1 != nil { return err1 } diff --git a/tun_linux.go b/tun_linux.go index 2782260..f9a27d6 100644 --- a/tun_linux.go +++ b/tun_linux.go @@ -89,7 +89,10 @@ func createNetlinkSocket() (int, error) { } func (tun *NativeTun) RoutineNetlinkListener() { - defer unix.Close(tun.netlinkSock) + defer func() { + unix.Close(tun.netlinkSock) + close(tun.events) + }() for msg := make([]byte, 1<<16); ; { @@ -357,7 +360,6 @@ func (tun *NativeTun) Close() error { } err2 := tun.fd.Close() err3 := tun.fdCancel.Cancel() - close(tun.events) if err1 != nil { return err1