NAT.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  1. /*
  2. ** Command & Conquer Generals(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. ////////////////////////////////////////////////////////////////////////////////
  19. // //
  20. // (c) 2001-2003 Electronic Arts Inc. //
  21. // //
  22. ////////////////////////////////////////////////////////////////////////////////
  23. // FILE: NAT.cpp /////////////////////////////////////////////////////////////////////////////////
  24. // Author: Bryan Cleveland April 2002
  25. // Props to Steve Tall for figuring all the NAT and Firewall behavior patterns out, making my job
  26. // a LOT easier.
  27. // Desc: Resolves NAT'd IPs and port numbers for the other players in a game.
  28. ///////////////////////////////////////////////////////////////////////////////////////////////////
  29. #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
  30. #include "GameNetwork/NAT.h"
  31. #include "GameNetwork/Transport.h"
  32. #include "GameNetwork/NetworkDefs.h"
  33. #include "GameClient/EstablishConnectionsMenu.h"
  34. #include "GameNetwork/NetworkInterface.h"
  35. #include "GameNetwork/GameInfo.h"
  36. #include "GameNetwork/GameSpy/PeerThread.h"
  37. #include "GameNetwork/GameSpy/PeerDefs.h"
  38. #include "GameNetwork/GameSpy/PersistentStorageThread.h"
  39. #include "GameNetwork/GameSpy/GSConfig.h"
  40. #ifdef _INTERNAL
  41. // for occasional debugging...
  42. //#pragma optimize("", off)
  43. //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  44. #endif
  45. /*
  46. * In case you're wondering, we do this weird connection pairing scheme
  47. * to speed up the negotiation process, especially in cases where there
  48. * are 4 or more players (nodes). Take for example an 8 player game...
  49. * In an 8 player game there are 28 connections that need to be negotiated,
  50. * doing this pairing scheme thing, we can make those 28 connections in the
  51. * time it would normally take to make 7 connections. Since each connection
  52. * could potentially take several seconds, this can be a HUGE time savings.
  53. * Right now you're probably wondering who this Bryan Cleveland guy is.
  54. * He's the network coder that got fired when this didn't work.
  55. * In case you're wondering, this did end up working and Bryan left by
  56. * his own choice.
  57. */
  58. // m_connectionPairs[num nodes] [round] [node index]
  59. /* static */ Int NAT::m_connectionPairs[MAX_SLOTS-1][MAX_SLOTS-1][MAX_SLOTS] =
  60. {
  61. { // 2 nodes
  62. // node 0 node 1 node 2 node 3 node 4 node 5 node 6 node 7
  63. { 1, 0, -1, -1, -1, -1, -1, -1}, // round 0
  64. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 1
  65. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 2
  66. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 3
  67. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 4
  68. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 5
  69. { -1, -1, -1, -1, -1, -1, -1, -1} // round 6
  70. },
  71. { // 3 nodes
  72. // node 0 node 1 node 2 node 3 node 4 node 5 node 6 node 7
  73. { 1, 0, -1, -1, -1, -1, -1, -1}, // round 0
  74. { 2, -1, 0, -1, -1, -1, -1, -1}, // round 1
  75. { -1, 2, 1, -1, -1, -1, -1, -1}, // round 2
  76. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 3
  77. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 4
  78. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 5
  79. { -1, -1, -1, -1, -1, -1, -1, -1} // round 6
  80. },
  81. { // 4 nodes
  82. // node 0 node 1 node 2 node 3 node 4 node 5 node 6 node 7
  83. { 1, 0, 3, 2, -1, -1, -1, -1}, // round 0
  84. { 2, 3, 0, 1, -1, -1, -1, -1}, // round 1
  85. { 3, 2, 1, 0, -1, -1, -1, -1}, // round 2
  86. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 3
  87. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 4
  88. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 5
  89. { -1, -1, -1, -1, -1, -1, -1, -1} // round 6
  90. },
  91. { // 5 nodes
  92. // node 0 node 1 node 2 node 3 node 4 node 5 node 6 node 7
  93. { 2, 4, 0, -1, 1, -1, -1, -1}, // round 0
  94. { -1, 3, 4, 1, 2, -1, -1, -1}, // round 1
  95. { 3, 2, 1, 0, -1, -1, -1, -1}, // round 2
  96. { 4, -1, 3, 2, 0, -1, -1, -1}, // round 3
  97. { 1, 0, -1, 4, 3, -1, -1, -1}, // round 4
  98. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 5
  99. { -1, -1, -1, -1, -1, -1, -1, -1} // round 6
  100. },
  101. { // 6 nodes
  102. // node 0 node 1 node 2 node 3 node 4 node 5 node 6 node 7
  103. { 3, 5, 4, 0, 2, 1, -1, -1}, // round 0
  104. { 2, 4, 0, 5, 1, 3, -1, -1}, // round 1
  105. { 4, 3, 5, 1, 0, 2, -1, -1}, // round 2
  106. { 1, 0, 3, 2, 5, 4, -1, -1}, // round 3
  107. { 5, 2, 1, 4, 3, 0, -1, -1}, // round 4
  108. { -1, -1, -1, -1, -1, -1, -1, -1}, // round 5
  109. { -1, -1, -1, -1, -1, -1, -1, -1} // round 6
  110. },
  111. { // 7 nodes
  112. // node 0 node 1 node 2 node 3 node 4 node 5 node 6 node 7
  113. { -1, 6, 5, 4, 3, 2, 1, -1}, // round 0
  114. { 2, -1, 0, 6, 5, 4, 3, -1}, // round 1
  115. { 4, 3, -1, 1, 0, 6, 5, -1}, // round 2
  116. { 6, 5, 4, -1, 2, 1, 0, -1}, // round 3
  117. { 1, 0, 6, 5, -1, 3, 2, -1}, // round 4
  118. { 3, 2, 1, 0, 6, -1, 4, -1}, // round 5
  119. { 5, 4, 3, 2, 1, 0, -1, -1} // round 6
  120. },
  121. { // 8 nodes
  122. // node 0 node 1 node 2 node 3 node 4 node 5 node 6 node 7
  123. { 4, 5, 6, 7, 0, 1, 2, 3}, // round 0
  124. { 5, 4, 7, 6, 1, 0, 3, 2}, // round 1
  125. { 3, 6, 5, 0, 7, 2, 1, 4}, // round 2
  126. { 2, 7, 0, 5, 6, 3, 4, 1}, // round 3
  127. { 6, 3, 4, 1, 2, 7, 0, 5}, // round 4
  128. { 1, 0, 3, 2, 5, 4, 7, 6}, // round 5
  129. { 7, 2, 1, 4, 3, 6, 5, 0} // round 6
  130. }
  131. };
  132. /* static */ Int NAT::m_timeBetweenRetries = 500; // .5 seconds between retries sounds good to me.
  133. /* static */ time_t NAT::m_manglerRetryTimeInterval = 300; // sounds good to me.
  134. /* static */ Int NAT::m_maxAllowedManglerRetries = 25; // works for me.
  135. /* static */ time_t NAT::m_keepaliveInterval = 15000; // 15 seconds between keepalive packets seems good.
  136. /* static */ time_t NAT::m_timeToWaitForPort = 15000; // wait for 15 seconds for the other player's port number.
  137. /* static */ time_t NAT::m_timeForRoundTimeout = 15000; // wait for at most 15 seconds for each connection round to finish.
  138. NAT *TheNAT = NULL;
  139. NAT::NAT()
  140. {
  141. //Added By Sadullah Nader
  142. //Initializations inserted
  143. m_beenProbed = FALSE;
  144. m_connectionPairIndex = 0;
  145. m_connectionRound = 0;
  146. m_localIP = 0;
  147. m_localNodeNumber = 0;
  148. m_manglerAddress = 0;
  149. m_manglerRetries = 0;
  150. m_numNodes = 0;
  151. m_numRetries = 0;
  152. m_previousSourcePort = 0;
  153. for(Int i = 0; i < MAX_SLOTS; i++)
  154. m_sourcePorts[i] = 0;
  155. m_spareSocketPort = 0;
  156. m_startingPortNumber = 0;
  157. m_targetNodeNumber = 0;
  158. //
  159. m_transport = NULL;
  160. m_slotList = NULL;
  161. m_roundTimeout = 0;
  162. m_maxNumRetriesAllowed = 10;
  163. m_packetID = 0x7f00;
  164. }
  165. NAT::~NAT() {
  166. }
  167. // if we're already finished, change to being idle
  168. // if we are negotiating now, check to see if this round is done
  169. // if it is, check to see if we're completely done with all rounds.
  170. // if we are, set state to be done.
  171. // if not go on to the next connection round.
  172. // if we are negotiating still, call the connection update
  173. // check to see if this connection is done for us, or if it has failed.
  174. enum { MS_TO_WAIT_FOR_STATS = 5000 };
  175. NATStateType NAT::update() {
  176. static UnsignedInt s_startStatWaitTime = 0;
  177. if (m_NATState == NATSTATE_DONE) {
  178. m_NATState = NATSTATE_IDLE;
  179. } else if (m_NATState == NATSTATE_WAITFORSTATS) {
  180. // check for all stats
  181. Bool gotAllStats = TRUE;
  182. Bool timedOut = FALSE;
  183. for (Int i=0; i<MAX_SLOTS; ++i)
  184. {
  185. const GameSpyGameSlot *slot = TheGameSpyGame->getGameSpySlot(i);
  186. if (slot && slot->isHuman())
  187. {
  188. PSPlayerStats stats = TheGameSpyPSMessageQueue->findPlayerStatsByID(slot->getProfileID());
  189. if (stats.id == 0)
  190. {
  191. gotAllStats = FALSE;
  192. //DEBUG_LOG(("Failed to find stats for %ls(%d)\n", slot->getName().str(), slot->getProfileID()));
  193. }
  194. }
  195. }
  196. // check for timeout. Timing out is not a fatal error - it just means we didn't get the other
  197. // player's stats. We'll see 0/0 as his record, but we can still play him just fine.
  198. UnsignedInt now = timeGetTime();
  199. if (now > s_startStatWaitTime + MS_TO_WAIT_FOR_STATS)
  200. {
  201. DEBUG_LOG(("Timed out waiting for stats. Let's just start the dang game.\n"));
  202. timedOut = TRUE;
  203. }
  204. if (gotAllStats || timedOut)
  205. {
  206. m_NATState = NATSTATE_DONE;
  207. TheEstablishConnectionsMenu->endMenu();
  208. if (TheFirewallHelper != NULL) {
  209. delete TheFirewallHelper;
  210. TheFirewallHelper = NULL;
  211. }
  212. }
  213. } else if (m_NATState == NATSTATE_DOCONNECTIONPATHS) {
  214. if (allConnectionsDoneThisRound() == TRUE) {
  215. // we finished this round, move on to the next one.
  216. ++m_connectionRound;
  217. // m_roundTimeout = timeGetTime() + TheGameSpyConfig->getRoundTimeout();
  218. m_roundTimeout = timeGetTime() + m_timeForRoundTimeout;
  219. DEBUG_LOG(("NAT::update - done with connection round, moving on to round %d\n", m_connectionRound));
  220. // we finished that round, now check to see if we're done, or if there are more rounds to go.
  221. if (allConnectionsDone() == TRUE) {
  222. // we're all done, time to go back home.
  223. m_NATState = NATSTATE_WAITFORSTATS;
  224. // 2/19/03 BGC - we have successfully negotaited a NAT thingy, so our behavior must be correct
  225. // so therefore we don't need to refresh our NAT even if we previously thought we had to.
  226. TheFirewallHelper->flagNeedToRefresh(FALSE);
  227. s_startStatWaitTime = timeGetTime();
  228. DEBUG_LOG(("NAT::update - done with all connections, woohoo!!\n"));
  229. /*
  230. m_NATState = NATSTATE_DONE;
  231. TheEstablishConnectionsMenu->endMenu();
  232. if (TheFirewallHelper != NULL) {
  233. delete TheFirewallHelper;
  234. TheFirewallHelper = NULL;
  235. }
  236. */
  237. } else {
  238. doThisConnectionRound();
  239. }
  240. }
  241. NATConnectionState state = connectionUpdate();
  242. if (timeGetTime() > m_roundTimeout) {
  243. DEBUG_LOG(("NAT::update - round timeout expired\n"));
  244. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  245. notifyUsersOfConnectionFailed(m_localNodeNumber);
  246. }
  247. if (state == NATCONNECTIONSTATE_FAILED) {
  248. // if we fail
  249. m_NATState = NATSTATE_FAILED;
  250. TheEstablishConnectionsMenu->endMenu();
  251. if (TheFirewallHelper != NULL) {
  252. // we failed NAT negotiation, perhaps we need to redetect our firewall settings.
  253. // We don't trust the user to do it for themselves so we force them to do it next time
  254. // the log in.
  255. // 2/19/03 - ok, we don't want to do this right away, if the user tries to play in another game
  256. // before they log out and log back in the game won't have a chance at working.
  257. // so we need to simply flag it so that when they log out the firewall behavior gets blown away.
  258. TheFirewallHelper->flagNeedToRefresh(TRUE);
  259. // TheWritableGlobalData->m_firewallBehavior = FirewallHelperClass::FIREWALL_TYPE_UNKNOWN;
  260. // TheFirewallHelper->writeFirewallBehavior();
  261. delete TheFirewallHelper;
  262. TheFirewallHelper = NULL;
  263. }
  264. // we failed to connect, so we don't have to pass on the transport to the network.
  265. if (m_transport != NULL) {
  266. delete m_transport;
  267. m_transport = NULL;
  268. }
  269. }
  270. }
  271. return m_NATState;
  272. }
  273. // update transport, check for PROBE packets from our target.
  274. // check to see if its time to PROBE our target
  275. // MANGLER:
  276. // if we are talking to the mangler, check to see if we got a response
  277. // if we didn't get a response, check to see if its time to send another packet to it
  278. NATConnectionState NAT::connectionUpdate() {
  279. GameSlot *targetSlot = NULL;
  280. if (m_targetNodeNumber >= 0) {
  281. targetSlot = m_slotList[m_connectionNodes[m_targetNodeNumber].m_slotIndex];
  282. } else {
  283. return m_connectionStates[m_localNodeNumber];
  284. }
  285. if (m_beenProbed == FALSE) {
  286. if (timeGetTime() >= m_nextPortSendTime) {
  287. // sendMangledPortNumberToTarget(m_previousSourcePort, targetSlot);
  288. sendMangledPortNumberToTarget(m_sourcePorts[m_targetNodeNumber], targetSlot);
  289. // m_nextPortSendTime = timeGetTime() + TheGameSpyConfig->getRetryInterval();
  290. m_nextPortSendTime = timeGetTime() + m_timeBetweenRetries;
  291. }
  292. }
  293. // check to see if its time to send out our keepalives.
  294. if (timeGetTime() >= m_nextKeepaliveTime) {
  295. for (Int node = 0; node < m_numNodes; ++node) {
  296. if (m_myConnections[node] == TRUE) {
  297. // we've made this connection, send a keepalive.
  298. Int slotIndex = m_connectionNodes[node].m_slotIndex;
  299. GameSlot *slot = m_slotList[slotIndex];
  300. DEBUG_ASSERTCRASH(slot != NULL, ("Trying to send keepalive to a NULL slot"));
  301. if (slot != NULL) {
  302. UnsignedInt ip = slot->getIP();
  303. DEBUG_LOG(("NAT::connectionUpdate - sending keep alive to node %d at %d.%d.%d.%d:%d\n", node,
  304. ip >> 24, (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff, slot->getPort()));
  305. m_transport->queueSend(ip, slot->getPort(), (const unsigned char *)"KEEPALIVE", strlen("KEEPALIVE") + 1);
  306. }
  307. }
  308. }
  309. // m_nextKeepaliveTime = timeGetTime() + TheGameSpyConfig->getKeepaliveInterval();
  310. m_nextKeepaliveTime = timeGetTime() + m_keepaliveInterval;
  311. }
  312. m_transport->update();
  313. // check to see if we've been probed.
  314. for (Int i = 0; i < MAX_MESSAGES; ++i) {
  315. if (m_transport->m_inBuffer[i].length > 0) {
  316. #ifdef DEBUG_LOGGING
  317. UnsignedInt ip = m_transport->m_inBuffer[i].addr;
  318. #endif
  319. DEBUG_LOG(("NAT::connectionUpdate - got a packet from %d.%d.%d.%d:%d, length = %d\n",
  320. ip >> 24, (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff, m_transport->m_inBuffer[i].port, m_transport->m_inBuffer[i].length));
  321. UnsignedByte *data = m_transport->m_inBuffer[i].data;
  322. if (memcmp(data, "PROBE", strlen("PROBE")) == 0) {
  323. Int fromNode = atoi((char *)data + strlen("PROBE"));
  324. DEBUG_LOG(("NAT::connectionUpdate - we've been probed by node %d.\n", fromNode));
  325. if (fromNode == m_targetNodeNumber) {
  326. DEBUG_LOG(("NAT::connectionUpdate - probe was sent by our target, setting connection state %d to done.\n", m_targetNodeNumber));
  327. setConnectionState(m_targetNodeNumber, NATCONNECTIONSTATE_DONE);
  328. if (m_transport->m_inBuffer[i].addr != targetSlot->getIP()) {
  329. UnsignedInt fromIP = m_transport->m_inBuffer[i].addr;
  330. #ifdef DEBUG_LOGGING
  331. UnsignedInt slotIP = targetSlot->getIP();
  332. #endif
  333. DEBUG_LOG(("NAT::connectionUpdate - incomming packet has different from address than we expected, incoming: %d.%d.%d.%d expected: %d.%d.%d.%d\n",
  334. fromIP >> 24, (fromIP >> 16) & 0xff, (fromIP >> 8) & 0xff, fromIP & 0xff,
  335. slotIP >> 24, (slotIP >> 16) & 0xff, (slotIP >> 8) & 0xff, slotIP & 0xff));
  336. targetSlot->setIP(fromIP);
  337. }
  338. if (m_transport->m_inBuffer[i].port != targetSlot->getPort()) {
  339. DEBUG_LOG(("NAT::connectionUpdate - incoming packet came from a different port than we expected, incoming: %d expected: %d\n",
  340. m_transport->m_inBuffer[i].port, targetSlot->getPort()));
  341. targetSlot->setPort(m_transport->m_inBuffer[i].port);
  342. m_sourcePorts[m_targetNodeNumber] = m_transport->m_inBuffer[i].port;
  343. }
  344. notifyUsersOfConnectionDone(m_targetNodeNumber);
  345. }
  346. m_transport->m_inBuffer[i].length = 0;
  347. }
  348. if (memcmp(data, "KEEPALIVE", strlen("KEEPALIVE")) == 0) {
  349. // keep alive packet, just toss it.
  350. DEBUG_LOG(("NAT::connectionUpdate - got keepalive from %d.%d.%d.%d:%d\n",
  351. ip >> 24, (ip >> 16) & 0xff, (ip >> 8) && 0xff, ip & 0xff, m_transport->m_inBuffer[i].port));
  352. m_transport->m_inBuffer[i].length = 0;
  353. }
  354. }
  355. }
  356. // we are waiting for our target to tell us that they have received our probe.
  357. if (m_connectionStates[m_localNodeNumber] == NATCONNECTIONSTATE_WAITINGFORRESPONSE) {
  358. // check to see if it's time to probe our target.
  359. if ((m_timeTillNextSend != -1) && (m_timeTillNextSend <= timeGetTime())) {
  360. if (m_numRetries > m_maxNumRetriesAllowed) {
  361. DEBUG_LOG(("NAT::connectionUpdate - too many retries, connection failed.\n"));
  362. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  363. notifyUsersOfConnectionFailed(m_localNodeNumber);
  364. } else {
  365. DEBUG_LOG(("NAT::connectionUpdate - trying to send another probe (#%d) to our target\n", m_numRetries+1));
  366. // Send a probe.
  367. sendAProbe(targetSlot->getIP(), targetSlot->getPort(), m_localNodeNumber);
  368. // m_timeTillNextSend = timeGetTime() + TheGameSpyConfig->getRetryInterval();
  369. m_timeTillNextSend = timeGetTime() + m_timeBetweenRetries;
  370. // tell the target they've been probed. In other words, our port is open.
  371. notifyTargetOfProbe(targetSlot);
  372. ++m_numRetries;
  373. }
  374. }
  375. }
  376. // we are waiting for a response from the mangler to tell us what port we're using.
  377. if (m_connectionStates[m_localNodeNumber] == NATCONNECTIONSTATE_WAITINGFORMANGLERRESPONSE) {
  378. UnsignedShort mangledPort = 0;
  379. if (TheFirewallHelper != NULL) {
  380. mangledPort = TheFirewallHelper->getManglerResponse(m_packetID);
  381. }
  382. if (mangledPort != 0) {
  383. // we got a response. now we need to start probing (unless of course we have a netgear)
  384. processManglerResponse(mangledPort);
  385. // we know there is a firewall helper if we got here.
  386. TheFirewallHelper->closeSpareSocket(m_spareSocketPort);
  387. m_spareSocketPort = 0;
  388. } else {
  389. if (timeGetTime() >= m_manglerRetryTime) {
  390. ++m_manglerRetries;
  391. // if (m_manglerRetries > TheGameSpyConfig->getMaxManglerRetries()) {
  392. if (m_manglerRetries > m_maxAllowedManglerRetries) {
  393. // we couldn't communicate with the mangler, just use our non-mangled
  394. // port number and hope that works.
  395. DEBUG_LOG(("NAT::connectionUpdate - couldn't talk with the mangler using default port number\n"));
  396. sendMangledPortNumberToTarget(getSlotPort(m_connectionNodes[m_localNodeNumber].m_slotIndex), targetSlot);
  397. m_sourcePorts[m_targetNodeNumber] = getSlotPort(m_connectionNodes[m_localNodeNumber].m_slotIndex);
  398. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORRESPONSE);
  399. } else {
  400. if (TheFirewallHelper != NULL) {
  401. DEBUG_LOG(("NAT::connectionUpdate - trying to send to the mangler again. mangler address: %d.%d.%d.%d, from port: %d, packet ID:%d\n",
  402. m_manglerAddress >> 24, (m_manglerAddress >> 16) & 0xff, (m_manglerAddress >> 8) & 0xff, m_manglerAddress & 0xff, m_spareSocketPort, m_packetID));
  403. TheFirewallHelper->sendToManglerFromPort(m_manglerAddress, m_spareSocketPort, m_packetID);
  404. }
  405. // m_manglerRetryTime = TheGameSpyConfig->getRetryInterval() + timeGetTime();
  406. m_manglerRetryTime = m_manglerRetryTimeInterval + timeGetTime();
  407. }
  408. }
  409. }
  410. }
  411. if (m_connectionStates[m_localNodeNumber] == NATCONNECTIONSTATE_WAITINGFORMANGLEDPORT) {
  412. if (timeGetTime() > m_timeoutTime) {
  413. DEBUG_LOG(("NAT::connectionUpdate - waiting too long to get the other player's port number, failed.\n"));
  414. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  415. notifyUsersOfConnectionFailed(m_localNodeNumber);
  416. }
  417. }
  418. return m_connectionStates[m_localNodeNumber];
  419. }
  420. // this is the function that starts the NAT/firewall negotiation process.
  421. // after calling this, you should call the update function untill it returns
  422. // NATSTATE_DONE.
  423. void NAT::establishConnectionPaths() {
  424. DEBUG_LOG(("NAT::establishConnectionPaths - entering\n"));
  425. m_NATState = NATSTATE_DOCONNECTIONPATHS;
  426. DEBUG_LOG(("NAT::establishConnectionPaths - using %d as our starting port number\n", m_startingPortNumber));
  427. if (TheEstablishConnectionsMenu == NULL) {
  428. TheEstablishConnectionsMenu = NEW EstablishConnectionsMenu;
  429. }
  430. TheEstablishConnectionsMenu->initMenu();
  431. if (TheFirewallHelper == NULL) {
  432. TheFirewallHelper = createFirewallHelper();
  433. }
  434. DEBUG_ASSERTCRASH(m_slotList != NULL, ("NAT::establishConnectionPaths - don't have a slot list"));
  435. if (m_slotList == NULL) {
  436. return;
  437. }
  438. // determine how many nodes we have.
  439. m_numNodes = 0;
  440. for (Int i = 0; i < MAX_SLOTS; ++i) {
  441. if (m_slotList[i] != NULL) {
  442. if (m_slotList[i]->isHuman()) {
  443. DEBUG_LOG(("NAT::establishConnectionPaths - slot %d is %ls\n", i, m_slotList[i]->getName().str()));
  444. ++m_numNodes;
  445. }
  446. }
  447. }
  448. DEBUG_LOG(("NAT::establishConnectionPaths - number of nodes: %d\n", m_numNodes));
  449. if (m_numNodes < 2)
  450. {
  451. // just start the game - there isn't anybody to which to connect. :P
  452. m_NATState = NATSTATE_DONE;
  453. return;
  454. }
  455. m_connectionRound = 0;
  456. m_connectionPairIndex = m_numNodes - 2;
  457. Bool connectionAssigned[MAX_SLOTS];
  458. for (i = 0; i < MAX_SLOTS; ++i) {
  459. m_connectionNodes[i].m_slotIndex = -1;
  460. connectionAssigned[i] = FALSE;
  461. m_sourcePorts[i] = 0;
  462. }
  463. m_previousSourcePort = 0;
  464. // check for netgear bug behavior.
  465. // as an aside, if there are more than 2 netgear bug firewall's in the game,
  466. // it probably isn't going to work so well. stupid netgear.
  467. // nodes with a netgear bug behavior need to be matched up first. This prevents
  468. // the NAT table from being reset for connections to other nodes. This also happens
  469. // to be the reason why I call them "nodes" rather than "slots" or "players" as the
  470. // ordering has to be messed with to get the netgears to make love, not war.
  471. DEBUG_LOG(("NAT::establishConnectionPaths - about to set up the node list\n"));
  472. DEBUG_LOG(("NAT::establishConnectionPaths - doing the netgear stuff\n"));
  473. UnsignedInt otherNetgearNum = -1;
  474. for (i = 0; i < MAX_SLOTS; ++i) {
  475. if ((m_slotList != NULL) && (m_slotList[i] != NULL)) {
  476. if ((m_slotList[i]->getNATBehavior() & FirewallHelperClass::FIREWALL_TYPE_NETGEAR_BUG) != 0) {
  477. if (otherNetgearNum == -1) {
  478. // this is the start of a new pair, put it in as the first non -1 node connection pair thing.
  479. Int nodeindex = 0;
  480. while ((m_connectionPairs[m_connectionPairIndex][0][nodeindex] == -1) || (m_connectionNodes[nodeindex].m_slotIndex != -1)) {
  481. ++nodeindex;
  482. }
  483. m_connectionNodes[nodeindex].m_slotIndex = i;
  484. m_connectionNodes[nodeindex].m_behavior = m_slotList[i]->getNATBehavior();
  485. connectionAssigned[i] = TRUE;
  486. otherNetgearNum = nodeindex;
  487. DEBUG_LOG(("NAT::establishConnectionPaths - first netgear in pair. assigning node %d to slot %d (%ls)\n", nodeindex, i, m_slotList[i]->getName().str()));
  488. } else {
  489. // this is the second in the pair of netgears, pair this up with the other one
  490. // for the first round.
  491. Int nodeindex = 0;
  492. while (m_connectionPairs[m_connectionPairIndex][0][nodeindex] != otherNetgearNum) {
  493. ++nodeindex;
  494. }
  495. m_connectionNodes[nodeindex].m_slotIndex = i;
  496. m_connectionNodes[nodeindex].m_behavior = m_slotList[i]->getNATBehavior();
  497. connectionAssigned[i] = TRUE;
  498. otherNetgearNum = -1;
  499. DEBUG_LOG(("NAT::establishConnectionPaths - second netgear in pair. assigning node %d to slot %d (%ls)\n", nodeindex, i, m_slotList[i]->getName().str()));
  500. }
  501. }
  502. }
  503. }
  504. // fill in the rest of the nodes with the remaining slots.
  505. DEBUG_LOG(("NAT::establishConnectionPaths - doing the non-Netgear nodes\n"));
  506. for (i = 0; i < MAX_SLOTS; ++i) {
  507. if (connectionAssigned[i] == TRUE) {
  508. continue;
  509. }
  510. if (m_slotList[i] == NULL) {
  511. continue;
  512. }
  513. if (!(m_slotList[i]->isHuman())) {
  514. continue;
  515. }
  516. // find the first available connection node for this slot.
  517. Int nodeindex = 0;
  518. while (m_connectionNodes[nodeindex].m_slotIndex != -1) {
  519. ++nodeindex;
  520. }
  521. DEBUG_LOG(("NAT::establishConnectionPaths - assigning node %d to slot %d (%ls)\n", nodeindex, i, m_slotList[i]->getName().str()));
  522. m_connectionNodes[nodeindex].m_slotIndex = i;
  523. m_connectionNodes[nodeindex].m_behavior = m_slotList[i]->getNATBehavior();
  524. connectionAssigned[i] = TRUE;
  525. }
  526. // sanity check
  527. #if defined(_DEBUG) || defined(_INTERNAL)
  528. for (i = 0; i < m_numNodes; ++i) {
  529. DEBUG_ASSERTCRASH(connectionAssigned[i] == TRUE, ("connection number %d not assigned", i));
  530. }
  531. #endif
  532. // find the local node number.
  533. for (i = 0; i < m_numNodes; ++i) {
  534. if (m_connectionNodes[i].m_slotIndex == TheGameSpyGame->getLocalSlotNum()) {
  535. m_localNodeNumber = i;
  536. DEBUG_LOG(("NAT::establishConnectionPaths - local node is %d\n", m_localNodeNumber));
  537. break;
  538. }
  539. }
  540. // set up the names in the connection window.
  541. Int playerNum = 0;
  542. for (i = 0; i < MAX_SLOTS; ++i) {
  543. while ((i < MAX_SLOTS) && (m_slotList[i] != NULL) && !(m_slotList[i]->isHuman())) {
  544. ++i;
  545. }
  546. if (i >= MAX_SLOTS) {
  547. break;
  548. }
  549. if (i != TheGameSpyGame->getLocalSlotNum()) {
  550. TheEstablishConnectionsMenu->setPlayerName(playerNum, m_slotList[i]->getName());
  551. TheEstablishConnectionsMenu->setPlayerStatus(playerNum, NATCONNECTIONSTATE_WAITINGTOBEGIN);
  552. ++playerNum;
  553. }
  554. }
  555. // m_roundTimeout = timeGetTime() + TheGameSpyConfig->getRoundTimeout();
  556. m_roundTimeout = timeGetTime() + m_timeForRoundTimeout;
  557. // make the connections for this round.
  558. // this song is cool.
  559. doThisConnectionRound();
  560. }
  561. void NAT::attachSlotList(GameSlot *slotList[], Int localSlot, UnsignedInt localIP) {
  562. m_slotList = slotList;
  563. m_localIP = localIP;
  564. m_transport = new Transport;
  565. DEBUG_LOG(("NAT::attachSlotList - initting the transport socket with address %d.%d.%d.%d:%d\n",
  566. m_localIP >> 24, (m_localIP >> 16) & 0xff, (m_localIP >> 8) & 0xff, m_localIP & 0xff, getSlotPort(localSlot)));
  567. m_startingPortNumber = NETWORK_BASE_PORT_NUMBER + ((timeGetTime() / 1000) % 20000);
  568. DEBUG_LOG(("NAT::attachSlotList - using %d as the starting port number\n", m_startingPortNumber));
  569. generatePortNumbers(slotList, localSlot);
  570. m_transport->init(m_localIP, getSlotPort(localSlot));
  571. }
  572. Int NAT::getSlotPort(Int slot) {
  573. // return (slot + m_startingPortNumber);
  574. if (m_slotList[slot] != NULL) {
  575. return m_slotList[slot]->getPort();
  576. }
  577. return 0;
  578. }
  579. void NAT::generatePortNumbers(GameSlot *slotList[], Int localSlot) {
  580. for (Int i = 0; i < MAX_SLOTS; ++i) {
  581. if (slotList[i] != NULL) {
  582. if ((i == localSlot) && (TheWritableGlobalData->m_firewallPortOverride != 0)) {
  583. slotList[i]->setPort(TheWritableGlobalData->m_firewallPortOverride);
  584. } else {
  585. slotList[i]->setPort(i + m_startingPortNumber);
  586. }
  587. }
  588. }
  589. }
  590. Transport * NAT::getTransport() {
  591. return m_transport;
  592. }
  593. // figure out which port I'll be using.
  594. // send the port number to our target for this round.
  595. // init the m_connectionStates for all players.
  596. void NAT::doThisConnectionRound() {
  597. DEBUG_LOG(("NAT::doThisConnectionRound - starting process for connection round %d\n", m_connectionRound));
  598. // clear out the states from the last round.
  599. m_targetNodeNumber = -1;
  600. for (Int i = 0; i < MAX_SLOTS; ++i) {
  601. setConnectionState(i, NATCONNECTIONSTATE_NOSTATE);
  602. }
  603. m_beenProbed = FALSE;
  604. m_numRetries = 0;
  605. for (i = 0; i < m_numNodes; ++i) {
  606. Int targetNodeNumber = m_connectionPairs[m_connectionPairIndex][m_connectionRound][i];
  607. DEBUG_LOG(("NAT::doThisConnectionRound - node %d needs to connect to node %d\n", i, targetNodeNumber));
  608. if (targetNodeNumber != -1) {
  609. if (i == m_localNodeNumber) {
  610. m_targetNodeNumber = targetNodeNumber;
  611. DEBUG_LOG(("NAT::doThisConnectionRound - Local node is connecting to node %d\n", m_targetNodeNumber));
  612. UnsignedInt targetSlotIndex = m_connectionNodes[(m_connectionPairs[m_connectionPairIndex][m_connectionRound][i])].m_slotIndex;
  613. GameSlot *targetSlot = m_slotList[targetSlotIndex];
  614. GameSlot *localSlot = m_slotList[m_connectionNodes[m_localNodeNumber].m_slotIndex];
  615. DEBUG_ASSERTCRASH(localSlot != NULL, ("local slot is NULL"));
  616. DEBUG_ASSERTCRASH(targetSlot != NULL, ("trying to negotiate with a NULL target slot, slot is %d", m_connectionPairs[m_connectionPairIndex][m_connectionRound][i]));
  617. DEBUG_LOG(("NAT::doThisConnectionRound - Target slot index = %d (%ls)\n", targetSlotIndex, m_slotList[targetSlotIndex]->getName().str()));
  618. DEBUG_LOG(("NAT::doThisConnectionRound - Target slot has NAT behavior 0x%8X, local slot has NAT behavior 0x%8X\n", targetSlot->getNATBehavior(), localSlot->getNATBehavior()));
  619. #if defined(DEBUG_LOGGING)
  620. UnsignedInt targetIP = targetSlot->getIP();
  621. UnsignedInt localIP = localSlot->getIP();
  622. #endif
  623. DEBUG_LOG(("NAT::doThisConnectionRound - Target slot has IP %d.%d.%d.%d Local slot has IP %d.%d.%d.%d\n",
  624. targetIP >> 24, (targetIP >> 16) & 0xff, (targetIP >> 8) & 0xff, targetIP & 0xff,
  625. localIP >> 24, (localIP >> 16) & 0xff, (localIP >> 8) & 0xff, localIP & 0xff));
  626. if (((targetSlot->getNATBehavior() & FirewallHelperClass::FIREWALL_TYPE_NETGEAR_BUG) == 0) &&
  627. ((localSlot->getNATBehavior() & FirewallHelperClass::FIREWALL_TYPE_NETGEAR_BUG) != 0)) {
  628. // we have a netgear bug type behavior and the target does not, so we need them to send to us
  629. // first to avoid having our NAT table reset.
  630. DEBUG_LOG(("NAT::doThisConnectionRound - Local node has a netgear and the target node does not, need to delay our probe.\n"));
  631. m_timeTillNextSend = -1;
  632. }
  633. // figure out which port number I'm using for this connection
  634. // this merely starts to talk to the mangler server, we have to keep calling
  635. // the update function till we get a response.
  636. DEBUG_LOG(("NAT::doThisConnectionRound - About to attempt to get the next mangled source port\n"));
  637. sendMangledSourcePort();
  638. // m_nextPortSendTime = timeGetTime() + TheGameSpyConfig->getRetryInterval();
  639. m_nextPortSendTime = timeGetTime() + m_timeBetweenRetries;
  640. // m_timeoutTime = timeGetTime() + TheGameSpyConfig->getPortTimeout();
  641. m_timeoutTime = timeGetTime() + m_timeToWaitForPort;
  642. } else {
  643. // this is someone else that needs to connect to someone, so wait till they tell us
  644. // that they're done.
  645. setConnectionState(i, NATCONNECTIONSTATE_WAITINGFORRESPONSE);
  646. }
  647. } else {
  648. // no one to connect to, so this one is done.
  649. DEBUG_LOG(("NAT::doThisConnectionRound - node %d has no one to connect to, so they're done\n", i));
  650. setConnectionState(i, NATCONNECTIONSTATE_DONE);
  651. }
  652. }
  653. }
  654. void NAT::sendAProbe(UnsignedInt ip, UnsignedShort port, Int fromNode) {
  655. DEBUG_LOG(("NAT::sendAProbe - sending a probe from port %d to %d.%d.%d.%d:%d\n", getSlotPort(m_connectionNodes[m_localNodeNumber].m_slotIndex),
  656. ip >> 24, (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff, port));
  657. AsciiString str;
  658. str.format("PROBE%d", fromNode);
  659. m_transport->queueSend(ip, port, (unsigned char *)str.str(), str.getLength() + 1);
  660. m_transport->doSend();
  661. }
  662. // find the next mangled source port, and then send it to the other player.
  663. // if this requires talking to the mangler, we'll have to wait till a later update
  664. // to send our port out.
  665. void NAT::sendMangledSourcePort() {
  666. UnsignedShort sourcePort = getSlotPort(m_connectionNodes[m_localNodeNumber].m_slotIndex);
  667. FirewallHelperClass::tFirewallBehaviorType fwType = m_slotList[m_connectionNodes[m_localNodeNumber].m_slotIndex]->getNATBehavior();
  668. GameSlot *targetSlot = m_slotList[m_connectionNodes[m_targetNodeNumber].m_slotIndex];
  669. DEBUG_ASSERTCRASH(targetSlot != NULL, ("NAT::sendMangledSourcePort - targetSlot is NULL"));
  670. if (targetSlot == NULL) {
  671. DEBUG_LOG(("NAT::sendMangledSourcePort - targetSlot is NULL, failed this connection\n"));
  672. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  673. return;
  674. }
  675. GameSlot *localSlot = m_slotList[m_connectionNodes[m_localNodeNumber].m_slotIndex];
  676. DEBUG_ASSERTCRASH(localSlot != NULL, ("NAT::sendMangledSourcePort - localSlot is NULL, WTF?"));
  677. if (localSlot == NULL) {
  678. DEBUG_LOG(("NAT::sendMangledSourcePort - localSlot is NULL, failed this connection\n"));
  679. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  680. return;
  681. }
  682. // check to see if the target and I are behind the same NAT
  683. if (targetSlot->getIP() == localSlot->getIP()) {
  684. #if defined(DEBUG_LOGGING)
  685. UnsignedInt localip = localSlot->getIP();
  686. UnsignedInt targetip = targetSlot->getIP();
  687. #endif
  688. DEBUG_LOG(("NAT::sendMangledSourcePort - target and I are behind the same NAT, no mangling\n"));
  689. DEBUG_LOG(("NAT::sendMangledSourcePort - I am %ls, target is %ls, my IP is %d.%d.%d.%d, target IP is %d.%d.%d.%d\n", localSlot->getName().str(), targetSlot->getName().str(),
  690. localip >> 24, (localip >> 16) & 0xff, (localip >> 8) & 0xff, localip & 0xff,
  691. targetip >> 24, (targetip >> 16) & 0xff, (targetip >> 8) & 0xff, targetip & 0xff));
  692. sendMangledPortNumberToTarget(sourcePort, targetSlot);
  693. m_sourcePorts[m_targetNodeNumber] = sourcePort;
  694. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORMANGLEDPORT);
  695. // In case you're wondering, we don't set the m_previousSourcePort here because this will be a different source
  696. // address than what other nodes will likely see (unless of course there are more than
  697. // two of us behind the same NAT, but we won't worry about that cause theres no mangling
  698. // in that case anyways)
  699. return;
  700. }
  701. // check to see if we are NAT'd at all.
  702. if ((fwType == 0) || (fwType == FirewallHelperClass::FIREWALL_TYPE_SIMPLE)) {
  703. // no mangling, just return the source port
  704. DEBUG_LOG(("NAT::sendMangledSourcePort - no mangling, just using the source port\n"));
  705. sendMangledPortNumberToTarget(sourcePort, targetSlot);
  706. m_previousSourcePort = sourcePort;
  707. m_sourcePorts[m_targetNodeNumber] = sourcePort;
  708. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORMANGLEDPORT);
  709. return;
  710. }
  711. // check to see if our NAT keeps the same source port for different destinations.
  712. // if this is the case, and we've already worked out what our mangled port number is
  713. // then we don't have to figure it out again.
  714. if (((fwType & FirewallHelperClass::FIREWALL_TYPE_DESTINATION_PORT_DELTA) == 0) &&
  715. ((fwType & FirewallHelperClass::FIREWALL_TYPE_SMART_MANGLING) == 0)) {
  716. DEBUG_LOG(("NAT::sendMangledSourcePort - our firewall doesn't NAT based on destination address, checking for old connections from this address\n"));
  717. if (m_previousSourcePort != 0) {
  718. DEBUG_LOG(("NAT::sendMangledSourcePort - Previous source port was %d, using that one\n", m_previousSourcePort));
  719. sendMangledPortNumberToTarget(m_previousSourcePort, targetSlot);
  720. m_sourcePorts[m_targetNodeNumber] = m_previousSourcePort;
  721. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORMANGLEDPORT);
  722. return;
  723. } else {
  724. DEBUG_LOG(("NAT::sendMangledSourcePort - Previous source port not found\n"));
  725. }
  726. }
  727. // At this point we know that our NAT uses some kind of relative port mapping scheme, so we
  728. // need to talk to the mangler to find out where we are now so we can find out where we'll be on the
  729. // next port allocation.
  730. // get the address of the mangler we need to talk to.
  731. Char manglerName[256];
  732. FirewallHelperClass::getManglerName(1, manglerName);
  733. DEBUG_LOG(("NAT::sendMangledSourcePort - about to call gethostbyname for mangler at %s\n", manglerName));
  734. struct hostent *hostInfo = gethostbyname(manglerName);
  735. if (hostInfo == NULL) {
  736. DEBUG_LOG(("NAT::sendMangledSourcePort - gethostbyname failed for mangler address %s\n", manglerName));
  737. // can't find the mangler, we're screwed so just send the source port.
  738. sendMangledPortNumberToTarget(sourcePort, targetSlot);
  739. m_sourcePorts[m_targetNodeNumber] = sourcePort;
  740. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORMANGLEDPORT);
  741. return;
  742. }
  743. memcpy(&m_manglerAddress, &(hostInfo->h_addr_list[0][0]), 4);
  744. m_manglerAddress = ntohl(m_manglerAddress);
  745. DEBUG_LOG(("NAT::sendMangledSourcePort - mangler %s address is %d.%d.%d.%d\n", manglerName,
  746. m_manglerAddress >> 24, (m_manglerAddress >> 16) & 0xff, (m_manglerAddress >> 8) & 0xff, m_manglerAddress & 0xff));
  747. DEBUG_LOG(("NAT::sendMangledSourcePort - NAT behavior = 0x%08x\n", fwType));
  748. // m_manglerRetryTime = TheGameSpyConfig->getRetryInterval() + timeGetTime();
  749. m_manglerRetryTime = m_manglerRetryTimeInterval + timeGetTime();
  750. m_manglerRetries = 0;
  751. if (TheFirewallHelper != NULL) {
  752. m_spareSocketPort = TheFirewallHelper->getNextTemporarySourcePort(0);
  753. TheFirewallHelper->openSpareSocket(m_spareSocketPort);
  754. TheFirewallHelper->sendToManglerFromPort(m_manglerAddress, m_spareSocketPort, m_packetID);
  755. // m_manglerRetryTime = TheGameSpyConfig->getRetryInterval() + timeGetTime();
  756. m_manglerRetryTime = m_manglerRetryTimeInterval + timeGetTime();
  757. }
  758. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORMANGLERRESPONSE);
  759. }
  760. void NAT::processManglerResponse(UnsignedShort mangledPort) {
  761. DEBUG_LOG(("NAT::processManglerResponse - Work out what my NAT'd port will be\n"));
  762. GameSlot *targetSlot = m_slotList[m_connectionNodes[m_targetNodeNumber].m_slotIndex];
  763. DEBUG_ASSERTCRASH(targetSlot != NULL, ("NAT::processManglerResponse - targetSlot is NULL"));
  764. if (targetSlot == NULL) {
  765. DEBUG_LOG(("NAT::processManglerResponse - targetSlot is NULL, failed this connection\n"));
  766. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  767. return;
  768. }
  769. Short delta = TheGlobalData->m_firewallPortAllocationDelta;
  770. UnsignedShort sourcePort = getSlotPort(m_connectionNodes[m_localNodeNumber].m_slotIndex);
  771. UnsignedShort returnPort = 0;
  772. FirewallHelperClass::tFirewallBehaviorType fwType = m_slotList[m_connectionNodes[m_localNodeNumber].m_slotIndex]->getNATBehavior();
  773. if ((fwType & FirewallHelperClass::FIREWALL_TYPE_SIMPLE_PORT_ALLOCATION) != 0) {
  774. returnPort = mangledPort + delta;
  775. } else {
  776. // to steal a line from Steve Tall...
  777. // Rats. It's a relative mangler. This is much harder. Damn NAT32 guy.
  778. if (delta == 100) {
  779. // Special NAT32 section.
  780. // NAT32 mangles source UDP port by ading 1700 + 100*NAT table index.
  781. returnPort = mangledPort - m_spareSocketPort;
  782. returnPort -= 1700;
  783. returnPort += delta;
  784. returnPort += sourcePort;
  785. returnPort += 1700;
  786. } else if (delta == 0) {
  787. returnPort = sourcePort;
  788. } else {
  789. returnPort = mangledPort / delta;
  790. returnPort = returnPort * delta;
  791. returnPort += (sourcePort % delta);
  792. returnPort += delta;
  793. }
  794. }
  795. // This bit is probably doomed.
  796. if (returnPort > 65535) {
  797. returnPort -= 65535;
  798. }
  799. if (returnPort < 1024) {
  800. returnPort += 1024;
  801. }
  802. DEBUG_LOG(("NAT::processManglerResponse - mangled port is %d\n", returnPort));
  803. m_previousSourcePort = returnPort;
  804. sendMangledPortNumberToTarget(returnPort, targetSlot);
  805. m_sourcePorts[m_targetNodeNumber] = returnPort;
  806. if (targetSlot->getPort() == 0) {
  807. // we haven't got the target's mangled port number yet, wait for it.
  808. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORMANGLEDPORT);
  809. } else {
  810. // in this case we should have already sent a PROBE, so we'll just change the state
  811. // and leave it at that.
  812. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORRESPONSE);
  813. }
  814. }
  815. // check to see if we've completed all the rounds
  816. // this is kind of a cheesy way to check, but it works.
  817. Bool NAT::allConnectionsDone() {
  818. if (m_numNodes == 2) {
  819. if (m_connectionRound >= 1) {
  820. return TRUE;
  821. }
  822. } else if (m_numNodes == 3) {
  823. if (m_connectionRound >= 3) {
  824. return TRUE;
  825. }
  826. } else if (m_numNodes == 4) {
  827. if (m_connectionRound >= 3) {
  828. return TRUE;
  829. }
  830. } else if (m_numNodes == 5) {
  831. if (m_connectionRound >= 5) {
  832. return TRUE;
  833. }
  834. } else if (m_numNodes == 6) {
  835. if (m_connectionRound >= 5) {
  836. return TRUE;
  837. }
  838. } else if (m_numNodes == 7) {
  839. if (m_connectionRound >= 7) {
  840. return TRUE;
  841. }
  842. } else if (m_numNodes == 8) {
  843. if (m_connectionRound >= 7) {
  844. return TRUE;
  845. }
  846. }
  847. return FALSE;
  848. }
  849. Bool NAT::allConnectionsDoneThisRound() {
  850. Bool retval = TRUE;
  851. for (Int i = 0; (i < m_numNodes) && (retval == TRUE); ++i) {
  852. if ((m_connectionStates[i] != NATCONNECTIONSTATE_DONE) && (m_connectionStates[i] != NATCONNECTIONSTATE_FAILED)) {
  853. retval = FALSE;
  854. }
  855. }
  856. return retval;
  857. }
  858. // this node's connection for this round has been completed.
  859. void NAT::connectionComplete(Int slotIndex) {
  860. }
  861. // this node's connection for this round has failed.
  862. void NAT::connectionFailed(Int slotIndex) {
  863. }
  864. // I have been probed by the target.
  865. void NAT::probed(Int nodeNumber) {
  866. GameSlot *localSlot = m_slotList[m_connectionNodes[m_localNodeNumber].m_slotIndex];
  867. DEBUG_ASSERTCRASH(localSlot != NULL, ("NAT::probed - localSlot is NULL, WTF?"));
  868. if (localSlot == NULL) {
  869. DEBUG_LOG(("NAT::probed - localSlot is NULL, failed this connection\n"));
  870. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  871. return;
  872. }
  873. if (m_beenProbed == FALSE) {
  874. m_beenProbed = TRUE;
  875. DEBUG_LOG(("NAT::probed - just got probed for the first time.\n"));
  876. if ((localSlot->getNATBehavior() & FirewallHelperClass::FIREWALL_TYPE_NETGEAR_BUG) != 0) {
  877. DEBUG_LOG(("NAT::probed - we have a NETGEAR and we were just probed for the first time\n"));
  878. GameSlot *targetSlot = m_slotList[m_connectionNodes[m_targetNodeNumber].m_slotIndex];
  879. DEBUG_ASSERTCRASH(targetSlot != NULL, ("NAT::probed - targetSlot is NULL"));
  880. if (targetSlot == NULL) {
  881. DEBUG_LOG(("NAT::probed - targetSlot is NULL, failed this connection\n"));
  882. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  883. return;
  884. }
  885. if (targetSlot->getPort() == 0) {
  886. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORMANGLEDPORT);
  887. DEBUG_LOG(("NAT::probed - still waiting for mangled port\n"));
  888. } else {
  889. DEBUG_LOG(("NAT::probed - sending a probe to %ls\n", targetSlot->getName().str()));
  890. sendAProbe(targetSlot->getIP(), targetSlot->getPort(), m_localNodeNumber);
  891. notifyTargetOfProbe(targetSlot);
  892. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORRESPONSE);
  893. }
  894. }
  895. }
  896. }
  897. // got the mangled port for our target for this round.
  898. void NAT::gotMangledPort(Int nodeNumber, UnsignedShort mangledPort) {
  899. // if we've already finished the connection, then we don't need to process this.
  900. if (m_connectionStates[m_localNodeNumber] == NATCONNECTIONSTATE_DONE) {
  901. DEBUG_LOG(("NAT::gotMangledPort - got a mangled port, but we've already finished this connection, ignoring.\n"));
  902. return;
  903. }
  904. GameSlot *targetSlot = m_slotList[m_connectionNodes[m_targetNodeNumber].m_slotIndex];
  905. DEBUG_ASSERTCRASH(targetSlot != NULL, ("NAT::gotMangledPort - targetSlot is NULL"));
  906. if (targetSlot == NULL) {
  907. DEBUG_LOG(("NAT::gotMangledPort - targetSlot is NULL, failed this connection\n"));
  908. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  909. return;
  910. }
  911. GameSlot *localSlot = m_slotList[m_connectionNodes[m_localNodeNumber].m_slotIndex];
  912. DEBUG_ASSERTCRASH(localSlot != NULL, ("NAT::gotMangledPort - localSlot is NULL, WTF?"));
  913. if (localSlot == NULL) {
  914. DEBUG_LOG(("NAT::gotMangledPort - localSlot is NULL, failed this connection\n"));
  915. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  916. return;
  917. }
  918. if (nodeNumber != m_targetNodeNumber) {
  919. DEBUG_LOG(("NAT::gotMangledPort - got a mangled port number for someone that isn't my target. node = %d, target node = %d\n", nodeNumber, m_targetNodeNumber));
  920. return;
  921. }
  922. targetSlot->setPort(mangledPort);
  923. DEBUG_LOG(("NAT::gotMangledPort - got mangled port number %d from our target node (%ls)\n", mangledPort, targetSlot->getName().str()));
  924. if (((localSlot->getNATBehavior() & FirewallHelperClass::FIREWALL_TYPE_NETGEAR_BUG) == 0) || (m_beenProbed == TRUE) ||
  925. (((localSlot->getNATBehavior() & FirewallHelperClass::FIREWALL_TYPE_NETGEAR_BUG) != 0) && ((targetSlot->getNATBehavior() & FirewallHelperClass::FIREWALL_TYPE_NETGEAR_BUG) != 0))) {
  926. #ifdef DEBUG_LOGGING
  927. UnsignedInt ip = targetSlot->getIP();
  928. #endif
  929. DEBUG_LOG(("NAT::gotMangledPort - don't have a netgear or we have already been probed, or both my target and I have a netgear, send a PROBE. Sending to %d.%d.%d.%d:%d\n",
  930. ip >> 24, (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff, targetSlot->getPort()));
  931. sendAProbe(targetSlot->getIP(), targetSlot->getPort(), m_localNodeNumber);
  932. notifyTargetOfProbe(targetSlot);
  933. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_WAITINGFORRESPONSE);
  934. } else {
  935. DEBUG_LOG(("NAT::gotMangledPort - we are a netgear, not sending a PROBE yet.\n"));
  936. }
  937. }
  938. void NAT::gotInternalAddress(Int nodeNumber, UnsignedInt address) {
  939. GameSlot *targetSlot = m_slotList[m_connectionNodes[nodeNumber].m_slotIndex];
  940. DEBUG_ASSERTCRASH(targetSlot != NULL, ("NAT::gotInternalAddress - targetSlot is NULL"));
  941. if (targetSlot == NULL) {
  942. return;
  943. }
  944. GameSlot *localSlot = m_slotList[m_connectionNodes[m_localNodeNumber].m_slotIndex];
  945. DEBUG_ASSERTCRASH(localSlot != NULL, ("NAT::gotInternalAddress - localSlot is NULL, WTF?"));
  946. if (localSlot == NULL) {
  947. return;
  948. }
  949. if (nodeNumber != m_targetNodeNumber) {
  950. DEBUG_LOG(("NAT::gotInternalAddress - got a internal address for someone that isn't my target. node = %d, target node = %d\n", nodeNumber, m_targetNodeNumber));
  951. return;
  952. }
  953. if (localSlot->getIP() == targetSlot->getIP()) {
  954. // we have the same IP address, i.e. we are behind the same NAT.
  955. // I need to talk directly to his internal address.
  956. DEBUG_LOG(("NAT::gotInternalAddress - target and local players have same external address, using internal address.\n"));
  957. targetSlot->setIP(address); // use the slot's internal address from now on
  958. }
  959. }
  960. void NAT::notifyTargetOfProbe(GameSlot *targetSlot) {
  961. PeerRequest req;
  962. AsciiString options;
  963. options.format("PROBED%d", m_localNodeNumber);
  964. req.peerRequestType = PeerRequest::PEERREQUEST_UTMPLAYER;
  965. req.UTM.isStagingRoom = TRUE;
  966. req.id = "NAT/";
  967. AsciiString hostName;
  968. hostName.translate(targetSlot->getName());
  969. req.nick = hostName.str();
  970. req.options = options.str();
  971. TheGameSpyPeerMessageQueue->addRequest(req);
  972. DEBUG_LOG(("NAT::notifyTargetOfProbe - notifying %ls that we have probed them.\n", targetSlot->getName().str()));
  973. }
  974. void NAT::notifyUsersOfConnectionDone(Int nodeIndex) {
  975. GameSlot *localSlot = m_slotList[m_connectionNodes[m_localNodeNumber].m_slotIndex];
  976. DEBUG_ASSERTCRASH(localSlot != NULL, ("NAT::notifyUsersOfConnectionDone - localSlot is NULL, WTF?"));
  977. if (localSlot == NULL) {
  978. DEBUG_LOG(("NAT::notifyUsersOfConnectionDone - localSlot is NULL, failed this connection\n"));
  979. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  980. return;
  981. }
  982. PeerRequest req;
  983. AsciiString options;
  984. options.format("CONNDONE%d %d", nodeIndex, m_localNodeNumber);
  985. req.peerRequestType = PeerRequest::PEERREQUEST_UTMPLAYER;
  986. req.UTM.isStagingRoom = TRUE;
  987. req.id = "NAT";
  988. AsciiString names;
  989. for (Int i=0; i<MAX_SLOTS; ++i)
  990. {
  991. if (m_connectionNodes[m_localNodeNumber].m_slotIndex == i) {
  992. continue;
  993. }
  994. if ((m_slotList[i] == NULL) || (m_slotList[i]->isHuman() == FALSE)) {
  995. continue;
  996. }
  997. AsciiString name;
  998. name.translate(m_slotList[i]->getName());
  999. if (names.isNotEmpty())
  1000. {
  1001. names.concat(',');
  1002. }
  1003. names.concat(name);
  1004. }
  1005. req.nick = names.str();
  1006. req.options = options.str();
  1007. DEBUG_LOG(("NAT::notifyUsersOfConnectionDone - sending %s to %s\n", options.str(), names.str()));
  1008. TheGameSpyPeerMessageQueue->addRequest(req);
  1009. }
  1010. void NAT::notifyUsersOfConnectionFailed(Int nodeIndex) {
  1011. GameSlot *localSlot = m_slotList[m_connectionNodes[m_localNodeNumber].m_slotIndex];
  1012. DEBUG_ASSERTCRASH(localSlot != NULL, ("NAT::notifyUsersOfConnectionFailed - localSlot is NULL, WTF?"));
  1013. if (localSlot == NULL) {
  1014. DEBUG_LOG(("NAT::notifyUsersOfConnectionFailed - localSlot is NULL, failed this connection\n"));
  1015. setConnectionState(m_localNodeNumber, NATCONNECTIONSTATE_FAILED);
  1016. return;
  1017. }
  1018. PeerRequest req;
  1019. AsciiString options;
  1020. options.format("CONNFAILED%d", nodeIndex);
  1021. /*
  1022. req.peerRequestType = PeerRequest::PEERREQUEST_UTMROOM;
  1023. req.UTM.isStagingRoom = TRUE;
  1024. req.id = "NAT/";
  1025. req.options = options.str();
  1026. DEBUG_LOG(("NAT::notifyUsersOfConnectionFailed - sending %s to room\n", options.str()));
  1027. */
  1028. req.peerRequestType = PeerRequest::PEERREQUEST_UTMPLAYER;
  1029. req.UTM.isStagingRoom = TRUE;
  1030. req.id = "NAT";
  1031. AsciiString names;
  1032. for (Int i=0; i<MAX_SLOTS; ++i)
  1033. {
  1034. if (m_connectionNodes[m_localNodeNumber].m_slotIndex == i) {
  1035. continue;
  1036. }
  1037. if ((m_slotList[i] == NULL) || (m_slotList[i]->isHuman() == FALSE)) {
  1038. continue;
  1039. }
  1040. AsciiString name;
  1041. name.translate(m_slotList[i]->getName());
  1042. if (names.isNotEmpty())
  1043. {
  1044. names.concat(',');
  1045. }
  1046. names.concat(name);
  1047. }
  1048. req.nick = names.str();
  1049. req.options = options.str();
  1050. DEBUG_LOG(("NAT::notifyUsersOfConnectionFailed - sending %s to %s\n", options.str(), names.str()));
  1051. TheGameSpyPeerMessageQueue->addRequest(req);
  1052. }
  1053. void NAT::sendMangledPortNumberToTarget(UnsignedShort mangledPort, GameSlot *targetSlot) {
  1054. PeerRequest req;
  1055. AsciiString options;
  1056. options.format("PORT%d %d %08X", m_localNodeNumber, mangledPort, m_localIP);
  1057. req.peerRequestType = PeerRequest::PEERREQUEST_UTMPLAYER;
  1058. req.UTM.isStagingRoom = TRUE;
  1059. req.id = "NAT/";
  1060. AsciiString hostName;
  1061. hostName.translate(targetSlot->getName());
  1062. req.nick = hostName.str();
  1063. req.options = options.str();
  1064. DEBUG_LOG(("NAT::sendMangledPortNumberToTarget - sending \"%s\" to %s\n", options.str(), hostName.str()));
  1065. TheGameSpyPeerMessageQueue->addRequest(req);
  1066. }
  1067. void NAT::processGlobalMessage(Int slotNum, const char *options) {
  1068. const char *ptr = options;
  1069. // skip preceding whitespace.
  1070. while (isspace(*ptr)) {
  1071. ++ptr;
  1072. }
  1073. DEBUG_LOG(("NAT::processGlobalMessage - got message from slot %d, message is \"%s\"\n", slotNum, ptr));
  1074. if (!strncmp(ptr, "PROBED", strlen("PROBED"))) {
  1075. // format: PROBED<node number>
  1076. // a probe has been sent at us, if we are waiting because of a netgear or something, we
  1077. // should start sending our own probes.
  1078. Int node = atoi(ptr + strlen("PROBED"));
  1079. if (node == m_targetNodeNumber) {
  1080. // make sure we're being probed by who we're supposed to be probed by.
  1081. probed(node);
  1082. } else {
  1083. DEBUG_LOG(("NAT::processGlobalMessage - probed by node %d, not our target\n", node));
  1084. }
  1085. } else if (!strncmp(ptr, "CONNDONE", strlen("CONNDONE"))) {
  1086. // format: CONNDONE<node number>
  1087. // we should get the node number of the player who's connection is done from the options
  1088. // and mark that down as part of the connectionStates.
  1089. const char *c = ptr + strlen("CONNDONE");
  1090. /* while (*c != ' ') {
  1091. ++c;
  1092. }
  1093. while (*c == ' ') {
  1094. ++c;
  1095. }
  1096. */ Int node;
  1097. Int sendingNode;
  1098. sscanf(c, "%d %d\n", &node, &sendingNode);
  1099. if (m_connectionPairs[m_connectionPairIndex][m_connectionRound][node] == sendingNode) {
  1100. // Int node = atoi(ptr + strlen("CONNDONE"));
  1101. DEBUG_LOG(("NAT::processGlobalMessage - got a CONNDONE message for node %d\n", node));
  1102. if ((node >= 0) && (node <= m_numNodes)) {
  1103. DEBUG_LOG(("NAT::processGlobalMessage - node %d's connection is complete, setting connection state to done\n", node));
  1104. setConnectionState(node, NATCONNECTIONSTATE_DONE);
  1105. }
  1106. } else {
  1107. DEBUG_LOG(("NAT::processGlobalMessage - got a connection done message that isn't from this round. node: %d sending node: %d\n", node, sendingNode));
  1108. }
  1109. } else if (!strncmp(ptr, "CONNFAILED", strlen("CONNFAILED"))) {
  1110. // format: CONNFAILED<node number>
  1111. // we should get the node number of the player who's connection failed from the options
  1112. // and mark that down as part of the connectionStates.
  1113. Int node = atoi(ptr + strlen("CONNFAILED"));
  1114. if ((node >= 0) && (node < m_numNodes)) {
  1115. DEBUG_LOG(("NAT::processGlobalMessage - node %d's connection failed, setting connection state to failed\n", node));
  1116. setConnectionState(node, NATCONNECTIONSTATE_FAILED);
  1117. }
  1118. } else if (!strncmp(ptr, "PORT", strlen("PORT"))) {
  1119. // format: PORT<node number> <port number> <internal IP>
  1120. // we should get the node number and the mangled port number of the client we
  1121. // are supposed to be communicating with and start probing them. No, that was not
  1122. // meant to be a phallic reference, you sicko.
  1123. const char *c = ptr + strlen("PORT");
  1124. Int node = atoi(c);
  1125. while (*c != ' ') {
  1126. ++c;
  1127. }
  1128. while (*c == ' ') {
  1129. ++c;
  1130. }
  1131. UnsignedInt intport = 0;
  1132. UnsignedInt addr = 0;
  1133. sscanf(c, "%d %X", &intport, &addr);
  1134. UnsignedShort port = (UnsignedShort)intport;
  1135. DEBUG_LOG(("NAT::processGlobalMessage - got port message from node %d, port: %d, internal address: %d.%d.%d.%d\n", node, port,
  1136. addr >> 24, (addr >> 16) & 0xff, (addr >> 8) & 0xff, addr & 0xff));
  1137. if ((node >= 0) && (node < m_numNodes)) {
  1138. if (port < 1024) {
  1139. // it has to be less than 65535 cause its a short duh.
  1140. DEBUG_ASSERTCRASH(port >= 1024, ("Was passed an invalid port number"));
  1141. port += 1024;
  1142. }
  1143. gotInternalAddress(node, addr);
  1144. gotMangledPort(node, port);
  1145. }
  1146. }
  1147. }
  1148. void NAT::setConnectionState(Int nodeNumber, NATConnectionState state) {
  1149. m_connectionStates[nodeNumber] = state;
  1150. if (nodeNumber != m_localNodeNumber) {
  1151. return;
  1152. }
  1153. // if this is the case we are starting a new round and we don't know
  1154. // who we're connecting to yet.
  1155. if (m_localNodeNumber == m_targetNodeNumber) {
  1156. return;
  1157. }
  1158. // if this is the start of a new connection round we don't have a
  1159. // target yet.
  1160. if (m_targetNodeNumber == -1) {
  1161. return;
  1162. }
  1163. // find the menu slot of the target node.
  1164. Int slotIndex = m_connectionNodes[m_targetNodeNumber].m_slotIndex;
  1165. Int slot = 0;
  1166. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1167. if (m_slotList[i] != NULL) {
  1168. if (m_slotList[i]->isHuman()) {
  1169. if (i != m_connectionNodes[m_localNodeNumber].m_slotIndex) {
  1170. if (i == slotIndex) {
  1171. break;
  1172. }
  1173. ++slot;
  1174. }
  1175. }
  1176. }
  1177. }
  1178. if (i == MAX_SLOTS) {
  1179. DEBUG_ASSERTCRASH(i < MAX_SLOTS, ("Didn't find the node number in the slot list"));
  1180. return;
  1181. }
  1182. TheEstablishConnectionsMenu->setPlayerStatus(slot, state);
  1183. }