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