From eefaed4b1ad9816841a56bd3f0bd1b64f2fe26d7 Mon Sep 17 00:00:00 2001 From: StephenButtolph Date: Wed, 24 Jun 2020 11:41:22 -0400 Subject: [PATCH] added error reporting to nat.Map --- main/main.go | 12 +++++++----- main/params.go | 4 ++-- nat/nat.go | 9 +++++++-- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/main/main.go b/main/main.go index 71de46f..250c1e0 100644 --- a/main/main.go +++ b/main/main.go @@ -67,13 +67,15 @@ func main() { mapper := nat.NewPortMapper(log, Config.Nat) defer mapper.UnmapAllPorts() - Config.StakingIP.Port = mapper.Map("TCP", Config.StakingLocalPort, "gecko-staking") // Open staking port - if Config.HTTPHost != "127.0.0.1" && Config.HTTPHost != "localhost" { // Open HTTP port iff HTTP server not listening on localhost - mapper.Map("TCP", Config.HTTPPort, "gecko-http") + port, err := mapper.Map("TCP", Config.StakingLocalPort, "gecko-staking") // Open staking port + if err == nil { + Config.StakingIP.Port = port + } else { + log.Warn("NAT traversal has failed. The node will be able to connect to less nodes.") } - if Config.StakingIP.IsZero() { - log.Warn("NAT traversal has failed. The node will be able to connect to less nodes.") + if Config.HTTPHost != "127.0.0.1" && Config.HTTPHost != "localhost" { // Open HTTP port iff HTTP server not listening on localhost + _, _ = mapper.Map("TCP", Config.HTTPPort, "gecko-http") } node := node.Node{} diff --git a/main/params.go b/main/params.go index 03b8459..47ea5f8 100644 --- a/main/params.go +++ b/main/params.go @@ -284,16 +284,16 @@ func init() { Config.DB = memdb.New() } - Config.Nat = nat.GetRouter() - var ip net.IP // If public IP is not specified, get it using shell command dig if *consensusIP == "" { + Config.Nat = nat.GetRouter() ip, err = Config.Nat.ExternalIP() if err != nil { ip = net.IPv4zero // Couldn't get my IP...set to 0.0.0.0 } } else { + Config.Nat = nat.NewNoRouter() ip = net.ParseIP(*consensusIP) } diff --git a/nat/nat.go b/nat/nat.go index 8c351c7..bd79fee 100644 --- a/nat/nat.go +++ b/nat/nat.go @@ -4,6 +4,7 @@ package nat import ( + "errors" "net" "sync" "time" @@ -63,12 +64,16 @@ func NewPortMapper(log logging.Logger, r Router) Mapper { // Map sets up port mapping using given protocol, internal and external ports // and returns the final port mapped. It returns 0 if mapping failed after the // maximun number of retries -func (dev *Mapper) Map(protocol string, intPort uint16, desc string) uint16 { +func (dev *Mapper) Map(protocol string, intPort uint16, desc string) (uint16, error) { mappedPort := make(chan uint16) go dev.keepPortMapping(mappedPort, protocol, intPort, desc) - return <-mappedPort + port := <-mappedPort + if port == 0 { + return 0, errors.New("failed to map port") + } + return port, nil } // keepPortMapping runs in the background to keep a port mapped. It renews the