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