Transport.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. ** Command & Conquer Generals Zero Hour(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. #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
  24. #include "Common/CRC.h"
  25. #include "GameNetwork/Transport.h"
  26. #include "GameNetwork/NetworkInterface.h"
  27. #ifdef _INTERNAL
  28. // for occasional debugging...
  29. //#pragma optimize("", off)
  30. //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  31. #endif
  32. //--------------------------------------------------------------------------
  33. // Packet-level encryption is an XOR operation, for speed reasons. To get
  34. // the max throughput, we only XOR whole 4-byte words, so the last bytes
  35. // can be non-XOR'd.
  36. // This assumes the buf is a multiple of 4 bytes. Extra is not encrypted.
  37. static inline void encryptBuf( unsigned char *buf, Int len )
  38. {
  39. UnsignedInt mask = 0x0000Fade;
  40. UnsignedInt *uintPtr = (UnsignedInt *) (buf);
  41. for (int i=0 ; i<len/4 ; i++) {
  42. *uintPtr = (*uintPtr) ^ mask;
  43. *uintPtr = htonl(*uintPtr);
  44. uintPtr++;
  45. mask += 0x00000321; // just for fun
  46. }
  47. }
  48. // This assumes the buf is a multiple of 4 bytes. Extra is not encrypted.
  49. static inline void decryptBuf( unsigned char *buf, Int len )
  50. {
  51. UnsignedInt mask = 0x0000Fade;
  52. UnsignedInt *uintPtr = (UnsignedInt *) (buf);
  53. for (int i=0 ; i<len/4 ; i++) {
  54. *uintPtr = htonl(*uintPtr);
  55. *uintPtr = (*uintPtr) ^ mask;
  56. uintPtr++;
  57. mask += 0x00000321; // just for fun
  58. }
  59. }
  60. //--------------------------------------------------------------------------
  61. Transport::Transport(void)
  62. {
  63. m_winsockInit = false;
  64. m_udpsock = NULL;
  65. }
  66. Transport::~Transport(void)
  67. {
  68. reset();
  69. }
  70. Bool Transport::init( AsciiString ip, UnsignedShort port )
  71. {
  72. return init(ResolveIP(ip), port);
  73. }
  74. Bool Transport::init( UnsignedInt ip, UnsignedShort port )
  75. {
  76. // ----- Initialize Winsock -----
  77. if (!m_winsockInit)
  78. {
  79. WORD verReq = MAKEWORD(2, 2);
  80. WSADATA wsadata;
  81. int err = WSAStartup(verReq, &wsadata);
  82. if (err != 0) {
  83. return false;
  84. }
  85. if ((LOBYTE(wsadata.wVersion) != 2) || (HIBYTE(wsadata.wVersion) !=2)) {
  86. WSACleanup();
  87. return false;
  88. }
  89. m_winsockInit = true;
  90. }
  91. // ------- Bind our port --------
  92. if (m_udpsock)
  93. delete m_udpsock;
  94. m_udpsock = NEW UDP();
  95. if (!m_udpsock)
  96. return false;
  97. int retval = -1;
  98. time_t now = timeGetTime();
  99. while ((retval != 0) && ((timeGetTime() - now) < 1000)) {
  100. retval = m_udpsock->Bind(ip, port);
  101. }
  102. if (retval != 0) {
  103. DEBUG_CRASH(("Could not bind to 0x%8.8X:%d\n", ip, port));
  104. DEBUG_LOG(("Transport::init - Failure to bind socket with error code %x\n", retval));
  105. delete m_udpsock;
  106. m_udpsock = NULL;
  107. return false;
  108. }
  109. // ------- Clear buffers --------
  110. for (int i=0; i<MAX_MESSAGES; ++i)
  111. {
  112. m_outBuffer[i].length = 0;
  113. m_inBuffer[i].length = 0;
  114. #if defined(_DEBUG) || defined(_INTERNAL)
  115. m_delayedInBuffer[i].message.length = 0;
  116. #endif
  117. }
  118. for (i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
  119. {
  120. m_incomingBytes[i] = 0;
  121. m_outgoingBytes[i] = 0;
  122. m_unknownBytes[i] = 0;
  123. m_incomingPackets[i] = 0;
  124. m_outgoingPackets[i] = 0;
  125. m_unknownPackets[i] = 0;
  126. }
  127. m_statisticsSlot = 0;
  128. m_lastSecond = timeGetTime();
  129. m_port = port;
  130. #if defined(_DEBUG) || defined(_INTERNAL)
  131. if (TheGlobalData->m_latencyAverage > 0 || TheGlobalData->m_latencyNoise)
  132. m_useLatency = true;
  133. if (TheGlobalData->m_packetLoss)
  134. m_usePacketLoss = true;
  135. #endif
  136. return true;
  137. }
  138. void Transport::reset( void )
  139. {
  140. if (m_udpsock)
  141. {
  142. delete m_udpsock;
  143. m_udpsock = NULL;
  144. }
  145. if (m_winsockInit)
  146. {
  147. WSACleanup();
  148. m_winsockInit = false;
  149. }
  150. }
  151. Bool Transport::update( void )
  152. {
  153. Bool retval = TRUE;
  154. if (doRecv() == FALSE && m_udpsock && m_udpsock->GetStatus() == UDP::ADDRNOTAVAIL)
  155. {
  156. retval = FALSE;
  157. }
  158. DEBUG_ASSERTLOG(retval, ("WSA error is %s\n", GetWSAErrorString(WSAGetLastError()).str()));
  159. if (doSend() == FALSE && m_udpsock && m_udpsock->GetStatus() == UDP::ADDRNOTAVAIL)
  160. {
  161. retval = FALSE;
  162. }
  163. DEBUG_ASSERTLOG(retval, ("WSA error is %s\n", GetWSAErrorString(WSAGetLastError()).str()));
  164. return retval;
  165. }
  166. Bool Transport::doSend() {
  167. if (!m_udpsock)
  168. {
  169. DEBUG_LOG(("Transport::doSend() - m_udpSock is NULL!\n"));
  170. return FALSE;
  171. }
  172. Bool retval = TRUE;
  173. // Statistics gathering
  174. UnsignedInt now = timeGetTime();
  175. if (m_lastSecond + 1000 < now)
  176. {
  177. m_lastSecond = now;
  178. m_statisticsSlot = (m_statisticsSlot + 1) % MAX_TRANSPORT_STATISTICS_SECONDS;
  179. m_outgoingPackets[m_statisticsSlot] = 0;
  180. m_outgoingBytes[m_statisticsSlot] = 0;
  181. m_incomingPackets[m_statisticsSlot] = 0;
  182. m_incomingBytes[m_statisticsSlot] = 0;
  183. m_unknownPackets[m_statisticsSlot] = 0;
  184. m_unknownBytes[m_statisticsSlot] = 0;
  185. }
  186. // Send all messages
  187. int i;
  188. for (i=0; i<MAX_MESSAGES; ++i)
  189. {
  190. if (m_outBuffer[i].length != 0)
  191. {
  192. int bytesSent = 0;
  193. // Send this message
  194. if ((bytesSent = m_udpsock->Write((unsigned char *)(&m_outBuffer[i]), m_outBuffer[i].length + sizeof(TransportMessageHeader), m_outBuffer[i].addr, m_outBuffer[i].port)) > 0)
  195. {
  196. //DEBUG_LOG(("Sending %d bytes to %d:%d\n", m_outBuffer[i].length + sizeof(TransportMessageHeader), m_outBuffer[i].addr, m_outBuffer[i].port));
  197. m_outgoingPackets[m_statisticsSlot]++;
  198. m_outgoingBytes[m_statisticsSlot] += m_outBuffer[i].length + sizeof(TransportMessageHeader);
  199. m_outBuffer[i].length = 0; // Remove from queue
  200. // DEBUG_LOG(("Transport::doSend - sent %d butes to %d.%d.%d.%d:%d\n", bytesSent,
  201. // (m_outBuffer[i].addr >> 24) & 0xff,
  202. // (m_outBuffer[i].addr >> 16) & 0xff,
  203. // (m_outBuffer[i].addr >> 8) & 0xff,
  204. // m_outBuffer[i].addr & 0xff,
  205. // m_outBuffer[i].port));
  206. }
  207. else
  208. {
  209. //DEBUG_LOG(("Could not write to socket!!! Not discarding message!\n"));
  210. retval = FALSE;
  211. //DEBUG_LOG(("Transport::doSend returning FALSE\n"));
  212. }
  213. }
  214. } // for (i=0; i<MAX_MESSAGES; ++i)
  215. #if defined(_DEBUG) || defined(_INTERNAL)
  216. // Latency simulation - deliver anything we're holding on to that is ready
  217. if (m_useLatency)
  218. {
  219. for (i=0; i<MAX_MESSAGES; ++i)
  220. {
  221. if (m_delayedInBuffer[i].message.length != 0 && m_delayedInBuffer[i].deliveryTime <= now)
  222. {
  223. for (int j=0; j<MAX_MESSAGES; ++j)
  224. {
  225. if (m_inBuffer[j].length == 0)
  226. {
  227. // Empty slot; use it
  228. memcpy(&m_inBuffer[j], &m_delayedInBuffer[i].message, sizeof(TransportMessage));
  229. m_delayedInBuffer[i].message.length = 0;
  230. break;
  231. }
  232. }
  233. }
  234. }
  235. }
  236. #endif
  237. return retval;
  238. }
  239. Bool Transport::doRecv()
  240. {
  241. if (!m_udpsock)
  242. {
  243. DEBUG_LOG(("Transport::doRecv() - m_udpSock is NULL!\n"));
  244. return FALSE;
  245. }
  246. Bool retval = TRUE;
  247. // Read in anything on our socket
  248. sockaddr_in from;
  249. #if defined(_DEBUG) || defined(_INTERNAL)
  250. UnsignedInt now = timeGetTime();
  251. #endif
  252. TransportMessage incomingMessage;
  253. unsigned char *buf = (unsigned char *)&incomingMessage;
  254. int len = MAX_MESSAGE_LEN;
  255. // DEBUG_LOG(("Transport::doRecv - checking\n"));
  256. while ( (len=m_udpsock->Read(buf, MAX_MESSAGE_LEN, &from)) > 0 )
  257. {
  258. #if defined(_DEBUG) || defined(_INTERNAL)
  259. // Packet loss simulation
  260. if (m_usePacketLoss)
  261. {
  262. if ( TheGlobalData->m_packetLoss >= GameClientRandomValue(0, 100) )
  263. {
  264. continue;
  265. }
  266. }
  267. #endif
  268. // DEBUG_LOG(("Transport::doRecv - Got something! len = %d\n", len));
  269. // Decrypt the packet
  270. // DEBUG_LOG(("buffer = "));
  271. // for (Int munkee = 0; munkee < len; ++munkee) {
  272. // DEBUG_LOG(("%02x", *(buf + munkee)));
  273. // }
  274. // DEBUG_LOG(("\n"));
  275. decryptBuf(buf, len);
  276. incomingMessage.length = len - sizeof(TransportMessageHeader);
  277. if (len <= sizeof(TransportMessageHeader) || !isGeneralsPacket( &incomingMessage ))
  278. {
  279. m_unknownPackets[m_statisticsSlot]++;
  280. m_unknownBytes[m_statisticsSlot] += len;
  281. continue;
  282. }
  283. // Something there; stick it somewhere
  284. // DEBUG_LOG(("Saw %d bytes from %d:%d\n", len, ntohl(from.sin_addr.S_un.S_addr), ntohs(from.sin_port)));
  285. m_incomingPackets[m_statisticsSlot]++;
  286. m_incomingBytes[m_statisticsSlot] += len;
  287. for (int i=0; i<MAX_MESSAGES; ++i)
  288. {
  289. #if defined(_DEBUG) || defined(_INTERNAL)
  290. // Latency simulation
  291. if (m_useLatency)
  292. {
  293. if (m_delayedInBuffer[i].message.length == 0)
  294. {
  295. // Empty slot; use it
  296. m_delayedInBuffer[i].deliveryTime =
  297. now + TheGlobalData->m_latencyAverage +
  298. (Int)(TheGlobalData->m_latencyAmplitude * sin(now * TheGlobalData->m_latencyPeriod)) +
  299. GameClientRandomValue(-TheGlobalData->m_latencyNoise, TheGlobalData->m_latencyNoise);
  300. m_delayedInBuffer[i].message.length = incomingMessage.length;
  301. m_delayedInBuffer[i].message.addr = ntohl(from.sin_addr.S_un.S_addr);
  302. m_delayedInBuffer[i].message.port = ntohs(from.sin_port);
  303. memcpy(&m_delayedInBuffer[i].message, buf, len);
  304. break;
  305. }
  306. }
  307. else
  308. {
  309. #endif
  310. if (m_inBuffer[i].length == 0)
  311. {
  312. // Empty slot; use it
  313. m_inBuffer[i].length = incomingMessage.length;
  314. m_inBuffer[i].addr = ntohl(from.sin_addr.S_un.S_addr);
  315. m_inBuffer[i].port = ntohs(from.sin_port);
  316. memcpy(&m_inBuffer[i], buf, len);
  317. break;
  318. }
  319. #if defined(_DEBUG) || defined(_INTERNAL)
  320. }
  321. #endif
  322. }
  323. //DEBUG_ASSERTCRASH(i<MAX_MESSAGES, ("Message lost!"));
  324. }
  325. if (len == -1) {
  326. // there was a socket error trying to perform a read.
  327. //DEBUG_LOG(("Transport::doRecv returning FALSE\n"));
  328. retval = FALSE;
  329. }
  330. return retval;
  331. }
  332. Bool Transport::queueSend(UnsignedInt addr, UnsignedShort port, const UnsignedByte *buf, Int len /*,
  333. NetMessageFlags flags, Int id */)
  334. {
  335. int i;
  336. if (len < 1 || len > MAX_PACKET_SIZE)
  337. {
  338. return false;
  339. }
  340. for (i=0; i<MAX_MESSAGES; ++i)
  341. {
  342. if (m_outBuffer[i].length == 0)
  343. {
  344. // Insert data here
  345. m_outBuffer[i].length = len;
  346. memcpy(m_outBuffer[i].data, buf, len);
  347. m_outBuffer[i].addr = addr;
  348. m_outBuffer[i].port = port;
  349. // m_outBuffer[i].header.flags = flags;
  350. // m_outBuffer[i].header.id = id;
  351. m_outBuffer[i].header.magic = GENERALS_MAGIC_NUMBER;
  352. CRC crc;
  353. crc.computeCRC( (unsigned char *)(&(m_outBuffer[i].header.magic)), m_outBuffer[i].length + sizeof(TransportMessageHeader) - sizeof(UnsignedInt) );
  354. // DEBUG_LOG(("About to assign the CRC for the packet\n"));
  355. m_outBuffer[i].header.crc = crc.get();
  356. // Encrypt packet
  357. // DEBUG_LOG(("buffer: "));
  358. encryptBuf((unsigned char *)&m_outBuffer[i], len + sizeof(TransportMessageHeader));
  359. // DEBUG_LOG(("\n"));
  360. return true;
  361. }
  362. }
  363. return false;
  364. }
  365. Bool Transport::isGeneralsPacket( TransportMessage *msg )
  366. {
  367. if (!msg)
  368. return false;
  369. if (msg->length < 0 || msg->length > MAX_MESSAGE_LEN)
  370. return false;
  371. CRC crc;
  372. // crc.computeCRC( (unsigned char *)msg->data, msg->length );
  373. crc.computeCRC( (unsigned char *)(&(msg->header.magic)), msg->length + sizeof(TransportMessageHeader) - sizeof(UnsignedInt) );
  374. if (crc.get() != msg->header.crc)
  375. return false;
  376. if (msg->header.magic != GENERALS_MAGIC_NUMBER)
  377. return false;
  378. return true;
  379. }
  380. // Statistics ---------------------------------------------------
  381. Real Transport::getIncomingBytesPerSecond( void )
  382. {
  383. Real val = 0.0;
  384. for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
  385. {
  386. if (i != m_statisticsSlot)
  387. val += m_incomingBytes[i];
  388. }
  389. return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
  390. }
  391. Real Transport::getIncomingPacketsPerSecond( void )
  392. {
  393. Real val = 0.0;
  394. for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
  395. {
  396. if (i != m_statisticsSlot)
  397. val += m_incomingPackets[i];
  398. }
  399. return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
  400. }
  401. Real Transport::getOutgoingBytesPerSecond( void )
  402. {
  403. Real val = 0.0;
  404. for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
  405. {
  406. if (i != m_statisticsSlot)
  407. val += m_outgoingBytes[i];
  408. }
  409. return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
  410. }
  411. Real Transport::getOutgoingPacketsPerSecond( void )
  412. {
  413. Real val = 0.0;
  414. for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
  415. {
  416. if (i != m_statisticsSlot)
  417. val += m_outgoingPackets[i];
  418. }
  419. return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
  420. }
  421. Real Transport::getUnknownBytesPerSecond( void )
  422. {
  423. Real val = 0.0;
  424. for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
  425. {
  426. if (i != m_statisticsSlot)
  427. val += m_unknownBytes[i];
  428. }
  429. return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
  430. }
  431. Real Transport::getUnknownPacketsPerSecond( void )
  432. {
  433. Real val = 0.0;
  434. for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
  435. {
  436. if (i != m_statisticsSlot)
  437. val += m_unknownPackets[i];
  438. }
  439. return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
  440. }