/
sys_network.c
1866 lines (1586 loc) · 47.1 KB
/
sys_network.c
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
/**\file
*\section License
* License: GPL
* Online License Link: http://www.gnu.org/licenses/gpl.html
*
*\author Copyright © 2003-2011 Jaakko Keränen <jaakko.keranen@iki.fi>
*\author Copyright © 2006-2011 Daniel Swanson <danij@dengine.net>
*\author Copyright © 2006-2007 Jamie Jones <jamie_jones_au@yahoo.com.au>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/**
* sys_network.c: Low-Level Sockets Networking
*
* TCP sockets are periodically polled for activity (Net_Update ->
* N_Listen).
*/
// HEADER FILES ------------------------------------------------------------
#ifdef DENG_SDLNET_DUMMY
# include "sdlnet_dummy.h"
#else
# include <SDL_net.h>
#endif
#include <errno.h>
#ifndef WIN32
#include <signal.h>
#endif
#include "de_base.h"
#include "de_network.h"
#include "de_console.h"
#include "de_system.h"
#include "de_misc.h"
#include "de_play.h"
// MACROS ------------------------------------------------------------------
/**
* The randomized transmitted is only used for simulating a poor
* network connection.
*/
#undef TRANSMIT_RANDOMIZER
#define RANDOMIZER_DROP_PERCENT 25
#define RANDOMIZER_MAX_DELAY 500
#define MAX_NODES 32
#define MAX_DATAGRAM_SIZE 1300
#define DEFAULT_TRANSMISSION_SIZE 4096
// TYPES -------------------------------------------------------------------
#if 0
/**
* Each network node has a send queue. The queue contains a number of
* sqpacks.
*/
typedef struct sqpack_s {
struct sqpack_s *next;
struct netnode_s *node;
UDPpacket *packet;
#ifdef TRANSMIT_RANDOMIZER
// The packet won't be sent until this time.
uint dueTime;
#endif
} sqpack_t;
#endif
/**
* On serverside, each client has its own network node. A node
* represents the TCP connection between the client and the server. On
* clientside, the node zero is used always.
*/
typedef struct netnode_s {
TCPsocket sock;
char name[256];
// The node is owned by a client in the game. This becomes true
// when the client issues the JOIN request.
boolean hasJoined;
// This is the client's remote address.
IPaddress addr;
#if 0
// Send queue statistics.
long mutex;
uint numWaiting;
uint bytesWaiting;
#endif
} netnode_t;
#if 0
typedef struct sendqueue_s {
long waiting;
long mutex;
sqpack_t *first, *last;
boolean online; // Set to false to make transmitter stop.
} sendqueue_t;
#endif
typedef struct foundhost_s {
boolean valid;
serverinfo_t info;
IPaddress addr;
} foundhost_t;
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
void N_IPToString(char *buf, IPaddress *ip);
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
static int C_DECL N_JoinedListenerThread(void* param);
// EXTERNAL DATA DECLARATIONS ----------------------------------------------
// PUBLIC DATA DEFINITIONS -------------------------------------------------
size_t maxDatagramSize = MAX_DATAGRAM_SIZE;
char *nptIPAddress = "";
int nptIPPort = 0; // This is the port *we* use to communicate.
int defaultTCPPort = DEFAULT_TCP_PORT;
#if 0
int nptUDPPort = 0;
int defaultUDPPort = DEFAULT_UDP_PORT;
#endif
// Operating mode of the currently active service provider.
boolean netIsActive = false;
boolean netServerMode = false;
// PRIVATE DATA DEFINITIONS ------------------------------------------------
static TCPsocket serverSock;
//static volatile UDPsocket inSock;
//static Uint16 recvUDPPort;
//static mutex_t mutexInSock;
static netnode_t netNodes[MAX_NODES];
static SDLNet_SocketSet sockSet;
static SDLNet_SocketSet joinedSockSet;
static mutex_t mutexJoinedSockSet;
//static thread_t hTransmitter;
static thread_t joinedListener;
static volatile boolean stopJoinedListener;
//static sendqueue_t sendQ;
static foundhost_t located;
//static volatile boolean stopReceiver;
static byte* transmissionBuffer;
static size_t transmissionBufferSize;
// CODE --------------------------------------------------------------------
void N_Register(void)
{
C_VAR_CHARPTR("net-ip-address", &nptIPAddress, 0, 0, 0);
C_VAR_INT("net-ip-port", &nptIPPort, CVF_NO_MAX, 0, 0);
}
static void N_StartJoinedListener(void)
{
Con_Message("N_StartJoinedListener.\n");
stopJoinedListener = false;
joinedListener = Sys_StartThread(N_JoinedListenerThread, 0);
}
static void N_StopJoinedListener(void)
{
if(joinedListener)
{
Con_Message("N_StopJoinedListener.\n");
stopJoinedListener = true;
Sys_WaitThread(joinedListener);
joinedListener = 0;
}
}
#if 0
/**
* Free any packets still waiting in the queue.
*/
static void N_ClearQueue(sendqueue_t *q)
{
sqpack_t *pack;
while((pack = q->first) != NULL)
{
q->first = pack->next;
SDLNet_FreePacket(pack->packet);
M_Free(pack);
}
}
/**
* Send the packet using UDP. If the packet is associated with no
* node, nothing will be sent because we don't know the destination
* address.
*/
static void N_UDPSend(sqpack_t *pack)
{
if(!pack->node)
return;
#ifdef PRINT_PACKETS
{
char buf[80];
N_IPToString(buf, &pack->packet->address);
Con_Message("Send: len=%i to %s\n", pack->packet->len, buf);
}
#endif
if(pack->node->hasJoined)
{
// Commence sending.
SDLNet_UDP_Send(inSock, -1, pack->packet);
}
// Update the node's counters.
Sem_P(pack->node->mutex);
pack->node->numWaiting--;
pack->node->bytesWaiting -= pack->packet->len;
Sem_V(pack->node->mutex);
}
#ifdef TRANSMIT_RANDOMIZER
/**
* The randomized version of the UDP transmitter. This can be used to
* simulate a real-life connection where UDP packets are received
* sometimes in the wrong order or get lost entirely.
*/
static int C_DECL N_UDPTransmitter(void *parm)
{
sendqueue_t *q = parm;
sqpack_t *pack;
uint nowTime = 0;
// When using the randomized transmitter, the send queue is always
// sorted by the due times.
while(q->online)
{
// If there are packets waiting, see if they should be sent now.
Sem_P(q->mutex);
nowTime = Sys_GetRealTime();
while((pack = q->first) != NULL)
{
if(pack->dueTime > nowTime)
{
// Too early.
break;
}
// Remove the packet from the queue.
q->first = pack->next;
N_UDPSend(pack);
// Now that the packet has been sent, we can discard the data.
SDLNet_FreePacket(pack->packet);
M_Free(pack);
}
Sem_V(q->mutex);
// Sleep for a short while before starting another loop.
Sys_Sleep(2);
}
N_ClearQueue(q);
return 0;
}
#else /* !TRANSMIT_RANDOMIZER */
/**
* A UDP transmitter thread takes messages off a network node's send
* queue and sends them one by one. On serverside, each client has its
* own transmitter thread.
*
* 'parm' is a pointer to the network node of this transmitter.
*/
static int C_DECL N_UDPTransmitter(void *parm)
{
sendqueue_t *q = parm;
sqpack_t *pack;
while(q->online)
{
// We will wait until there are messages to send. The
// semaphore is incremented when a new message is added to the
// queue. Waiting for this semaphore causes us to sleep
// until there are messages to send.
Sem_P(q->waiting);
// Lock the send queue.
Sem_P(q->mutex);
// There should be a message waiting.
if(!q->online || !q->first)
{
Sem_V(q->mutex);
continue;
}
// Extract the next message from the FIFO queue.
pack = q->first;
q->first = q->first->next;
if(!q->first)
q->last = NULL;
// Release the send queue.
Sem_V(q->mutex);
N_UDPSend(pack);
// Now that the packet has been sent, we can discard the data.
SDLNet_FreePacket(pack->packet);
M_Free(pack);
}
// Free any packets still waiting in the queue.
N_ClearQueue(q);
return 0;
}
#endif
/**
* The UDP receiver thread waits for UDP packets and places them into
* the incoming message buffer. The UDP receiver is started when the
* TCP/IP service is initialized. The thread is stopped when the
* service is shut down.
*/
static int C_DECL N_UDPReceiver(void *parm)
{
SDLNet_SocketSet set;
UDPpacket *packet = NULL;
// Put the UDP socket in our socket set so we can wait for it.
set = SDLNet_AllocSocketSet(1);
SDLNet_UDP_AddSocket(set, inSock);
while(!stopReceiver)
{
// Most of the time we will be sleeping here, waiting for
// incoming packets.
while(SDLNet_CheckSockets(set, 250) > 0)
{
// There is activity on the socket. Allocate a new packet
// to store the data into. The packet will be released later,
// in N_ReturnBuffer.
if(!packet)
{
// Allocate a new packet.
packet = SDLNet_AllocPacket((int) maxDatagramSize);
}
// The mutex will prevent problems when new channels are
// bound to the socket.
Sys_Lock(mutexInSock);
if(SDLNet_UDP_Recv(inSock, packet) > 0)
{
netmessage_t *msg = NULL;
Sys_Unlock(mutexInSock);
#ifdef PRINT_PACKETS
{
char buf[80];
N_IPToString(buf, &packet->address);
Con_Message("Recv: ch=%i len=%i %s\n", packet->channel,
packet->len, buf);
}
#endif
// If we don't know the sender, discard the packet.
if(packet->channel < 0)
continue;
// Successfully received a packet.
msg = (netmessage_t *) M_Calloc(sizeof(netmessage_t));
msg->sender = packet->channel;
msg->data = packet->data;
msg->size = packet->len;
msg->handle = packet;
// The message queue will handle the message from now on.
N_PostMessage(msg);
// This packet has now been used.
packet = NULL;
}
else
{
Sys_Unlock(mutexInSock);
continue;
}
}
}
if(packet)
SDLNet_FreePacket(packet);
SDLNet_FreeSocketSet(set);
return 0;
}
#endif
/**
* Free a message buffer.
*/
void N_ReturnBuffer(void *handle)
{
if(handle)
{
M_Free(handle);
}
}
/**
* Read a packet from the TCP connection and put it in the incoming
* packet queue. This function blocks until the entire packet has
* been read, so large packets should be avoided during normal
* gameplay.
*
* Returns true if a packet was successfully received.
*/
boolean N_ReceiveReliably(nodeid_t from)
{
ushort size = 0;
TCPsocket sock = netNodes[from].sock;
int bytes = 0;
boolean error, read;
char* packet = 0;
// \todo What if we get one byte? How come we are here if there's nothing to receive?
if((bytes = SDLNet_TCP_Recv(sock, &size, 2)) != 2)
{
//int number = errno;
//Con_Message("N_ReceiveReliably: Packet header was truncated. Got %i bytes.\n", bytes);
//Con_Message(" Error: %s (%s)\n", SDLNet_GetError(), strerror(number));
return false;
}
size = SHORT(size);
// Read the entire packet's data.
packet = M_Malloc(size);
bytes = 0;
read = false;
error = false;
while(!read)
{
int received = SDLNet_TCP_Recv(sock, packet + bytes, size - bytes);
if(received == -1)
{
//int number = errno;
M_Free(packet);
packet = 0;
/*Con_Message("N_ReceiveReliably: Error during TCP recv.\n %s (%s)\n",
SDLNet_GetError(), strerror(number));*/
error = true;
read = true;
}
bytes += received;
if(bytes == size)
read = true;
assert(bytes <= size);
}
if(error)
return false;
// Post the received message.
{
netmessage_t *msg = M_Calloc(sizeof(netmessage_t));
msg->sender = from;
msg->data = (byte*) packet;
msg->size = size;
msg->handle = packet;
/*#ifdef _DEBUG
VERBOSE2(Con_Message("N_ReceiveReliably: Posting message, from=%i, size=%i\n", from, size));
#endif*/
// The message queue will handle the message from now on.
N_PostMessage(msg);
}
return true;
}
/**
* Send the data buffer over the control link, which is a TCP
* connection.
*/
void N_SendDataBufferReliably(void *data, size_t size, nodeid_t destination)
{
int result = 0;
netnode_t *node = &netNodes[destination];
short packetSize = 0;
if(size == 0 || !node->sock || !node->hasJoined)
return;
if(size > DDMAXSHORT)
{
Con_Error("N_SendDataBufferReliably: Trying to send a too large data "
"buffer.\n Attempted size is %lu bytes.\n", (unsigned long) size);
}
// Resize the buffer to fit the entire message + size short.
if(transmissionBufferSize < size + 2)
{
transmissionBufferSize = size + 2;
transmissionBuffer = M_Realloc(transmissionBuffer, size + 2);
}
// Compose the message into the transmission buffer.
packetSize = SHORT(size);
memcpy(transmissionBuffer, &packetSize, 2);
memcpy(transmissionBuffer + 2, data, size);
// Send the data over the socket.
result = SDLNet_TCP_Send(node->sock, transmissionBuffer, (int) size + 2);
#ifdef _DEBUG
VERBOSE2( Con_Message("N_SendDataBufferReliably: Sent %lu bytes, result=%i\n",
(unsigned long) (size + 2), result) );
#endif
if((size_t)result != size + 2)
{
perror("Socket error");
}
}
#if 0
/**
* Send the buffer to the destination. For clients, the server is the only
* possible destination (doesn't depend on the value of 'destination').
*/
void N_SendDataBuffer(void *data, size_t size, nodeid_t destination)
{
sqpack_t *pack;
UDPpacket *p;
netnode_t *node;
// If the send queue is not active, we can't send anything.
if(!sendQ.online)
return;
#ifdef TRANSMIT_RANDOMIZER
// There is a chance that the packet is dropped.
if(RNG_RandFloat() < RANDOMIZER_DROP_PERCENT / 100.0)
{
VERBOSE( Con_Message("N_SendDataBuffer: Randomizer dropped packet to %i "
"(%lu bytes).\n", destination,
(unsigned long) size) );
return;
}
#endif
if(size > maxDatagramSize)
{
Con_Error("N_SendDataBuffer: Too large packet (%lu), risk of "
"fragmentation (MTU=%lu).\n", (unsigned long) size,
(unsigned long) maxDatagramSize);
}
// This memory is freed after the packet is sent.
pack = M_Malloc(sizeof(sqpack_t));
p = pack->packet = SDLNet_AllocPacket((int) size);
// The destination node.
pack->node = node = netNodes + destination;
// Init the packet's data.
p->channel = -1;
memcpy(p->data, data, (int) size);
p->len = (int) size;
memcpy(&p->address, &node->addr, sizeof(p->address));
#ifdef TRANSMIT_RANDOMIZER
pack->dueTime = Sys_GetRealTime() + RNG_RandFloat() * RANDOMIZER_MAX_DELAY;
#endif
// Add the packet to the send queue.
Sem_P(sendQ.mutex);
#ifndef TRANSMIT_RANDOMIZER
if(!sendQ.first)
{
sendQ.first = sendQ.last = pack;
}
else
{
sendQ.last->next = pack;
sendQ.last = pack;
}
pack->next = NULL;
#else
// Insertion sort.
if(sendQ.first)
{
// Does the new packet come before all others?
if(pack->dueTime < sendQ.first->dueTime)
{
pack->next = sendQ.first;
sendQ.first = pack;
}
else
{
// Find the packet after which the new packet belongs.
sqpack_t *i = sendQ.first;
for(; i; i = i->next)
{
if(!i->next || i->next->dueTime >= pack->dueTime)
{
// Add after this one.
pack->next = i->next;
i->next = pack;
break;
}
}
}
}
else
{
sendQ.first = pack;
pack->next = NULL;
}
#endif
Sem_V(sendQ.mutex);
// Increment the statistics.
Sem_P(node->mutex);
node->numWaiting++;
node->bytesWaiting += (uint) size;
Sem_V(node->mutex);
// Signal the transmitter to start working.
Sem_V(sendQ.waiting);
}
/**
* @return The number of messages waiting in the player's send
* queue.
*/
uint N_GetSendQueueCount(int player)
{
netnode_t *node = netNodes + player;
uint count;
Sem_P(node->mutex);
count = node->numWaiting;
Sem_V(node->mutex);
return count;
}
/**
* @return The number of bytes waiting in the player's send
* queue.
*/
uint N_GetSendQueueSize(int player)
{
netnode_t *node = netNodes + player;
uint bytes;
Sem_P(node->mutex);
bytes = node->bytesWaiting;
Sem_V(node->mutex);
return bytes;
}
/**
* Blocks until all the send queues have been emptied.
*/
void N_FlushOutgoing(void)
{
int i;
boolean allClear = false;
while(!allClear)
{
allClear = true;
for(i = 0; i < DDMAXPLAYERS; ++i)
if(netNodes[i].hasJoined && N_GetSendQueueCount(i))
allClear = false;
Sys_Sleep(5);
}
}
/**
* Initialize the transmitter thread and the send queue.
*/
static void N_StartTransmitter(sendqueue_t *q)
{
q->online = true;
q->waiting = Sem_Create(0);
q->mutex = Sem_Create(1);
q->first = NULL;
q->last = NULL;
hTransmitter = Sys_StartThread(N_UDPTransmitter, q);
}
/**
* Blocks until the transmitter thread has been exited.
*/
static void N_StopTransmitter(sendqueue_t *q)
{
uint i;
if(!hTransmitter)
return;
// Tell the transmitter to stop sending.
q->online = false;
// Increment the semaphore without adding a new message: this'll
// make the transmitter "run dry."
for(i = 0; i < 10; ++i)
Sem_V(q->waiting);
// Wait until the transmitter thread finishes.
Sys_WaitThread(hTransmitter);
hTransmitter = NULL;
// Destroy the semaphores.
Sem_Destroy(q->waiting);
Sem_Destroy(q->mutex);
}
/**
* Start the UDP receiver thread.
*/
static void N_StartReceiver(void)
{
stopReceiver = false;
mutexInSock = Sys_CreateMutex("UDPIncomingMutex");
hReceiver = Sys_StartThread(N_UDPReceiver, NULL);
}
/**
* Blocks until the UDP receiver thread has exited.
*/
static void N_StopReceiver(void)
{
// Wait for the receiver thread the stop.
stopReceiver = true;
Sys_WaitThread(hReceiver);
hReceiver = 0;
// Close the incoming UDP socket.
SDLNet_UDP_Close(inSock);
inSock = NULL;
Sys_DestroyMutex(mutexInSock);
mutexInSock = 0;
}
/**
* Bind or unbind the address to/from the incoming UDP socket. When
* the address is bound, packets from it will be accepted.
*/
void N_BindIncoming(IPaddress *addr, nodeid_t id)
{
if(!inSock)
return;
Sys_Lock(mutexInSock);
if(addr)
{
SDLNet_UDP_Bind(inSock, id, addr);
}
else
{
SDLNet_UDP_Unbind(inSock, id);
}
Sys_Unlock(mutexInSock);
}
#endif
/**
* Initialize the low-level network subsystem. This is called always
* during startup (via Sys_Init()).
*/
void N_SystemInit(void)
{
// The MTU can be customized.
if(ArgCheckWith("-mtu", 1))
{
maxDatagramSize = (size_t) strtol(ArgNext(), NULL, 0);
Con_Message("N_SystemInit: Custom MTU: %lu bytes.\n", (unsigned long) maxDatagramSize);
}
// Allocate the transmission buffer.
transmissionBufferSize = DEFAULT_TRANSMISSION_SIZE;
transmissionBuffer = M_Malloc(transmissionBufferSize);
}
/**
* Shut down the low-level network interface. Called during engine
* shutdown (not before).
*/
void N_SystemShutdown(void)
{
M_Free(transmissionBuffer);
transmissionBuffer = NULL;
transmissionBufferSize = 0;
N_ShutdownService();
}
/**
* Convert an IPaddress to a string.
*/
void N_IPToString(char *buf, IPaddress *ip)
{
uint host = SDLNet_Read32(&ip->host);
sprintf(buf, "%i.%i.%i.%i:%i", host >> 24, (host >> 16) & 0xff,
(host >> 8) & 0xff, host & 0xff, SDLNet_Read16(&ip->port));
}
#if 0
/**
* Opens an UDP socket. The used port number is returned. If the
* socket cannot be opened, 'sock' is set to NULL. 'defaultPort'
* should never be zero.
*/
Uint16 N_OpenUDPSocket(UDPsocket *sock, Uint16 preferPort, Uint16 defaultPort)
{
Uint16 port = (!preferPort ? defaultPort : preferPort);
*sock = NULL;
if((*sock = SDLNet_UDP_Open(port)) != NULL)
return port;
#ifdef _DEBUG
Con_Message("N_OpenUDPSocket: Failed to open UDP socket %i.\n", port);
Con_Message(" (%s)\n", SDLNet_GetError());
#endif
return 0; // Failure!
}
#endif
/**
* Initialize the chosen service provider each in server or client
* mode. If a service provider has already been initialized, it will
* be shut down first. Returns true if successful.
*/
boolean N_InitService(boolean inServerMode)
{
IPaddress ip;
uint16_t port;
if(N_IsAvailable() && netServerMode == inServerMode)
{
// Nothing to change.
return true;
}
// Get rid of the currently active service provider.
N_ShutdownService();
if(!SDLNet_Init())
{
VERBOSE(Con_Message("N_InitService: SDLNet_Init OK\n"));
}
else
{
Con_Message("N_InitService: SDLNet_Init %s\n", SDLNet_GetError());
}
// Mutex for the socket set.
mutexJoinedSockSet = Sys_CreateMutex("sockSet");
if(inServerMode)
{
port = (!nptIPPort ? defaultTCPPort : nptIPPort);
Con_Message("N_InitService: Listening TCP socket on port %i.\n", port);
// Open a listening TCP socket. It will accept client
// connections.
if(SDLNet_ResolveHost(&ip, NULL, port))
{
Con_Message("N_InitService: %s\n", SDLNet_GetError());
return false;
}
if(!(serverSock = SDLNet_TCP_Open(&ip)))
{
Con_Message("N_InitService: %s\n", SDLNet_GetError());
return false;
}
memcpy(&netNodes[0].addr, &ip, sizeof(ip));
// Allocate socket sets, which we'll use for listening to the
// client sockets.
if(!(sockSet = SDLNet_AllocSocketSet(MAX_NODES)))
{
Con_Message("N_InitService: %s\n", SDLNet_GetError());
return false;
}
if(!(joinedSockSet = SDLNet_AllocSocketSet(MAX_NODES)))
{
Con_Message("N_InitService: %s\n", SDLNet_GetError());
return false;
}
// We can start the listener immediately.
N_StartJoinedListener();
}
else
{
// Let's forget about servers found earlier.
located.valid = false;
}
#if 0
// Open the socket that will be used for UDP communications.
recvUDPPort = N_OpenUDPSocket((UDPsocket *) &inSock, nptUDPPort, defaultUDPPort);
Con_Message("N_InitService: In/out UDP port %i.\n", recvUDPPort);
#endif
// Success.
netIsActive = true;
netServerMode = inServerMode;
#if 0
// Did we fail in opening the UDP port?
if(!inSock)
{
Con_Message("N_InitService: Failed to open in/out UDP port.\n");
Con_Message(" %s\n", SDLNet_GetError());
N_ShutdownService();
return false;
}
// Start the UDP receiver right away.
N_StartReceiver();
// Start the UDP transmitter.
N_StartTransmitter(&sendQ);
#endif
return true;
}
/**
* Shut down the TCP/IP network services.
*/
void N_ShutdownService(void)
{
uint i;
if(!N_IsAvailable())
return; // Nothing to do.
if(netGame)
{
// We seem to be shutting down while a netGame is running.
Con_Execute(CMDS_DDAY, isServer ? "net server close" : "net disconnect", true, false);
}
// Any queued messages will be destroyed.
N_ClearMessages();
#if 0
// Kill the transmission threads.
N_StopTransmitter(&sendQ);
N_StopReceiver();