simulated packet loss (cl_fakepacketloss_receive, cl_fakepacketloss_send, sv_fakepack...
[divverent/darkplaces.git] / netconn.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
5
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 */
22
23 #include "quakedef.h"
24 #include "lhnet.h"
25
26 #define MASTER_PORT 27950
27
28 cvar_t sv_public = {0, "sv_public", "0"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
30
31 static cvar_t sv_masters [] =
32 {
33         {CVAR_SAVE, "sv_master1", ""},
34         {CVAR_SAVE, "sv_master2", ""},
35         {CVAR_SAVE, "sv_master3", ""},
36         {CVAR_SAVE, "sv_master4", ""},
37         {0, "sv_masterextra1", "198.88.152.4"},
38         {0, "sv_masterextra2", "68.102.242.12"},
39         {0, NULL, NULL}
40 };
41
42 static double nextheartbeattime = 0;
43
44 sizebuf_t net_message;
45
46 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
47 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
48 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
49 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
50 cvar_t developer_networking = {0, "developer_networking", "0"};
51
52 cvar_t cl_fakelocalping_min = {0, "cl_fakelocalping_min","0"};
53 cvar_t cl_fakelocalping_max = {0, "cl_fakelocalping_max","0"};
54 static cvar_t cl_fakepacketloss_receive = {0, "cl_fakepacketloss_receive","0"};
55 static cvar_t cl_fakepacketloss_send = {0, "cl_fakepacketloss_send","0"};
56 static cvar_t sv_fakepacketloss_receive = {0, "sv_fakepacketloss_receive","0"};
57 static cvar_t sv_fakepacketloss_send = {0, "sv_fakepacketloss_send","0"};
58
59
60 /* statistic counters */
61 static int packetsSent = 0;
62 static int packetsReSent = 0;
63 static int packetsReceived = 0;
64 static int receivedDuplicateCount = 0;
65 static int droppedDatagrams = 0;
66
67 static int unreliableMessagesSent = 0;
68 static int unreliableMessagesReceived = 0;
69 static int reliableMessagesSent = 0;
70 static int reliableMessagesReceived = 0;
71
72 int hostCacheCount = 0;
73 hostcache_t hostcache[HOSTCACHESIZE];
74
75 static qbyte sendbuffer[NET_MAXMESSAGE];
76 static qbyte readbuffer[NET_MAXMESSAGE];
77
78 int cl_numsockets;
79 lhnetsocket_t *cl_sockets[16];
80 int sv_numsockets;
81 lhnetsocket_t *sv_sockets[16];
82
83 netconn_t *netconn_list = NULL;
84 mempool_t *netconn_mempool = NULL;
85
86 cvar_t cl_netport = {0, "cl_port", "0"};
87 cvar_t cl_netaddress = {0, "cl_netaddress", "0.0.0.0"};
88 cvar_t cl_netaddress_ipv6 = {0, "cl_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:0"};
89
90 cvar_t sv_netport = {0, "port", "26000"};
91 cvar_t sv_netaddress = {0, "sv_netaddress", "0.0.0.0"};
92 cvar_t sv_netaddress_ipv6 = {0, "sv_netaddress_ipv6", "[0:0:0:0:0:0:0:0]:26000"};
93
94 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
95 {
96         int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
97         int i;
98         if (cl_fakepacketloss_receive.integer)
99                 for (i = 0;i < cl_numsockets;i++)
100                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_receive.integer)
101                                 return 0;
102         if (sv_fakepacketloss_receive.integer)
103                 for (i = 0;i < cl_numsockets;i++)
104                         if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_receive.integer)
105                                 return 0;
106         if (developer_networking.integer && length != 0)
107         {
108                 char addressstring[128], addressstring2[128];
109                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
110                 if (length > 0)
111                 {
112                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
113                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
114                         Com_HexDumpToConsole(data, length);
115                 }
116                 else
117                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
118         }
119         return length;
120 }
121
122 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
123 {
124         int ret;
125         int i;
126         if (cl_fakepacketloss_send.integer)
127                 for (i = 0;i < cl_numsockets;i++)
128                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_fakepacketloss_send.integer)
129                                 return length;
130         if (sv_fakepacketloss_send.integer)
131                 for (i = 0;i < cl_numsockets;i++)
132                         if (sv_sockets[i] == mysocket && (rand() % 100) < sv_fakepacketloss_send.integer)
133                                 return length;
134         ret = LHNET_Write(mysocket, data, length, peeraddress);
135         if (developer_networking.integer)
136         {
137                 char addressstring[128], addressstring2[128];
138                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
139                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
140                 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
141                 Com_HexDumpToConsole(data, length);
142         }
143         return ret;
144 }
145
146 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
147 {
148         // note this does not include the trailing NULL because we add that in the parser
149         return NetConn_Write(mysocket, string, strlen(string), peeraddress);
150 }
151
152 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
153 {
154         unsigned int packetLen;
155         unsigned int dataLen;
156         unsigned int eom;
157         unsigned int *header;
158
159 //#ifdef DEBUG
160         if (data->cursize == 0)
161                 Sys_Error("Datagram_SendMessage: zero length message\n");
162
163         if (data->cursize > NET_MAXMESSAGE)
164                 Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize);
165
166         if (conn->canSend == false)
167                 Sys_Error("SendMessage: called with canSend == false\n");
168 //#endif
169
170         memcpy(conn->sendMessage, data->data, data->cursize);
171         conn->sendMessageLength = data->cursize;
172
173         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
174         {
175                 dataLen = conn->sendMessageLength;
176                 eom = NETFLAG_EOM;
177         }
178         else
179         {
180                 dataLen = MAX_PACKETFRAGMENT;
181                 eom = 0;
182         }
183
184         packetLen = NET_HEADERSIZE + dataLen;
185
186         header = (void *)sendbuffer;
187         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
188         header[1] = BigLong(conn->sendSequence);
189         memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
190
191         conn->sendSequence++;
192         conn->canSend = false;
193
194         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
195                 return -1;
196
197         conn->lastSendTime = realtime;
198         packetsSent++;
199         reliableMessagesSent++;
200         return 1;
201 }
202
203 static void NetConn_SendMessageNext(netconn_t *conn)
204 {
205         unsigned int packetLen;
206         unsigned int dataLen;
207         unsigned int eom;
208         unsigned int *header;
209
210         if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
211         {
212                 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
213                 {
214                         dataLen = conn->sendMessageLength;
215                         eom = NETFLAG_EOM;
216                 }
217                 else
218                 {
219                         dataLen = MAX_PACKETFRAGMENT;
220                         eom = 0;
221                 }
222
223                 packetLen = NET_HEADERSIZE + dataLen;
224
225                 header = (void *)sendbuffer;
226                 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
227                 header[1] = BigLong(conn->sendSequence);
228                 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
229
230                 conn->sendSequence++;
231                 conn->sendNext = false;
232
233                 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
234                         return;
235
236                 conn->lastSendTime = realtime;
237                 packetsSent++;
238         }
239 }
240
241 static void NetConn_ReSendMessage(netconn_t *conn)
242 {
243         unsigned int packetLen;
244         unsigned int dataLen;
245         unsigned int eom;
246         unsigned int *header;
247
248         if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
249         {
250                 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
251                 {
252                         dataLen = conn->sendMessageLength;
253                         eom = NETFLAG_EOM;
254                 }
255                 else
256                 {
257                         dataLen = MAX_PACKETFRAGMENT;
258                         eom = 0;
259                 }
260
261                 packetLen = NET_HEADERSIZE + dataLen;
262
263                 header = (void *)sendbuffer;
264                 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
265                 header[1] = BigLong(conn->sendSequence - 1);
266                 memcpy(sendbuffer + 8, conn->sendMessage, dataLen);
267
268                 conn->sendNext = false;
269
270                 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
271                         return;
272
273                 conn->lastSendTime = realtime;
274                 packetsReSent++;
275         }
276 }
277
278 qboolean NetConn_CanSendMessage(netconn_t *conn)
279 {
280         return conn->canSend;
281 }
282
283 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
284 {
285         int packetLen;
286         int *header;
287
288 #ifdef DEBUG
289         if (data->cursize == 0)
290                 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
291
292         if (data->cursize > MAX_DATAGRAM)
293                 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
294 #endif
295
296         packetLen = NET_HEADERSIZE + data->cursize;
297
298         header = (void *)sendbuffer;
299         header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
300         header[1] = BigLong(conn->unreliableSendSequence);
301         memcpy(sendbuffer + 8, data->data, data->cursize);
302
303         conn->unreliableSendSequence++;
304
305         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
306                 return -1;
307
308         packetsSent++;
309         unreliableMessagesSent++;
310         return 1;
311 }
312
313 void NetConn_CloseClientPorts(void)
314 {
315         for (;cl_numsockets > 0;cl_numsockets--)
316                 if (cl_sockets[cl_numsockets - 1])
317                         LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
318 }
319
320 void NetConn_OpenClientPorts(void)
321 {
322         int port;
323         lhnetaddress_t address;
324         NetConn_CloseClientPorts();
325         port = bound(0, cl_netport.integer, 65535);
326         if (cl_netport.integer != port)
327                 Cvar_SetValueQuick(&cl_netport, port);
328         LHNETADDRESS_FromString(&address, "local", port);
329         cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
330         LHNETADDRESS_FromString(&address, cl_netaddress.string, port);
331         cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
332         LHNETADDRESS_FromString(&address, cl_netaddress_ipv6.string, port);
333         cl_sockets[cl_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
334 }
335
336 void NetConn_CloseServerPorts(void)
337 {
338         for (;sv_numsockets > 0;sv_numsockets--)
339                 if (sv_sockets[sv_numsockets - 1])
340                         LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
341 }
342
343 void NetConn_OpenServerPorts(int opennetports)
344 {
345         int port;
346         lhnetaddress_t address;
347         NetConn_CloseServerPorts();
348         port = bound(0, sv_netport.integer, 65535);
349         if (port == 0)
350                 port = 26000;
351         if (sv_netport.integer != port)
352                 Cvar_SetValueQuick(&sv_netport, port);
353         LHNETADDRESS_FromString(&address, "local", port);
354         sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
355         if (opennetports)
356         {
357                 LHNETADDRESS_FromString(&address, sv_netaddress.string, port);
358                 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
359                 LHNETADDRESS_FromString(&address, sv_netaddress_ipv6.string, port);
360                 sv_sockets[sv_numsockets++] = LHNET_OpenSocket_Connectionless(&address);
361         }
362 }
363
364 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
365 {
366         int i, a = LHNETADDRESS_GetAddressType(address);
367         for (i = 0;i < cl_numsockets;i++)
368                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
369                         return cl_sockets[i];
370         return NULL;
371 }
372
373 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
374 {
375         int i, a = LHNETADDRESS_GetAddressType(address);
376         for (i = 0;i < sv_numsockets;i++)
377                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
378                         return sv_sockets[i];
379         return NULL;
380 }
381
382 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
383 {
384         netconn_t *conn;
385         conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
386         conn->mysocket = mysocket;
387         conn->peeraddress = *peeraddress;
388         conn->canSend = true;
389         conn->connecttime = realtime;
390         conn->lastMessageTime = realtime;
391         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
392         // reduce effectiveness of connection request floods
393         conn->timeout = realtime + net_connecttimeout.value;
394         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
395         conn->next = netconn_list;
396         netconn_list = conn;
397         return conn;
398 }
399
400 void NetConn_Close(netconn_t *conn)
401 {
402         netconn_t *c;
403         // remove connection from list
404         if (conn == netconn_list)
405                 netconn_list = conn->next;
406         else
407         {
408                 for (c = netconn_list;c;c = c->next)
409                 {
410                         if (c->next == conn)
411                         {
412                                 c->next = conn->next;
413                                 break;
414                         }
415                 }
416                 // not found in list, we'll avoid crashing here...
417                 if (!c)
418                         return;
419         }
420         // free connection
421         Mem_Free(conn);
422 }
423
424 static int clientport = -1;
425 static int clientport2 = -1;
426 static int hostport = -1;
427 static void NetConn_UpdateServerStuff(void)
428 {
429         if (clientport2 != cl_netport.integer)
430         {
431                 clientport2 = cl_netport.integer;
432                 if (cls.state == ca_connected)
433                         Con_Printf("Changing \"cl_port\" will not take effect until you reconnect.\n");
434         }
435         if (cls.state != ca_dedicated)
436         {
437                 if (cls.state == ca_disconnected && clientport != cl_netport.integer)
438                 {
439                         clientport = cl_netport.integer;
440                         NetConn_CloseClientPorts();
441                 }
442                 if (cl_numsockets == 0)
443                         NetConn_OpenClientPorts();
444         }
445
446         if (hostport != sv_netport.integer)
447         {
448                 hostport = sv_netport.integer;
449                 if (sv.active)
450                         Con_Printf("Changing \"port\" will not take effect until \"map\" command is executed.\n");
451         }
452 }
453
454 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
455 {
456         unsigned int count;
457         unsigned int flags;
458         unsigned int sequence;
459
460         if (length >= 8)
461         {
462                 length = BigLong(((int *)data)[0]);
463                 flags = length & ~NETFLAG_LENGTH_MASK;
464                 length &= NETFLAG_LENGTH_MASK;
465                 // control packets were already handled
466                 if (!(flags & NETFLAG_CTL))
467                 {
468                         sequence = BigLong(((int *)data)[1]);
469                         packetsReceived++;
470                         data += 8;
471                         length -= 8;
472                         if (flags & NETFLAG_UNRELIABLE)
473                         {
474                                 if (sequence >= conn->unreliableReceiveSequence)
475                                 {
476                                         if (sequence > conn->unreliableReceiveSequence)
477                                         {
478                                                 count = sequence - conn->unreliableReceiveSequence;
479                                                 droppedDatagrams += count;
480                                                 Con_DPrintf("Dropped %u datagram(s)\n", count);
481                                         }
482                                         conn->unreliableReceiveSequence = sequence + 1;
483                                         conn->lastMessageTime = realtime;
484                                         conn->timeout = realtime + net_messagetimeout.value;
485                                         unreliableMessagesReceived++;
486                                         if (length > 0)
487                                         {
488                                                 SZ_Clear(&net_message);
489                                                 SZ_Write(&net_message, data, length);
490                                                 MSG_BeginReading();
491                                                 return 2;
492                                         }
493                                 }
494                                 else
495                                         Con_DPrintf("Got a stale datagram\n");
496                                 return 1;
497                         }
498                         else if (flags & NETFLAG_ACK)
499                         {
500                                 if (sequence == (conn->sendSequence - 1))
501                                 {
502                                         if (sequence == conn->ackSequence)
503                                         {
504                                                 conn->ackSequence++;
505                                                 if (conn->ackSequence != conn->sendSequence)
506                                                         Con_DPrintf("ack sequencing error\n");
507                                                 conn->lastMessageTime = realtime;
508                                                 conn->timeout = realtime + net_messagetimeout.value;
509                                                 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
510                                                 if (conn->sendMessageLength > 0)
511                                                 {
512                                                         memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
513                                                         conn->sendNext = true;
514                                                         NetConn_SendMessageNext(conn);
515                                                 }
516                                                 else
517                                                 {
518                                                         conn->sendMessageLength = 0;
519                                                         conn->canSend = true;
520                                                 }
521                                         }
522                                         else
523                                                 Con_DPrintf("Duplicate ACK received\n");
524                                 }
525                                 else
526                                         Con_DPrintf("Stale ACK received\n");
527                                 return 1;
528                         }
529                         else if (flags & NETFLAG_DATA)
530                         {
531                                 unsigned int temppacket[2];
532                                 temppacket[0] = BigLong(8 | NETFLAG_ACK);
533                                 temppacket[1] = BigLong(sequence);
534                                 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
535                                 if (sequence == conn->receiveSequence)
536                                 {
537                                         conn->lastMessageTime = realtime;
538                                         conn->timeout = realtime + net_messagetimeout.value;
539                                         conn->receiveSequence++;
540                                         memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
541                                         conn->receiveMessageLength += length;
542                                         if (flags & NETFLAG_EOM)
543                                         {
544                                                 reliableMessagesReceived++;
545                                                 length = conn->receiveMessageLength;
546                                                 conn->receiveMessageLength = 0;
547                                                 if (length > 0)
548                                                 {
549                                                         SZ_Clear(&net_message);
550                                                         SZ_Write(&net_message, conn->receiveMessage, length);
551                                                         MSG_BeginReading();
552                                                         return 2;
553                                                 }
554                                         }
555                                 }
556                                 else
557                                         receivedDuplicateCount++;
558                                 return 1;
559                         }
560                 }
561         }
562         return 0;
563 }
564
565 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
566 {
567         cls.netcon = NetConn_Open(mysocket, peeraddress);
568         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
569         key_dest = key_game;
570         m_state = m_none;
571         cls.connect_trying = false;
572         cls.demonum = -1;                       // not in the demo loop now
573         cls.state = ca_connected;
574         cls.signon = 0;                         // need all the signon messages before playing
575         CL_ClearState();
576         Host_Reconnect_f();
577 }
578
579 int NetConn_IsLocalGame(void)
580 {
581         int i;
582         if (cls.state == ca_connected && sv.active/* && LHNETADDRESS_GetAddressType(cl.netcon->peeraddress) == LHNETADDRESSTYPE_LOOP*/)
583         {
584                 // make sure there are no other connected clients
585                 for (i = 1;i < MAX_SCOREBOARD;i++)
586                         if (svs.connectedclients[i])
587                                 return false;
588                 return true;
589         }
590         return false;
591 }
592
593 static struct
594 {
595         double senttime;
596         lhnetaddress_t peeraddress;
597 }
598 pingcache[HOSTCACHESIZE];
599
600 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
601 {
602         int ret, c, control;
603         lhnetaddress_t svaddress;
604         const char *s;
605         char *string, addressstring2[128], cname[128], ipstring[32];
606         char stringbuf[16384];
607
608         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
609         {
610                 // received a command string - strip off the packaging and put it
611                 // into our string buffer with NULL termination
612                 data += 4;
613                 length -= 4;
614                 length = min(length, (int)sizeof(stringbuf) - 1);
615                 memcpy(stringbuf, data, length);
616                 stringbuf[length] = 0;
617                 string = stringbuf;
618
619                 if (developer.integer)
620                 {
621                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
622                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
623                         Com_HexDumpToConsole(data, length);
624                 }
625
626                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
627                 {
628                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
629                         Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
630                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
631                         return true;
632                 }
633                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
634                 {
635                         NetConn_ConnectionEstablished(mysocket, peeraddress);
636                         return true;
637                 }
638                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
639                 {
640                         cls.connect_trying = false;
641                         string += 7;
642                         length = max(length - 7, (int)sizeof(m_return_reason) - 1);
643                         memcpy(m_return_reason, string, length);
644                         m_return_reason[length] = 0;
645                         Con_Printf("%s\n", m_return_reason);
646                         return true;
647                 }
648                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
649                 {
650                         int i, j, c, n, users, maxusers;
651                         char game[32], mod[32], map[32], name[128];
652                         double pingtime;
653                         hostcache_t temp;
654                         string += 13;
655                         // hostcache only uses text addresses
656                         LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
657                         // search the cache for this server
658                         for (n = 0; n < hostCacheCount; n++)
659                                 if (!strcmp(cname, hostcache[n].cname))
660                                         break;
661                         // add it or update it
662                         if (n == hostCacheCount)
663                         {
664                                 // if cache is full replace highest ping server (the list is
665                                 // kept sorted so this is always the last, and if this server
666                                 // is good it will be sorted into an early part of the list)
667                                 if (hostCacheCount >= HOSTCACHESIZE)
668                                         n = hostCacheCount - 1;
669                                 else
670                                         hostCacheCount++;
671                         }
672                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strncpy(game, s, sizeof(game) - 1);else game[0] = 0;
673                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strncpy(mod , s, sizeof(mod ) - 1);else mod[0] = 0;
674                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strncpy(map , s, sizeof(map ) - 1);else map[0] = 0;
675                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strncpy(name, s, sizeof(name) - 1);else name[0] = 0;
676                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) c = atoi(s);else c = -1;
677                         if ((s = SearchInfostring(string, "clients"      )) != NULL) users = atoi(s);else users = 0;
678                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) maxusers = atoi(s);else maxusers = 0;
679                         pingtime = 9999;
680                         for (i = 0;i < HOSTCACHESIZE;i++)
681                                 if (!LHNETADDRESS_Compare(peeraddress, &pingcache[i].peeraddress))
682                                         pingtime = (int)(realtime - pingcache[i].senttime);
683                         pingtime = bound(0, pingtime, 9999);
684                         memset(&hostcache[n], 0, sizeof(hostcache[n]));
685                         // store the data the engine cares about (address and ping)
686                         strcpy(hostcache[n].cname, cname);
687                         hostcache[n].ping = pingtime;
688                         // build description strings for the things users care about
689                         snprintf(hostcache[n].line1, sizeof(hostcache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, c != NET_PROTOCOL_VERSION ? '*' : ' ', users, maxusers, name);
690                         snprintf(hostcache[n].line2, sizeof(hostcache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", cname, game, mod, map);
691                         // if ping is especially high, display it as such
692                         if (pingtime >= 300)
693                         {
694                                 // orange numbers (lower block)
695                                 for (i = 0;i < 5;i++)
696                                         if (hostcache[n].line1[i] != ' ')
697                                                 hostcache[n].line1[i] += 128;
698                         }
699                         else if (pingtime >= 200)
700                         {
701                                 // yellow numbers (in upper block)
702                                 for (i = 0;i < 5;i++)
703                                         if (hostcache[n].line1[i] != ' ')
704                                                 hostcache[n].line1[i] -= 30;
705                         }
706                         // if not in the slist menu we should print the server to console
707                         if (m_state != m_slist)
708                                 Con_Printf("%s\n%s\n", hostcache[n].line1, hostcache[n].line2);
709                         // and finally, re-sort the list
710                         for (i = 0;i < hostCacheCount;i++)
711                         {
712                                 for (j = i + 1;j < hostCacheCount;j++)
713                                 {
714                                         //if (strcmp(hostcache[j].name, hostcache[i].name) < 0)
715                                         if (hostcache[i].ping > hostcache[j].ping)
716                                         {
717                                                 memcpy(&temp, &hostcache[j], sizeof(hostcache_t));
718                                                 memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t));
719                                                 memcpy(&hostcache[i], &temp, sizeof(hostcache_t));
720                                         }
721                                 }
722                         }
723                         return true;
724                 }
725                 if (!strncmp(string, "getserversResponse\\", 19) && hostCacheCount < HOSTCACHESIZE)
726                 {
727                         int i, best;
728                         double besttime;
729                         // Extract the IP addresses
730                         data += 18;
731                         length -= 18;
732                         while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
733                         {
734                                 sprintf(ipstring, "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
735                                 if (developer.integer)
736                                         Con_Printf("Requesting info from server %s\n", ipstring);
737                                 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
738                                 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
739                                 // replace oldest or matching entry in ping cache
740                                 // we scan this later when getting a reply to see how long it took
741                                 besttime = realtime;
742                                 best = 0;
743                                 for (i = 0;i < HOSTCACHESIZE;i++)
744                                 {
745                                         if (!LHNETADDRESS_Compare(&svaddress, &pingcache[i].peeraddress))
746                                         {
747                                                 best = i;
748                                                 break;
749                                         }
750                                         if (besttime > pingcache[i].senttime)
751                                         {
752                                                 besttime = pingcache[i].senttime;
753                                                 best = i;
754                                                 // if ping cache isn't full yet we can skip out early
755                                                 if (!besttime)
756                                                         break;
757                                         }
758                                 }
759                                 pingcache[best].peeraddress = svaddress;
760                                 pingcache[best].senttime = realtime;
761                                 // move on to next address in packet
762                                 data += 7;
763                                 length -= 7;
764                         }
765                         return true;
766                 }
767                 /*
768                 if (!strncmp(string, "ping", 4))
769                 {
770                         if (developer.integer)
771                                 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
772                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
773                         return true;
774                 }
775                 if (!strncmp(string, "ack", 3))
776                         return true;
777                 */
778                 // we may not have liked the packet, but it was a command packet, so
779                 // we're done processing this packet now
780                 return true;
781         }
782         // netquake control packets, supported for compatibility only
783         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
784         {
785                 c = data[4];
786                 data += 5;
787                 length -= 5;
788                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
789                 switch (c)
790                 {
791                 case CCREP_ACCEPT:
792                         if (developer.integer)
793                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
794                         if (cls.connect_trying)
795                         {
796                                 lhnetaddress_t clientportaddress;
797                                 clientportaddress = *peeraddress;
798                                 if (length >= 4)
799                                 {
800                                         unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
801                                         data += 4;
802                                         length -= 4;
803                                         LHNETADDRESS_SetPort(&clientportaddress, port);
804                                 }
805                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
806                         }
807                         break;
808                 case CCREP_REJECT:
809                         if (developer.integer)
810                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
811                         Con_Printf("%s\n", data);
812                         strncpy(m_return_reason, data, sizeof(m_return_reason) - 1);
813                         break;
814 #if 0
815                 case CCREP_SERVER_INFO:
816                         if (developer.integer)
817                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
818                         if (cls.state != ca_dedicated)
819                         {
820                                 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
821                                 // string we just ignore it and keep the real address
822                                 MSG_ReadString();
823                                 // hostcache only uses text addresses
824                                 cname = UDP_AddrToString(readaddr);
825                                 // search the cache for this server
826                                 for (n = 0; n < hostCacheCount; n++)
827                                         if (!strcmp(cname, hostcache[n].cname))
828                                                 break;
829                                 // add it
830                                 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
831                                 {
832                                         hostCacheCount++;
833                                         memset(&hostcache[n], 0, sizeof(hostcache[n]));
834                                         strcpy(hostcache[n].name, MSG_ReadString());
835                                         strcpy(hostcache[n].map, MSG_ReadString());
836                                         hostcache[n].users = MSG_ReadByte();
837                                         hostcache[n].maxusers = MSG_ReadByte();
838                                         c = MSG_ReadByte();
839                                         if (c != NET_PROTOCOL_VERSION)
840                                         {
841                                                 strncpy(hostcache[n].cname, hostcache[n].name, sizeof(hostcache[n].cname) - 1);
842                                                 hostcache[n].cname[sizeof(hostcache[n].cname) - 1] = 0;
843                                                 strcpy(hostcache[n].name, "*");
844                                                 strncat(hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name) - 1);
845                                                 hostcache[n].name[sizeof(hostcache[n].name) - 1] = 0;
846                                         }
847                                         strcpy(hostcache[n].cname, cname);
848                                 }
849                         }
850                         break;
851                 case CCREP_PLAYER_INFO:
852                         // we got a CCREP_PLAYER_INFO??
853                         //if (developer.integer)
854                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
855                         break;
856                 case CCREP_RULE_INFO:
857                         // we got a CCREP_RULE_INFO??
858                         //if (developer.integer)
859                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
860                         break;
861 #endif
862                 default:
863                         break;
864                 }
865                 // we may not have liked the packet, but it was a valid control
866                 // packet, so we're done processing this packet now
867                 return true;
868         }
869         ret = 0;
870         if (length >= (int)NET_HEADERSIZE && cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress) && (ret = NetConn_ReceivedMessage(cls.netcon, data, length)) == 2)
871                 CL_ParseServerMessage();
872         return ret;
873 }
874
875 void NetConn_ClientFrame(void)
876 {
877         int i, length;
878         lhnetaddress_t peeraddress;
879         netconn_t *conn;
880         NetConn_UpdateServerStuff();
881         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
882         {
883                 if (cls.connect_remainingtries == 0)
884                 {
885                         cls.connect_trying = false;
886                         Host_Error("Connect failed\n");
887                         return;
888                 }
889                 if (cls.connect_nextsendtime)
890                         Con_Printf("Still trying...\n");
891                 else
892                         Con_Printf("Trying...\n");
893                 cls.connect_nextsendtime = realtime + 1;
894                 cls.connect_remainingtries--;
895                 // try challenge first (newer server)
896                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
897                 // then try netquake as a fallback (old server, or netquake)
898                 SZ_Clear(&net_message);
899                 // save space for the header, filled in later
900                 MSG_WriteLong(&net_message, 0);
901                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
902                 MSG_WriteString(&net_message, "QUAKE");
903                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
904                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
905                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
906                 SZ_Clear(&net_message);
907         }
908         for (i = 0;i < cl_numsockets;i++)
909                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
910                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
911         if (cls.netcon && realtime > cls.netcon->timeout)
912         {
913                 Con_Printf("Connection timed out\n");
914                 CL_Disconnect();
915         }
916         for (conn = netconn_list;conn;conn = conn->next)
917                 NetConn_ReSendMessage(conn);
918 }
919
920 #define MAX_CHALLENGES 128
921 struct
922 {
923         lhnetaddress_t address;
924         double time;
925         char string[12];
926 }
927 challenge[MAX_CHALLENGES];
928
929 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
930 {
931         int i;
932         char c;
933         for (i = 0;i < bufferlength - 1;i++)
934         {
935                 do
936                 {
937                         c = rand () % (127 - 33) + 33;
938                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
939                 buffer[i] = c;
940         }
941         buffer[i] = 0;
942 }
943
944 extern void SV_ConnectClient(int clientnum, netconn_t *netconnection);
945 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
946 {
947         int i, n, ret, clientnum, responselength, best, clientcount;
948         double besttime;
949         client_t *client;
950         netconn_t *conn;
951         char *s, *string, response[512], addressstring2[128], stringbuf[16384];
952
953         if (sv.active)
954         {
955                 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
956                 {
957                         // received a command string - strip off the packaging and put it
958                         // into our string buffer with NULL termination
959                         data += 4;
960                         length -= 4;
961                         length = min(length, (int)sizeof(stringbuf) - 1);
962                         memcpy(stringbuf, data, length);
963                         stringbuf[length] = 0;
964                         string = stringbuf;
965
966                         if (developer.integer)
967                         {
968                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
969                                 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
970                                 Com_HexDumpToConsole(data, length);
971                         }
972
973                         if (length >= 12 && !memcmp(string, "getchallenge", 12))
974                         {
975                                 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
976                                 {
977                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
978                                                 break;
979                                         if (besttime > challenge[i].time)
980                                                 besttime = challenge[best = i].time;
981                                 }
982                                 // if we did not find an exact match, choose the oldest and
983                                 // update address and string
984                                 if (i == MAX_CHALLENGES)
985                                 {
986                                         i = best;
987                                         challenge[i].address = *peeraddress;
988                                         NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
989                                 }
990                                 challenge[i].time = realtime;
991                                 // send the challenge
992                                 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
993                                 return true;
994                         }
995                         if (length > 8 && !memcmp(string, "connect\\", 8))
996                         {
997                                 string += 7;
998                                 length -= 7;
999                                 if ((s = SearchInfostring(string, "challenge")))
1000                                 {
1001                                         // validate the challenge
1002                                         for (i = 0;i < MAX_CHALLENGES;i++)
1003                                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1004                                                         break;
1005                                         if (i < MAX_CHALLENGES)
1006                                         {
1007                                                 // check engine protocol
1008                                                 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1009                                                 {
1010                                                         if (developer.integer)
1011                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1012                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1013                                                 }
1014                                                 else
1015                                                 {
1016                                                         // see if this is a duplicate connection request
1017                                                         for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1018                                                                 if ((client = svs.connectedclients[clientnum]) && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1019                                                                         break;
1020                                                         if (clientnum < MAX_SCOREBOARD)
1021                                                         {
1022                                                                 // duplicate connection request
1023                                                                 if (realtime - client->netconnection->connecttime < 2.0)
1024                                                                 {
1025                                                                         // client is still trying to connect,
1026                                                                         // so we send a duplicate reply
1027                                                                         if (developer.integer)
1028                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1029                                                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1030                                                                 }
1031                                                                 // only kick if old connection seems dead
1032                                                                 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1033                                                                 {
1034                                                                         // kick off connection and await retry
1035                                                                         client->deadsocket = true;
1036                                                                 }
1037                                                         }
1038                                                         else
1039                                                         {
1040                                                                 // this is a new client, find a slot
1041                                                                 for (clientcount = 0, clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1042                                                                         if (svs.connectedclients[clientnum])
1043                                                                                 clientcount++;
1044                                                                 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1045                                                                         if (!svs.connectedclients[clientnum])
1046                                                                                 break;
1047                                                                 if (clientcount < max(1, sv_maxplayers.integer) && clientnum < MAX_SCOREBOARD)
1048                                                                 {
1049                                                                         // allocate and prepare the client struct
1050                                                                         if ((client = Mem_Alloc(sv_clients_mempool, sizeof(client_t))))
1051                                                                         {
1052                                                                                 if ((client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool)))
1053                                                                                 {
1054                                                                                         if ((conn = NetConn_Open(mysocket, peeraddress)))
1055                                                                                         {
1056                                                                                                 // allocated connection
1057                                                                                                 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1058                                                                                                 if (developer.integer)
1059                                                                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1060                                                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1061                                                                                                 // now set up the client struct
1062                                                                                                 svs.connectedclients[clientnum] = client;
1063                                                                                                 SV_ConnectClient(clientnum, conn);
1064                                                                                                 NetConn_Heartbeat(1);
1065                                                                                         }
1066                                                                                         else
1067                                                                                         {
1068                                                                                                 EntityFrame4_FreeDatabase(client->entitydatabase4);
1069                                                                                                 Mem_Free(client);
1070                                                                                         }
1071                                                                                 }
1072                                                                                 else
1073                                                                                         Mem_Free(client);
1074                                                                         }
1075                                                                 }
1076                                                                 else
1077                                                                 {
1078                                                                         // server is full
1079                                                                         if (developer.integer)
1080                                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1081                                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1082                                                                 }
1083                                                         }
1084                                                 }
1085                                         }
1086                                 }
1087                                 return true;
1088                         }
1089                         if (length >= 7 && !memcmp(string, "getinfo", 7))
1090                         {
1091                                 const char *challenge = NULL;
1092                                 // If there was a challenge in the getinfo message
1093                                 if (length > 8 && string[7] == ' ')
1094                                         challenge = string + 8;
1095                                 for (i = 0, n = 0;i < MAX_SCOREBOARD;i++)
1096                                         if (svs.connectedclients[i])
1097                                                 n++;
1098                                 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1099                                                         "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1100                                                         "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1101                                                         gamename, com_modname, min(sv_maxplayers.integer, MAX_SCOREBOARD), n,
1102                                                         sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1103                                 // does it fit in the buffer?
1104                                 if (responselength < (int)sizeof(response))
1105                                 {
1106                                         if (developer.integer)
1107                                                 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1108                                         NetConn_WriteString(mysocket, response, peeraddress);
1109                                 }
1110                                 return true;
1111                         }
1112                         /*
1113                         if (!strncmp(string, "ping", 4))
1114                         {
1115                                 if (developer.integer)
1116                                         Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1117                                 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1118                                 return true;
1119                         }
1120                         if (!strncmp(string, "ack", 3))
1121                                 return true;
1122                         */
1123                         // we may not have liked the packet, but it was a command packet, so
1124                         // we're done processing this packet now
1125                         return true;
1126                 }
1127                 // LordHavoc: disabled netquake control packet support in server
1128 #if 0
1129                 {
1130                         int c, control;
1131                         // netquake control packets, supported for compatibility only
1132                         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1133                         {
1134                                 c = data[4];
1135                                 data += 5;
1136                                 length -= 5;
1137                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1138                                 switch (c)
1139                                 {
1140                                 case CCREQ_CONNECT:
1141                                         //if (developer.integer)
1142                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1143                                         if (length >= (int)strlen("QUAKE") + 1 + 1)
1144                                         {
1145                                                 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1146                                                 {
1147                                                         if (developer.integer)
1148                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1149                                                         SZ_Clear(&net_message);
1150                                                         // save space for the header, filled in later
1151                                                         MSG_WriteLong(&net_message, 0);
1152                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1153                                                         MSG_WriteString(&net_message, "Incompatible version.\n");
1154                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1155                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1156                                                         SZ_Clear(&net_message);
1157                                                 }
1158                                                 else
1159                                                 {
1160                                                         // see if this is a duplicate connection request
1161                                                         for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1162                                                                 if ((client = svs.connectedclients[clientnum]) && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1163                                                                         break;
1164                                                         if (clientnum < MAX_SCOREBOARD)
1165                                                         {
1166                                                                 // duplicate connection request
1167                                                                 if (realtime - client->netconnection->connecttime < 2.0)
1168                                                                 {
1169                                                                         // client is still trying to connect,
1170                                                                         // so we send a duplicate reply
1171                                                                         if (developer.integer)
1172                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1173                                                                         SZ_Clear(&net_message);
1174                                                                         // save space for the header, filled in later
1175                                                                         MSG_WriteLong(&net_message, 0);
1176                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1177                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1178                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1179                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1180                                                                         SZ_Clear(&net_message);
1181                                                                 }
1182                                                                 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1183                                                                 {
1184                                                                         // the old client hasn't sent us anything
1185                                                                         // in quite a while, so kick off and let
1186                                                                         // the retry take care of it...
1187                                                                         client->deadsocket = true;
1188                                                                 }
1189                                                         }
1190                                                         else
1191                                                         {
1192                                                                 // this is a new client, find a slot
1193                                                                 for (clientnum = 0;clientnum < MAX_SCOREBOARD;clientnum++)
1194                                                                         if (!(client = svs.connectedclients[clientnum]))
1195                                                                                 break;
1196                                                                 // WARNING: this is broken code
1197                                                                 if (clientnum < MAX_SCOREBOARD && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1198                                                                 {
1199                                                                         // connect to the client
1200                                                                         // everything is allocated, just fill in the details
1201                                                                         strcpy(conn->address, addressstring2);
1202                                                                         if (developer.integer)
1203                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1204                                                                         // send back the info about the server connection
1205                                                                         SZ_Clear(&net_message);
1206                                                                         // save space for the header, filled in later
1207                                                                         MSG_WriteLong(&net_message, 0);
1208                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1209                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1210                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1211                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1212                                                                         SZ_Clear(&net_message);
1213                                                                         // now set up the client struct
1214                                                                         SV_ConnectClient(clientnum, conn);
1215                                                                         NetConn_Heartbeat(1);
1216                                                                 }
1217                                                                 else
1218                                                                 {
1219                                                                         //if (developer.integer)
1220                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1221                                                                         // no room; try to let player know
1222                                                                         SZ_Clear(&net_message);
1223                                                                         // save space for the header, filled in later
1224                                                                         MSG_WriteLong(&net_message, 0);
1225                                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1226                                                                         MSG_WriteString(&net_message, "Server is full.\n");
1227                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1228                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1229                                                                         SZ_Clear(&net_message);
1230                                                                 }
1231                                                         }
1232                                                 }
1233                                         }
1234                                         break;
1235 #if 0
1236                                 case CCREQ_SERVER_INFO:
1237                                         if (developer.integer)
1238                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1239                                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1240                                         {
1241                                                 if (developer.integer)
1242                                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1243                                                 SZ_Clear(&net_message);
1244                                                 // save space for the header, filled in later
1245                                                 MSG_WriteLong(&net_message, 0);
1246                                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1247                                                 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1248                                                 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1249                                                 MSG_WriteString(&net_message, hostname.string);
1250                                                 MSG_WriteString(&net_message, sv.name);
1251                                                 MSG_WriteByte(&net_message, net_activeconnections);
1252                                                 MSG_WriteByte(&net_message, min(sv_maxplayers.integer, MAX_SCOREBOARD));
1253                                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1254                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1255                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1256                                                 SZ_Clear(&net_message);
1257                                         }
1258                                         break;
1259                                 case CCREQ_PLAYER_INFO:
1260                                         if (developer.integer)
1261                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1262                                         if (sv.active)
1263                                         {
1264                                                 int playerNumber, activeNumber, clientNumber;
1265                                                 client_t *client;
1266
1267                                                 playerNumber = MSG_ReadByte();
1268                                                 activeNumber = -1;
1269                                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1270                                                         if (client->active && ++activeNumber == playerNumber)
1271                                                                 break;
1272                                                 if (clientNumber != svs.maxclients)
1273                                                 {
1274                                                         SZ_Clear(&net_message);
1275                                                         // save space for the header, filled in later
1276                                                         MSG_WriteLong(&net_message, 0);
1277                                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1278                                                         MSG_WriteByte(&net_message, playerNumber);
1279                                                         MSG_WriteString(&net_message, client->name);
1280                                                         MSG_WriteLong(&net_message, client->colors);
1281                                                         MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1282                                                         MSG_WriteLong(&net_message, (int)(realtime - client->netconnection->connecttime));
1283                                                         MSG_WriteString(&net_message, client->netconnection->address);
1284                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1285                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1286                                                         SZ_Clear(&net_message);
1287                                                 }
1288                                         }
1289                                         break;
1290                                 case CCREQ_RULE_INFO:
1291                                         if (developer.integer)
1292                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1293                                         if (sv.active)
1294                                         {
1295                                                 char *prevCvarName;
1296                                                 cvar_t *var;
1297
1298                                                 // find the search start location
1299                                                 prevCvarName = MSG_ReadString();
1300                                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1301
1302                                                 // send the response
1303                                                 SZ_Clear(&net_message);
1304                                                 // save space for the header, filled in later
1305                                                 MSG_WriteLong(&net_message, 0);
1306                                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1307                                                 if (var)
1308                                                 {
1309                                                         MSG_WriteString(&net_message, var->name);
1310                                                         MSG_WriteString(&net_message, var->string);
1311                                                 }
1312                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1313                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1314                                                 SZ_Clear(&net_message);
1315                                         }
1316                                         break;
1317 #endif
1318                                 default:
1319                                         break;
1320                                 }
1321                                 // we may not have liked the packet, but it was a valid control
1322                                 // packet, so we're done processing this packet now
1323                                 return true;
1324                         }
1325                 }
1326 #endif
1327                 for (i = 0;i < MAX_SCOREBOARD;i++)
1328                 {
1329                         if ((host_client = svs.connectedclients[i]))
1330                         {
1331                                 if (host_client->netconnection)
1332                                 {
1333                                         if (host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1334                                         {
1335                                                 sv_player = host_client->edict;
1336                                                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1337                                                         SV_ReadClientMessage();
1338                                                 return ret;
1339                                         }
1340                                 }
1341                                 else
1342                                 {
1343                                         Con_Printf("Removing client with no netconnection!\n");
1344                                         SV_DropClient(true);
1345                                 }
1346                         }
1347                 }
1348         }
1349         return 0;
1350 }
1351
1352 void NetConn_ServerFrame(void)
1353 {
1354         int i, length;
1355         lhnetaddress_t peeraddress;
1356         netconn_t *conn;
1357         NetConn_UpdateServerStuff();
1358         for (i = 0;i < sv_numsockets;i++)
1359                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1360                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1361         for (i = 0;i < MAX_SCOREBOARD;i++)
1362         {
1363                 if ((host_client = svs.connectedclients[i]) && realtime > host_client->netconnection->timeout)
1364                 {
1365                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1366                         sv_player = host_client->edict;
1367                         SV_DropClient(false);
1368                 }
1369         }
1370         for (conn = netconn_list;conn;conn = conn->next)
1371                 NetConn_ReSendMessage(conn);
1372 }
1373
1374 void NetConn_QueryMasters(void)
1375 {
1376         int i;
1377         int masternum;
1378         lhnetaddress_t masteraddress;
1379         char request[256];
1380
1381         if (hostCacheCount >= HOSTCACHESIZE)
1382                 return;
1383
1384         for (i = 0;i < cl_numsockets;i++)
1385         {
1386                 if (cl_sockets[i])
1387                 {
1388 #if 0
1389                         // search LAN
1390 #if 1
1391                         UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1392 #else
1393                         SZ_Clear(&net_message);
1394                         // save space for the header, filled in later
1395                         MSG_WriteLong(&net_message, 0);
1396                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1397                         MSG_WriteString(&net_message, "QUAKE");
1398                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1399                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1400                         UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1401                         SZ_Clear(&net_message);
1402 #endif
1403 #endif
1404
1405                         // build the getservers
1406                         snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1407
1408                         // search internet
1409                         for (masternum = 0;sv_masters[masternum].name;masternum++)
1410                                 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1411                                         NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1412                 }
1413         }
1414 }
1415
1416 void NetConn_Heartbeat(int priority)
1417 {
1418         lhnetaddress_t masteraddress;
1419         int masternum;
1420         lhnetsocket_t *mysocket;
1421
1422         // if it's a state change (client connected), limit next heartbeat to no
1423         // more than 30 sec in the future
1424         if (priority == 1 && nextheartbeattime > realtime + 30.0)
1425                 nextheartbeattime = realtime + 30.0;
1426
1427         // limit heartbeatperiod to 30 to 270 second range,
1428         // lower limit is to avoid abusing master servers with excess traffic,
1429         // upper limit is to avoid timing out on the master server (which uses
1430         // 300 sec timeout)
1431         if (sv_heartbeatperiod.value < 30)
1432                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1433         if (sv_heartbeatperiod.value > 270)
1434                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1435
1436         // make advertising optional and don't advertise singleplayer games, and
1437         // only send a heartbeat as often as the admin wants
1438         if (sv.active && sv_public.integer && (!cl.islocalgame || sv_maxplayers.integer >= 2) && (priority > 1 || realtime > nextheartbeattime))
1439         {
1440                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1441                 for (masternum = 0;sv_masters[masternum].name;masternum++)
1442                         if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1443                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1444         }
1445 }
1446
1447 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1448 {
1449         int i, count = 0;
1450         qbyte sent[MAX_SCOREBOARD];
1451
1452         memset(sent, 0, sizeof(sent));
1453
1454         // simultaneously wait for the first CanSendMessage and send the message,
1455         // then wait for a second CanSendMessage (verifying it was received), or
1456         // the client drops and is no longer counted
1457         // the loop aborts when either it runs out of clients to send to, or a
1458         // timeout expires
1459         blocktime += Sys_DoubleTime();
1460         do
1461         {
1462                 count = 0;
1463                 NetConn_ClientFrame();
1464                 NetConn_ServerFrame();
1465                 for (i = 0;i < MAX_SCOREBOARD;i++)
1466                 {
1467                         if ((host_client = svs.connectedclients[i]))
1468                         {
1469                                 if (NetConn_CanSendMessage(host_client->netconnection))
1470                                 {
1471                                         if (!sent[i])
1472                                                 NetConn_SendReliableMessage(host_client->netconnection, data);
1473                                         sent[i] = true;
1474                                 }
1475                                 if (!NetConn_CanSendMessage(host_client->netconnection))
1476                                         count++;
1477                         }
1478                 }
1479         }
1480         while (count && Sys_DoubleTime() < blocktime);
1481         return count;
1482 }
1483
1484 static void Net_Heartbeat_f(void)
1485 {
1486         NetConn_Heartbeat(2);
1487 }
1488
1489 void PrintStats(netconn_t *conn)
1490 {
1491         Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1492 }
1493
1494 void Net_Stats_f(void)
1495 {
1496         netconn_t *conn;
1497         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
1498         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
1499         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
1500         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1501         Con_Printf("packetsSent                = %i\n", packetsSent);
1502         Con_Printf("packetsReSent              = %i\n", packetsReSent);
1503         Con_Printf("packetsReceived            = %i\n", packetsReceived);
1504         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
1505         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
1506         Con_Printf("connections                =\n");
1507         for (conn = netconn_list;conn;conn = conn->next)
1508                 PrintStats(conn);
1509 }
1510
1511 void Net_Slist_f(void)
1512 {
1513         hostCacheCount = 0;
1514         memset(&pingcache, 0, sizeof(pingcache));
1515         if (m_state != m_slist)
1516                 Con_Printf("Sending requests to master servers\n");
1517         NetConn_QueryMasters();
1518         if (m_state != m_slist)
1519                 Con_Printf("Listening for replies...\n");
1520 }
1521
1522 void NetConn_Init(void)
1523 {
1524         int masternum;
1525         netconn_mempool = Mem_AllocPool("Networking");
1526         Cmd_AddCommand("net_stats", Net_Stats_f);
1527         Cmd_AddCommand("net_slist", Net_Slist_f);
1528         Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1529         Cvar_RegisterVariable(&net_messagetimeout);
1530         Cvar_RegisterVariable(&net_messagerejointimeout);
1531         Cvar_RegisterVariable(&net_connecttimeout);
1532         Cvar_RegisterVariable(&cl_fakelocalping_min);
1533         Cvar_RegisterVariable(&cl_fakelocalping_max);
1534         Cvar_RegisterVariable(&cl_fakepacketloss_receive);
1535         Cvar_RegisterVariable(&cl_fakepacketloss_send);
1536         Cvar_RegisterVariable(&sv_fakepacketloss_receive);
1537         Cvar_RegisterVariable(&sv_fakepacketloss_send);
1538         Cvar_RegisterVariable(&hostname);
1539         Cvar_RegisterVariable(&developer_networking);
1540         Cvar_RegisterVariable(&cl_netport);
1541         Cvar_RegisterVariable(&cl_netaddress);
1542         Cvar_RegisterVariable(&cl_netaddress_ipv6);
1543         Cvar_RegisterVariable(&sv_netport);
1544         Cvar_RegisterVariable(&sv_netaddress);
1545         Cvar_RegisterVariable(&sv_netaddress_ipv6);
1546         Cvar_RegisterVariable(&sv_public);
1547         Cvar_RegisterVariable(&sv_heartbeatperiod);
1548         for (masternum = 0;sv_masters[masternum].name;masternum++)
1549                 Cvar_RegisterVariable(&sv_masters[masternum]);
1550         cl_numsockets = 0;
1551         sv_numsockets = 0;
1552         memset(&pingcache, 0, sizeof(pingcache));
1553         SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1554         LHNET_Init();
1555 }
1556
1557 void NetConn_Shutdown(void)
1558 {
1559         NetConn_CloseClientPorts();
1560         NetConn_CloseServerPorts();
1561         LHNET_Shutdown();
1562 }
1563