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