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