From 5542dbcc0bf33d18a35c26680822bf57bc19af92 Mon Sep 17 00:00:00 2001
From: travisladuke <travisladuke@gmail.com>
Date: Tue, 9 Jan 2024 09:10:06 -0800
Subject: [PATCH] Fix random port rebinding

It was checking for "offline" every loop.
But the port rebinding happens only ever X
loops. So the port would keep changing before it
would get bound.
---
 service/OneService.cpp | 34 +++++++++++++++++-----------------
 1 file changed, 17 insertions(+), 17 deletions(-)

diff --git a/service/OneService.cpp b/service/OneService.cpp
index 8a0aee294..fcebe4677 100644
--- a/service/OneService.cpp
+++ b/service/OneService.cpp
@@ -1172,25 +1172,25 @@ public:
 					}
 				}
 
-				// If secondary port is not configured to a constant value and we've been offline for a while,
-				// bind a new secondary port. This is a workaround for a "coma" issue caused by buggy NATs that stop
-				// working on one port after a while.
-				if (_secondaryPort == 0) {
-					if (_node->online()) {
-						lastOnline = now;
-					}
-					if ((now - lastOnline) > ZT_PATH_HEARTBEAT_PERIOD  || restarted) {
-						_ports[1] = _getRandomPort();
-#if ZT_DEBUG==1
-						fprintf(stderr, "randomized secondary port. Now it's %d\n", _ports[1]);
-#endif
-						lastOnline = now; // don't keep spamming this branch. online() will be false for a few seconds
-					}
-				}
-
-
 				// Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
 				if (((now - lastBindRefresh) >= (_node->bondController()->inUse() ? ZT_BINDER_REFRESH_PERIOD / 4 : ZT_BINDER_REFRESH_PERIOD))||restarted) {
+					// If secondary port is not configured to a constant value and we've been offline for a while,
+					// bind a new secondary port. This is a workaround for a "coma" issue caused by buggy NATs that stop
+					// working on one port after a while.
+					if (_secondaryPort == 0) {
+						if (_node->online()) {
+							lastOnline = now;
+						}
+						else if (now - lastOnline > (ZT_PEER_PING_PERIOD * 2) || restarted) {
+							lastOnline = now;	// don't keep changing the port before we have a chance to connect
+							_ports[1] = _getRandomPort();
+
+#if ZT_DEBUG==1
+							fprintf(stderr, "Randomized secondary port. Now it's %d\n", _ports[1]);
+#endif
+						}
+					}
+
 					unsigned int p[3];
 					unsigned int pc = 0;
 					for(int i=0;i<3;++i) {