From 5b6f730f18d3e6804aad9e2c9ffb3790dfc60265 Mon Sep 17 00:00:00 2001 From: Arceliar Date: Sat, 12 Jun 2021 06:06:39 -0500 Subject: [PATCH] keep a context in the core, use it for listen/dial, cancel it when closing --- src/core/core.go | 17 ++++++++++++----- src/core/tcp.go | 6 +++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/core/core.go b/src/core/core.go index de916c1..b17bf19 100644 --- a/src/core/core.go +++ b/src/core/core.go @@ -1,6 +1,7 @@ package core import ( + "context" "crypto/ed25519" "encoding/hex" "errors" @@ -31,6 +32,8 @@ type Core struct { links links log *log.Logger addPeerTimer *time.Timer + ctx context.Context + ctxCancel context.CancelFunc } func (c *Core) _init() error { @@ -57,6 +60,7 @@ func (c *Core) _init() error { // TODO check public against current.PublicKey, error if they don't match c.PacketConn, err = iw.NewPacketConn(c.secret) + c.ctx, c.ctxCancel = context.WithCancel(context.Background()) return err } @@ -67,6 +71,10 @@ func (c *Core) _addPeerLoop() { c.config.RLock() defer c.config.RUnlock() + if c.addPeerTimer == nil { + return + } + // Add peers from the Peers section for _, peer := range c.config.Peers { go func(peer string, intf string) { @@ -95,11 +103,9 @@ func (c *Core) _addPeerLoop() { } } - if c.addPeerTimer != nil { - c.addPeerTimer = time.AfterFunc(time.Minute, func() { - c.Act(nil, c._addPeerLoop) - }) - } + c.addPeerTimer = time.AfterFunc(time.Minute, func() { + c.Act(nil, c._addPeerLoop) + }) } // Start starts up Yggdrasil using the provided config.NodeConfig, and outputs @@ -152,6 +158,7 @@ func (c *Core) Stop() { // This function is unsafe and should only be ran by the core actor. func (c *Core) _stop() { + c.ctxCancel() c.PacketConn.Close() c.log.Infoln("Stopping...") if c.addPeerTimer != nil { diff --git a/src/core/tcp.go b/src/core/tcp.go index c5487d5..c9bfd65 100644 --- a/src/core/tcp.go +++ b/src/core/tcp.go @@ -153,7 +153,7 @@ func (t *tcp) listenURL(u *url.URL, sintf string) (*TcpListener, error) { func (t *tcp) listen(listenaddr string, upgrade *TcpUpgrade) (*TcpListener, error) { var err error - ctx := context.Background() + ctx := t.links.core.ctx lc := net.ListenConfig{ Control: t.tcpContext, } @@ -270,7 +270,7 @@ func (t *tcp) call(saddr string, options tcpOptions, sintf string) { if err != nil { return } - ctx, done := context.WithTimeout(context.Background(), default_timeout) + ctx, done := context.WithTimeout(t.links.core.ctx, default_timeout) conn, err = dialer.(proxy.ContextDialer).DialContext(ctx, "tcp", saddr) done() if err != nil { @@ -339,7 +339,7 @@ func (t *tcp) call(saddr string, options tcpOptions, sintf string) { } } } - ctx, done := context.WithTimeout(context.Background(), default_timeout) + ctx, done := context.WithTimeout(t.links.core.ctx, default_timeout) conn, err = dialer.DialContext(ctx, "tcp", dst.String()) done() if err != nil {