From 23ef742e08215d467369c81c66f68e58fbe92d6b Mon Sep 17 00:00:00 2001 From: Grant Limberg Date: Wed, 13 Apr 2022 13:53:42 -0700 Subject: [PATCH] Fix for #1626 Port used for PortMapping was not properly randomized causing multiple clients on the same lan to request the same UPnP port, and not all routers handle this gracefully. Also fixes issue where the portmapper wasn't started at all if a secondary port wasn't specified, or if the tertiary port was manually specified. --- service/OneService.cpp | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/service/OneService.cpp b/service/OneService.cpp index f01b479df..e585a464e 100644 --- a/service/OneService.cpp +++ b/service/OneService.cpp @@ -1002,27 +1002,16 @@ public: // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't // use the other two ports for that because some NATs do really funky // stuff with ports that are explicitly mapped that breaks things. - if (_ports[1]) { - if (_tertiaryPort) { - _ports[2] = _tertiaryPort; - } else { - _ports[2] = 20000 + (_ports[0] % 40000); - for(int i=0;;++i) { - if (i > 1000) { - _ports[2] = 0; - break; - } else if (++_ports[2] >= 65536) { - _ports[2] = 20000; - } - if (_trialBind(_ports[2])) - break; - } - if (_ports[2]) { - char uniqueName[64]; - OSUtils::ztsnprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]); - _portMapper = new PortMapper(_ports[2],uniqueName); - } - } + if (_tertiaryPort) { + _ports[2] = _tertiaryPort; + } else { + _ports[2] = _getRandomPort(); + } + + if (_ports[2]) { + char uniqueName[64]; + OSUtils::ztsnprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]); + _portMapper = new PortMapper(_ports[2],uniqueName); } } #endif