NatPunchthroughClient.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. #include "NativeFeatureIncludes.h"
  11. #if _RAKNET_SUPPORT_NatPunchthroughClient==1
  12. #include "NatPunchthroughClient.h"
  13. #include "BitStream.h"
  14. #include "MessageIdentifiers.h"
  15. #include "RakPeerInterface.h"
  16. #include "GetTime.h"
  17. #include "PacketLogger.h"
  18. #include "Itoa.h"
  19. using namespace RakNet;
  20. void NatPunchthroughDebugInterface_Printf::OnClientMessage(const char *msg)
  21. {
  22. printf("%s\n", msg);
  23. }
  24. #if _RAKNET_SUPPORT_PacketLogger==1
  25. void NatPunchthroughDebugInterface_PacketLogger::OnClientMessage(const char *msg)
  26. {
  27. if (pl)
  28. {
  29. pl->WriteMiscellaneous("Nat", msg);
  30. }
  31. }
  32. #endif
  33. STATIC_FACTORY_DEFINITIONS(NatPunchthroughClient,NatPunchthroughClient);
  34. NatPunchthroughClient::NatPunchthroughClient()
  35. {
  36. natPunchthroughDebugInterface=0;
  37. mostRecentExternalPort=0;
  38. sp.nextActionTime=0;
  39. portStride=0;
  40. hasPortStride=UNKNOWN_PORT_STRIDE;
  41. }
  42. NatPunchthroughClient::~NatPunchthroughClient()
  43. {
  44. rakPeerInterface=0;
  45. Clear();
  46. }
  47. void NatPunchthroughClient::FindRouterPortStride(const SystemAddress &facilitator)
  48. {
  49. ConnectionState cs = rakPeerInterface->GetConnectionState(facilitator);
  50. if (cs!=IS_CONNECTED)
  51. return;
  52. if (hasPortStride!=UNKNOWN_PORT_STRIDE)
  53. return;
  54. hasPortStride=CALCULATING_PORT_STRIDE;
  55. portStrideCalTimeout = RakNet::GetTime()+5000;
  56. if (natPunchthroughDebugInterface)
  57. {
  58. natPunchthroughDebugInterface->OnClientMessage(RakString("Calculating port stride from %s", facilitator.ToString(true)));
  59. }
  60. RakNet::BitStream outgoingBs;
  61. outgoingBs.Write((MessageID)ID_NAT_REQUEST_BOUND_ADDRESSES);
  62. rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,facilitator,false);
  63. }
  64. bool NatPunchthroughClient::OpenNAT(RakNetGUID destination, const SystemAddress &facilitator)
  65. {
  66. ConnectionState cs = rakPeerInterface->GetConnectionState(facilitator);
  67. if (cs!=IS_CONNECTED)
  68. return false;
  69. if (hasPortStride==UNKNOWN_PORT_STRIDE)
  70. {
  71. FindRouterPortStride(facilitator);
  72. QueueOpenNAT(destination, facilitator);
  73. }
  74. else if (hasPortStride==CALCULATING_PORT_STRIDE)
  75. {
  76. QueueOpenNAT(destination, facilitator);
  77. }
  78. else
  79. {
  80. SendPunchthrough(destination, facilitator);
  81. }
  82. return true;
  83. }
  84. /*
  85. bool NatPunchthroughClient::OpenNATGroup(DataStructures::List<RakNetGUID> destinationSystems, const SystemAddress &facilitator)
  86. {
  87. ConnectionState cs = rakPeerInterface->GetConnectionState(facilitator);
  88. if (cs!=IS_CONNECTED)
  89. return false;
  90. unsigned long i;
  91. for (i=0; i < destinationSystems.Size(); i++)
  92. {
  93. SendPunchthrough(destinationSystems[i], facilitator);
  94. }
  95. GroupPunchRequest *gpr = RakNet::OP_NEW<GroupPunchRequest>(_FILE_AND_LINE_);
  96. gpr->facilitator=facilitator;
  97. gpr->pendingList=destinationSystems;
  98. groupPunchRequests.Push(gpr, _FILE_AND_LINE_);
  99. return true;
  100. }
  101. */
  102. void NatPunchthroughClient::SetDebugInterface(NatPunchthroughDebugInterface *i)
  103. {
  104. natPunchthroughDebugInterface=i;
  105. }
  106. void NatPunchthroughClient::Update(void)
  107. {
  108. RakNet::Time time = RakNet::GetTime();
  109. if (hasPortStride==CALCULATING_PORT_STRIDE && time > portStrideCalTimeout)
  110. {
  111. if (natPunchthroughDebugInterface)
  112. {
  113. natPunchthroughDebugInterface->OnClientMessage("CALCULATING_PORT_STRIDE timeout");
  114. }
  115. SendQueuedOpenNAT();
  116. hasPortStride=UNKNOWN_PORT_STRIDE;
  117. }
  118. if (sp.nextActionTime && sp.nextActionTime < time)
  119. {
  120. RakNet::Time delta = time - sp.nextActionTime;
  121. if (sp.testMode==SendPing::TESTING_INTERNAL_IPS)
  122. {
  123. SendOutOfBand(sp.internalIds[sp.attemptCount],ID_NAT_ESTABLISH_UNIDIRECTIONAL);
  124. if (++sp.retryCount>=pc.UDP_SENDS_PER_PORT_INTERNAL)
  125. {
  126. ++sp.attemptCount;
  127. sp.retryCount=0;
  128. }
  129. if (sp.attemptCount>=pc.MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK)
  130. {
  131. sp.testMode=SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE;
  132. if (pc.INTERNAL_IP_WAIT_AFTER_ATTEMPTS>0)
  133. {
  134. sp.nextActionTime=time+pc.INTERNAL_IP_WAIT_AFTER_ATTEMPTS-delta;
  135. }
  136. else
  137. {
  138. sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT;
  139. sp.attemptCount=0;
  140. sp.sentTTL=false;
  141. }
  142. }
  143. else
  144. {
  145. sp.nextActionTime=time+pc.TIME_BETWEEN_PUNCH_ATTEMPTS_INTERNAL-delta;
  146. }
  147. }
  148. else if (sp.testMode==SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE)
  149. {
  150. sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT;
  151. sp.attemptCount=0;
  152. sp.sentTTL=false;
  153. }
  154. /*
  155. else if (sp.testMode==SendPing::SEND_WITH_TTL)
  156. {
  157. // Send to unused port. We do not want the message to arrive, just to open our router's table
  158. SystemAddress sa=sp.targetAddress;
  159. int ttlSendIndex;
  160. for (ttlSendIndex=0; ttlSendIndex <= pc.MAX_PREDICTIVE_PORT_RANGE; ttlSendIndex++)
  161. {
  162. sa.SetPortHostOrder((unsigned short) (sp.targetAddress.GetPort()+ttlSendIndex));
  163. SendTTL(sa);
  164. }
  165. // Only do this stage once
  166. // Wait 250 milliseconds for next stage. The delay is so that even with timing errors both systems send out the
  167. // datagram with TTL before either sends a real one
  168. sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT;
  169. sp.nextActionTime=time-delta+250;
  170. }
  171. */
  172. else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT)
  173. {
  174. if (sp.sentTTL==false)
  175. {
  176. SystemAddress sa=sp.targetAddress;
  177. sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount));
  178. SendTTL(sa);
  179. if (natPunchthroughDebugInterface)
  180. {
  181. natPunchthroughDebugInterface->OnClientMessage(RakString("Send with TTL 2 to %s", sa.ToString(true)));
  182. }
  183. sp.nextActionTime = time+pc.EXTERNAL_IP_WAIT_AFTER_FIRST_TTL-delta;
  184. sp.sentTTL=true;
  185. }
  186. else
  187. {
  188. SystemAddress sa=sp.targetAddress;
  189. sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount));
  190. SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL);
  191. IncrementExternalAttemptCount(time, delta);
  192. if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE)
  193. {
  194. sp.testMode=SendPing::WAITING_AFTER_ALL_ATTEMPTS;
  195. sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS-delta;
  196. // Skip TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT, etc.
  197. /*
  198. sp.testMode=SendPing::TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT;
  199. sp.attemptCount=0;
  200. */
  201. }
  202. }
  203. }
  204. else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT)
  205. {
  206. SystemAddress sa=sp.targetAddress;
  207. if ( sp.targetGuid < rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) )
  208. sa.SetPortHostOrder((unsigned short) (1024+sp.attemptCount));
  209. else
  210. sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount));
  211. SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL);
  212. IncrementExternalAttemptCount(time, delta);
  213. if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE)
  214. {
  215. // From 1024 disabled, never helps as I've seen, but slows down the process by half
  216. sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024;
  217. sp.attemptCount=0;
  218. }
  219. }
  220. else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024)
  221. {
  222. SystemAddress sa=sp.targetAddress;
  223. if ( sp.targetGuid > rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) )
  224. sa.SetPortHostOrder((unsigned short) (1024+sp.attemptCount));
  225. else
  226. sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount));
  227. SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL);
  228. IncrementExternalAttemptCount(time, delta);
  229. if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE)
  230. {
  231. // From 1024 disabled, never helps as I've seen, but slows down the process by half
  232. sp.testMode=SendPing::TESTING_EXTERNAL_IPS_1024_TO_1024;
  233. sp.attemptCount=0;
  234. }
  235. }
  236. else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_1024_TO_1024)
  237. {
  238. SystemAddress sa=sp.targetAddress;
  239. sa.SetPortHostOrder((unsigned short) (1024+sp.attemptCount));
  240. SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL);
  241. IncrementExternalAttemptCount(time, delta);
  242. if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE)
  243. {
  244. if (natPunchthroughDebugInterface)
  245. {
  246. char ipAddressString[32];
  247. sp.targetAddress.ToString(true, ipAddressString);
  248. char guidString[128];
  249. sp.targetGuid.ToString(guidString);
  250. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Likely bidirectional punchthrough failure to guid %s, system address %s.", guidString, ipAddressString));
  251. }
  252. sp.testMode=SendPing::WAITING_AFTER_ALL_ATTEMPTS;
  253. sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS-delta;
  254. }
  255. }
  256. else if (sp.testMode==SendPing::WAITING_AFTER_ALL_ATTEMPTS)
  257. {
  258. // Failed. Tell the user
  259. OnPunchthroughFailure();
  260. // UpdateGroupPunchOnNatResult(sp.facilitator, sp.targetGuid, sp.targetAddress, 1);
  261. }
  262. if (sp.testMode==SendPing::PUNCHING_FIXED_PORT)
  263. {
  264. SendOutOfBand(sp.targetAddress,ID_NAT_ESTABLISH_BIDIRECTIONAL);
  265. if (++sp.retryCount>=sp.punchingFixedPortAttempts)
  266. {
  267. if (natPunchthroughDebugInterface)
  268. {
  269. char ipAddressString[32];
  270. sp.targetAddress.ToString(true, ipAddressString);
  271. char guidString[128];
  272. sp.targetGuid.ToString(guidString);
  273. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Likely unidirectional punchthrough failure to guid %s, system address %s.", guidString, ipAddressString));
  274. }
  275. sp.testMode=SendPing::WAITING_AFTER_ALL_ATTEMPTS;
  276. sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS-delta;
  277. }
  278. else
  279. {
  280. if ((sp.retryCount%pc.UDP_SENDS_PER_PORT_EXTERNAL)==0)
  281. sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_BETWEEN_PORTS-delta;
  282. else
  283. sp.nextActionTime=time+pc.TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL-delta;
  284. }
  285. }
  286. }
  287. /*
  288. // Remove elapsed groupRequestsInProgress
  289. unsigned int i;
  290. i=0;
  291. while (i < groupRequestsInProgress.Size())
  292. {
  293. if (time > groupRequestsInProgress[i].time)
  294. groupRequestsInProgress.RemoveAtIndexFast(i);
  295. else
  296. i++;
  297. }
  298. */
  299. }
  300. void NatPunchthroughClient::PushFailure(void)
  301. {
  302. Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char));
  303. p->data[0]=ID_NAT_PUNCHTHROUGH_FAILED;
  304. p->systemAddress=sp.targetAddress;
  305. p->systemAddress.systemIndex=(SystemIndex)-1;
  306. p->guid=sp.targetGuid;
  307. if (sp.weAreSender)
  308. p->data[1]=1;
  309. else
  310. p->data[1]=0;
  311. p->wasGeneratedLocally=true;
  312. rakPeerInterface->PushBackPacket(p, true);
  313. }
  314. void NatPunchthroughClient::OnPunchthroughFailure(void)
  315. {
  316. if (pc.retryOnFailure==false)
  317. {
  318. if (natPunchthroughDebugInterface)
  319. {
  320. char ipAddressString[32];
  321. sp.targetAddress.ToString(true, ipAddressString);
  322. char guidString[128];
  323. sp.targetGuid.ToString(guidString);
  324. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Failed punchthrough once. Returning failure to guid %s, system address %s to user.", guidString, ipAddressString));
  325. }
  326. PushFailure();
  327. OnReadyForNextPunchthrough();
  328. return;
  329. }
  330. unsigned int i;
  331. for (i=0; i < failedAttemptList.Size(); i++)
  332. {
  333. if (failedAttemptList[i].guid==sp.targetGuid)
  334. {
  335. if (natPunchthroughDebugInterface)
  336. {
  337. char ipAddressString[32];
  338. sp.targetAddress.ToString(true, ipAddressString);
  339. char guidString[128];
  340. sp.targetGuid.ToString(guidString);
  341. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Failed punchthrough twice. Returning failure to guid %s, system address %s to user.", guidString, ipAddressString));
  342. }
  343. // Failed a second time, so return failed to user
  344. PushFailure();
  345. OnReadyForNextPunchthrough();
  346. failedAttemptList.RemoveAtIndexFast(i);
  347. return;
  348. }
  349. }
  350. if (rakPeerInterface->GetConnectionState(sp.facilitator)!=IS_CONNECTED)
  351. {
  352. if (natPunchthroughDebugInterface)
  353. {
  354. char ipAddressString[32];
  355. sp.targetAddress.ToString(true, ipAddressString);
  356. char guidString[128];
  357. sp.targetGuid.ToString(guidString);
  358. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Not connected to facilitator, so cannot retry punchthrough after first failure. Returning failure onj guid %s, system address %s to user.", guidString, ipAddressString));
  359. }
  360. // Failed, and can't try again because no facilitator
  361. PushFailure();
  362. return;
  363. }
  364. if (natPunchthroughDebugInterface)
  365. {
  366. char ipAddressString[32];
  367. sp.targetAddress.ToString(true, ipAddressString);
  368. char guidString[128];
  369. sp.targetGuid.ToString(guidString);
  370. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("First punchthrough failure on guid %s, system address %s. Reattempting.", guidString, ipAddressString));
  371. }
  372. // Failed the first time. Add to the failure queue and try again
  373. AddrAndGuid aag;
  374. aag.addr=sp.targetAddress;
  375. aag.guid=sp.targetGuid;
  376. failedAttemptList.Push(aag, _FILE_AND_LINE_);
  377. // Tell the server we are ready
  378. OnReadyForNextPunchthrough();
  379. // If we are the sender, try again, immediately if possible, else added to the queue on the faciltiator
  380. if (sp.weAreSender)
  381. SendPunchthrough(sp.targetGuid, sp.facilitator);
  382. }
  383. PluginReceiveResult NatPunchthroughClient::OnReceive(Packet *packet)
  384. {
  385. switch (packet->data[0])
  386. {
  387. case ID_NAT_GET_MOST_RECENT_PORT:
  388. {
  389. OnGetMostRecentPort(packet);
  390. return RR_STOP_PROCESSING_AND_DEALLOCATE;
  391. }
  392. case ID_NAT_PUNCHTHROUGH_FAILED:
  393. case ID_NAT_PUNCHTHROUGH_SUCCEEDED:
  394. if (packet->wasGeneratedLocally==false)
  395. return RR_STOP_PROCESSING_AND_DEALLOCATE;
  396. break;
  397. case ID_NAT_RESPOND_BOUND_ADDRESSES:
  398. {
  399. RakNet::BitStream bs(packet->data,packet->length,false);
  400. bs.IgnoreBytes(sizeof(MessageID));
  401. unsigned char boundAddressCount;
  402. bs.Read(boundAddressCount);
  403. if (boundAddressCount<2)
  404. {
  405. if (natPunchthroughDebugInterface)
  406. natPunchthroughDebugInterface->OnClientMessage(RakString("INCAPABLE_PORT_STRIDE. My external ID is %s", rakPeerInterface->GetExternalID(packet->systemAddress).ToString()));
  407. hasPortStride=INCAPABLE_PORT_STRIDE;
  408. SendQueuedOpenNAT();
  409. }
  410. SystemAddress boundAddresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS];
  411. for (int i=0; i < boundAddressCount && i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++)
  412. {
  413. bs.Read(boundAddresses[i]);
  414. if (boundAddresses[i]!=packet->systemAddress)
  415. {
  416. RakNet::BitStream outgoingBs;
  417. outgoingBs.Write((MessageID)ID_NAT_PING);
  418. uint16_t externalPort = rakPeerInterface->GetExternalID(packet->systemAddress).GetPort();
  419. outgoingBs.Write( externalPort );
  420. rakPeerInterface->SendOutOfBand((const char*) boundAddresses[i].ToString(false),boundAddresses[i].GetPort(),(const char*) outgoingBs.GetData(),outgoingBs.GetNumberOfBytesUsed());
  421. break;
  422. }
  423. }
  424. }
  425. return RR_STOP_PROCESSING_AND_DEALLOCATE;
  426. case ID_OUT_OF_BAND_INTERNAL:
  427. if (packet->length>=2 && packet->data[1]==ID_NAT_PONG)
  428. {
  429. RakNet::BitStream bs(packet->data,packet->length,false);
  430. bs.IgnoreBytes(sizeof(MessageID)*2);
  431. uint16_t externalPort;
  432. bs.Read(externalPort);
  433. uint16_t externalPort2;
  434. bs.Read(externalPort2);
  435. portStride = externalPort2 - externalPort;
  436. mostRecentExternalPort = externalPort2;
  437. hasPortStride=HAS_PORT_STRIDE;
  438. if (natPunchthroughDebugInterface)
  439. natPunchthroughDebugInterface->OnClientMessage(RakString("HAS_PORT_STRIDE %i. First external port %i. Second external port %i.", portStride, externalPort, externalPort2));
  440. SendQueuedOpenNAT();
  441. return RR_STOP_PROCESSING_AND_DEALLOCATE;
  442. }
  443. else if (packet->length>=2 &&
  444. (packet->data[1]==ID_NAT_ESTABLISH_UNIDIRECTIONAL || packet->data[1]==ID_NAT_ESTABLISH_BIDIRECTIONAL) &&
  445. sp.nextActionTime!=0)
  446. {
  447. RakNet::BitStream bs(packet->data,packet->length,false);
  448. bs.IgnoreBytes(2);
  449. uint16_t sessionId;
  450. bs.Read(sessionId);
  451. // RakAssert(sessionId<100);
  452. if (sessionId!=sp.sessionId)
  453. break;
  454. char ipAddressString[32];
  455. packet->systemAddress.ToString(true,ipAddressString);
  456. // sp.targetGuid==packet->guid is because the internal IP addresses reported may include loopbacks not reported by RakPeer::IsLocalIP()
  457. if (packet->data[1]==ID_NAT_ESTABLISH_UNIDIRECTIONAL && sp.targetGuid==packet->guid)
  458. {
  459. if (sp.testMode!=SendPing::PUNCHING_FIXED_PORT)
  460. {
  461. sp.testMode=SendPing::PUNCHING_FIXED_PORT;
  462. sp.retryCount+=sp.attemptCount*pc.UDP_SENDS_PER_PORT_EXTERNAL;
  463. sp.targetAddress=packet->systemAddress;
  464. // Keeps trying until the other side gives up too, in case it is unidirectional
  465. sp.punchingFixedPortAttempts=pc.UDP_SENDS_PER_PORT_EXTERNAL*(pc.MAX_PREDICTIVE_PORT_RANGE+1);
  466. if (natPunchthroughDebugInterface)
  467. {
  468. char guidString[128];
  469. sp.targetGuid.ToString(guidString);
  470. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("PUNCHING_FIXED_PORT: Received ID_NAT_ESTABLISH_UNIDIRECTIONAL from guid %s, system address %s.", guidString, ipAddressString));
  471. }
  472. }
  473. else {
  474. if (natPunchthroughDebugInterface)
  475. {
  476. char guidString[128];
  477. sp.targetGuid.ToString(guidString);
  478. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Received ID_NAT_ESTABLISH_UNIDIRECTIONAL from guid %s, system address %s.", guidString, ipAddressString));
  479. }
  480. }
  481. SendOutOfBand(sp.targetAddress,ID_NAT_ESTABLISH_BIDIRECTIONAL);
  482. }
  483. else if (packet->data[1]==ID_NAT_ESTABLISH_BIDIRECTIONAL &&
  484. sp.targetGuid==packet->guid)
  485. {
  486. // They send back our port
  487. unsigned short ourExternalPort;
  488. bs.Read(ourExternalPort);
  489. if (mostRecentExternalPort==0)
  490. {
  491. mostRecentExternalPort=ourExternalPort;
  492. if (natPunchthroughDebugInterface)
  493. {
  494. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("ID_NAT_ESTABLISH_BIDIRECTIONAL mostRecentExternalPort first time set to %i", mostRecentExternalPort));
  495. }
  496. }
  497. else
  498. {
  499. if (sp.testMode!=SendPing::TESTING_INTERNAL_IPS && sp.testMode!=SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE)
  500. {
  501. if (hasPortStride!=HAS_PORT_STRIDE)
  502. {
  503. portStride = ourExternalPort - mostRecentExternalPort;
  504. hasPortStride=HAS_PORT_STRIDE;
  505. if (natPunchthroughDebugInterface)
  506. {
  507. natPunchthroughDebugInterface->OnClientMessage(RakString("ID_NAT_ESTABLISH_BIDIRECTIONAL: Estimated port stride from incoming connection at %i. ourExternalPort=%i mostRecentExternalPort=%i", portStride, ourExternalPort, mostRecentExternalPort));
  508. }
  509. SendQueuedOpenNAT();
  510. }
  511. //nextExternalPort += portStride * (pc.MAX_PREDICTIVE_PORT_RANGE+1);
  512. mostRecentExternalPort = ourExternalPort;
  513. if (natPunchthroughDebugInterface)
  514. {
  515. natPunchthroughDebugInterface->OnClientMessage(RakString("ID_NAT_ESTABLISH_BIDIRECTIONAL: New mostRecentExternalPort %i", mostRecentExternalPort));
  516. }
  517. }
  518. }
  519. SendOutOfBand(packet->systemAddress,ID_NAT_ESTABLISH_BIDIRECTIONAL);
  520. // Tell the user about the success
  521. sp.targetAddress=packet->systemAddress;
  522. PushSuccess();
  523. //UpdateGroupPunchOnNatResult(sp.facilitator, sp.targetGuid, sp.targetAddress, 1);
  524. OnReadyForNextPunchthrough();
  525. bool removedFromFailureQueue=RemoveFromFailureQueue();
  526. if (natPunchthroughDebugInterface)
  527. {
  528. char guidString[128];
  529. sp.targetGuid.ToString(guidString);
  530. if (removedFromFailureQueue)
  531. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough to guid %s, system address %s succeeded on 2nd attempt.", guidString, ipAddressString));
  532. else
  533. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough to guid %s, system address %s succeeded on 1st attempt.", guidString, ipAddressString));
  534. }
  535. }
  536. // mostRecentNewExternalPort=packet->systemAddress.GetPort();
  537. }
  538. return RR_STOP_PROCESSING_AND_DEALLOCATE;
  539. case ID_NAT_ALREADY_IN_PROGRESS:
  540. {
  541. RakNet::BitStream incomingBs(packet->data, packet->length, false);
  542. incomingBs.IgnoreBytes(sizeof(MessageID));
  543. RakNetGUID targetGuid;
  544. incomingBs.Read(targetGuid);
  545. // Don't update group, just use later message
  546. // UpdateGroupPunchOnNatResult(packet->systemAddress, targetGuid, UNASSIGNED_SYSTEM_ADDRESS, 2);
  547. if (natPunchthroughDebugInterface)
  548. {
  549. char guidString[128];
  550. targetGuid.ToString(guidString);
  551. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough retry to guid %s failed due to ID_NAT_ALREADY_IN_PROGRESS. Returning failure.", guidString));
  552. }
  553. }
  554. break;
  555. case ID_NAT_TARGET_NOT_CONNECTED:
  556. case ID_NAT_CONNECTION_TO_TARGET_LOST:
  557. case ID_NAT_TARGET_UNRESPONSIVE:
  558. {
  559. const char *reason;
  560. if (packet->data[0]==ID_NAT_TARGET_NOT_CONNECTED)
  561. reason=(char *)"ID_NAT_TARGET_NOT_CONNECTED";
  562. else if (packet->data[0]==ID_NAT_CONNECTION_TO_TARGET_LOST)
  563. reason=(char *)"ID_NAT_CONNECTION_TO_TARGET_LOST";
  564. else
  565. reason=(char *)"ID_NAT_TARGET_UNRESPONSIVE";
  566. RakNet::BitStream incomingBs(packet->data, packet->length, false);
  567. incomingBs.IgnoreBytes(sizeof(MessageID));
  568. RakNetGUID targetGuid;
  569. incomingBs.Read(targetGuid);
  570. //UpdateGroupPunchOnNatResult(packet->systemAddress, targetGuid, UNASSIGNED_SYSTEM_ADDRESS, 2);
  571. if (packet->data[0]==ID_NAT_CONNECTION_TO_TARGET_LOST ||
  572. packet->data[0]==ID_NAT_TARGET_UNRESPONSIVE)
  573. {
  574. uint16_t sessionId;
  575. incomingBs.Read(sessionId);
  576. if (sessionId!=sp.sessionId)
  577. break;
  578. }
  579. unsigned int i;
  580. for (i=0; i < failedAttemptList.Size(); i++)
  581. {
  582. if (failedAttemptList[i].guid==targetGuid)
  583. {
  584. if (natPunchthroughDebugInterface)
  585. {
  586. char guidString[128];
  587. targetGuid.ToString(guidString);
  588. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough retry to guid %s failed due to %s.", guidString, reason));
  589. }
  590. // If the retry target is not connected, or loses connection, or is not responsive, then previous failures cannot be retried.
  591. // Don't need to return failed, the other messages indicate failure anyway
  592. /*
  593. Packet *p = AllocatePacketUnified(sizeof(MessageID));
  594. p->data[0]=ID_NAT_PUNCHTHROUGH_FAILED;
  595. p->systemAddress=failedAttemptList[i].addr;
  596. p->systemAddress.systemIndex=(SystemIndex)-1;
  597. p->guid=failedAttemptList[i].guid;
  598. rakPeerInterface->PushBackPacket(p, false);
  599. */
  600. failedAttemptList.RemoveAtIndexFast(i);
  601. break;
  602. }
  603. }
  604. if (natPunchthroughDebugInterface)
  605. {
  606. char guidString[128];
  607. targetGuid.ToString(guidString);
  608. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough attempt to guid %s failed due to %s.", guidString, reason));
  609. }
  610. // Stop trying punchthrough
  611. sp.nextActionTime=0;
  612. /*
  613. RakNet::BitStream bs(packet->data, packet->length, false);
  614. bs.IgnoreBytes(sizeof(MessageID));
  615. RakNetGUID failedSystem;
  616. bs.Read(failedSystem);
  617. bool deletedFirst=false;
  618. unsigned int i=0;
  619. while (i < pendingOpenNAT.Size())
  620. {
  621. if (pendingOpenNAT[i].destination==failedSystem)
  622. {
  623. if (i==0)
  624. deletedFirst=true;
  625. pendingOpenNAT.RemoveAtIndex(i);
  626. }
  627. else
  628. i++;
  629. }
  630. // Failed while in progress. Go to next in attempt queue
  631. if (deletedFirst && pendingOpenNAT.Size())
  632. {
  633. SendPunchthrough(pendingOpenNAT[0].destination, pendingOpenNAT[0].facilitator);
  634. sp.nextActionTime=0;
  635. }
  636. */
  637. }
  638. break;
  639. case ID_TIMESTAMP:
  640. if (packet->data[sizeof(MessageID)+sizeof(RakNet::Time)]==ID_NAT_CONNECT_AT_TIME)
  641. {
  642. OnConnectAtTime(packet);
  643. return RR_STOP_PROCESSING_AND_DEALLOCATE;
  644. }
  645. break;
  646. }
  647. return RR_CONTINUE_PROCESSING;
  648. }
  649. /*
  650. void NatPunchthroughClient::ProcessNextPunchthroughQueue(void)
  651. {
  652. // Go to the next attempt
  653. if (pendingOpenNAT.Size())
  654. pendingOpenNAT.RemoveAtIndex(0);
  655. // Do next punchthrough attempt
  656. if (pendingOpenNAT.Size())
  657. SendPunchthrough(pendingOpenNAT[0].destination, pendingOpenNAT[0].facilitator);
  658. sp.nextActionTime=0;
  659. }
  660. */
  661. void NatPunchthroughClient::OnConnectAtTime(Packet *packet)
  662. {
  663. // RakAssert(sp.nextActionTime==0);
  664. RakNet::BitStream bs(packet->data, packet->length, false);
  665. bs.IgnoreBytes(sizeof(MessageID));
  666. bs.Read(sp.nextActionTime);
  667. bs.IgnoreBytes(sizeof(MessageID));
  668. bs.Read(sp.sessionId);
  669. bs.Read(sp.targetAddress);
  670. int j;
  671. // int k;
  672. // k=0;
  673. for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++)
  674. bs.Read(sp.internalIds[j]);
  675. // Prevents local testing
  676. /*
  677. for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++)
  678. {
  679. SystemAddress id;
  680. bs.Read(id);
  681. char str[32];
  682. id.ToString(false,str);
  683. if (rakPeerInterface->IsLocalIP(str)==false)
  684. sp.internalIds[k++]=id;
  685. }
  686. */
  687. sp.attemptCount=0;
  688. sp.retryCount=0;
  689. if (pc.MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK>0)
  690. {
  691. sp.testMode=SendPing::TESTING_INTERNAL_IPS;
  692. }
  693. else
  694. {
  695. // TESTING: Try sending to unused ports on the remote system to reserve our own ports while not getting banned
  696. //sp.testMode=SendPing::SEND_WITH_TTL;
  697. sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT;
  698. sp.attemptCount=0;
  699. sp.sentTTL=false;
  700. }
  701. bs.Read(sp.targetGuid);
  702. bs.Read(sp.weAreSender);
  703. }
  704. void NatPunchthroughClient::SendTTL(const SystemAddress &sa)
  705. {
  706. if (sa==UNASSIGNED_SYSTEM_ADDRESS)
  707. return;
  708. if (sa.GetPort()==0)
  709. return;
  710. char ipAddressString[32];
  711. sa.ToString(false, ipAddressString);
  712. // TTL of 1 doesn't get past the router, 2 might hit the other system on a LAN
  713. rakPeerInterface->SendTTL(ipAddressString,sa.GetPort(), 2);
  714. }
  715. char *TestModeToString(NatPunchthroughClient::SendPing::TestMode tm)
  716. {
  717. switch (tm)
  718. {
  719. case NatPunchthroughClient::SendPing::TESTING_INTERNAL_IPS:
  720. return "TESTING_INTERNAL_IPS";
  721. break;
  722. case NatPunchthroughClient::SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE:
  723. return "WAITING_FOR_INTERNAL_IPS_RESPONSE";
  724. break;
  725. // case NatPunchthroughClient::SendPing::SEND_WITH_TTL:
  726. // return "SEND_WITH_TTL";
  727. // break;
  728. case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT:
  729. return "TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT";
  730. break;
  731. case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT:
  732. return "TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT";
  733. break;
  734. case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024:
  735. return "TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024";
  736. break;
  737. case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_1024_TO_1024:
  738. return "TESTING_EXTERNAL_IPS_1024_TO_1024";
  739. break;
  740. case NatPunchthroughClient::SendPing::WAITING_AFTER_ALL_ATTEMPTS:
  741. return "WAITING_AFTER_ALL_ATTEMPTS";
  742. break;
  743. case NatPunchthroughClient::SendPing::PUNCHING_FIXED_PORT:
  744. return "PUNCHING_FIXED_PORT";
  745. break;
  746. }
  747. return "";
  748. }
  749. void NatPunchthroughClient::SendOutOfBand(SystemAddress sa, MessageID oobId)
  750. {
  751. if (sa==UNASSIGNED_SYSTEM_ADDRESS)
  752. return;
  753. if (sa.GetPort()==0)
  754. return;
  755. RakNet::BitStream oob;
  756. oob.Write(oobId);
  757. oob.Write(sp.sessionId);
  758. // RakAssert(sp.sessionId<100);
  759. if (oobId==ID_NAT_ESTABLISH_BIDIRECTIONAL)
  760. oob.Write(sa.GetPort());
  761. char ipAddressString[32];
  762. sa.ToString(false, ipAddressString);
  763. rakPeerInterface->SendOutOfBand((const char*) ipAddressString,sa.GetPort(),(const char*) oob.GetData(),oob.GetNumberOfBytesUsed());
  764. if (natPunchthroughDebugInterface)
  765. {
  766. sa.ToString(true,ipAddressString);
  767. char guidString[128];
  768. sp.targetGuid.ToString(guidString);
  769. // server - diff = my time
  770. // server = myTime + diff
  771. RakNet::Time clockDifferential = rakPeerInterface->GetClockDifferential(sp.facilitator);
  772. RakNet::Time serverTime = RakNet::GetTime() + clockDifferential;
  773. if (oobId==ID_NAT_ESTABLISH_UNIDIRECTIONAL)
  774. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("%I64d: %s: OOB ID_NAT_ESTABLISH_UNIDIRECTIONAL to guid %s, system address %s.\n", serverTime, TestModeToString(sp.testMode), guidString, ipAddressString));
  775. else
  776. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("%I64d: %s: OOB ID_NAT_ESTABLISH_BIDIRECTIONAL to guid %s, system address %s.\n", serverTime, TestModeToString(sp.testMode), guidString, ipAddressString));
  777. }
  778. }
  779. void NatPunchthroughClient::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming)
  780. {
  781. (void) rakNetGUID;
  782. (void) isIncoming;
  783. // Try to track new port mappings on the router. Not reliable, but better than nothing.
  784. SystemAddress ourExternalId = rakPeerInterface->GetExternalID(systemAddress);
  785. if (ourExternalId!=UNASSIGNED_SYSTEM_ADDRESS && mostRecentExternalPort==0) {
  786. mostRecentExternalPort=ourExternalId.GetPort();
  787. if (natPunchthroughDebugInterface)
  788. {
  789. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("OnNewConnection mostRecentExternalPort first time set to %i", mostRecentExternalPort));
  790. }
  791. }
  792. /*
  793. unsigned int i;
  794. i=0;
  795. while (i < groupRequestsInProgress.Size())
  796. {
  797. if (groupRequestsInProgress[i].guid==rakNetGUID)
  798. {
  799. groupRequestsInProgress.RemoveAtIndexFast(i);
  800. }
  801. else
  802. {
  803. i++;
  804. }
  805. }
  806. */
  807. }
  808. void NatPunchthroughClient::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason )
  809. {
  810. (void) systemAddress;
  811. (void) rakNetGUID;
  812. (void) lostConnectionReason;
  813. if (sp.facilitator==systemAddress)
  814. {
  815. // If we lose the connection to the facilitator, all previous failures not currently in progress are returned as such
  816. unsigned int i=0;
  817. while (i < failedAttemptList.Size())
  818. {
  819. if (sp.nextActionTime!=0 && sp.targetGuid==failedAttemptList[i].guid)
  820. {
  821. i++;
  822. continue;
  823. }
  824. PushFailure();
  825. failedAttemptList.RemoveAtIndexFast(i);
  826. }
  827. }
  828. /*
  829. unsigned int i;
  830. i=0;
  831. while (i < groupPunchRequests.Size())
  832. {
  833. if (groupPunchRequests[i]->facilitator==systemAddress)
  834. {
  835. RakNet::OP_DELETE(groupPunchRequests[i],_FILE_AND_LINE_);
  836. groupPunchRequests.RemoveAtIndexFast(i);
  837. }
  838. else
  839. {
  840. i++;
  841. }
  842. }
  843. */
  844. }
  845. void NatPunchthroughClient::GetUPNPPortMappings(char *externalPort, char *internalPort, const SystemAddress &natPunchthroughServerAddress)
  846. {
  847. DataStructures::List< RakNet::RakNetSocket2* > sockets;
  848. rakPeerInterface->GetSockets(sockets);
  849. Itoa(sockets[0]->GetBoundAddress().GetPort(),internalPort,10);
  850. if (mostRecentExternalPort==0)
  851. mostRecentExternalPort=rakPeerInterface->GetExternalID(natPunchthroughServerAddress).GetPort();
  852. Itoa(mostRecentExternalPort,externalPort,10);
  853. }
  854. void NatPunchthroughClient::OnFailureNotification(Packet *packet)
  855. {
  856. RakNet::BitStream incomingBs(packet->data,packet->length,false);
  857. incomingBs.IgnoreBytes(sizeof(MessageID));
  858. RakNetGUID senderGuid;
  859. incomingBs.Read(senderGuid);
  860. /*
  861. unsigned int i;
  862. i=0;
  863. while (i < groupRequestsInProgress.Size())
  864. {
  865. if (groupRequestsInProgress[i].guid==senderGuid)
  866. {
  867. groupRequestsInProgress.RemoveAtIndexFast(i);
  868. break;
  869. }
  870. else
  871. {
  872. i++;
  873. }
  874. }
  875. */
  876. }
  877. void NatPunchthroughClient::OnGetMostRecentPort(Packet *packet)
  878. {
  879. RakNet::BitStream incomingBs(packet->data,packet->length,false);
  880. incomingBs.IgnoreBytes(sizeof(MessageID));
  881. uint16_t sessionId;
  882. incomingBs.Read(sessionId);
  883. RakNet::BitStream outgoingBs;
  884. outgoingBs.Write((MessageID)ID_NAT_GET_MOST_RECENT_PORT);
  885. outgoingBs.Write(sessionId);
  886. if (mostRecentExternalPort==0)
  887. {
  888. mostRecentExternalPort=rakPeerInterface->GetExternalID(packet->systemAddress).GetPort();
  889. RakAssert(mostRecentExternalPort!=0);
  890. if (natPunchthroughDebugInterface)
  891. {
  892. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("OnGetMostRecentPort mostRecentExternalPort first time set to %i", mostRecentExternalPort));
  893. }
  894. }
  895. unsigned short portWithStride;
  896. if (hasPortStride==HAS_PORT_STRIDE)
  897. portWithStride = mostRecentExternalPort + portStride;
  898. else
  899. portWithStride = mostRecentExternalPort;
  900. outgoingBs.Write(portWithStride);
  901. rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet->systemAddress,false);
  902. sp.facilitator=packet->systemAddress;
  903. }
  904. /*
  905. unsigned int NatPunchthroughClient::GetPendingOpenNATIndex(RakNetGUID destination, const SystemAddress &facilitator)
  906. {
  907. unsigned int i;
  908. for (i=0; i < pendingOpenNAT.Size(); i++)
  909. {
  910. if (pendingOpenNAT[i].destination==destination && pendingOpenNAT[i].facilitator==facilitator)
  911. return i;
  912. }
  913. return (unsigned int) -1;
  914. }
  915. */
  916. void NatPunchthroughClient::QueueOpenNAT(RakNetGUID destination, const SystemAddress &facilitator)
  917. {
  918. DSTAndFac daf;
  919. daf.destination=destination;
  920. daf.facilitator=facilitator;
  921. queuedOpenNat.Push(daf, _FILE_AND_LINE_);
  922. }
  923. void NatPunchthroughClient::SendQueuedOpenNAT(void)
  924. {
  925. while (queuedOpenNat.IsEmpty()==false)
  926. {
  927. DSTAndFac daf = queuedOpenNat.Pop();
  928. SendPunchthrough(daf.destination, daf.facilitator);
  929. }
  930. }
  931. void NatPunchthroughClient::SendPunchthrough(RakNetGUID destination, const SystemAddress &facilitator)
  932. {
  933. RakNet::BitStream outgoingBs;
  934. outgoingBs.Write((MessageID)ID_NAT_PUNCHTHROUGH_REQUEST);
  935. outgoingBs.Write(destination);
  936. rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,facilitator,false);
  937. // RakAssert(rakPeerInterface->GetSystemAddressFromGuid(destination)==UNASSIGNED_SYSTEM_ADDRESS);
  938. if (natPunchthroughDebugInterface)
  939. {
  940. char guidString[128];
  941. destination.ToString(guidString);
  942. natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Starting ID_NAT_PUNCHTHROUGH_REQUEST to guid %s.", guidString));
  943. }
  944. }
  945. void NatPunchthroughClient::OnAttach(void)
  946. {
  947. Clear();
  948. }
  949. void NatPunchthroughClient::OnDetach(void)
  950. {
  951. Clear();
  952. }
  953. void NatPunchthroughClient::OnRakPeerShutdown(void)
  954. {
  955. Clear();
  956. }
  957. void NatPunchthroughClient::Clear(void)
  958. {
  959. OnReadyForNextPunchthrough();
  960. failedAttemptList.Clear(false, _FILE_AND_LINE_);
  961. queuedOpenNat.Clear(_FILE_AND_LINE_);
  962. /*
  963. groupRequestsInProgress.Clear(false, _FILE_AND_LINE_);
  964. unsigned int i;
  965. for (i=0; i < groupPunchRequests.Size(); i++)
  966. {
  967. RakNet::OP_DELETE(groupPunchRequests[i],_FILE_AND_LINE_);
  968. }
  969. groupPunchRequests.Clear(true, _FILE_AND_LINE_);
  970. */
  971. }
  972. PunchthroughConfiguration* NatPunchthroughClient::GetPunchthroughConfiguration(void)
  973. {
  974. return &pc;
  975. }
  976. void NatPunchthroughClient::OnReadyForNextPunchthrough(void)
  977. {
  978. if (rakPeerInterface==0)
  979. return;
  980. sp.nextActionTime=0;
  981. RakNet::BitStream outgoingBs;
  982. outgoingBs.Write((MessageID)ID_NAT_CLIENT_READY);
  983. rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,sp.facilitator,false);
  984. }
  985. void NatPunchthroughClient::PushSuccess(void)
  986. {
  987. Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char));
  988. p->data[0]=ID_NAT_PUNCHTHROUGH_SUCCEEDED;
  989. p->systemAddress=sp.targetAddress;
  990. p->systemAddress.systemIndex=(SystemIndex)-1;
  991. p->guid=sp.targetGuid;
  992. if (sp.weAreSender)
  993. p->data[1]=1;
  994. else
  995. p->data[1]=0;
  996. p->wasGeneratedLocally=true;
  997. rakPeerInterface->PushBackPacket(p, true);
  998. }
  999. bool NatPunchthroughClient::RemoveFromFailureQueue(void)
  1000. {
  1001. unsigned int i;
  1002. for (i=0; i < failedAttemptList.Size(); i++)
  1003. {
  1004. if (failedAttemptList[i].guid==sp.targetGuid)
  1005. {
  1006. // Remove from failure queue
  1007. failedAttemptList.RemoveAtIndexFast(i);
  1008. return true;
  1009. }
  1010. }
  1011. return false;
  1012. }
  1013. void NatPunchthroughClient::IncrementExternalAttemptCount(RakNet::Time time, RakNet::Time delta)
  1014. {
  1015. if (++sp.retryCount>=pc.UDP_SENDS_PER_PORT_EXTERNAL)
  1016. {
  1017. ++sp.attemptCount;
  1018. sp.retryCount=0;
  1019. sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_BETWEEN_PORTS-delta;
  1020. sp.sentTTL=false;
  1021. }
  1022. else
  1023. {
  1024. sp.nextActionTime=time+pc.TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL-delta;
  1025. }
  1026. }
  1027. /*
  1028. // 0=failed, 1=success, 2=ignore
  1029. void NatPunchthroughClient::UpdateGroupPunchOnNatResult(SystemAddress facilitator, RakNetGUID targetSystem, SystemAddress targetSystemAddress, int result)
  1030. {
  1031. GroupPunchRequest *gpr;
  1032. unsigned long i,j,k;
  1033. i=0;
  1034. while (i < groupPunchRequests.Size())
  1035. {
  1036. gpr = groupPunchRequests[i];
  1037. if (gpr->facilitator==facilitator)
  1038. {
  1039. j=0;
  1040. while (j < gpr->pendingList.Size())
  1041. {
  1042. if (gpr->pendingList[j]==targetSystem)
  1043. {
  1044. if (result==0)
  1045. {
  1046. gpr->failedList.Push(targetSystem, _FILE_AND_LINE_);
  1047. }
  1048. else if (result==1)
  1049. {
  1050. gpr->passedListGuid.Push(targetSystem, _FILE_AND_LINE_);
  1051. gpr->passedListAddress.Push(targetSystemAddress, _FILE_AND_LINE_);
  1052. }
  1053. else
  1054. {
  1055. gpr->ignoredList.Push(targetSystem, _FILE_AND_LINE_);
  1056. }
  1057. gpr->pendingList.RemoveAtIndex(j);
  1058. }
  1059. else
  1060. j++;
  1061. }
  1062. }
  1063. if (gpr->pendingList.Size()==0)
  1064. {
  1065. RakNet::BitStream output;
  1066. if (gpr->failedList.Size()==0)
  1067. {
  1068. output.Write(ID_NAT_GROUP_PUNCH_SUCCEEDED);
  1069. }
  1070. else
  1071. {
  1072. output.Write(ID_NAT_GROUP_PUNCH_FAILED);
  1073. }
  1074. output.WriteCasted<unsigned char>(gpr->passedListGuid.Size());
  1075. for (k=0; k < gpr->passedListGuid.Size(); k++)
  1076. {
  1077. output.Write(gpr->passedListGuid[k]);
  1078. output.Write(gpr->passedListAddress[k]);
  1079. }
  1080. output.WriteCasted<unsigned char>(gpr->ignoredList.Size());
  1081. for (k=0; k < gpr->ignoredList.Size(); k++)
  1082. {
  1083. output.Write(gpr->ignoredList[k]);
  1084. }
  1085. output.WriteCasted<unsigned char>(gpr->failedList.Size());
  1086. for (k=0; k < gpr->failedList.Size(); k++)
  1087. {
  1088. output.Write(gpr->failedList[k]);
  1089. }
  1090. Packet *p = AllocatePacketUnified(output.GetNumberOfBytesUsed());
  1091. p->systemAddress=gpr->facilitator;
  1092. p->systemAddress.systemIndex=(SystemIndex)-1;
  1093. p->guid=rakPeerInterface->GetGuidFromSystemAddress(gpr->facilitator);
  1094. p->wasGeneratedLocally=true;
  1095. memcpy(p->data, output.GetData(), output.GetNumberOfBytesUsed());
  1096. rakPeerInterface->PushBackPacket(p, true);
  1097. groupPunchRequests.RemoveAtIndex(i);
  1098. RakNet::OP_DELETE(gpr, _FILE_AND_LINE_);
  1099. }
  1100. else
  1101. i++;
  1102. }
  1103. }
  1104. */
  1105. #endif // _RAKNET_SUPPORT_*
粤ICP备19079148号