forked from electronicarts/CnC_Generals_Zero_Hour
-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathTransport.cpp
More file actions
511 lines (445 loc) · 13.9 KB
/
Transport.cpp
File metadata and controls
511 lines (445 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine
#include "Common/crc.h"
#include "GameNetwork/Transport.h"
#include "GameNetwork/NetworkInterface.h"
//--------------------------------------------------------------------------
// Packet-level encryption is an XOR operation, for speed reasons. To get
// the max throughput, we only XOR whole 4-byte words, so the last bytes
// can be non-XOR'd.
// This assumes the buf is a multiple of 4 bytes. Extra is not encrypted.
static inline void encryptBuf( unsigned char *buf, Int len )
{
UnsignedInt mask = 0x0000Fade;
UnsignedInt *uintPtr = (UnsignedInt *) (buf);
for (int i=0 ; i<len/4 ; i++) {
*uintPtr = (*uintPtr) ^ mask;
*uintPtr = htonl(*uintPtr);
uintPtr++;
mask += 0x00000321; // just for fun
}
}
// This assumes the buf is a multiple of 4 bytes. Extra is not encrypted.
static inline void decryptBuf( unsigned char *buf, Int len )
{
UnsignedInt mask = 0x0000Fade;
UnsignedInt *uintPtr = (UnsignedInt *) (buf);
for (int i=0 ; i<len/4 ; i++) {
*uintPtr = htonl(*uintPtr);
*uintPtr = (*uintPtr) ^ mask;
uintPtr++;
mask += 0x00000321; // just for fun
}
}
//--------------------------------------------------------------------------
Transport::Transport()
{
m_winsockInit = false;
m_udpsock = nullptr;
}
Transport::~Transport()
{
reset();
}
Bool Transport::init( AsciiString ip, UnsignedShort port )
{
return init(ResolveIP(ip), port);
}
Bool Transport::init( UnsignedInt ip, UnsignedShort port )
{
// ----- Initialize Winsock -----
if (!m_winsockInit)
{
WORD verReq = MAKEWORD(2, 2);
WSADATA wsadata;
int err = WSAStartup(verReq, &wsadata);
if (err != 0) {
return false;
}
if ((LOBYTE(wsadata.wVersion) != 2) || (HIBYTE(wsadata.wVersion) !=2)) {
WSACleanup();
return false;
}
m_winsockInit = true;
}
// ------- Bind our port --------
delete m_udpsock;
m_udpsock = NEW UDP();
if (!m_udpsock)
return false;
int retval = -1;
time_t now = timeGetTime();
while ((retval != 0) && ((timeGetTime() - now) < 1000)) {
retval = m_udpsock->Bind(ip, port);
}
if (retval != 0) {
DEBUG_CRASH(("Could not bind to 0x%8.8X:%d", ip, port));
DEBUG_LOG(("Transport::init - Failure to bind socket with error code %x", retval));
delete m_udpsock;
m_udpsock = nullptr;
return false;
}
// ------- Clear buffers --------
int i=0;
for (; i<MAX_MESSAGES; ++i)
{
m_outBuffer[i].length = 0;
m_inBuffer[i].length = 0;
#if defined(RTS_DEBUG)
m_delayedInBuffer[i].message.length = 0;
#endif
}
for (i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
{
m_incomingBytes[i] = 0;
m_outgoingBytes[i] = 0;
m_unknownBytes[i] = 0;
m_incomingPackets[i] = 0;
m_outgoingPackets[i] = 0;
m_unknownPackets[i] = 0;
}
m_statisticsSlot = 0;
m_lastSecond = timeGetTime();
m_port = port;
#if defined(RTS_DEBUG)
if (TheGlobalData->m_latencyAverage > 0 || TheGlobalData->m_latencyNoise)
m_useLatency = true;
if (TheGlobalData->m_packetLoss)
m_usePacketLoss = true;
#endif
return true;
}
void Transport::reset()
{
delete m_udpsock;
m_udpsock = nullptr;
if (m_winsockInit)
{
WSACleanup();
m_winsockInit = false;
}
}
Bool Transport::update()
{
Bool retval = TRUE;
if (doRecv() == FALSE && m_udpsock && m_udpsock->GetStatus() == UDP::ADDRNOTAVAIL)
{
retval = FALSE;
}
DEBUG_ASSERTLOG(retval, ("WSA error is %s", GetWSAErrorString(WSAGetLastError()).str()));
if (doSend() == FALSE && m_udpsock && m_udpsock->GetStatus() == UDP::ADDRNOTAVAIL)
{
retval = FALSE;
}
DEBUG_ASSERTLOG(retval, ("WSA error is %s", GetWSAErrorString(WSAGetLastError()).str()));
return retval;
}
Bool Transport::doSend() {
if (!m_udpsock)
{
DEBUG_LOG(("Transport::doSend() - m_udpSock is null!"));
return FALSE;
}
Bool retval = TRUE;
// Statistics gathering
UnsignedInt now = timeGetTime();
if (m_lastSecond + 1000 < now)
{
m_lastSecond = now;
m_statisticsSlot = (m_statisticsSlot + 1) % MAX_TRANSPORT_STATISTICS_SECONDS;
m_outgoingPackets[m_statisticsSlot] = 0;
m_outgoingBytes[m_statisticsSlot] = 0;
m_incomingPackets[m_statisticsSlot] = 0;
m_incomingBytes[m_statisticsSlot] = 0;
m_unknownPackets[m_statisticsSlot] = 0;
m_unknownBytes[m_statisticsSlot] = 0;
}
// Send all messages
for (size_t i = 0; i < ARRAY_SIZE(m_outBuffer); ++i)
{
if (m_outBuffer[i].length != 0)
{
int bytesSent = 0;
// TheSuperHackers @info The handling of data sizing of the payload within a UDP packet is confusing due to the current networking implementation
// The max game packet size needs to be smaller than max udp payload by sizeof(TransportMessageHeader)
// But the max network message size needs to include the bytes of the transport message header and equal the max udp payload
// Therefore, transmitted data needs to add the extra bytes of the network header to the payloads length
int bytesToSend = m_outBuffer[i].length + sizeof(TransportMessageHeader);
// Send this message
if ((bytesSent = m_udpsock->Write((unsigned char *)(&m_outBuffer[i]), bytesToSend, m_outBuffer[i].addr, m_outBuffer[i].port)) > 0)
{
//DEBUG_LOG(("Sending %d bytes to %d.%d.%d.%d:%d", bytesToSend, PRINTF_IP_AS_4_INTS(m_outBuffer[i].addr), m_outBuffer[i].port));
m_outgoingPackets[m_statisticsSlot]++;
m_outgoingBytes[m_statisticsSlot] += m_outBuffer[i].length + sizeof(TransportMessageHeader);
m_outBuffer[i].length = 0; // Remove from queue
if (bytesSent != bytesToSend)
{
DEBUG_LOG(("Transport::doSend - wanted to send %d bytes, only sent %d bytes to %d.%d.%d.%d:%d",
bytesToSend, bytesSent,
PRINTF_IP_AS_4_INTS(m_outBuffer[i].addr), m_outBuffer[i].port));
}
}
else
{
//DEBUG_LOG(("Could not write to socket!!! Not discarding message!"));
retval = FALSE;
//DEBUG_LOG(("Transport::doSend returning FALSE"));
}
}
}
#if defined(RTS_DEBUG)
// Latency simulation - deliver anything we're holding on to that is ready
if (m_useLatency)
{
for (int i=0; i<MAX_MESSAGES; ++i)
{
if (m_delayedInBuffer[i].message.length != 0 && m_delayedInBuffer[i].deliveryTime <= now)
{
for (int j=0; j<MAX_MESSAGES; ++j)
{
if (m_inBuffer[j].length == 0)
{
// Empty slot; use it
memcpy(&m_inBuffer[j], &m_delayedInBuffer[i].message, sizeof(TransportMessage));
m_delayedInBuffer[i].message.length = 0;
break;
}
}
}
}
}
#endif
return retval;
}
Bool Transport::doRecv()
{
if (!m_udpsock)
{
DEBUG_LOG(("Transport::doRecv() - m_udpSock is null!"));
return FALSE;
}
Bool retval = TRUE;
// Read in anything on our socket
sockaddr_in from;
#if defined(RTS_DEBUG)
UnsignedInt now = timeGetTime();
#endif
// TheSuperHackers @info The handling of data sizing of the payload within a UDP packet is confusing due to the current networking implementation
// The max game packet size needs to be smaller than max udp payload by sizeof(TransportMessageHeader)
// But the max network message size needs to include the bytes of the transport message header and equal the max udp payload
// Therefore, when receiving data we use the max udp payload size to receive the game packet payload and network header
TransportMessage incomingMessage;
unsigned char *buf = (unsigned char *)&incomingMessage;
int len = MAX_NETWORK_MESSAGE_LEN;
size_t bufferIndex = 0;
// DEBUG_LOG(("Transport::doRecv - checking"));
while ( (len=m_udpsock->Read(buf, MAX_NETWORK_MESSAGE_LEN, &from)) > 0 )
{
#if defined(RTS_DEBUG)
// Packet loss simulation
if (m_usePacketLoss)
{
if ( TheGlobalData->m_packetLoss >= GameClientRandomValue(0, 100) )
{
continue;
}
}
#endif
// DEBUG_LOG(("Transport::doRecv - Got something! len = %d", len));
// Decrypt the packet
// DEBUG_LOG_RAW(("buffer = "));
// for (Int munkee = 0; munkee < len; ++munkee) {
// DEBUG_LOG_RAW(("%02x", *(buf + munkee)));
// }
// DEBUG_LOG_RAW(("\n"));
decryptBuf(buf, len);
incomingMessage.length = len - sizeof(TransportMessageHeader);
if (len <= sizeof(TransportMessageHeader) || !isGeneralsPacket( &incomingMessage ))
{
DEBUG_LOG(("Transport::doRecv - unknownPacket! len = %d", len));
m_unknownPackets[m_statisticsSlot]++;
m_unknownBytes[m_statisticsSlot] += len;
continue;
}
// Something there; stick it somewhere
// DEBUG_LOG(("Saw %d bytes from %d:%d", len, ntohl(from.sin_addr.S_un.S_addr), ntohs(from.sin_port)));
m_incomingPackets[m_statisticsSlot]++;
m_incomingBytes[m_statisticsSlot] += len;
for (; bufferIndex < ARRAY_SIZE(m_inBuffer); ++bufferIndex)
{
#if defined(RTS_DEBUG)
// Latency simulation
if (m_useLatency)
{
if (m_delayedInBuffer[bufferIndex].message.length == 0)
{
// Empty slot; use it
m_delayedInBuffer[bufferIndex].deliveryTime =
now + TheGlobalData->m_latencyAverage +
(Int)(TheGlobalData->m_latencyAmplitude * sin(now * TheGlobalData->m_latencyPeriod)) +
GameClientRandomValue(-TheGlobalData->m_latencyNoise, TheGlobalData->m_latencyNoise);
m_delayedInBuffer[bufferIndex].message.length = incomingMessage.length;
m_delayedInBuffer[bufferIndex].message.addr = ntohl(from.sin_addr.S_un.S_addr);
m_delayedInBuffer[bufferIndex].message.port = ntohs(from.sin_port);
memcpy(&m_delayedInBuffer[bufferIndex].message, buf, len);
++bufferIndex;
break;
}
}
else
{
#endif
if (m_inBuffer[bufferIndex].length == 0)
{
// Empty slot; use it
m_inBuffer[bufferIndex].length = incomingMessage.length;
m_inBuffer[bufferIndex].addr = ntohl(from.sin_addr.S_un.S_addr);
m_inBuffer[bufferIndex].port = ntohs(from.sin_port);
memcpy(&m_inBuffer[bufferIndex], buf, len);
++bufferIndex;
break;
}
#if defined(RTS_DEBUG)
}
#endif
}
//DEBUG_ASSERTCRASH(i<MAX_MESSAGES, ("Message lost!"));
}
if (len == -1) {
// there was a socket error trying to perform a read.
//DEBUG_LOG(("Transport::doRecv returning FALSE"));
retval = FALSE;
}
return retval;
}
Bool Transport::queueSend(UnsignedInt addr, UnsignedShort port, const UnsignedByte *buf, Int len /*,
NetMessageFlags flags, Int id */)
{
if (len < 1 || len > MAX_PACKET_SIZE)
{
DEBUG_LOG(("Transport::queueSend - Invalid Packet size"));
return false;
}
for (size_t i = 0; i < ARRAY_SIZE(m_outBuffer); ++i)
{
if (m_outBuffer[i].length == 0)
{
// Insert data here
m_outBuffer[i].length = len;
memcpy(m_outBuffer[i].data, buf, len);
m_outBuffer[i].addr = addr;
m_outBuffer[i].port = port;
// m_outBuffer[i].header.flags = flags;
// m_outBuffer[i].header.id = id;
m_outBuffer[i].header.magic = GENERALS_MAGIC_NUMBER;
CRC crc;
crc.computeCRC( (unsigned char *)(&(m_outBuffer[i].header.magic)), m_outBuffer[i].length + sizeof(TransportMessageHeader) - sizeof(UnsignedInt) );
// DEBUG_LOG(("About to assign the CRC for the packet"));
m_outBuffer[i].header.crc = crc.get();
// Encrypt packet
// DEBUG_LOG(("buffer: "));
encryptBuf((unsigned char *)&m_outBuffer[i], len + sizeof(TransportMessageHeader));
// DEBUG_LOG((""));
return true;
}
}
DEBUG_LOG(("Send Queue is getting full, dropping packets"));
return false;
}
Bool Transport::isGeneralsPacket( TransportMessage *msg )
{
if (!msg)
return false;
if (msg->length < 0 || msg->length > MAX_NETWORK_MESSAGE_LEN)
return false;
CRC crc;
// crc.computeCRC( (unsigned char *)msg->data, msg->length );
crc.computeCRC( (unsigned char *)(&(msg->header.magic)), msg->length + sizeof(TransportMessageHeader) - sizeof(UnsignedInt) );
if (crc.get() != msg->header.crc)
return false;
if (msg->header.magic != GENERALS_MAGIC_NUMBER)
return false;
return true;
}
// Statistics ---------------------------------------------------
Real Transport::getIncomingBytesPerSecond()
{
Real val = 0.0;
for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
{
if (i != m_statisticsSlot)
val += m_incomingBytes[i];
}
return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
}
Real Transport::getIncomingPacketsPerSecond()
{
Real val = 0.0;
for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
{
if (i != m_statisticsSlot)
val += m_incomingPackets[i];
}
return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
}
Real Transport::getOutgoingBytesPerSecond()
{
Real val = 0.0;
for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
{
if (i != m_statisticsSlot)
val += m_outgoingBytes[i];
}
return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
}
Real Transport::getOutgoingPacketsPerSecond()
{
Real val = 0.0;
for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
{
if (i != m_statisticsSlot)
val += m_outgoingPackets[i];
}
return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
}
Real Transport::getUnknownBytesPerSecond()
{
Real val = 0.0;
for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
{
if (i != m_statisticsSlot)
val += m_unknownBytes[i];
}
return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
}
Real Transport::getUnknownPacketsPerSecond()
{
Real val = 0.0;
for (int i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i)
{
if (i != m_statisticsSlot)
val += m_unknownPackets[i];
}
return val / (MAX_TRANSPORT_STATISTICS_SECONDS-1);
}