/
netplay.cpp
2711 lines (2344 loc) · 76.5 KB
/
netplay.cpp
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This file is part of Warzone 2100.
Copyright (C) 1999-2004 Eidos Interactive
Copyright (C) 2005-2011 Warzone 2100 Project
Warzone 2100 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 2 of the License, or
(at your option) any later version.
Warzone 2100 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 Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file netplay.c
*
* Basic netcode.
*/
#include "lib/framework/frame.h"
#include "lib/framework/wzapp_c.h"
#include "lib/framework/string_ext.h"
#include "lib/framework/crc.h"
#include "lib/framework/file.h"
#include "lib/gamelib/gtime.h"
#include "src/component.h" // FIXME: we need to handle this better
#include "src/modding.h" // FIXME: we need to handle this better
#include <time.h> // for stats
#include <physfs.h>
#include <string.h>
#include <memory>
#include "netplay.h"
#include "netlog.h"
#include "netsocket.h"
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include "lib/exceptionhandler/dumpinfo.h"
#include "src/multistat.h"
#include "src/multijoin.h"
#include "src/multiint.h"
#include "src/multiplay.h"
#include "src/warzoneconfig.h"
#ifdef WZ_OS_LINUX
#include <execinfo.h> // Nonfatal runtime backtraces.
#endif //WZ_OS_LINUX
// WARNING !!! This is initialised via configuration.c !!!
static unsigned int gameserver_port = 0;
#define NET_TIMEOUT_DELAY 2500 // we wait this amount of time for socket activity
#define NET_READ_TIMEOUT 0
/*
* === Using new socket code, this might not hold true any longer ===
* NOTE /rant: If the buffer size isn't big enough, it will invalidate the socket.
* Which means that we need to allocate a buffer big enough to handle worst case
* situations.
* reference: MaxMsgSize in netplay.h (currently set to 16K)
*
*/
#define NET_BUFFER_SIZE (MaxMsgSize) // Would be 16K
// ////////////////////////////////////////////////////////////////////////
// Function prototypes
static void NETplayerLeaving(UDWORD player); // Cleanup sockets on player leaving (nicely)
static void NETplayerDropped(UDWORD player); // Broadcast NET_PLAYER_DROPPED & cleanup
static void NETallowJoining(void);
static void recvDebugSync(NETQUEUE queue);
static bool onBanList(const char *ip);
static void addToBanList(const char *ip, const char *name);
/*
* Network globals, these are part of the new network API
*/
SYNC_COUNTER sync_counter; // keeps track on how well we are in sync
// ////////////////////////////////////////////////////////////////////////
// Types
struct NETSTATS // data regarding the last one second or so.
{
UDWORD bytesRecvd;
UDWORD bytesSent; // number of bytes sent in about 1 sec.
UDWORD packetsSent;
UDWORD packetsRecvd;
};
struct NET_PLAYER_DATA
{
uint16_t size;
void* data;
size_t buffer_size;
};
// ////////////////////////////////////////////////////////////////////////
// Variables
NETPLAY NetPlay;
PLAYER_IP *IPlist = NULL;
static bool allow_joining = false;
// update flags
bool netPlayersUpdated;
int mapDownloadProgress;
/**
* Socket used for these purposes:
* * Host a game, be a server.
* * Join a server for a game.
*/
static Socket* tcp_socket = NULL; //socket used to talk to host machine
static Socket *bsocket = NULL; //buffered socket (holds tcp_socket) (clients only?)
static Socket *connected_bsocket[MAX_CONNECTED_PLAYERS] = { NULL };
static SocketSet* socket_set = NULL;
// UPnP
static int upnp = false;
static bool upnp_done = false;
WZ_THREAD *upnpdiscover;
static struct UPNPUrls urls;
static struct IGDdatas data;
// local ip address
static char lanaddr[16];
/**
* Used for connections with clients.
*/
static Socket* tmp_socket[MAX_TMP_SOCKETS] = { NULL };
static SocketSet* tmp_socket_set = NULL;
static NETSTATS nStats = { 0, 0, 0, 0 };
static int32_t NetGameFlags[4] = { 0, 0, 0, 0 };
char iptoconnect[PATH_MAX] = "\0"; // holds IP/hostname from command line
unsigned NET_PlayerConnectionStatus[CONNECTIONSTATUS_NORMAL][MAX_PLAYERS];
// ////////////////////////////////////////////////////////////////////////////
#define VersionStringSize 80
/************************************************************************************
** NOTE (!) Change the VersionString when net code changes!!
** ie ("trunk", "2.1.3", "3.0", ...)
************************************************************************************
**/
char VersionString[VersionStringSize] = "master_20111026";
static int NETCODE_VERSION_MAJOR = 5;
static int NETCODE_VERSION_MINOR = 20111026;
// The Lobby Client - declared external in netplay.h
Lobby::Client lobbyclient;
bool NETisCorrectVersion(uint32_t game_version_major, uint32_t game_version_minor)
{
return (NETCODE_VERSION_MAJOR == game_version_major && NETCODE_VERSION_MINOR == game_version_minor);
}
// Sets if the game is password protected or not
void NETGameLocked( bool flag)
{
NetPlay.GamePassworded = flag;
NETlogEntry("Password is", SYNC_FLAG, NetPlay.GamePassworded);
debug(LOG_NET, "Passworded game is %s", NetPlay.GamePassworded ? "TRUE" : "FALSE" );
}
// Sets the game password
void NETsetGamePassword(const char *password)
{
sstrcpy(NetPlay.gamePassword, password);
debug(LOG_NET, "Password entered is: [%s]", NetPlay.gamePassword);
}
// Resets the game password
void NETresetGamePassword(void)
{
sstrcpy(NetPlay.gamePassword, _("Enter password here"));
debug(LOG_NET, "password reset to 'Enter password here'");
NETGameLocked(false);
}
// *********** Socket with buffer that read NETMSGs ******************
static size_t NET_fillBuffer(Socket **pSocket, SocketSet* socket_set, uint8_t *bufstart, int bufsize)
{
Socket *socket = *pSocket;
ssize_t size;
if (!socketReadReady(socket))
{
return 0;
}
size = readNoInt(socket, bufstart, bufsize);
if ((size != 0 || !socketReadDisconnected(socket)) && size != SOCKET_ERROR)
{
return size;
}
else
{
if (size == 0)
{
debug(LOG_NET, "Connection closed from the other side");
NETlogEntry("Connection closed from the other side..", SYNC_FLAG, selectedPlayer);
}
else
{
debug(LOG_NET, "%s tcp_socket %p is now invalid", strSockError(getSockErr()), socket);
}
// an error occured, or the remote host has closed the connection.
if (socket_set != NULL)
{
SocketSet_DelSocket(socket_set, socket);
}
ASSERT(size <= bufsize, "Socket buffer is too small!");
if (size > bufsize)
{
debug(LOG_ERROR, "Fatal connection error: buffer size of (%d) was too small, current byte count was %ld", bufsize, (long)size);
NETlogEntry("Fatal connection error: buffer size was too small!", SYNC_FLAG, selectedPlayer);
}
if (tcp_socket == socket)
{
debug(LOG_NET, "Host connection was lost!");
NETlogEntry("Host connection was lost!", SYNC_FLAG, selectedPlayer);
tcp_socket = NULL;
bsocket = NULL; // Because tcp_socket == bsocket...
//Game is pretty much over --should just end everything when HOST dies.
NetPlay.isHostAlive = false;
setLobbyError(ERROR_HOSTDROPPED);
NETclose();
return 0;
}
socketClose(socket);
*pSocket = NULL;
}
return 0;
}
void NET_InitPlayer(int i, bool initPosition)
{
NetPlay.players[i].allocated = false;
NetPlay.players[i].heartattacktime = 0;
NetPlay.players[i].heartbeat = true; // we always start with a hearbeat
NetPlay.players[i].kick = false;
if (!NetPlay.isHost)
{ // only clear name outside of games.
NetPlay.players[i].name[0] = '\0';
}
if (initPosition)
{
NetPlay.players[i].colour = i;
setPlayerColour(i, i); // PlayerColour[] in component.c must match this! Why is this in more than one place??!
NetPlay.players[i].position = i;
NetPlay.players[i].team = i;
}
NetPlay.players[i].ready = false;
NetPlay.players[i].needFile = false;
if (NetPlay.bComms)
{
NetPlay.players[i].ai = AI_OPEN;
}
else
{
NetPlay.players[i].ai = 0; // default AI
}
NetPlay.players[i].difficulty = 1; // normal
NetPlay.players[i].wzFile.isCancelled = false;
NetPlay.players[i].wzFile.isSending = false;
}
void NET_InitPlayers()
{
unsigned int i;
for (i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
{
NET_InitPlayer(i, true);
NETinitQueue(NETnetQueue(i));
}
NETinitQueue(NETbroadcastQueue());
NetPlay.hostPlayer = NET_HOST_ONLY; // right now, host starts always at index zero
NetPlay.playercount = 0;
NetPlay.pMapFileHandle = NULL;
debug(LOG_NET, "Players initialized");
}
static void NETSendNPlayerInfoTo(uint32_t *index, uint32_t indexLen, unsigned to)
{
int n;
NETbeginEncode(NETnetQueue(to), NET_PLAYER_INFO);
NETuint32_t(&indexLen);
for (n = 0; n < indexLen; ++n)
{
debug(LOG_NET, "sending player's (%u) info to all players", index[n]);
NETlogEntry(" sending player's info to all players", SYNC_FLAG, index[n]);
NETuint32_t(&index[n]);
NETbool(&NetPlay.players[index[n]].allocated);
NETbool(&NetPlay.players[index[n]].heartbeat);
NETbool(&NetPlay.players[index[n]].kick);
NETstring(NetPlay.players[index[n]].name, sizeof(NetPlay.players[index[n]].name));
NETuint32_t(&NetPlay.players[index[n]].heartattacktime);
NETint32_t(&NetPlay.players[index[n]].colour);
NETint32_t(&NetPlay.players[index[n]].position);
NETint32_t(&NetPlay.players[index[n]].team);
NETbool(&NetPlay.players[index[n]].ready);
NETint8_t(&NetPlay.players[index[n]].ai);
NETint8_t(&NetPlay.players[index[n]].difficulty);
NETuint8_t(&game.skDiff[index[n]]); // This one might be possible to calculate from the other values. // TODO game.skDiff should probably be eliminated somehow.
}
NETend();
}
static void NETSendPlayerInfoTo(uint32_t index, unsigned to)
{
NETSendNPlayerInfoTo(&index, 1, to);
}
static void NETSendAllPlayerInfoTo(unsigned to)
{
static uint32_t indices[MAX_PLAYERS];
for (int i = 0; i < MAX_PLAYERS; ++i)
{
indices[i] = i;
}
ASSERT_OR_RETURN( , NetPlay.isHost == true, "Invalid call for non-host");
NETSendNPlayerInfoTo(indices, ARRAY_SIZE(indices), to);
}
void NETBroadcastTwoPlayerInfo(uint32_t index1, uint32_t index2)
{
uint32_t indices[2] = {index1, index2};
NETSendNPlayerInfoTo(indices, 2, NET_ALL_PLAYERS);
}
void NETBroadcastPlayerInfo(uint32_t index)
{
NETSendPlayerInfoTo(index, NET_ALL_PLAYERS);
}
static signed int NET_CreatePlayer(const char* name)
{
signed int index;
for (index = 0; index < MAX_CONNECTED_PLAYERS; index++)
{
if (NetPlay.players[index].allocated == false && NetPlay.players[index].ai == AI_OPEN)
{
char buf[250] = {'\0'};
ssprintf(buf, "A new player has been created. Player, %s, is set to slot %u", name, index);
debug(LOG_NET,"%s", buf);
NETlogEntry(buf, SYNC_FLAG, index);
NET_InitPlayer(index, false); // re-init everything
NetPlay.players[index].allocated = true;
sstrcpy(NetPlay.players[index].name, name);
NetPlay.playercount++;
sync_counter.joins++;
return index;
}
}
debug(LOG_ERROR, "Could not find place for player %s", name);
NETlogEntry("Could not find a place for player!", SYNC_FLAG, index);
return -1;
}
static void NET_DestroyPlayer(unsigned int index)
{
debug(LOG_NET, "Freeing slot %u for a new player", index);
NETlogEntry("Freeing slot for a new player.", SYNC_FLAG, index);
if (NetPlay.players[index].allocated)
{
NetPlay.players[index].allocated = false;
NetPlay.playercount--;
// Inform the masterserver.
if (allow_joining && NetPlay.isHost)
{
lobbyclient.delPlayer(index);
lobbyclient.freeError();
}
}
NET_InitPlayer(index, false); // reinitialize
}
/**
* @note Connection dropped. Handle it gracefully.
* \param index
*/
static void NETplayerClientDisconnect(uint32_t index)
{
if(connected_bsocket[index])
{
debug(LOG_NET, "Player (%u) has left unexpectedly, closing socket %p", index, connected_bsocket[index]);
NETplayerLeaving(index);
NETlogEntry("Player has left unexpectedly.", SYNC_FLAG, index);
// Announce to the world. This was really icky, because we may have been calling the send
// function recursively. We really ought to have had a send queue, and now we finally do...
NETbeginEncode(NETbroadcastQueue(), NET_PLAYER_DROPPED);
NETuint32_t(&index);
NETend();
}
else
{
debug(LOG_ERROR, "Player (%u) has left unexpectedly - but socket already closed?", index);
}
}
/**
* @note When a player leaves nicely (ie, we got a NET_PLAYER_LEAVING
* message), we clean up the socket that we used.
* \param index
*/
static void NETplayerLeaving(UDWORD index)
{
if(connected_bsocket[index])
{
debug(LOG_NET, "Player (%u) has left, closing socket %p", index, connected_bsocket[index]);
NETlogEntry("Player has left nicely.", SYNC_FLAG, index);
// Although we can get a error result from DelSocket, it don't really matter here.
SocketSet_DelSocket(socket_set, connected_bsocket[index]);
socketClose(connected_bsocket[index]);
connected_bsocket[index] = NULL;
}
else
{
debug(LOG_NET, "Player (%u) has left nicely, socket already closed?", index);
}
sync_counter.left++;
MultiPlayerLeave(index); // more cleanup
NET_DestroyPlayer(index); // sets index player's array to false
}
/**
* @note When a player's connection is broken we broadcast the NET_PLAYER_DROPPED
* message.
* \param index
*/
static void NETplayerDropped(UDWORD index)
{
uint32_t id = index;
// Send message type specifically for dropped / disconnects
NETbeginEncode(NETbroadcastQueue(), NET_PLAYER_DROPPED);
NETuint32_t(&id);
NETend();
debug(LOG_INFO, "sending NET_PLAYER_DROPPED for player %d", id);
sync_counter.drops++;
NET_DestroyPlayer(id); // just clears array
MultiPlayerLeave(id); // more cleanup
NETsetPlayerConnectionStatus(CONNECTIONSTATUS_PLAYER_DROPPED, id);
}
/**
* @note Cleanup for when a player is kicked.
* \param index
*/
void NETplayerKicked(UDWORD index)
{
// kicking a player counts as "leaving nicely", since "nicely" in this case
// simply means "there wasn't a connection error."
debug(LOG_INFO, "Player %u was kicked.", index);
sync_counter.kicks++;
NETlogEntry("Player was kicked.", SYNC_FLAG, index);
addToBanList(NetPlay.players[index].IPtextAddress, NetPlay.players[index].name);
NETplayerLeaving(index); // need to close socket for the player that left.
NETsetPlayerConnectionStatus(CONNECTIONSTATUS_PLAYER_LEAVING, index);
}
// ////////////////////////////////////////////////////////////////////////
// rename the local player
bool NETchangePlayerName(UDWORD index, char *newName)
{
if(!NetPlay.bComms)
{
sstrcpy(NetPlay.players[0].name, newName);
return true;
}
if (NetPlay.isHost && allow_joining)
{
lobbyclient.updatePlayer(index, newName);
lobbyclient.freeError();
}
debug(LOG_NET, "Requesting a change of player name for pid=%u to %s", index, newName);
NETlogEntry("Player wants a name change.", SYNC_FLAG, index);
sstrcpy(NetPlay.players[index].name, newName);
NETBroadcastPlayerInfo(index);
return true;
}
void NETfixDuplicatePlayerNames(void)
{
char name[StringSize];
unsigned i, j, pass;
for (i = 1; i != MAX_PLAYERS; ++i)
{
sstrcpy(name, NetPlay.players[i].name);
if (name[0] == '\0')
{
continue; // Ignore empty names.
}
for (pass = 0; pass != 101; ++pass)
{
if (pass != 0)
{
ssprintf(name, "%s_%X", NetPlay.players[i].name, pass + 1);
}
for (j = 0; j != i; ++j)
{
if (strcmp(name, NetPlay.players[j].name) == 0)
{
break; // Duplicate name.
}
}
if (i == j)
{
break; // Unique name.
}
}
if (pass != 0)
{
NETchangePlayerName(i, name);
}
}
}
// ////////////////////////////////////////////////////////////////////////
// return one of the four user flags in the current sessiondescription.
SDWORD NETgetGameFlags(UDWORD flag)
{
if (flag < 1 || flag > 4)
{
return 0;
}
else
{
return NetGameFlags[flag-1];
}
}
static void NETsendGameFlags(void)
{
debug(LOG_NET, "sending game flags");
NETbeginEncode(NETbroadcastQueue(), NET_GAME_FLAGS);
{
// Send the amount of game flags we're about to send
uint8_t i, count = ARRAY_SIZE(NetGameFlags);
NETuint8_t(&count);
// Send over all game flags
for (i = 0; i < count; ++i)
{
NETint32_t(&NetGameFlags[i]);
}
}
NETend();
}
// ////////////////////////////////////////////////////////////////////////
// Set a game flag
bool NETsetGameFlags(UDWORD flag, SDWORD value)
{
if(!NetPlay.bComms)
{
return true;
}
if (flag > 0 && flag < 5)
{
return (NetGameFlags[flag-1] = value);
}
NETsendGameFlags();
return true;
}
static int upnp_init(void *asdf)
{
struct UPNPDev *devlist;
struct UPNPDev *dev;
char *descXML;
int descXMLsize = 0;
char buf[255];
memset(&urls, 0, sizeof(struct UPNPUrls));
memset(&data, 0, sizeof(struct IGDdatas));
if (NetPlay.isUPNP)
{
debug(LOG_NET, "Searching for UPnP devices for automatic port forwarding...");
devlist = upnpDiscover(2000, NULL, NULL, 0);
debug(LOG_NET, "UPnP device search finished.");
if (devlist)
{
dev = devlist;
while (dev)
{
if (strstr(dev->st, "InternetGatewayDevice"))
break;
dev = dev->pNext;
}
if (!dev)
{
dev = devlist; /* defaulting to first device */
}
debug(LOG_NET, "UPnP device found: %s %s\n", dev->descURL, dev->st);
descXML = (char *)miniwget_getaddr(dev->descURL, &descXMLsize, lanaddr, sizeof(lanaddr));
debug(LOG_NET, "LAN address: %s", lanaddr);
if (descXML)
{
parserootdesc (descXML, descXMLsize, &data);
free (descXML); descXML = 0;
GetUPNPUrls (&urls, &data, dev->descURL);
}
ssprintf(buf, "UPnP device found: %s %s LAN address %s", dev->descURL, dev->st, lanaddr);
addDumpInfo(buf);
freeUPNPDevlist(devlist);
if (!urls.controlURL || urls.controlURL[0] == '\0')
{
ssprintf(buf, "controlURL not available, UPnP disabled");
addDumpInfo(buf);
return false;
}
return true;
}
ssprintf(buf, "UPnP device not found.");
addDumpInfo(buf);
debug(LOG_NET, "No UPnP devices found.");
return false;
}
else
{
ssprintf(buf, "UPnP detection routine disabled by user.");
addDumpInfo(buf);
debug(LOG_NET, "UPnP detection routine disabled by user.");
return false;
}
}
static bool upnp_add_redirect(int port)
{
char externalIP[16];
char port_str[16];
int r;
debug(LOG_NET, "upnp_add_redir(%d)\n", port);
UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIP);
sprintf(port_str, "%d", port);
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port_str, port_str, lanaddr, "Warzone 2100", "TCP", 0);
if (r != UPNPCOMMAND_SUCCESS)
{
debug(LOG_NET, "AddPortMapping(%s, %s, %s) failed\n", port_str, port_str, lanaddr);
return false;
}
return true;
}
static void upnp_rem_redirect(int port)
{
char port_str[16];
debug(LOG_NET, "upnp_rem_redir(%d)", port);
sprintf(port_str, "%d", port);
UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port_str, "TCP", 0);
}
void NETaddRedirects(void)
{
debug(LOG_NET, "%s\n", __FUNCTION__);
if (!upnp_done)
{
upnp = wzThreadJoin(upnpdiscover);
upnp_done = true;
}
if (upnp) {
upnp_add_redirect(gameserver_port);
}
}
void NETremRedirects(void)
{
debug(LOG_NET, "%s\n", __FUNCTION__);
if (upnp)
{
upnp_rem_redirect(gameserver_port);
}
}
void NETdiscoverUPnPDevices(void)
{
upnpdiscover = wzThreadCreate(&upnp_init, NULL);
wzThreadStart(upnpdiscover);
}
// ////////////////////////////////////////////////////////////////////////
// setup stuff
int NETinit(bool bFirstCall)
{
debug(LOG_NET, "NETinit");
NETlogEntry("NETinit!", SYNC_FLAG, selectedPlayer);
NET_InitPlayers();
SOCKETinit();
if(bFirstCall)
{
debug(LOG_NET, "NETPLAY: Init called, MORNIN'");
// NOTE NetPlay.isUPNP is already set in configuration.c!
NetPlay.bComms = true;
NetPlay.GamePassworded = false;
NetPlay.isHostAlive = false;
NetPlay.gamePassword[0] = '\0';
sstrcpy(NetPlay.gamePassword,_("Enter password here"));
NETstartLogging();
}
NetPlay.GamePassworded = false;
memset(&sync_counter, 0x0, sizeof(sync_counter)); //clear counters
// Add the certificate.
lobbyclient.addCACertificate("wz::cacert.org-root.pem");
lobbyclient.addCACertificate("wz::cacert.org-class3.pem");
return 0;
}
// ////////////////////////////////////////////////////////////////////////
// SHUTDOWN THE CONNECTION.
int NETshutdown(void)
{
debug( LOG_NET, "NETshutdown" );
NETlogEntry("NETshutdown", SYNC_FLAG, selectedPlayer);
// Stop the lobbyclient.
lobbyclient.stop();
NETstopLogging();
if (IPlist)
free(IPlist);
IPlist = NULL;
SOCKETshutdown();
if (NetPlay.bComms && NetPlay.isUPNP)
{
NETremRedirects();
}
return 0;
}
// ////////////////////////////////////////////////////////////////////////
//close the open game..
int NETclose(void)
{
unsigned int i;
// reset flag
NEThaltJoining();
debug(LOG_NET, "Terminating sockets.");
NetPlay.isHost = false;
allow_joining = false;
if(bsocket)
{ // need SocketSet_DelSocket() as well, socket_set or tmp_socket_set?
debug(LOG_NET, "Closing bsocket %p socket %p (tcp_socket=%p)", bsocket, bsocket, tcp_socket);
//socketClose(bsocket);
bsocket=NULL;
}
for(i = 0; i < MAX_CONNECTED_PLAYERS; i++)
{
if (connected_bsocket[i])
{
debug(LOG_NET, "Closing connected_bsocket[%u], %p", i, connected_bsocket[i]);
socketClose(connected_bsocket[i]);
connected_bsocket[i]=NULL;
}
NET_DestroyPlayer(i);
}
if (tmp_socket_set)
{
debug(LOG_NET, "Freeing tmp_socket_set %p", tmp_socket_set);
deleteSocketSet(tmp_socket_set);
tmp_socket_set=NULL;
}
for (i = 0; i < MAX_TMP_SOCKETS; i++)
{
if (tmp_socket[i])
{
// FIXME: need SocketSet_DelSocket() as well, socket_set or tmp_socket_set?
debug(LOG_NET, "Closing tmp_socket[%d] %p", i, tmp_socket[i]);
socketClose(tmp_socket[i]);
tmp_socket[i]=NULL;
}
}
if (socket_set)
{
// checking to make sure tcp_socket is still valid
if (tcp_socket)
{
SocketSet_DelSocket(socket_set, tcp_socket);
}
debug(LOG_NET, "Freeing socket_set %p", socket_set);
deleteSocketSet(socket_set);
socket_set=NULL;
}
if (tcp_socket)
{
debug(LOG_NET, "Closing tcp_socket %p", tcp_socket);
socketClose(tcp_socket);
tcp_socket=NULL;
}
return 0;
}
// ////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////
// Send and Recv functions
// ////////////////////////////////////////////////////////////////////////
// return bytes of data sent recently.
UDWORD NETgetBytesSent(void)
{
static UDWORD lastsec=0;
static UDWORD timy=0;
if( (UDWORD)clock() > (timy+CLOCKS_PER_SEC) )
{
timy = clock();
lastsec = nStats.bytesSent;
nStats.bytesSent = 0;
}
return lastsec;
}
UDWORD NETgetRecentBytesSent(void)
{
return nStats.bytesSent;
}
UDWORD NETgetBytesRecvd(void)
{
static UDWORD lastsec=0;
static UDWORD timy=0;
if( (UDWORD)clock() > (timy+CLOCKS_PER_SEC) )
{
timy = clock();
lastsec = nStats.bytesRecvd;
nStats.bytesRecvd = 0;
}
return lastsec;
}
UDWORD NETgetRecentBytesRecvd(void)
{
return nStats.bytesRecvd;
}
//return number of packets sent last sec.
UDWORD NETgetPacketsSent(void)
{
static UDWORD lastsec=0;
static UDWORD timy=0;
if( (UDWORD)clock() > (timy+CLOCKS_PER_SEC) )
{
timy = clock();
lastsec = nStats.packetsSent;
nStats.packetsSent = 0;
}
return lastsec;
}
UDWORD NETgetRecentPacketsSent(void)
{
return nStats.packetsSent;
}
UDWORD NETgetPacketsRecvd(void)
{
static UDWORD lastsec=0;
static UDWORD timy=0;
if( (UDWORD)clock() > (timy+CLOCKS_PER_SEC) )
{
timy = clock();
lastsec = nStats.packetsRecvd;
nStats.packetsRecvd = 0;
}
return lastsec;
}
// ////////////////////////////////////////////////////////////////////////
// Send a message to a player, option to guarantee message
bool NETsend(uint8_t player, NetMessage const *message)
{
ssize_t result = 0;
if(!NetPlay.bComms)
{
return true;
}
if (player >= MAX_CONNECTED_PLAYERS && player != NET_ALL_PLAYERS) return false;
if (NetPlay.isHost)
{
int firstPlayer = player == NET_ALL_PLAYERS ? 0 : player;
int lastPlayer = player == NET_ALL_PLAYERS ? MAX_CONNECTED_PLAYERS - 1 : player;
for (player = firstPlayer; player <= lastPlayer; ++player)
{
// We are the host, send directly to player.
if (connected_bsocket[player] != NULL)
{
uint8_t *rawData = message->rawDataDup();
ssize_t rawLen = message->rawLen();
result = writeAll(connected_bsocket[player], rawData, rawLen);
delete[] rawData; // Done with the data.
if (result == rawLen)
{
nStats.bytesSent += rawLen;
nStats.packetsSent += 1;
}
else if (result == SOCKET_ERROR)
{
// Write error, most likely client disconnect.
debug(LOG_ERROR, "Failed to send message: %s", strSockError(getSockErr()));
NETlogEntry("client disconnect?", SYNC_FLAG, player);
NETplayerClientDisconnect(player);
}
}
}
return true;
}
else if (player == NetPlay.hostPlayer)
{
// We are a client, send directly to player, who happens to be the host.
if (tcp_socket)
{
uint8_t *rawData = message->rawDataDup();
ssize_t rawLen = message->rawLen();
result = writeAll(tcp_socket, rawData, rawLen);
delete[] rawData; // Done with the data.
if (result == rawLen)
{
nStats.bytesSent += rawLen;
nStats.packetsSent += 1;
}
else if (result == SOCKET_ERROR)
{
// Write error, most likely host disconnect.
debug(LOG_ERROR, "Failed to send message: %s", strSockError(getSockErr()));
debug(LOG_ERROR, "Host connection was broken, socket %p.", tcp_socket);