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