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