/
i_net.cpp
1065 lines (939 loc) · 24.6 KB
/
i_net.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
//-----------------------------------------------------------------------------
//
// Copyright 1993-1996 id Software
// Copyright 1999-2016 Randy Heit
//
// 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/
//
//-----------------------------------------------------------------------------
//
// DESCRIPTION:
// Low-level networking code. Uses BSD sockets for UDP networking.
//
//-----------------------------------------------------------------------------
/* [Petteri] Check if compiling for Win32: */
#if defined(__WINDOWS__) || defined(__NT__) || defined(_MSC_VER) || defined(_WIN32)
#ifndef __WIN32__
# define __WIN32__
#endif
#endif
/* Follow #ifdef __WIN32__ marks */
#include <stdlib.h>
#include <string.h>
/* [Petteri] Use Winsock for Win32: */
#ifdef __WIN32__
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <winsock.h>
#else
# include <sys/socket.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <errno.h>
# include <unistd.h>
# include <netdb.h>
# include <sys/ioctl.h>
# ifdef __sun
# include <fcntl.h>
# endif
#endif
#include "doomtype.h"
#include "i_system.h"
#include "d_net.h"
#include "m_argv.h"
#include "m_crc32.h"
#include "d_player.h"
#include "st_start.h"
#include "m_misc.h"
#include "doomerrors.h"
#include "atterm.h"
#include "i_net.h"
// As per http://support.microsoft.com/kb/q192599/ the standard
// size for network buffers is 8k.
#define TRANSMIT_SIZE 8000
/* [Petteri] Get more portable: */
#ifndef __WIN32__
typedef int SOCKET;
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#define closesocket close
#define ioctlsocket ioctl
#define Sleep(x) usleep (x * 1000)
#define WSAEWOULDBLOCK EWOULDBLOCK
#define WSAECONNRESET ECONNRESET
#define WSAGetLastError() errno
#endif
#ifndef IPPORT_USERRESERVED
#define IPPORT_USERRESERVED 5000
#endif
#ifdef __WIN32__
typedef int socklen_t;
#endif
//
// NETWORKING
//
static u_short DOOMPORT = (IPPORT_USERRESERVED + 29);
static SOCKET mysocket = INVALID_SOCKET;
static sockaddr_in sendaddress[MAXNETNODES];
static uint8_t sendplayer[MAXNETNODES];
#ifdef __WIN32__
const char *neterror (void);
#else
#define neterror() strerror(errno)
#endif
enum
{
PRE_CONNECT, // Sent from guest to host for initial connection
PRE_KEEPALIVE,
PRE_DISCONNECT, // Sent from guest that aborts the game
PRE_ALLHERE, // Sent from host to guest when everybody has connected
PRE_CONACK, // Sent from host to guest to acknowledge PRE_CONNECT receipt
PRE_ALLFULL, // Sent from host to an unwanted guest
PRE_ALLHEREACK, // Sent from guest to host to acknowledge PRE_ALLHEREACK receipt
PRE_GO // Sent from host to guest to continue game startup
};
// Set PreGamePacket.fake to this so that the game rejects any pregame packets
// after it starts. This translates to NCMD_SETUP|NCMD_MULTI.
#define PRE_FAKE 0x30
struct PreGamePacket
{
uint8_t Fake;
uint8_t Message;
uint8_t NumNodes;
union
{
uint8_t ConsoleNum;
uint8_t NumPresent;
};
struct
{
uint32_t address;
uint16_t port;
uint8_t player;
uint8_t pad;
} machines[MAXNETNODES];
};
uint8_t TransmitBuffer[TRANSMIT_SIZE];
//
// UDPsocket
//
SOCKET UDPsocket (void)
{
SOCKET s;
// allocate a socket
s = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
I_FatalError ("can't create socket: %s", neterror ());
return s;
}
//
// BindToLocalPort
//
void BindToLocalPort (SOCKET s, u_short port)
{
int v;
sockaddr_in address;
memset (&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
v = bind (s, (sockaddr *)&address, sizeof(address));
if (v == SOCKET_ERROR)
I_FatalError ("BindToPort: %s", neterror ());
}
int FindNode (const sockaddr_in *address)
{
int i;
// find remote node number
for (i = 0; i<doomcom.numnodes; i++)
if (address->sin_addr.s_addr == sendaddress[i].sin_addr.s_addr
&& address->sin_port == sendaddress[i].sin_port)
break;
if (i == doomcom.numnodes)
{
// packet is not from one of the players (new game broadcast?)
i = -1;
}
return i;
}
//
// PacketSend
//
void PacketSend (void)
{
int c;
// FIXME: Catch this before we've overflown the buffer. With long chat
// text and lots of backup tics, it could conceivably happen. (Though
// apparently it hasn't yet, which is good.)
if (doomcom.datalength > MAX_MSGLEN)
{
I_FatalError("Netbuffer overflow!");
}
assert(!(doomcom.data[0] & NCMD_COMPRESSED));
uLong size = TRANSMIT_SIZE - 1;
if (doomcom.datalength >= 10)
{
TransmitBuffer[0] = doomcom.data[0] | NCMD_COMPRESSED;
c = compress2(TransmitBuffer + 1, &size, doomcom.data + 1, doomcom.datalength - 1, 9);
size += 1;
}
else
{
c = -1; // Just some random error code to avoid sending the compressed buffer.
}
if (c == Z_OK && size < (uLong)doomcom.datalength)
{
// Printf("send %lu/%d\n", size, doomcom.datalength);
c = sendto(mysocket, (char *)TransmitBuffer, size,
0, (sockaddr *)&sendaddress[doomcom.remotenode],
sizeof(sendaddress[doomcom.remotenode]));
}
else
{
if (doomcom.datalength > TRANSMIT_SIZE)
{
I_Error("Net compression failed (zlib error %d)", c);
}
else
{
// Printf("send %d\n", doomcom.datalength);
c = sendto(mysocket, (char *)doomcom.data, doomcom.datalength,
0, (sockaddr *)&sendaddress[doomcom.remotenode],
sizeof(sendaddress[doomcom.remotenode]));
}
}
// if (c == -1)
// I_Error ("SendPacket error: %s",strerror(errno));
}
//
// PacketGet
//
void PacketGet (void)
{
int c;
socklen_t fromlen;
sockaddr_in fromaddress;
int node;
fromlen = sizeof(fromaddress);
c = recvfrom (mysocket, (char*)TransmitBuffer, TRANSMIT_SIZE, 0,
(sockaddr *)&fromaddress, &fromlen);
node = FindNode (&fromaddress);
if (node >= 0 && c == SOCKET_ERROR)
{
int err = WSAGetLastError();
if (err == WSAECONNRESET)
{ // The remote node aborted unexpectedly, so pretend it sent an exit packet
if (StartScreen != NULL)
{
StartScreen->NetMessage ("The connection from %s was dropped.\n",
players[sendplayer[node]].userinfo.GetName());
}
else
{
Printf("The connection from %s was dropped.\n",
players[sendplayer[node]].userinfo.GetName());
}
doomcom.data[0] = 0x80; // NCMD_EXIT
c = 1;
}
else if (err != WSAEWOULDBLOCK)
{
I_Error ("GetPacket: %s", neterror ());
}
else
{
doomcom.remotenode = -1; // no packet
return;
}
}
else if (node >= 0 && c > 0)
{
doomcom.data[0] = TransmitBuffer[0] & ~NCMD_COMPRESSED;
if (TransmitBuffer[0] & NCMD_COMPRESSED)
{
uLongf msgsize = MAX_MSGLEN - 1;
int err = uncompress(doomcom.data + 1, &msgsize, TransmitBuffer + 1, c - 1);
// Printf("recv %d/%lu\n", c, msgsize + 1);
if (err != Z_OK)
{
Printf("Net decompression failed (zlib error %s)\n", M_ZLibError(err).GetChars());
// Pretend no packet
doomcom.remotenode = -1;
return;
}
c = msgsize + 1;
}
else
{
// Printf("recv %d\n", c);
memcpy(doomcom.data + 1, TransmitBuffer + 1, c - 1);
}
}
else if (c > 0)
{ //The packet is not from any in-game node, so we might as well discard it.
// Don't show the message for disconnect notifications.
if (c != 2 || TransmitBuffer[0] != PRE_FAKE || TransmitBuffer[1] != PRE_DISCONNECT)
{
DPrintf(DMSG_WARNING, "Dropped packet: Unknown host (%s:%d)\n", inet_ntoa(fromaddress.sin_addr), fromaddress.sin_port);
}
doomcom.remotenode = -1;
return;
}
doomcom.remotenode = node;
doomcom.datalength = (short)c;
}
sockaddr_in *PreGet (void *buffer, int bufferlen, bool noabort)
{
static sockaddr_in fromaddress;
socklen_t fromlen;
int c;
fromlen = sizeof(fromaddress);
c = recvfrom (mysocket, (char *)buffer, bufferlen, 0,
(sockaddr *)&fromaddress, &fromlen);
if (c == SOCKET_ERROR)
{
int err = WSAGetLastError();
if (err == WSAEWOULDBLOCK || (noabort && err == WSAECONNRESET))
return NULL; // no packet
I_Error ("PreGet: %s", neterror ());
}
return &fromaddress;
}
void PreSend (const void *buffer, int bufferlen, const sockaddr_in *to)
{
sendto (mysocket, (const char *)buffer, bufferlen, 0, (const sockaddr *)to, sizeof(*to));
}
void BuildAddress (sockaddr_in *address, const char *name)
{
hostent *hostentry; // host information entry
u_short port;
const char *portpart;
bool isnamed = false;
int curchar;
char c;
FString target;
address->sin_family = AF_INET;
if ( (portpart = strchr (name, ':')) )
{
target = FString(name, portpart - name);
port = atoi (portpart + 1);
if (!port)
{
Printf ("Weird port: %s (using %d)\n", portpart + 1, DOOMPORT);
port = DOOMPORT;
}
}
else
{
target = name;
port = DOOMPORT;
}
address->sin_port = htons(port);
for (curchar = 0; (c = target[curchar]) ; curchar++)
{
if ((c < '0' || c > '9') && c != '.')
{
isnamed = true;
break;
}
}
if (!isnamed)
{
address->sin_addr.s_addr = inet_addr (target);
Printf ("Node number %d, address %s\n", doomcom.numnodes, target.GetChars());
}
else
{
hostentry = gethostbyname (target);
if (!hostentry)
I_FatalError ("gethostbyname: couldn't find %s\n%s", target.GetChars(), neterror());
address->sin_addr.s_addr = *(int *)hostentry->h_addr_list[0];
Printf ("Node number %d, hostname %s\n",
doomcom.numnodes, hostentry->h_name);
}
}
void CloseNetwork (void)
{
if (mysocket != INVALID_SOCKET)
{
closesocket (mysocket);
mysocket = INVALID_SOCKET;
}
#ifdef __WIN32__
WSACleanup ();
#endif
}
void StartNetwork (bool autoPort)
{
u_long trueval = 1;
#ifdef __WIN32__
WSADATA wsad;
if (WSAStartup (0x0101, &wsad))
{
I_FatalError ("Could not initialize Windows Sockets");
}
#endif
atterm (CloseNetwork);
netgame = true;
multiplayer = true;
// create communication socket
mysocket = UDPsocket ();
BindToLocalPort (mysocket, autoPort ? 0 : DOOMPORT);
#ifndef __sun
ioctlsocket (mysocket, FIONBIO, &trueval);
#else
fcntl(mysocket, F_SETFL, trueval | O_NONBLOCK);
#endif
}
void SendAbort (void)
{
uint8_t dis[2] = { PRE_FAKE, PRE_DISCONNECT };
int i, j;
if (doomcom.numnodes > 1)
{
if (consoleplayer == 0)
{
// The host needs to let everyone know
for (i = 1; i < doomcom.numnodes; ++i)
{
for (j = 4; j > 0; --j)
{
PreSend (dis, 2, &sendaddress[i]);
}
}
}
else
{
// Guests only need to let the host know.
for (i = 4; i > 0; --i)
{
PreSend (dis, 2, &sendaddress[1]);
}
}
}
}
static void SendConAck (int num_connected, int num_needed)
{
PreGamePacket packet;
packet.Fake = PRE_FAKE;
packet.Message = PRE_CONACK;
packet.NumNodes = num_needed;
packet.NumPresent = num_connected;
for (int node = 1; node < doomcom.numnodes; ++node)
{
PreSend (&packet, 4, &sendaddress[node]);
}
StartScreen->NetProgress (doomcom.numnodes);
}
bool Host_CheckForConnects (void *userdata)
{
PreGamePacket packet;
int numplayers = (int)(intptr_t)userdata;
sockaddr_in *from;
int node;
while ( (from = PreGet (&packet, sizeof(packet), false)) )
{
if (packet.Fake != PRE_FAKE)
{
continue;
}
switch (packet.Message)
{
case PRE_CONNECT:
node = FindNode (from);
if (doomcom.numnodes == numplayers)
{
if (node == -1)
{
const uint8_t *s_addr_bytes = (const uint8_t *)&from->sin_addr;
StartScreen->NetMessage ("Got extra connect from %d.%d.%d.%d:%d",
s_addr_bytes[0], s_addr_bytes[1], s_addr_bytes[2], s_addr_bytes[3],
from->sin_port);
packet.Message = PRE_ALLFULL;
PreSend (&packet, 2, from);
}
}
else
{
if (node == -1)
{
node = doomcom.numnodes++;
sendaddress[node] = *from;
StartScreen->NetMessage ("Got connect from node %d.", node);
}
// Let the new guest (and everyone else) know we got their message.
SendConAck (doomcom.numnodes, numplayers);
}
break;
case PRE_DISCONNECT:
node = FindNode (from);
if (node >= 0)
{
StartScreen->NetMessage ("Got disconnect from node %d.", node);
doomcom.numnodes--;
while (node < doomcom.numnodes)
{
sendaddress[node] = sendaddress[node+1];
node++;
}
// Let remaining guests know that somebody left.
SendConAck (doomcom.numnodes, numplayers);
}
break;
case PRE_KEEPALIVE:
break;
}
}
if (doomcom.numnodes < numplayers)
{
// Send message to everyone as a keepalive
SendConAck(doomcom.numnodes, numplayers);
return false;
}
// It's possible somebody bailed out after all players were found.
// Unfortunately, this isn't guaranteed to catch all of them.
// Oh well. Better than nothing.
while ( (from = PreGet (&packet, sizeof(packet), false)) )
{
if (packet.Fake == PRE_FAKE && packet.Message == PRE_DISCONNECT)
{
node = FindNode (from);
if (node >= 0)
{
doomcom.numnodes--;
while (node < doomcom.numnodes)
{
sendaddress[node] = sendaddress[node+1];
node++;
}
// Let remaining guests know that somebody left.
SendConAck (doomcom.numnodes, numplayers);
}
break;
}
}
return doomcom.numnodes >= numplayers;
}
bool Host_SendAllHere (void *userdata)
{
int *gotack = (int *)userdata; // ackcount is at gotack[MAXNETNODES]
PreGamePacket packet;
int node;
sockaddr_in *from;
// Send out address information to all guests. Guests that have already
// acknowledged receipt effectively get just a heartbeat packet.
packet.Fake = PRE_FAKE;
packet.Message = PRE_ALLHERE;
for (node = 1; node < doomcom.numnodes; node++)
{
int machine, spot = 0;
packet.ConsoleNum = node;
if (!gotack[node])
{
for (spot = 0, machine = 1; machine < doomcom.numnodes; machine++)
{
if (node != machine)
{
packet.machines[spot].address = sendaddress[machine].sin_addr.s_addr;
packet.machines[spot].port = sendaddress[machine].sin_port;
packet.machines[spot].player = node;
spot++; // fixes problem of new address replacing existing address in
// array; it's supposed to increment the index before getting
// and storing in the packet the next address.
}
}
packet.NumNodes = doomcom.numnodes - 2;
}
else
{
packet.NumNodes = 0;
}
PreSend (&packet, 4 + spot*8, &sendaddress[node]);
}
// Check for replies.
while ( (from = PreGet (&packet, sizeof(packet), false)) )
{
if (packet.Fake == PRE_FAKE && packet.Message == PRE_ALLHEREACK)
{
node = FindNode (from);
if (node >= 0)
{
if (!gotack[node])
{
gotack[node] = true;
gotack[MAXNETNODES]++;
}
}
PreSend (&packet, 2, from);
}
}
// If everybody has replied, then this loop can end.
return gotack[MAXNETNODES] == doomcom.numnodes - 1;
}
void HostGame (int i)
{
PreGamePacket packet;
int numplayers;
int node;
int gotack[MAXNETNODES+1];
if ((i == Args->NumArgs() - 1) || !(numplayers = atoi (Args->GetArg(i+1))))
{ // No player count specified, assume 2
numplayers = 2;
}
if (numplayers > MAXNETNODES)
{
I_FatalError("You cannot host a game with %d players. The limit is currently %d.", numplayers, MAXNETNODES);
return;
}
if (numplayers == 1)
{ // Special case: Only 1 player, so don't bother starting the network
netgame = false;
multiplayer = true;
doomcom.id = DOOMCOM_ID;
doomcom.numplayers = doomcom.numnodes = 1;
doomcom.consoleplayer = 0;
return;
}
StartNetwork (false);
// [JC] - this computer is starting the game, therefore it should
// be the Net Arbitrator.
doomcom.consoleplayer = 0;
Printf ("Console player number: %d\n", doomcom.consoleplayer);
doomcom.numnodes = 1;
atterm (SendAbort);
StartScreen->NetInit ("Waiting for players", numplayers);
// Wait for numplayers-1 different connections
if (!StartScreen->NetLoop (Host_CheckForConnects, (void *)(intptr_t)numplayers))
{
exit (0);
}
// Now inform everyone of all machines involved in the game
memset (gotack, 0, sizeof(gotack));
StartScreen->NetMessage ("Sending all here.");
StartScreen->NetInit ("Done waiting", 1);
if (!StartScreen->NetLoop (Host_SendAllHere, (void *)gotack))
{
exit (0);
}
popterm ();
// Now go
StartScreen->NetMessage ("Go");
packet.Fake = PRE_FAKE;
packet.Message = PRE_GO;
for (node = 1; node < doomcom.numnodes; node++)
{
// If we send the packets eight times to each guest,
// hopefully at least one of them will get through.
for (int i = 8; i != 0; --i)
{
PreSend (&packet, 2, &sendaddress[node]);
}
}
StartScreen->NetMessage ("Total players: %d", doomcom.numnodes);
doomcom.id = DOOMCOM_ID;
doomcom.numplayers = doomcom.numnodes;
// On the host, each player's number is the same as its node number
for (i = 0; i < doomcom.numnodes; ++i)
{
sendplayer[i] = i;
}
}
// This routine is used by a guest to notify the host of its presence.
// Once that host acknowledges receipt of the notification, this routine
// is never called again.
bool Guest_ContactHost (void *userdata)
{
sockaddr_in *from;
PreGamePacket packet;
// Let the host know we are here.
packet.Fake = PRE_FAKE;
packet.Message = PRE_CONNECT;
PreSend (&packet, 2, &sendaddress[1]);
// Listen for a reply.
while ( (from = PreGet (&packet, sizeof(packet), true)) )
{
if (packet.Fake == PRE_FAKE && FindNode(from) == 1)
{
if (packet.Message == PRE_CONACK)
{
StartScreen->NetMessage ("Total players: %d", packet.NumNodes);
StartScreen->NetInit ("Waiting for other players", packet.NumNodes);
StartScreen->NetProgress (packet.NumPresent);
return true;
}
else if (packet.Message == PRE_DISCONNECT)
{
doomcom.numnodes = 0;
I_FatalError ("The host cancelled the game.");
}
else if (packet.Message == PRE_ALLFULL)
{
doomcom.numnodes = 0;
I_FatalError ("The game is full.");
}
}
}
// In case the progress bar could not be marqueed, bump it.
StartScreen->NetProgress (0);
return false;
}
bool Guest_WaitForOthers (void *userdata)
{
sockaddr_in *from;
PreGamePacket packet;
while ( (from = PreGet (&packet, sizeof(packet), false)) )
{
if (packet.Fake != PRE_FAKE || FindNode(from) != 1)
{
continue;
}
switch (packet.Message)
{
case PRE_CONACK:
StartScreen->NetProgress (packet.NumPresent);
break;
case PRE_ALLHERE:
if (doomcom.numnodes == 2)
{
int node;
doomcom.numnodes = packet.NumNodes + 2;
sendplayer[0] = packet.ConsoleNum; // My player number
doomcom.consoleplayer = packet.ConsoleNum;
StartScreen->NetMessage ("Console player number: %d", doomcom.consoleplayer);
for (node = 0; node < packet.NumNodes; node++)
{
sendaddress[node+2].sin_addr.s_addr = packet.machines[node].address;
sendaddress[node+2].sin_port = packet.machines[node].port;
sendplayer[node+2] = packet.machines[node].player;
// [JC] - fixes problem of games not starting due to
// no address family being assigned to nodes stored in
// sendaddress[] from the All Here packet.
sendaddress[node+2].sin_family = AF_INET;
}
}
StartScreen->NetMessage ("Received All Here, sending ACK.");
packet.Fake = PRE_FAKE;
packet.Message = PRE_ALLHEREACK;
PreSend (&packet, 2, &sendaddress[1]);
break;
case PRE_GO:
StartScreen->NetMessage ("Received \"Go.\"");
return true;
case PRE_DISCONNECT:
I_FatalError ("The host cancelled the game.");
break;
}
}
packet.Fake = PRE_FAKE;
packet.Message = PRE_KEEPALIVE;
PreSend(&packet, 2, &sendaddress[1]);
return false;
}
void JoinGame (int i)
{
if ((i == Args->NumArgs() - 1) ||
(Args->GetArg(i+1)[0] == '-') ||
(Args->GetArg(i+1)[0] == '+'))
I_FatalError ("You need to specify the host machine's address");
StartNetwork (true);
// Host is always node 1
BuildAddress (&sendaddress[1], Args->GetArg(i+1));
sendplayer[1] = 0;
doomcom.numnodes = 2;
atterm (SendAbort);
// Let host know we are here
StartScreen->NetInit ("Contacting host", 0);
if (!StartScreen->NetLoop (Guest_ContactHost, NULL))
{
exit (0);
}
// Wait for everyone else to connect
if (!StartScreen->NetLoop (Guest_WaitForOthers, 0))
{
exit (0);
}
popterm ();
StartScreen->NetMessage ("Total players: %d", doomcom.numnodes);
doomcom.id = DOOMCOM_ID;
doomcom.numplayers = doomcom.numnodes;
}
static int PrivateNetOf(in_addr in)
{
int addr = ntohl(in.s_addr);
if ((addr & 0xFFFF0000) == 0xC0A80000) // 192.168.0.0
{
return 0xC0A80000;
}
else if ((addr & 0xFFF00000) == 0xAC100000) // 172.16.0.0
{
return 0xAC100000;
}
else if ((addr & 0xFF000000) == 0x0A000000) // 10.0.0.0
{
return 0x0A000000;
}
else if ((addr & 0xFF000000) == 0x7F000000) // 127.0.0.0 (localhost)
{
return 0x7F000000;
}
// Not a private IP
return 0;
}
//
// NodesOnSameNetwork
//
// The best I can really do here is check if the others are on the same
// private network, since that means we (probably) are too.
//
static bool NodesOnSameNetwork()
{
int net1;
net1 = PrivateNetOf(sendaddress[1].sin_addr);
// Printf("net1 = %08x\n", net1);
if (net1 == 0)
{
return false;
}
for (int i = 2; i < doomcom.numnodes; ++i)
{
int net = PrivateNetOf(sendaddress[i].sin_addr);
// Printf("Net[%d] = %08x\n", i, net);
if (net != net1)
{
return false;
}
}
return true;
}
//
// I_InitNetwork
//
// Returns true if packet server mode might be a good idea.
//
bool I_InitNetwork (void)
{
int i;
const char *v;
memset (&doomcom, 0, sizeof(doomcom));
// set up for network
v = Args->CheckValue ("-dup");
if (v)
{
doomcom.ticdup = clamp (atoi (v), 1, MAXTICDUP);
}
else
{
doomcom.ticdup = 1;
}
v = Args->CheckValue ("-port");
if (v)
{
DOOMPORT = atoi (v);
Printf ("using alternate port %i\n", DOOMPORT);
}
// parse network game options,
// player 1: -host <numplayers>
// player x: -join <player 1's address>
if ( (i = Args->CheckParm ("-host")) )
{
HostGame (i);
}
else if ( (i = Args->CheckParm ("-join")) )
{
JoinGame (i);
}
else
{
// single player game
netgame = false;
multiplayer = false;
doomcom.id = DOOMCOM_ID;
doomcom.numplayers = doomcom.numnodes = 1;
doomcom.consoleplayer = 0;
return false;
}
if (doomcom.numnodes < 3)
{ // Packet server mode with only two players is effectively the same as
// peer-to-peer but with some slightly larger packets.
return false;
}
return doomcom.numnodes > 3 || !NodesOnSameNetwork();
}
void I_NetCmd (void)
{
if (doomcom.command == CMD_SEND)
{
PacketSend ();