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