diff --git a/application.go b/application.go index 29b1fae..2784df5 100644 --- a/application.go +++ b/application.go @@ -226,6 +226,14 @@ func (a *Application) Close() { a.logger.Errorf("closing api server: %v", err) } } + + if a.Tunnel != nil { + a.Tunnel.Close() + } + if a.SOCKS5 != nil { + a.SOCKS5.Close() + } + if a.P2p != nil { err := a.P2p.Close() if err != nil { @@ -235,12 +243,6 @@ func (a *Application) Close() { if a.Dns != nil { a.Dns.Close() } - if a.Tunnel != nil { - a.Tunnel.Close() - } - if a.SOCKS5 != nil { - a.SOCKS5.Close() - } if a.vpnDevice != nil { err := a.vpnDevice.Close() if err != nil { diff --git a/vpn/vpn.go b/vpn/vpn.go index 22a1cea..75d5cf3 100644 --- a/vpn/vpn.go +++ b/vpn/vpn.go @@ -32,6 +32,7 @@ type Device struct { localIP net.IP outboundCh chan *Packet + closeCh chan struct{} packetsPool sync.Pool logger *log.ZapEventLogger } @@ -62,7 +63,8 @@ func NewDevice(existingTun tun.Device, interfaceName string, localIP net.IP, ipM New: func() interface{} { return new(Packet) }}, - logger: log.Logger("awl/vpn"), + logger: log.Logger("awl/vpn"), + closeCh: make(chan struct{}), } go dev.tunEventsReader() go dev.tunPacketsReader() @@ -106,6 +108,7 @@ func (d *Device) OutboundChan() <-chan *Packet { } func (d *Device) Close() error { + close(d.closeCh) return d.tun.Close() } @@ -173,7 +176,12 @@ func (d *Device) tunPacketsReader() { continue } - d.outboundCh <- data + select { + case <-d.closeCh: + return + case d.outboundCh <- data: + // ok + } packets[i] = nil }