removed crash parameter from Host_ShudownServer, eliminated NetConn_SendToAll and...
[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 // note this defaults on for dedicated servers, off for listen servers
29 cvar_t sv_public = {0, "sv_public", "0", "advertises this server on the master server (so that players can find it in the server browser)"};
30 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
31
32 // FIXME: resolve DNS on masters whenever their value changes and cache it (to avoid major delays in active servers when they heartbeat)
33 static cvar_t sv_masters [] =
34 {
35         {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
36         {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
37         {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
38         {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
39         {0, "sv_masterextra1", "ghdigital.com", "default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
40         {0, "sv_masterextra2", "dpmaster.deathmask.net", "default master server 2 (admin: Willis)"}, // admin: Willis
41         {0, "sv_masterextra3", "12.166.196.192", "default master server 3 (admin: Venim)"}, // admin: Venim
42         {0, "sv_masterextra4", "excalibur.nvg.ntnu.no", "default master server 4 (admin: tChr)"}, // admin: tChr
43         {0, NULL, NULL, NULL}
44 };
45
46 static double nextheartbeattime = 0;
47
48 sizebuf_t net_message;
49 static unsigned char net_message_buf[NET_MAXMESSAGE];
50
51 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
52 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10", "give a player this much time in seconds to rejoin and continue playing (not losing frags and such)"};
53 cvar_t net_connecttimeout = {0, "net_connecttimeout","10", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods)"};
54 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
55 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
56
57 cvar_t cl_netlocalping = {0, "cl_netlocalping","0", "lags local loopback connection by this much ping time (useful to play more fairly on your own server with people with higher pings)"};
58 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0", "drops this percentage of packets (incoming and outgoing), useful for testing network protocol robustness (effects failing to start, sounds failing to play, etc)"};
59 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
60 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", "maximum number of server information requests to send each rendered frame (guards against low framerates causing problems)"};
61 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
62 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
63
64 /* statistic counters */
65 static int packetsSent = 0;
66 static int packetsReSent = 0;
67 static int packetsReceived = 0;
68 static int receivedDuplicateCount = 0;
69 static int droppedDatagrams = 0;
70
71 static int unreliableMessagesSent = 0;
72 static int unreliableMessagesReceived = 0;
73 static int reliableMessagesSent = 0;
74 static int reliableMessagesReceived = 0;
75
76 double masterquerytime = -1000;
77 int masterquerycount = 0;
78 int masterreplycount = 0;
79 int serverquerycount = 0;
80 int serverreplycount = 0;
81
82 // this is only false if there are still servers left to query
83 int serverlist_querysleep = true;
84
85 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
86 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
87
88 int cl_numsockets;
89 lhnetsocket_t *cl_sockets[16];
90 int sv_numsockets;
91 lhnetsocket_t *sv_sockets[16];
92
93 netconn_t *netconn_list = NULL;
94 mempool_t *netconn_mempool = NULL;
95
96 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
97 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
98 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
99 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
100
101 // ServerList interface
102 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
103 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
104
105 serverlist_infofield_t serverlist_sortbyfield;
106 qboolean serverlist_sortdescending;
107
108 int serverlist_viewcount = 0;
109 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
110
111 int serverlist_cachecount;
112 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
113
114 qboolean serverlist_consoleoutput;
115
116 // helper function to insert a value into the viewset
117 // spare entries will be removed
118 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
119 {
120     int i;
121         if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
122                 i = serverlist_viewcount++;
123         } else {
124                 i = SERVERLIST_VIEWLISTSIZE - 1;
125         }
126
127         for( ; i > index ; i-- )
128                 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
129
130         serverlist_viewlist[index] = entry;
131 }
132
133 // we suppose serverlist_viewcount to be valid, ie > 0
134 static void _ServerList_ViewList_Helper_Remove( int index )
135 {
136         serverlist_viewcount--;
137         for( ; index < serverlist_viewcount ; index++ )
138                 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
139 }
140
141 // returns true if A should be inserted before B
142 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
143 {
144         int result = 0; // > 0 if for numbers A > B and for text if A < B
145
146         switch( serverlist_sortbyfield ) {
147                 case SLIF_PING:
148                         result = A->info.ping - B->info.ping;
149                         break;
150                 case SLIF_MAXPLAYERS:
151                         result = A->info.maxplayers - B->info.maxplayers;
152                         break;
153                 case SLIF_NUMPLAYERS:
154                         result = A->info.numplayers - B->info.numplayers;
155                         break;
156                 case SLIF_PROTOCOL:
157                         result = A->info.protocol - B->info.protocol;
158                         break;
159                 case SLIF_CNAME:
160                         result = strcmp( B->info.cname, A->info.cname );
161                         break;
162                 case SLIF_GAME:
163                         result = strcmp( B->info.game, A->info.game );
164                         break;
165                 case SLIF_MAP:
166                         result = strcmp( B->info.map, A->info.map );
167                         break;
168                 case SLIF_MOD:
169                         result = strcmp( B->info.mod, A->info.mod );
170                         break;
171                 case SLIF_NAME:
172                         result = strcmp( B->info.name, A->info.name );
173                         break;
174                 default:
175                         Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
176                         break;
177         }
178
179         if( serverlist_sortdescending )
180                 return result > 0;
181         return result < 0;
182 }
183
184 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
185 {
186         // This should actually be done with some intermediate and end-of-function return
187         switch( op ) {
188                 case SLMO_LESS:
189                         return A < B;
190                 case SLMO_LESSEQUAL:
191                         return A <= B;
192                 case SLMO_EQUAL:
193                         return A == B;
194                 case SLMO_GREATER:
195                         return A > B;
196                 case SLMO_NOTEQUAL:
197                         return A != B;
198                 case SLMO_GREATEREQUAL:
199                 case SLMO_CONTAINS:
200                 case SLMO_NOTCONTAIN:
201                         return A >= B;
202                 default:
203                         Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
204                         return false;
205         }
206 }
207
208 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
209 {
210         int i;
211         char bufferA[ 256 ], bufferB[ 256 ]; // should be more than enough
212         for (i = 0;i < (int)sizeof(bufferA)-1 && A[i];i++)
213                 bufferA[i] = (A[i] >= 'A' && A[i] <= 'Z') ? (A[i] + 'a' - 'A') : A[i];
214         bufferA[i] = 0;
215         for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
216                 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
217         bufferB[i] = 0;
218
219         // Same here, also using an intermediate & final return would be more appropriate
220         // A info B mask
221         switch( op ) {
222                 case SLMO_CONTAINS:
223                         return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
224                 case SLMO_NOTCONTAIN:
225                         return !*bufferB || !strstr( bufferA, bufferB );
226                 case SLMO_LESS:
227                         return strcmp( bufferA, bufferB ) < 0;
228                 case SLMO_LESSEQUAL:
229                         return strcmp( bufferA, bufferB ) <= 0;
230                 case SLMO_EQUAL:
231                         return strcmp( bufferA, bufferB ) == 0;
232                 case SLMO_GREATER:
233                         return strcmp( bufferA, bufferB ) > 0;
234                 case SLMO_NOTEQUAL:
235                         return strcmp( bufferA, bufferB ) != 0;
236                 case SLMO_GREATEREQUAL:
237                         return strcmp( bufferA, bufferB ) >= 0;
238                 default:
239                         Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
240                         return false;
241         }
242 }
243
244 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
245 {
246         if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
247                 return false;
248         if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
249                 return false;
250         if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
251                 return false;
252         if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
253                 return false;
254         if( *mask->info.cname
255                 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
256                 return false;
257         if( *mask->info.game
258                 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
259                 return false;
260         if( *mask->info.mod
261                 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
262                 return false;
263         if( *mask->info.map
264                 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
265                 return false;
266         if( *mask->info.name
267                 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
268                 return false;
269         return true;
270 }
271
272 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
273 {
274         int start, end, mid;
275
276         // FIXME: change this to be more readable (...)
277         // now check whether it passes through the masks
278         for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
279                 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
280                         return;
281
282         for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
283                 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
284                         break;
285         if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
286                 return;
287
288         if( !serverlist_viewcount ) {
289                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
290                 return;
291         }
292         // ok, insert it, we just need to find out where exactly:
293
294         // two special cases
295         // check whether to insert it as new first item
296         if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
297                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
298                 return;
299         } // check whether to insert it as new last item
300         else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
301                 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
302                 return;
303         }
304         start = 0;
305         end = serverlist_viewcount - 1;
306         while( end > start + 1 )
307         {
308                 mid = (start + end) / 2;
309                 // test the item that lies in the middle between start and end
310                 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
311                         // the item has to be in the upper half
312                         end = mid;
313                 else
314                         // the item has to be in the lower half
315                         start = mid;
316         }
317         _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
318 }
319
320 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
321 {
322         int i;
323         for( i = 0; i < serverlist_viewcount; i++ )
324         {
325                 if (serverlist_viewlist[i] == entry)
326                 {
327                         _ServerList_ViewList_Helper_Remove(i);
328                         break;
329                 }
330         }
331 }
332
333 void ServerList_RebuildViewList(void)
334 {
335         int i;
336
337         serverlist_viewcount = 0;
338         for( i = 0 ; i < serverlist_cachecount ; i++ )
339                 if( serverlist_cache[i].query == SQS_QUERIED )
340                         ServerList_ViewList_Insert( &serverlist_cache[i] );
341 }
342
343 void ServerList_ResetMasks(void)
344 {
345         memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
346         memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
347 }
348
349 #if 0
350 static void _ServerList_Test(void)
351 {
352         int i;
353         for( i = 0 ; i < 1024 ; i++ ) {
354                 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
355                 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
356                 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
357                 serverlist_cache[serverlist_cachecount].finished = true;
358                 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
359                 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
360                 serverlist_cachecount++;
361         }
362 }
363 #endif
364
365 void ServerList_QueryList(void)
366 {
367         masterquerytime = realtime;
368         masterquerycount = 0;
369         masterreplycount = 0;
370         serverquerycount = 0;
371         serverreplycount = 0;
372         serverlist_cachecount = 0;
373         serverlist_viewcount = 0;
374         serverlist_consoleoutput = false;
375
376         //_ServerList_Test();
377
378         NetConn_QueryMasters();
379 }
380
381 // rest
382
383 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
384 {
385         int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
386         int i;
387         if (length == 0)
388                 return 0;
389         if (cl_netpacketloss.integer)
390                 for (i = 0;i < cl_numsockets;i++)
391                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
392                                 return 0;
393         if (developer_networking.integer)
394         {
395                 char addressstring[128], addressstring2[128];
396                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
397                 if (length > 0)
398                 {
399                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
400                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
401                         Com_HexDumpToConsole((unsigned char *)data, length);
402                 }
403                 else
404                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
405         }
406         return length;
407 }
408
409 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
410 {
411         int ret;
412         int i;
413         if (cl_netpacketloss.integer)
414                 for (i = 0;i < cl_numsockets;i++)
415                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
416                                 return length;
417         ret = LHNET_Write(mysocket, data, length, peeraddress);
418         if (developer_networking.integer)
419         {
420                 char addressstring[128], addressstring2[128];
421                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
422                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
423                 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
424                 Com_HexDumpToConsole((unsigned char *)data, length);
425         }
426         return ret;
427 }
428
429 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
430 {
431         // note this does not include the trailing NULL because we add that in the parser
432         return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
433 }
434
435 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
436 {
437         unsigned int packetLen;
438         unsigned int dataLen;
439         unsigned int eom;
440         unsigned int *header;
441
442 //#ifdef DEBUG
443         if (data->cursize == 0)
444         {
445                 Con_Printf ("Datagram_SendMessage: zero length message\n");
446                 return -1;
447         }
448
449         if (data->cursize > (int)sizeof(conn->sendMessage))
450         {
451                 Con_Printf ("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
452                 return -1;
453         }
454
455         if (conn->canSend == false)
456         {
457                 Con_Printf ("SendMessage: called with canSend == false\n");
458                 return -1;
459         }
460 //#endif
461
462         memcpy(conn->sendMessage, data->data, data->cursize);
463         conn->sendMessageLength = data->cursize;
464
465         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
466         {
467                 dataLen = conn->sendMessageLength;
468                 eom = NETFLAG_EOM;
469         }
470         else
471         {
472                 dataLen = MAX_PACKETFRAGMENT;
473                 eom = 0;
474         }
475
476         packetLen = NET_HEADERSIZE + dataLen;
477
478         header = (unsigned int *)sendbuffer;
479         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
480         header[1] = BigLong(conn->sendSequence);
481         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
482
483         conn->sendSequence++;
484         conn->canSend = false;
485
486         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
487                 return -1;
488
489         conn->lastSendTime = realtime;
490         packetsSent++;
491         reliableMessagesSent++;
492         return 1;
493 }
494
495 static void NetConn_SendMessageNext(netconn_t *conn)
496 {
497         unsigned int packetLen;
498         unsigned int dataLen;
499         unsigned int eom;
500         unsigned int *header;
501
502         if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
503         {
504                 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
505                 {
506                         dataLen = conn->sendMessageLength;
507                         eom = NETFLAG_EOM;
508                 }
509                 else
510                 {
511                         dataLen = MAX_PACKETFRAGMENT;
512                         eom = 0;
513                 }
514
515                 packetLen = NET_HEADERSIZE + dataLen;
516
517                 header = (unsigned int *)sendbuffer;
518                 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
519                 header[1] = BigLong(conn->sendSequence);
520                 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
521
522                 conn->sendSequence++;
523                 conn->sendNext = false;
524
525                 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
526                         return;
527
528                 conn->lastSendTime = realtime;
529                 packetsSent++;
530         }
531 }
532
533 static void NetConn_ReSendMessage(netconn_t *conn)
534 {
535         unsigned int packetLen;
536         unsigned int dataLen;
537         unsigned int eom;
538         unsigned int *header;
539
540         if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
541         {
542                 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
543                 {
544                         dataLen = conn->sendMessageLength;
545                         eom = NETFLAG_EOM;
546                 }
547                 else
548                 {
549                         dataLen = MAX_PACKETFRAGMENT;
550                         eom = 0;
551                 }
552
553                 packetLen = NET_HEADERSIZE + dataLen;
554
555                 header = (unsigned int *)sendbuffer;
556                 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
557                 header[1] = BigLong(conn->sendSequence - 1);
558                 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
559
560                 conn->sendNext = false;
561
562                 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
563                         return;
564
565                 conn->lastSendTime = realtime;
566                 packetsReSent++;
567         }
568 }
569
570 qboolean NetConn_CanSendMessage(netconn_t *conn)
571 {
572         return conn->canSend;
573 }
574
575 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
576 {
577         int packetLen;
578         unsigned int *header;
579
580         packetLen = NET_HEADERSIZE + data->cursize;
581
582 //#ifdef DEBUG
583         if (data->cursize == 0)
584         {
585                 Con_Printf ("Datagram_SendUnreliableMessage: zero length message\n");
586                 return -1;
587         }
588
589         if (packetLen > (int)sizeof(sendbuffer))
590         {
591                 Con_Printf ("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
592                 return -1;
593         }
594 //#endif
595
596         header = (unsigned int *)sendbuffer;
597         header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
598         header[1] = BigLong(conn->unreliableSendSequence);
599         memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
600
601         conn->unreliableSendSequence++;
602
603         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
604                 return -1;
605
606         packetsSent++;
607         unreliableMessagesSent++;
608         return 1;
609 }
610
611 void NetConn_CloseClientPorts(void)
612 {
613         for (;cl_numsockets > 0;cl_numsockets--)
614                 if (cl_sockets[cl_numsockets - 1])
615                         LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
616 }
617
618 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
619 {
620         lhnetaddress_t address;
621         lhnetsocket_t *s;
622         char addressstring2[1024];
623         if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
624         {
625                 if ((s = LHNET_OpenSocket_Connectionless(&address)))
626                 {
627                         cl_sockets[cl_numsockets++] = s;
628                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
629                         Con_Printf("Client opened a socket on address %s\n", addressstring2);
630                 }
631                 else
632                 {
633                         LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
634                         Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
635                 }
636         }
637         else
638                 Con_Printf("Client unable to parse address %s\n", addressstring);
639 }
640
641 void NetConn_OpenClientPorts(void)
642 {
643         int port;
644         NetConn_CloseClientPorts();
645         port = bound(0, cl_netport.integer, 65535);
646         if (cl_netport.integer != port)
647                 Cvar_SetValueQuick(&cl_netport, port);
648         Con_Printf("Client using port %i\n", port);
649         NetConn_OpenClientPort("local:2", 0);
650         NetConn_OpenClientPort(net_address.string, port);
651         //NetConn_OpenClientPort(net_address_ipv6.string, port);
652 }
653
654 void NetConn_CloseServerPorts(void)
655 {
656         for (;sv_numsockets > 0;sv_numsockets--)
657                 if (sv_sockets[sv_numsockets - 1])
658                         LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
659 }
660
661 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
662 {
663         lhnetaddress_t address;
664         lhnetsocket_t *s;
665         int port;
666         char addressstring2[1024];
667
668         for (port = defaultport; port <= defaultport + 100; port++)
669         {
670                 if (LHNETADDRESS_FromString(&address, addressstring, port))
671                 {
672                         if ((s = LHNET_OpenSocket_Connectionless(&address)))
673                         {
674                                 sv_sockets[sv_numsockets++] = s;
675                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
676                                 Con_Printf("Server listening on address %s\n", addressstring2);
677                                 break;
678                         }
679                         else
680                         {
681                                 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
682                                 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
683                         }
684                 }
685                 else
686                 {
687                         Con_Printf("Server unable to parse address %s\n", addressstring);
688                         // if it cant parse one address, it wont be able to parse another for sure
689                         break;
690                 }
691         }
692 }
693
694 static void NetConn_UpdateServerStuff(void);
695 void NetConn_OpenServerPorts(int opennetports)
696 {
697         int port;
698         NetConn_CloseServerPorts();
699         NetConn_UpdateServerStuff();
700         port = bound(0, sv_netport.integer, 65535);
701         if (port == 0)
702                 port = 26000;
703         Con_Printf("Server using port %i\n", port);
704         if (sv_netport.integer != port)
705                 Cvar_SetValueQuick(&sv_netport, port);
706         if (cls.state != ca_dedicated)
707                 NetConn_OpenServerPort("local:1", 0);
708         if (opennetports)
709         {
710                 NetConn_OpenServerPort(net_address.string, port);
711                 //NetConn_OpenServerPort(net_address_ipv6.string, port);
712         }
713         if (sv_numsockets == 0)
714                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
715 }
716
717 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
718 {
719         int i, a = LHNETADDRESS_GetAddressType(address);
720         for (i = 0;i < cl_numsockets;i++)
721                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
722                         return cl_sockets[i];
723         return NULL;
724 }
725
726 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
727 {
728         int i, a = LHNETADDRESS_GetAddressType(address);
729         for (i = 0;i < sv_numsockets;i++)
730                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
731                         return sv_sockets[i];
732         return NULL;
733 }
734
735 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
736 {
737         netconn_t *conn;
738         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
739         conn->mysocket = mysocket;
740         conn->peeraddress = *peeraddress;
741         conn->canSend = true;
742         conn->lastMessageTime = realtime;
743         conn->message.data = conn->messagedata;
744         conn->message.maxsize = sizeof(conn->messagedata);
745         conn->message.cursize = 0;
746         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
747         // reduce effectiveness of connection request floods
748         conn->timeout = realtime + net_connecttimeout.value;
749         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
750         conn->next = netconn_list;
751         netconn_list = conn;
752         return conn;
753 }
754
755 void NetConn_Close(netconn_t *conn)
756 {
757         netconn_t *c;
758         // remove connection from list
759         if (conn == netconn_list)
760                 netconn_list = conn->next;
761         else
762         {
763                 for (c = netconn_list;c;c = c->next)
764                 {
765                         if (c->next == conn)
766                         {
767                                 c->next = conn->next;
768                                 break;
769                         }
770                 }
771                 // not found in list, we'll avoid crashing here...
772                 if (!c)
773                         return;
774         }
775         // free connection
776         Mem_Free(conn);
777 }
778
779 static int clientport = -1;
780 static int clientport2 = -1;
781 static int hostport = -1;
782 static void NetConn_UpdateServerStuff(void)
783 {
784         if (cls.state != ca_dedicated)
785         {
786                 if (clientport2 != cl_netport.integer)
787                 {
788                         clientport2 = cl_netport.integer;
789                         if (cls.state == ca_connected)
790                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
791                 }
792                 if (cls.state == ca_disconnected && clientport != clientport2)
793                 {
794                         clientport = clientport2;
795                         NetConn_CloseClientPorts();
796                 }
797                 if (cl_numsockets == 0)
798                         NetConn_OpenClientPorts();
799         }
800
801         if (hostport != sv_netport.integer)
802         {
803                 hostport = sv_netport.integer;
804                 if (sv.active)
805                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
806         }
807 }
808
809 int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length)
810 {
811         unsigned int count;
812         unsigned int flags;
813         unsigned int sequence;
814         int qlength;
815
816         if (length >= 8)
817         {
818                 qlength = (unsigned int)BigLong(((int *)data)[0]);
819                 flags = qlength & ~NETFLAG_LENGTH_MASK;
820                 qlength &= NETFLAG_LENGTH_MASK;
821                 // control packets were already handled
822                 if (!(flags & NETFLAG_CTL) && qlength == length)
823                 {
824                         sequence = BigLong(((int *)data)[1]);
825                         packetsReceived++;
826                         data += 8;
827                         length -= 8;
828                         if (flags & NETFLAG_UNRELIABLE)
829                         {
830                                 if (sequence >= conn->unreliableReceiveSequence)
831                                 {
832                                         if (sequence > conn->unreliableReceiveSequence)
833                                         {
834                                                 count = sequence - conn->unreliableReceiveSequence;
835                                                 droppedDatagrams += count;
836                                                 Con_DPrintf("Dropped %u datagram(s)\n", count);
837                                         }
838                                         conn->unreliableReceiveSequence = sequence + 1;
839                                         conn->lastMessageTime = realtime;
840                                         conn->timeout = realtime + net_messagetimeout.value;
841                                         unreliableMessagesReceived++;
842                                         if (length > 0)
843                                         {
844                                                 SZ_Clear(&net_message);
845                                                 SZ_Write(&net_message, data, length);
846                                                 MSG_BeginReading();
847                                                 return 2;
848                                         }
849                                 }
850                                 else
851                                         Con_DPrint("Got a stale datagram\n");
852                                 return 1;
853                         }
854                         else if (flags & NETFLAG_ACK)
855                         {
856                                 if (sequence == (conn->sendSequence - 1))
857                                 {
858                                         if (sequence == conn->ackSequence)
859                                         {
860                                                 conn->ackSequence++;
861                                                 if (conn->ackSequence != conn->sendSequence)
862                                                         Con_DPrint("ack sequencing error\n");
863                                                 conn->lastMessageTime = realtime;
864                                                 conn->timeout = realtime + net_messagetimeout.value;
865                                                 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
866                                                 if (conn->sendMessageLength > 0)
867                                                 {
868                                                         memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
869                                                         conn->sendNext = true;
870                                                         NetConn_SendMessageNext(conn);
871                                                 }
872                                                 else
873                                                 {
874                                                         conn->sendMessageLength = 0;
875                                                         conn->canSend = true;
876                                                 }
877                                         }
878                                         else
879                                                 Con_DPrint("Duplicate ACK received\n");
880                                 }
881                                 else
882                                         Con_DPrint("Stale ACK received\n");
883                                 return 1;
884                         }
885                         else if (flags & NETFLAG_DATA)
886                         {
887                                 unsigned int temppacket[2];
888                                 temppacket[0] = BigLong(8 | NETFLAG_ACK);
889                                 temppacket[1] = BigLong(sequence);
890                                 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
891                                 if (sequence == conn->receiveSequence)
892                                 {
893                                         conn->lastMessageTime = realtime;
894                                         conn->timeout = realtime + net_messagetimeout.value;
895                                         conn->receiveSequence++;
896                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
897                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
898                                                 conn->receiveMessageLength += length;
899                                         } else {
900                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
901                                                                         "Dropping the message!\n", sequence );
902                                                 conn->receiveMessageLength = 0;
903                                                 return 1;
904                                         }
905                                         if (flags & NETFLAG_EOM)
906                                         {
907                                                 reliableMessagesReceived++;
908                                                 length = conn->receiveMessageLength;
909                                                 conn->receiveMessageLength = 0;
910                                                 if (length > 0)
911                                                 {
912                                                         SZ_Clear(&net_message);
913                                                         SZ_Write(&net_message, conn->receiveMessage, length);
914                                                         MSG_BeginReading();
915                                                         return 2;
916                                                 }
917                                         }
918                                 }
919                                 else
920                                         receivedDuplicateCount++;
921                                 return 1;
922                         }
923                 }
924         }
925         return 0;
926 }
927
928 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
929 {
930         cls.connect_trying = false;
931         M_Update_Return_Reason("");
932         // the connection request succeeded, stop current connection and set up a new connection
933         CL_Disconnect();
934         // if we're connecting to a remote server, shut down any local server
935         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
936                 Host_ShutdownServer ();
937         // allocate a net connection to keep track of things
938         cls.netcon = NetConn_Open(mysocket, peeraddress);
939         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
940         key_dest = key_game;
941         m_state = m_none;
942         cls.demonum = -1;                       // not in the demo loop now
943         cls.state = ca_connected;
944         cls.signon = 0;                         // need all the signon messages before playing
945 }
946
947 int NetConn_IsLocalGame(void)
948 {
949         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
950                 return true;
951         return false;
952 }
953
954 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
955 {
956         int ret, c, control;
957         const char *s;
958         char *string, addressstring2[128], cname[128], ipstring[32];
959         char stringbuf[16384];
960
961         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
962         {
963                 // received a command string - strip off the packaging and put it
964                 // into our string buffer with NULL termination
965                 data += 4;
966                 length -= 4;
967                 length = min(length, (int)sizeof(stringbuf) - 1);
968                 memcpy(stringbuf, data, length);
969                 stringbuf[length] = 0;
970                 string = stringbuf;
971
972                 if (developer.integer)
973                 {
974                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
975                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
976                         Com_HexDumpToConsole(data, length);
977                 }
978
979                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
980                 {
981                         char protocolnames[1400];
982                         Protocol_Names(protocolnames, sizeof(protocolnames));
983                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
984                         Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
985                         M_Update_Return_Reason("Got challenge response");
986                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
987                         return true;
988                 }
989                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
990                 {
991                         M_Update_Return_Reason("Accepted");
992                         NetConn_ConnectionEstablished(mysocket, peeraddress);
993                         return true;
994                 }
995                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
996                 {
997                         char rejectreason[32];
998                         cls.connect_trying = false;
999                         string += 7;
1000                         length = max(length - 7, (int)sizeof(rejectreason) - 1);
1001                         memcpy(rejectreason, string, length);
1002                         rejectreason[length] = 0;
1003                         M_Update_Return_Reason(rejectreason);
1004                         return true;
1005                 }
1006                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1007                 {
1008                         serverlist_info_t *info;
1009                         int n;
1010                         double pingtime;
1011
1012                         string += 13;
1013                         // serverlist only uses text addresses
1014                         LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
1015                         // search the cache for this server and update it
1016                         for( n = 0; n < serverlist_cachecount; n++ )
1017                                 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
1018                                         break;
1019                         if( n == serverlist_cachecount ) {
1020                                 // LAN search doesnt require an answer from the master server so we wont
1021                                 // know the ping nor will it be initialized already...
1022
1023                                 // find a slot
1024                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1025                                         return true;
1026
1027                                 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1028                                 // store the data the engine cares about (address and ping)
1029                                 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1030                                 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1031                                 serverlist_cache[serverlist_cachecount].querytime = realtime;
1032                                 // if not in the slist menu we should print the server to console
1033                                 if (serverlist_consoleoutput) {
1034                                         Con_Printf("querying %s\n", ipstring);
1035                                 }
1036
1037                                 ++serverlist_cachecount;
1038                         }
1039
1040                         info = &serverlist_cache[n].info;
1041                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1042                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1043                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1044                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1045                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1046                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1047                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1048
1049                         if (info->ping == 100000)
1050                                         serverreplycount++;
1051
1052                         pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
1053                         pingtime = bound(0, pingtime, 9999);
1054                         // update the ping
1055                         info->ping = pingtime;
1056
1057                         // legacy/old stuff move it to the menu ASAP
1058
1059                         // build description strings for the things users care about
1060                         dpsnprintf(serverlist_cache[n].line1, sizeof(serverlist_cache[n].line1), "%c%c%5d%c%c%c%3u/%3u %-65.65s", STRING_COLOR_TAG, pingtime >= 300 ? '1' : (pingtime >= 200 ? '3' : '7'), (int)pingtime, STRING_COLOR_TAG, STRING_COLOR_DEFAULT + '0', info->protocol != NET_PROTOCOL_VERSION ? '*' : ' ', info->numplayers, info->maxplayers, info->name);
1061                         dpsnprintf(serverlist_cache[n].line2, sizeof(serverlist_cache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", info->cname, info->game, info->mod, info->map);
1062                         if( serverlist_cache[n].query == SQS_QUERIED ) {
1063                                 ServerList_ViewList_Remove( &serverlist_cache[n] );
1064                         }
1065                         // if not in the slist menu we should print the server to console (if wanted)
1066                         else if( serverlist_consoleoutput )
1067                                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1068                         // and finally, update the view set
1069                         ServerList_ViewList_Insert( &serverlist_cache[n] );
1070                         serverlist_cache[n].query = SQS_QUERIED;
1071
1072                         return true;
1073                 }
1074                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1075                 {
1076                         // Extract the IP addresses
1077                         data += 18;
1078                         length -= 18;
1079                         masterreplycount++;
1080                         if (serverlist_consoleoutput)
1081                                 Con_Print("received server list...\n");
1082                         while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1083                         {
1084                                 int n;
1085
1086                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1087                                 if (developer.integer)
1088                                         Con_Printf("Requesting info from server %s\n", ipstring);
1089                                 // ignore the rest of the message if the serverlist is full
1090                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1091                                         break;
1092                                 // also ignore it if we have already queried it (other master server response)
1093                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1094                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1095                                                 break;
1096                                 if( n >= serverlist_cachecount )
1097                                 {
1098                                         serverquerycount++;
1099
1100                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1101                                         // store the data the engine cares about (address and ping)
1102                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1103                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1104                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1105
1106                                         ++serverlist_cachecount;
1107                                 }
1108
1109                                 // move on to next address in packet
1110                                 data += 7;
1111                                 length -= 7;
1112                         }
1113                         // begin or resume serverlist queries
1114                         serverlist_querysleep = false;
1115                         return true;
1116                 }
1117                 /*
1118                 if (!strncmp(string, "ping", 4))
1119                 {
1120                         if (developer.integer)
1121                                 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1122                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1123                         return true;
1124                 }
1125                 if (!strncmp(string, "ack", 3))
1126                         return true;
1127                 */
1128                 // we may not have liked the packet, but it was a command packet, so
1129                 // we're done processing this packet now
1130                 return true;
1131         }
1132         // netquake control packets, supported for compatibility only
1133         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1134         {
1135                 c = data[4];
1136                 data += 5;
1137                 length -= 5;
1138                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1139                 switch (c)
1140                 {
1141                 case CCREP_ACCEPT:
1142                         if (developer.integer)
1143                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1144                         if (cls.connect_trying)
1145                         {
1146                                 lhnetaddress_t clientportaddress;
1147                                 clientportaddress = *peeraddress;
1148                                 if (length >= 4)
1149                                 {
1150                                         unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1151                                         data += 4;
1152                                         length -= 4;
1153                                         LHNETADDRESS_SetPort(&clientportaddress, port);
1154                                 }
1155                                 M_Update_Return_Reason("Accepted");
1156                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1157                         }
1158                         break;
1159                 case CCREP_REJECT:
1160                         if (developer.integer)
1161                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1162                         cls.connect_trying = false;
1163                         M_Update_Return_Reason((char *)data);
1164                         break;
1165 #if 0
1166                 case CCREP_SERVER_INFO:
1167                         if (developer.integer)
1168                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1169                         if (cls.state != ca_dedicated)
1170                         {
1171                                 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1172                                 // string we just ignore it and keep the real address
1173                                 MSG_ReadString();
1174                                 // serverlist only uses text addresses
1175                                 cname = UDP_AddrToString(readaddr);
1176                                 // search the cache for this server
1177                                 for (n = 0; n < hostCacheCount; n++)
1178                                         if (!strcmp(cname, serverlist[n].cname))
1179                                                 break;
1180                                 // add it
1181                                 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1182                                 {
1183                                         hostCacheCount++;
1184                                         memset(&serverlist[n], 0, sizeof(serverlist[n]));
1185                                         strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1186                                         strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1187                                         serverlist[n].users = MSG_ReadByte();
1188                                         serverlist[n].maxusers = MSG_ReadByte();
1189                                         c = MSG_ReadByte();
1190                                         if (c != NET_PROTOCOL_VERSION)
1191                                         {
1192                                                 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1193                                                 strcpy(serverlist[n].name, "*");
1194                                                 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1195                                         }
1196                                         strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1197                                 }
1198                         }
1199                         break;
1200                 case CCREP_PLAYER_INFO:
1201                         // we got a CCREP_PLAYER_INFO??
1202                         //if (developer.integer)
1203                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1204                         break;
1205                 case CCREP_RULE_INFO:
1206                         // we got a CCREP_RULE_INFO??
1207                         //if (developer.integer)
1208                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1209                         break;
1210 #endif
1211                 default:
1212                         break;
1213                 }
1214                 // we may not have liked the packet, but it was a valid control
1215                 // packet, so we're done processing this packet now
1216                 return true;
1217         }
1218         ret = 0;
1219         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)
1220                 CL_ParseServerMessage();
1221         return ret;
1222 }
1223
1224 void NetConn_QueryQueueFrame(void)
1225 {
1226         int index;
1227         int queries;
1228         int maxqueries;
1229         double timeouttime;
1230         static double querycounter = 0;
1231
1232         if (serverlist_querysleep)
1233                 return;
1234
1235         // each time querycounter reaches 1.0 issue a query
1236         querycounter += host_realframetime * net_slist_queriespersecond.value;
1237         maxqueries = (int)querycounter;
1238         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1239         querycounter -= maxqueries;
1240
1241         if( maxqueries == 0 ) {
1242                 return;
1243         }
1244
1245         // scan serverlist and issue queries as needed
1246     serverlist_querysleep = true;
1247
1248         timeouttime = realtime - net_slist_timeout.value;
1249         for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1250         {
1251                 serverlist_entry_t *entry = &serverlist_cache[ index ];
1252                 if( entry->query != SQS_QUERYING )
1253                 {
1254                         continue;
1255                 }
1256
1257         serverlist_querysleep = false;
1258                 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1259                 {
1260                         continue;
1261                 }
1262
1263                 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1264                 {
1265                         lhnetaddress_t address;
1266                         int socket;
1267
1268                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1269                         for (socket = 0; socket < cl_numsockets ; socket++) {
1270                                 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1271                         }
1272
1273                         entry->querytime = realtime;
1274                         entry->querycounter++;
1275
1276                         // if not in the slist menu we should print the server to console
1277                         if (serverlist_consoleoutput)
1278                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1279
1280                         queries++;
1281                 }
1282                 else
1283                 {
1284                         entry->query = SQS_TIMEDOUT;
1285                 }
1286         }
1287 }
1288
1289 void NetConn_ClientFrame(void)
1290 {
1291         int i, length;
1292         lhnetaddress_t peeraddress;
1293         netconn_t *conn;
1294         NetConn_UpdateServerStuff();
1295         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1296         {
1297                 if (cls.connect_remainingtries == 0)
1298                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1299                 cls.connect_nextsendtime = realtime + 1;
1300                 cls.connect_remainingtries--;
1301                 if (cls.connect_remainingtries <= -10)
1302                 {
1303                         cls.connect_trying = false;
1304                         M_Update_Return_Reason("Connect: Failed");
1305                         return;
1306                 }
1307                 // try challenge first (newer server)
1308                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1309                 // then try netquake as a fallback (old server, or netquake)
1310                 SZ_Clear(&net_message);
1311                 // save space for the header, filled in later
1312                 MSG_WriteLong(&net_message, 0);
1313                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1314                 MSG_WriteString(&net_message, "QUAKE");
1315                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1316                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1317                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1318                 SZ_Clear(&net_message);
1319         }
1320         for (i = 0;i < cl_numsockets;i++) {
1321                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0) {
1322                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1323                 }
1324         }
1325         NetConn_QueryQueueFrame();
1326         if (cls.netcon && realtime > cls.netcon->timeout)
1327         {
1328                 Con_Print("Connection timed out\n");
1329                 CL_Disconnect();
1330                 Host_ShutdownServer ();
1331         }
1332         for (conn = netconn_list;conn;conn = conn->next)
1333                 NetConn_ReSendMessage(conn);
1334 }
1335
1336 #define MAX_CHALLENGES 128
1337 struct challenge_s
1338 {
1339         lhnetaddress_t address;
1340         double time;
1341         char string[12];
1342 }
1343 challenge[MAX_CHALLENGES];
1344
1345 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1346 {
1347         int i;
1348         char c;
1349         for (i = 0;i < bufferlength - 1;i++)
1350         {
1351                 do
1352                 {
1353                         c = rand () % (127 - 33) + 33;
1354                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1355                 buffer[i] = c;
1356         }
1357         buffer[i] = 0;
1358 }
1359
1360 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1361 {
1362         unsigned int nb_clients = 0, i;
1363         int length;
1364
1365         // How many clients are there?
1366         for (i = 0;i < (unsigned int)svs.maxclients;i++)
1367                 if (svs.clients[i].active)
1368                         nb_clients++;
1369
1370         // TODO: we should add more information for the full status string
1371         length = dpsnprintf(out_msg, out_size,
1372                                                 "\377\377\377\377%s\x0A"
1373                                                 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1374                                                 "\\clients\\%d\\mapname\\%s\\hostname\\%s""\\protocol\\%d"
1375                                                 "%s%s"
1376                                                 "%s",
1377                                                 fullstatus ? "statusResponse" : "infoResponse",
1378                                                 gamename, com_modname, svs.maxclients,
1379                                                 nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1380                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1381                                                 fullstatus ? "\n" : "");
1382
1383         // Make sure it fits in the buffer
1384         if (length < 0)
1385                 return false;
1386
1387         if (fullstatus)
1388         {
1389                 char *ptr;
1390                 int left;
1391
1392                 ptr = out_msg + length;
1393                 left = (int)out_size - length;
1394
1395                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1396                 {
1397                         client_t *cl = &svs.clients[i];
1398                         if (cl->active)
1399                         {
1400                                 int nameind, cleanind;
1401                                 char curchar;
1402                                 char cleanname [sizeof(cl->name)];
1403
1404                                 // Remove all characters '"' and '\' in the player name
1405                                 nameind = 0;
1406                                 cleanind = 0;
1407                                 do
1408                                 {
1409                                         curchar = cl->name[nameind++];
1410                                         if (curchar != '"' && curchar != '\\')
1411                                         {
1412                                                 cleanname[cleanind++] = curchar;
1413                                                 if (cleanind == sizeof(cleanname) - 1)
1414                                                         break;
1415                                         }
1416                                 } while (curchar != '\0');
1417
1418                                 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1419                                                                         cl->frags,
1420                                                                         (int)(cl->ping * 1000.0f),
1421                                                                         cleanname);
1422                                 if(length < 0)
1423                                         return false;
1424                                 left -= length;
1425                                 ptr += length;
1426                         }
1427                 }
1428         }
1429
1430         return true;
1431 }
1432
1433 extern void SV_SendServerinfo (client_t *client);
1434 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1435 {
1436         int i, ret, clientnum, best;
1437         double besttime;
1438         client_t *client;
1439         netconn_t *conn;
1440         char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1441
1442         if (sv.active)
1443         {
1444                 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1445                 {
1446                         // received a command string - strip off the packaging and put it
1447                         // into our string buffer with NULL termination
1448                         data += 4;
1449                         length -= 4;
1450                         length = min(length, (int)sizeof(stringbuf) - 1);
1451                         memcpy(stringbuf, data, length);
1452                         stringbuf[length] = 0;
1453                         string = stringbuf;
1454
1455                         if (developer.integer)
1456                         {
1457                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1458                                 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1459                                 Com_HexDumpToConsole(data, length);
1460                         }
1461
1462                         if (length >= 12 && !memcmp(string, "getchallenge", 12))
1463                         {
1464                                 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1465                                 {
1466                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1467                                                 break;
1468                                         if (besttime > challenge[i].time)
1469                                                 besttime = challenge[best = i].time;
1470                                 }
1471                                 // if we did not find an exact match, choose the oldest and
1472                                 // update address and string
1473                                 if (i == MAX_CHALLENGES)
1474                                 {
1475                                         i = best;
1476                                         challenge[i].address = *peeraddress;
1477                                         NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1478                                 }
1479                                 challenge[i].time = realtime;
1480                                 // send the challenge
1481                                 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1482                                 return true;
1483                         }
1484                         if (length > 8 && !memcmp(string, "connect\\", 8))
1485                         {
1486                                 string += 7;
1487                                 length -= 7;
1488                                 if ((s = SearchInfostring(string, "challenge")))
1489                                 {
1490                                         // validate the challenge
1491                                         for (i = 0;i < MAX_CHALLENGES;i++)
1492                                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1493                                                         break;
1494                                         if (i < MAX_CHALLENGES)
1495                                         {
1496                                                 // check engine protocol
1497                                                 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1498                                                 {
1499                                                         if (developer.integer)
1500                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1501                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1502                                                 }
1503                                                 else
1504                                                 {
1505                                                         // see if this is a duplicate connection request
1506                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1507                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1508                                                                         break;
1509                                                         if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1510                                                         {
1511                                                                 // client is still trying to connect,
1512                                                                 // so we send a duplicate reply
1513                                                                 if (developer.integer)
1514                                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1515                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1516                                                         }
1517 #if 0
1518                                                         else if (clientnum < svs.maxclients)
1519                                                         {
1520                                                                 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1521                                                                 {
1522                                                                         // client crashed and is coming back, keep their stuff intact
1523                                                                         SV_SendServerinfo(client);
1524                                                                         //host_client = client;
1525                                                                         //SV_DropClient (true);
1526                                                                 }
1527                                                                 // else ignore them
1528                                                         }
1529 #endif
1530                                                         else
1531                                                         {
1532                                                                 // this is a new client, find a slot
1533                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1534                                                                         if (!client->active)
1535                                                                                 break;
1536                                                                 if (clientnum < svs.maxclients)
1537                                                                 {
1538                                                                         // prepare the client struct
1539                                                                         if ((conn = NetConn_Open(mysocket, peeraddress)))
1540                                                                         {
1541                                                                                 // allocated connection
1542                                                                                 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1543                                                                                 if (developer.integer)
1544                                                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1545                                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1546                                                                                 // now set up the client
1547                                                                                 SV_ConnectClient(clientnum, conn);
1548                                                                                 NetConn_Heartbeat(1);
1549                                                                         }
1550                                                                 }
1551                                                                 else
1552                                                                 {
1553                                                                         // server is full
1554                                                                         if (developer.integer)
1555                                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1556                                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1557                                                                 }
1558                                                         }
1559                                                 }
1560                                         }
1561                                 }
1562                                 return true;
1563                         }
1564                         if (length >= 7 && !memcmp(string, "getinfo", 7))
1565                         {
1566                                 const char *challenge = NULL;
1567
1568                                 // If there was a challenge in the getinfo message
1569                                 if (length > 8 && string[7] == ' ')
1570                                         challenge = string + 8;
1571
1572                                 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
1573                                 {
1574                                         if (developer.integer)
1575                                                 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1576                                         NetConn_WriteString(mysocket, response, peeraddress);
1577                                 }
1578                                 return true;
1579                         }
1580                         if (length >= 9 && !memcmp(string, "getstatus", 9))
1581                         {
1582                                 const char *challenge = NULL;
1583
1584                                 // If there was a challenge in the getinfo message
1585                                 if (length > 10 && string[9] == ' ')
1586                                         challenge = string + 10;
1587
1588                                 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
1589                                 {
1590                                         if (developer.integer)
1591                                                 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
1592                                         NetConn_WriteString(mysocket, response, peeraddress);
1593                                 }
1594                                 return true;
1595                         }
1596                         /*
1597                         if (!strncmp(string, "ping", 4))
1598                         {
1599                                 if (developer.integer)
1600                                         Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1601                                 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1602                                 return true;
1603                         }
1604                         if (!strncmp(string, "ack", 3))
1605                                 return true;
1606                         */
1607                         // we may not have liked the packet, but it was a command packet, so
1608                         // we're done processing this packet now
1609                         return true;
1610                 }
1611                 // LordHavoc: disabled netquake control packet support in server
1612 #if 0
1613                 {
1614                         int c, control;
1615                         // netquake control packets, supported for compatibility only
1616                         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1617                         {
1618                                 c = data[4];
1619                                 data += 5;
1620                                 length -= 5;
1621                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1622                                 switch (c)
1623                                 {
1624                                 case CCREQ_CONNECT:
1625                                         //if (developer.integer)
1626                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1627                                         if (length >= (int)strlen("QUAKE") + 1 + 1)
1628                                         {
1629                                                 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1630                                                 {
1631                                                         if (developer.integer)
1632                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1633                                                         SZ_Clear(&net_message);
1634                                                         // save space for the header, filled in later
1635                                                         MSG_WriteLong(&net_message, 0);
1636                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1637                                                         MSG_WriteString(&net_message, "Incompatible version.\n");
1638                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1639                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1640                                                         SZ_Clear(&net_message);
1641                                                 }
1642                                                 else
1643                                                 {
1644                                                         // see if this is a duplicate connection request
1645                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1646                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1647                                                                         break;
1648                                                         if (clientnum < svs.maxclients)
1649                                                         {
1650                                                                 // duplicate connection request
1651                                                                 if (realtime - client->connecttime < 2.0)
1652                                                                 {
1653                                                                         // client is still trying to connect,
1654                                                                         // so we send a duplicate reply
1655                                                                         if (developer.integer)
1656                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1657                                                                         SZ_Clear(&net_message);
1658                                                                         // save space for the header, filled in later
1659                                                                         MSG_WriteLong(&net_message, 0);
1660                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1661                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1662                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1663                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1664                                                                         SZ_Clear(&net_message);
1665                                                                 }
1666 #if 0
1667                                                                 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1668                                                                 {
1669                                                                         SV_SendServerinfo(client);
1670                                                                         // the old client hasn't sent us anything
1671                                                                         // in quite a while, so kick off and let
1672                                                                         // the retry take care of it...
1673                                                                         //host_client = client;
1674                                                                         //SV_DropClient (true);
1675                                                                 }
1676 #endif
1677                                                         }
1678                                                         else
1679                                                         {
1680                                                                 // this is a new client, find a slot
1681                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1682                                                                         if (!client->active)
1683                                                                                 break;
1684                                                                 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1685                                                                 {
1686                                                                         // connect to the client
1687                                                                         // everything is allocated, just fill in the details
1688                                                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
1689                                                                         if (developer.integer)
1690                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1691                                                                         // send back the info about the server connection
1692                                                                         SZ_Clear(&net_message);
1693                                                                         // save space for the header, filled in later
1694                                                                         MSG_WriteLong(&net_message, 0);
1695                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1696                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1697                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1698                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1699                                                                         SZ_Clear(&net_message);
1700                                                                         // now set up the client struct
1701                                                                         SV_ConnectClient(clientnum, conn);
1702                                                                         NetConn_Heartbeat(1);
1703                                                                 }
1704                                                                 else
1705                                                                 {
1706                                                                         //if (developer.integer)
1707                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1708                                                                         // no room; try to let player know
1709                                                                         SZ_Clear(&net_message);
1710                                                                         // save space for the header, filled in later
1711                                                                         MSG_WriteLong(&net_message, 0);
1712                                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1713                                                                         MSG_WriteString(&net_message, "Server is full.\n");
1714                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1715                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1716                                                                         SZ_Clear(&net_message);
1717                                                                 }
1718                                                         }
1719                                                 }
1720                                         }
1721                                         break;
1722 #if 0
1723                                 case CCREQ_SERVER_INFO:
1724                                         if (developer.integer)
1725                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1726                                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1727                                         {
1728                                                 if (developer.integer)
1729                                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1730                                                 SZ_Clear(&net_message);
1731                                                 // save space for the header, filled in later
1732                                                 MSG_WriteLong(&net_message, 0);
1733                                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1734                                                 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1735                                                 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1736                                                 MSG_WriteString(&net_message, hostname.string);
1737                                                 MSG_WriteString(&net_message, sv.name);
1738                                                 MSG_WriteByte(&net_message, net_activeconnections);
1739                                                 MSG_WriteByte(&net_message, svs.maxclients);
1740                                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1741                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1742                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1743                                                 SZ_Clear(&net_message);
1744                                         }
1745                                         break;
1746                                 case CCREQ_PLAYER_INFO:
1747                                         if (developer.integer)
1748                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1749                                         if (sv.active)
1750                                         {
1751                                                 int playerNumber, activeNumber, clientNumber;
1752                                                 client_t *client;
1753
1754                                                 playerNumber = MSG_ReadByte();
1755                                                 activeNumber = -1;
1756                                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1757                                                         if (client->active && ++activeNumber == playerNumber)
1758                                                                 break;
1759                                                 if (clientNumber != svs.maxclients)
1760                                                 {
1761                                                         SZ_Clear(&net_message);
1762                                                         // save space for the header, filled in later
1763                                                         MSG_WriteLong(&net_message, 0);
1764                                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1765                                                         MSG_WriteByte(&net_message, playerNumber);
1766                                                         MSG_WriteString(&net_message, client->name);
1767                                                         MSG_WriteLong(&net_message, client->colors);
1768                                                         MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
1769                                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1770                                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1771                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1772                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1773                                                         SZ_Clear(&net_message);
1774                                                 }
1775                                         }
1776                                         break;
1777                                 case CCREQ_RULE_INFO:
1778                                         if (developer.integer)
1779                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1780                                         if (sv.active)
1781                                         {
1782                                                 char *prevCvarName;
1783                                                 cvar_t *var;
1784
1785                                                 // find the search start location
1786                                                 prevCvarName = MSG_ReadString();
1787                                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1788
1789                                                 // send the response
1790                                                 SZ_Clear(&net_message);
1791                                                 // save space for the header, filled in later
1792                                                 MSG_WriteLong(&net_message, 0);
1793                                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1794                                                 if (var)
1795                                                 {
1796                                                         MSG_WriteString(&net_message, var->name);
1797                                                         MSG_WriteString(&net_message, var->string);
1798                                                 }
1799                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1800                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1801                                                 SZ_Clear(&net_message);
1802                                         }
1803                                         break;
1804 #endif
1805                                 default:
1806                                         break;
1807                                 }
1808                                 // we may not have liked the packet, but it was a valid control
1809                                 // packet, so we're done processing this packet now
1810                                 return true;
1811                         }
1812                 }
1813 #endif
1814                 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1815                 {
1816                         if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1817                         {
1818                                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1819                                         SV_ReadClientMessage();
1820                                 return ret;
1821                         }
1822                 }
1823         }
1824         return 0;
1825 }
1826
1827 void NetConn_ServerFrame(void)
1828 {
1829         int i, length;
1830         lhnetaddress_t peeraddress;
1831         netconn_t *conn;
1832         NetConn_UpdateServerStuff();
1833         for (i = 0;i < sv_numsockets;i++)
1834                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1835                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1836         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1837         {
1838                 // never timeout loopback connections
1839                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1840                 {
1841                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1842                         SV_DropClient(false);
1843                 }
1844         }
1845         for (conn = netconn_list;conn;conn = conn->next)
1846                 NetConn_ReSendMessage(conn);
1847 }
1848
1849 void NetConn_QueryMasters(void)
1850 {
1851         int i;
1852         int masternum;
1853         lhnetaddress_t masteraddress;
1854         lhnetaddress_t broadcastaddress;
1855         char request[256];
1856
1857         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1858                 return;
1859
1860         // 26000 is the default quake server port, servers on other ports will not
1861         // be found
1862         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1863         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1864
1865         for (i = 0;i < cl_numsockets;i++)
1866         {
1867                 if (cl_sockets[i])
1868                 {
1869                         // search LAN for Quake servers
1870                         SZ_Clear(&net_message);
1871                         // save space for the header, filled in later
1872                         MSG_WriteLong(&net_message, 0);
1873                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1874                         MSG_WriteString(&net_message, "QUAKE");
1875                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1876                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1877                         NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1878                         SZ_Clear(&net_message);
1879
1880                         // search LAN for DarkPlaces servers
1881                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1882
1883                         // build the getservers message to send to the master servers
1884                         dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1885
1886                         // search internet
1887                         for (masternum = 0;sv_masters[masternum].name;masternum++)
1888                         {
1889                                 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1890                                 {
1891                                         masterquerycount++;
1892                                         NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1893                                 }
1894                         }
1895                 }
1896         }
1897         if (!masterquerycount)
1898         {
1899                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1900                 M_Update_Return_Reason("No network");
1901         }
1902 }
1903
1904 void NetConn_Heartbeat(int priority)
1905 {
1906         lhnetaddress_t masteraddress;
1907         int masternum;
1908         lhnetsocket_t *mysocket;
1909
1910         // if it's a state change (client connected), limit next heartbeat to no
1911         // more than 30 sec in the future
1912         if (priority == 1 && nextheartbeattime > realtime + 30.0)
1913                 nextheartbeattime = realtime + 30.0;
1914
1915         // limit heartbeatperiod to 30 to 270 second range,
1916         // lower limit is to avoid abusing master servers with excess traffic,
1917         // upper limit is to avoid timing out on the master server (which uses
1918         // 300 sec timeout)
1919         if (sv_heartbeatperiod.value < 30)
1920                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1921         if (sv_heartbeatperiod.value > 270)
1922                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1923
1924         // make advertising optional and don't advertise singleplayer games, and
1925         // only send a heartbeat as often as the admin wants
1926         if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1927         {
1928                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1929                 for (masternum = 0;sv_masters[masternum].name;masternum++)
1930                         if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1931                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1932         }
1933 }
1934
1935 static void Net_Heartbeat_f(void)
1936 {
1937         if (sv.active)
1938                 NetConn_Heartbeat(2);
1939         else
1940                 Con_Print("No server running, can not heartbeat to master server.\n");
1941 }
1942
1943 void PrintStats(netconn_t *conn)
1944 {
1945         Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1946 }
1947
1948 void Net_Stats_f(void)
1949 {
1950         netconn_t *conn;
1951         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
1952         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
1953         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
1954         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1955         Con_Printf("packetsSent                = %i\n", packetsSent);
1956         Con_Printf("packetsReSent              = %i\n", packetsReSent);
1957         Con_Printf("packetsReceived            = %i\n", packetsReceived);
1958         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
1959         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
1960         Con_Print("connections                =\n");
1961         for (conn = netconn_list;conn;conn = conn->next)
1962                 PrintStats(conn);
1963 }
1964
1965 void Net_Slist_f(void)
1966 {
1967         ServerList_ResetMasks();
1968         serverlist_sortbyfield = SLIF_PING;
1969         serverlist_sortdescending = false;
1970     if (m_state != m_slist) {
1971                 Con_Print("Sending requests to master servers\n");
1972                 ServerList_QueryList();
1973                 serverlist_consoleoutput = true;
1974                 Con_Print("Listening for replies...\n");
1975         } else
1976                 ServerList_QueryList();
1977 }
1978
1979 void NetConn_Init(void)
1980 {
1981         int i;
1982         lhnetaddress_t tempaddress;
1983         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
1984         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
1985         Cmd_AddCommand("net_slist", Net_Slist_f, "query master series and print all server information");
1986         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
1987         Cvar_RegisterVariable(&net_slist_queriespersecond);
1988         Cvar_RegisterVariable(&net_slist_queriesperframe);
1989         Cvar_RegisterVariable(&net_slist_timeout);
1990         Cvar_RegisterVariable(&net_slist_maxtries);
1991         Cvar_RegisterVariable(&net_messagetimeout);
1992         Cvar_RegisterVariable(&net_messagerejointimeout);
1993         Cvar_RegisterVariable(&net_connecttimeout);
1994         Cvar_RegisterVariable(&cl_netlocalping);
1995         Cvar_RegisterVariable(&cl_netpacketloss);
1996         Cvar_RegisterVariable(&hostname);
1997         Cvar_RegisterVariable(&developer_networking);
1998         Cvar_RegisterVariable(&cl_netport);
1999         Cvar_RegisterVariable(&sv_netport);
2000         Cvar_RegisterVariable(&net_address);
2001         //Cvar_RegisterVariable(&net_address_ipv6);
2002         Cvar_RegisterVariable(&sv_public);
2003         Cvar_RegisterVariable(&sv_heartbeatperiod);
2004         for (i = 0;sv_masters[i].name;i++)
2005                 Cvar_RegisterVariable(&sv_masters[i]);
2006 // COMMANDLINEOPTION: Server: -ip <ipaddress> sets the ip address of this machine for purposes of networking (default 0.0.0.0 also known as INADDR_ANY), use only if you have multiple network adapters and need to choose one specifically.
2007         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2008         {
2009                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2010                 {
2011                         Con_Printf("-ip option used, setting net_address to \"%s\"\n");
2012                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
2013                 }
2014                 else
2015                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2016         }
2017 // COMMANDLINEOPTION: Server: -port <portnumber> sets the port to use for a server (default 26000, the same port as QUAKE itself), useful if you host multiple servers on your machine
2018         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2019         {
2020                 i = atoi(com_argv[i + 1]);
2021                 if (i >= 0 && i < 65536)
2022                 {
2023                         Con_Printf("-port option used, setting port cvar to %i\n", i);
2024                         Cvar_SetValueQuick(&sv_netport, i);
2025                 }
2026                 else
2027                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
2028         }
2029         cl_numsockets = 0;
2030         sv_numsockets = 0;
2031         net_message.data = net_message_buf;
2032         net_message.maxsize = sizeof(net_message_buf);
2033         net_message.cursize = 0;
2034         LHNET_Init();
2035 }
2036
2037 void NetConn_Shutdown(void)
2038 {
2039         NetConn_CloseClientPorts();
2040         NetConn_CloseServerPorts();
2041         LHNET_Shutdown();
2042 }
2043