rearrange SV_VM_Begin/End again to fix crashes
[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_SendUnreliableMessage(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         // if a reliable message fragment has been lost, send it again
443         if (!conn->canSend && conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
444         {
445                 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
446                 {
447                         dataLen = conn->sendMessageLength;
448                         eom = NETFLAG_EOM;
449                 }
450                 else
451                 {
452                         dataLen = MAX_PACKETFRAGMENT;
453                         eom = 0;
454                 }
455
456                 packetLen = NET_HEADERSIZE + dataLen;
457
458                 header = (unsigned int *)sendbuffer;
459                 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
460                 header[1] = BigLong(conn->sendSequence - 1);
461                 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
462
463                 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
464                 {
465                         conn->lastSendTime = realtime;
466                         packetsReSent++;
467                 }
468         }
469
470         // if we have a new reliable message to send, do so
471         if (conn->canSend && conn->message.cursize)
472         {
473                 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
474                 {
475                         Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, sizeof(conn->sendMessage));
476                         conn->message.overflowed = true;
477                         return -1;
478                 }
479
480                 if (developer_networking.integer && conn == cls.netcon)
481                 {
482                         Con_Print("client sending reliable message to server:\n");
483                         SZ_HexDumpToConsole(&conn->message);
484                 }
485
486                 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
487                 conn->sendMessageLength = conn->message.cursize;
488                 SZ_Clear(&conn->message);
489
490                 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
491                 {
492                         dataLen = conn->sendMessageLength;
493                         eom = NETFLAG_EOM;
494                 }
495                 else
496                 {
497                         dataLen = MAX_PACKETFRAGMENT;
498                         eom = 0;
499                 }
500
501                 packetLen = NET_HEADERSIZE + dataLen;
502
503                 header = (unsigned int *)sendbuffer;
504                 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
505                 header[1] = BigLong(conn->sendSequence);
506                 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
507
508                 conn->sendSequence++;
509                 conn->canSend = false;
510
511                 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
512
513                 conn->lastSendTime = realtime;
514                 packetsSent++;
515                 reliableMessagesSent++;
516         }
517
518         // if we have an unreliable message to send, do so
519         if (data->cursize)
520         {
521                 packetLen = NET_HEADERSIZE + data->cursize;
522
523                 if (packetLen > (int)sizeof(sendbuffer))
524                 {
525                         Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
526                         return -1;
527                 }
528
529                 header = (unsigned int *)sendbuffer;
530                 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
531                 header[1] = BigLong(conn->unreliableSendSequence);
532                 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
533
534                 conn->unreliableSendSequence++;
535
536                 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
537
538                 packetsSent++;
539                 unreliableMessagesSent++;
540         }
541         return 0;
542 }
543
544 void NetConn_CloseClientPorts(void)
545 {
546         for (;cl_numsockets > 0;cl_numsockets--)
547                 if (cl_sockets[cl_numsockets - 1])
548                         LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
549 }
550
551 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
552 {
553         lhnetaddress_t address;
554         lhnetsocket_t *s;
555         char addressstring2[1024];
556         if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
557         {
558                 if ((s = LHNET_OpenSocket_Connectionless(&address)))
559                 {
560                         cl_sockets[cl_numsockets++] = s;
561                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
562                         Con_Printf("Client opened a socket on address %s\n", addressstring2);
563                 }
564                 else
565                 {
566                         LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
567                         Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
568                 }
569         }
570         else
571                 Con_Printf("Client unable to parse address %s\n", addressstring);
572 }
573
574 void NetConn_OpenClientPorts(void)
575 {
576         int port;
577         NetConn_CloseClientPorts();
578         port = bound(0, cl_netport.integer, 65535);
579         if (cl_netport.integer != port)
580                 Cvar_SetValueQuick(&cl_netport, port);
581         Con_Printf("Client using port %i\n", port);
582         NetConn_OpenClientPort("local:2", 0);
583         NetConn_OpenClientPort(net_address.string, port);
584         //NetConn_OpenClientPort(net_address_ipv6.string, port);
585 }
586
587 void NetConn_CloseServerPorts(void)
588 {
589         for (;sv_numsockets > 0;sv_numsockets--)
590                 if (sv_sockets[sv_numsockets - 1])
591                         LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
592 }
593
594 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
595 {
596         lhnetaddress_t address;
597         lhnetsocket_t *s;
598         int port;
599         char addressstring2[1024];
600
601         for (port = defaultport; port <= defaultport + 100; port++)
602         {
603                 if (LHNETADDRESS_FromString(&address, addressstring, port))
604                 {
605                         if ((s = LHNET_OpenSocket_Connectionless(&address)))
606                         {
607                                 sv_sockets[sv_numsockets++] = s;
608                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
609                                 Con_Printf("Server listening on address %s\n", addressstring2);
610                                 break;
611                         }
612                         else
613                         {
614                                 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
615                                 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
616                         }
617                 }
618                 else
619                 {
620                         Con_Printf("Server unable to parse address %s\n", addressstring);
621                         // if it cant parse one address, it wont be able to parse another for sure
622                         break;
623                 }
624         }
625 }
626
627 void NetConn_OpenServerPorts(int opennetports)
628 {
629         int port;
630         NetConn_CloseServerPorts();
631         NetConn_UpdateSockets();
632         port = bound(0, sv_netport.integer, 65535);
633         if (port == 0)
634                 port = 26000;
635         Con_Printf("Server using port %i\n", port);
636         if (sv_netport.integer != port)
637                 Cvar_SetValueQuick(&sv_netport, port);
638         if (cls.state != ca_dedicated)
639                 NetConn_OpenServerPort("local:1", 0);
640         if (opennetports)
641         {
642                 NetConn_OpenServerPort(net_address.string, port);
643                 //NetConn_OpenServerPort(net_address_ipv6.string, port);
644         }
645         if (sv_numsockets == 0)
646                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
647 }
648
649 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
650 {
651         int i, a = LHNETADDRESS_GetAddressType(address);
652         for (i = 0;i < cl_numsockets;i++)
653                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
654                         return cl_sockets[i];
655         return NULL;
656 }
657
658 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
659 {
660         int i, a = LHNETADDRESS_GetAddressType(address);
661         for (i = 0;i < sv_numsockets;i++)
662                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
663                         return sv_sockets[i];
664         return NULL;
665 }
666
667 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
668 {
669         netconn_t *conn;
670         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
671         conn->mysocket = mysocket;
672         conn->peeraddress = *peeraddress;
673         conn->canSend = true;
674         conn->lastMessageTime = realtime;
675         conn->message.data = conn->messagedata;
676         conn->message.maxsize = sizeof(conn->messagedata);
677         conn->message.cursize = 0;
678         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
679         // reduce effectiveness of connection request floods
680         conn->timeout = realtime + net_connecttimeout.value;
681         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
682         conn->next = netconn_list;
683         netconn_list = conn;
684         return conn;
685 }
686
687 void NetConn_Close(netconn_t *conn)
688 {
689         netconn_t *c;
690         // remove connection from list
691         if (conn == netconn_list)
692                 netconn_list = conn->next;
693         else
694         {
695                 for (c = netconn_list;c;c = c->next)
696                 {
697                         if (c->next == conn)
698                         {
699                                 c->next = conn->next;
700                                 break;
701                         }
702                 }
703                 // not found in list, we'll avoid crashing here...
704                 if (!c)
705                         return;
706         }
707         // free connection
708         Mem_Free(conn);
709 }
710
711 static int clientport = -1;
712 static int clientport2 = -1;
713 static int hostport = -1;
714 void NetConn_UpdateSockets(void)
715 {
716         if (cls.state != ca_dedicated)
717         {
718                 if (clientport2 != cl_netport.integer)
719                 {
720                         clientport2 = cl_netport.integer;
721                         if (cls.state == ca_connected)
722                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
723                 }
724                 if (cls.state == ca_disconnected && clientport != clientport2)
725                 {
726                         clientport = clientport2;
727                         NetConn_CloseClientPorts();
728                 }
729                 if (cl_numsockets == 0)
730                         NetConn_OpenClientPorts();
731         }
732
733         if (hostport != sv_netport.integer)
734         {
735                 hostport = sv_netport.integer;
736                 if (sv.active)
737                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
738         }
739 }
740
741 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length)
742 {
743         unsigned int count;
744         unsigned int flags;
745         unsigned int sequence;
746         int qlength;
747
748         if (length >= 8)
749         {
750                 qlength = (unsigned int)BigLong(((int *)data)[0]);
751                 flags = qlength & ~NETFLAG_LENGTH_MASK;
752                 qlength &= NETFLAG_LENGTH_MASK;
753                 // control packets were already handled
754                 if (!(flags & NETFLAG_CTL) && qlength == length)
755                 {
756                         sequence = BigLong(((int *)data)[1]);
757                         packetsReceived++;
758                         data += 8;
759                         length -= 8;
760                         if (flags & NETFLAG_UNRELIABLE)
761                         {
762                                 if (sequence >= conn->unreliableReceiveSequence)
763                                 {
764                                         if (sequence > conn->unreliableReceiveSequence)
765                                         {
766                                                 count = sequence - conn->unreliableReceiveSequence;
767                                                 droppedDatagrams += count;
768                                                 Con_DPrintf("Dropped %u datagram(s)\n", count);
769                                         }
770                                         conn->unreliableReceiveSequence = sequence + 1;
771                                         conn->lastMessageTime = realtime;
772                                         conn->timeout = realtime + net_messagetimeout.value;
773                                         unreliableMessagesReceived++;
774                                         if (length > 0)
775                                         {
776                                                 SZ_Clear(&net_message);
777                                                 SZ_Write(&net_message, data, length);
778                                                 MSG_BeginReading();
779                                                 return 2;
780                                         }
781                                 }
782                                 else
783                                         Con_DPrint("Got a stale datagram\n");
784                                 return 1;
785                         }
786                         else if (flags & NETFLAG_ACK)
787                         {
788                                 if (sequence == (conn->sendSequence - 1))
789                                 {
790                                         if (sequence == conn->ackSequence)
791                                         {
792                                                 conn->ackSequence++;
793                                                 if (conn->ackSequence != conn->sendSequence)
794                                                         Con_DPrint("ack sequencing error\n");
795                                                 conn->lastMessageTime = realtime;
796                                                 conn->timeout = realtime + net_messagetimeout.value;
797                                                 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
798                                                 {
799                                                         unsigned int packetLen;
800                                                         unsigned int dataLen;
801                                                         unsigned int eom;
802                                                         unsigned int *header;
803
804                                                         conn->sendMessageLength -= MAX_PACKETFRAGMENT;
805                                                         memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
806
807                                                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
808                                                         {
809                                                                 dataLen = conn->sendMessageLength;
810                                                                 eom = NETFLAG_EOM;
811                                                         }
812                                                         else
813                                                         {
814                                                                 dataLen = MAX_PACKETFRAGMENT;
815                                                                 eom = 0;
816                                                         }
817
818                                                         packetLen = NET_HEADERSIZE + dataLen;
819
820                                                         header = (unsigned int *)sendbuffer;
821                                                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
822                                                         header[1] = BigLong(conn->sendSequence);
823                                                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
824
825                                                         conn->sendSequence++;
826
827                                                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
828                                                         {
829                                                                 conn->lastSendTime = realtime;
830                                                                 packetsSent++;
831                                                         }
832                                                 }
833                                                 else
834                                                 {
835                                                         conn->sendMessageLength = 0;
836                                                         conn->canSend = true;
837                                                 }
838                                         }
839                                         else
840                                                 Con_DPrint("Duplicate ACK received\n");
841                                 }
842                                 else
843                                         Con_DPrint("Stale ACK received\n");
844                                 return 1;
845                         }
846                         else if (flags & NETFLAG_DATA)
847                         {
848                                 unsigned int temppacket[2];
849                                 temppacket[0] = BigLong(8 | NETFLAG_ACK);
850                                 temppacket[1] = BigLong(sequence);
851                                 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
852                                 if (sequence == conn->receiveSequence)
853                                 {
854                                         conn->lastMessageTime = realtime;
855                                         conn->timeout = realtime + net_messagetimeout.value;
856                                         conn->receiveSequence++;
857                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
858                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
859                                                 conn->receiveMessageLength += length;
860                                         } else {
861                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
862                                                                         "Dropping the message!\n", sequence );
863                                                 conn->receiveMessageLength = 0;
864                                                 return 1;
865                                         }
866                                         if (flags & NETFLAG_EOM)
867                                         {
868                                                 reliableMessagesReceived++;
869                                                 length = conn->receiveMessageLength;
870                                                 conn->receiveMessageLength = 0;
871                                                 if (length > 0)
872                                                 {
873                                                         SZ_Clear(&net_message);
874                                                         SZ_Write(&net_message, conn->receiveMessage, length);
875                                                         MSG_BeginReading();
876                                                         return 2;
877                                                 }
878                                         }
879                                 }
880                                 else
881                                         receivedDuplicateCount++;
882                                 return 1;
883                         }
884                 }
885         }
886         return 0;
887 }
888
889 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
890 {
891         cls.connect_trying = false;
892         M_Update_Return_Reason("");
893         // the connection request succeeded, stop current connection and set up a new connection
894         CL_Disconnect();
895         // if we're connecting to a remote server, shut down any local server
896         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
897                 Host_ShutdownServer ();
898         // allocate a net connection to keep track of things
899         cls.netcon = NetConn_Open(mysocket, peeraddress);
900         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
901         key_dest = key_game;
902         m_state = m_none;
903         cls.demonum = -1;                       // not in the demo loop now
904         cls.state = ca_connected;
905         cls.signon = 0;                         // need all the signon messages before playing
906 }
907
908 int NetConn_IsLocalGame(void)
909 {
910         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
911                 return true;
912         return false;
913 }
914
915 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
916 {
917         int ret, c, control;
918         const char *s;
919         char *string, addressstring2[128], cname[128], ipstring[32];
920         char stringbuf[16384];
921
922         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
923         {
924                 // received a command string - strip off the packaging and put it
925                 // into our string buffer with NULL termination
926                 data += 4;
927                 length -= 4;
928                 length = min(length, (int)sizeof(stringbuf) - 1);
929                 memcpy(stringbuf, data, length);
930                 stringbuf[length] = 0;
931                 string = stringbuf;
932
933                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
934
935                 if (developer.integer)
936                 {
937                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
938                         Com_HexDumpToConsole(data, length);
939                 }
940
941                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
942                 {
943                         char protocolnames[1400];
944                         Protocol_Names(protocolnames, sizeof(protocolnames));
945                         Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
946                         M_Update_Return_Reason("Got challenge response");
947                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
948                         return true;
949                 }
950                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
951                 {
952                         M_Update_Return_Reason("Accepted");
953                         NetConn_ConnectionEstablished(mysocket, peeraddress);
954                         return true;
955                 }
956                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
957                 {
958                         char rejectreason[32];
959                         cls.connect_trying = false;
960                         string += 7;
961                         length = max(length - 7, (int)sizeof(rejectreason) - 1);
962                         memcpy(rejectreason, string, length);
963                         rejectreason[length] = 0;
964                         M_Update_Return_Reason(rejectreason);
965                         return true;
966                 }
967                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
968                 {
969                         serverlist_info_t *info;
970                         int n;
971                         double pingtime;
972
973                         string += 13;
974                         // serverlist only uses text addresses
975                         LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
976                         // search the cache for this server and update it
977                         for( n = 0; n < serverlist_cachecount; n++ )
978                                 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
979                                         break;
980                         if( n == serverlist_cachecount ) {
981                                 // LAN search doesnt require an answer from the master server so we wont
982                                 // know the ping nor will it be initialized already...
983
984                                 // find a slot
985                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
986                                         return true;
987
988                                 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
989                                 // store the data the engine cares about (address and ping)
990                                 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
991                                 serverlist_cache[serverlist_cachecount].info.ping = 100000;
992                                 serverlist_cache[serverlist_cachecount].querytime = realtime;
993                                 // if not in the slist menu we should print the server to console
994                                 if (serverlist_consoleoutput) {
995                                         Con_Printf("querying %s\n", ipstring);
996                                 }
997
998                                 ++serverlist_cachecount;
999                         }
1000
1001                         info = &serverlist_cache[n].info;
1002                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1003                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1004                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1005                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1006                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1007                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1008                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1009
1010                         if (info->ping == 100000)
1011                                         serverreplycount++;
1012
1013                         pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
1014                         pingtime = bound(0, pingtime, 9999);
1015                         // update the ping
1016                         info->ping = pingtime;
1017
1018                         // legacy/old stuff move it to the menu ASAP
1019
1020                         // build description strings for the things users care about
1021                         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);
1022                         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);
1023                         if( serverlist_cache[n].query == SQS_QUERIED ) {
1024                                 ServerList_ViewList_Remove( &serverlist_cache[n] );
1025                         }
1026                         // if not in the slist menu we should print the server to console (if wanted)
1027                         else if( serverlist_consoleoutput )
1028                                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1029                         // and finally, update the view set
1030                         ServerList_ViewList_Insert( &serverlist_cache[n] );
1031                         serverlist_cache[n].query = SQS_QUERIED;
1032
1033                         return true;
1034                 }
1035                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1036                 {
1037                         // Extract the IP addresses
1038                         data += 18;
1039                         length -= 18;
1040                         masterreplycount++;
1041                         if (serverlist_consoleoutput)
1042                                 Con_Print("received server list...\n");
1043                         while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1044                         {
1045                                 int n;
1046
1047                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1048                                 if (developer.integer)
1049                                         Con_Printf("Requesting info from server %s\n", ipstring);
1050                                 // ignore the rest of the message if the serverlist is full
1051                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1052                                         break;
1053                                 // also ignore it if we have already queried it (other master server response)
1054                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1055                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1056                                                 break;
1057                                 if( n >= serverlist_cachecount )
1058                                 {
1059                                         serverquerycount++;
1060
1061                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1062                                         // store the data the engine cares about (address and ping)
1063                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1064                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1065                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1066
1067                                         ++serverlist_cachecount;
1068                                 }
1069
1070                                 // move on to next address in packet
1071                                 data += 7;
1072                                 length -= 7;
1073                         }
1074                         // begin or resume serverlist queries
1075                         serverlist_querysleep = false;
1076                         return true;
1077                 }
1078                 /*
1079                 if (!strncmp(string, "ping", 4))
1080                 {
1081                         if (developer.integer)
1082                                 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1083                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1084                         return true;
1085                 }
1086                 if (!strncmp(string, "ack", 3))
1087                         return true;
1088                 */
1089                 if (string[0] == 'n')
1090                 {
1091                         // qw print command
1092                         Con_Printf("QW print command from server at %s:\n", addressstring2, string + 1);
1093                 }
1094                 // we may not have liked the packet, but it was a command packet, so
1095                 // we're done processing this packet now
1096                 return true;
1097         }
1098         // netquake control packets, supported for compatibility only
1099         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1100         {
1101                 c = data[4];
1102                 data += 5;
1103                 length -= 5;
1104                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1105                 switch (c)
1106                 {
1107                 case CCREP_ACCEPT:
1108                         if (developer.integer)
1109                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1110                         if (cls.connect_trying)
1111                         {
1112                                 lhnetaddress_t clientportaddress;
1113                                 clientportaddress = *peeraddress;
1114                                 if (length >= 4)
1115                                 {
1116                                         unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1117                                         data += 4;
1118                                         length -= 4;
1119                                         LHNETADDRESS_SetPort(&clientportaddress, port);
1120                                 }
1121                                 M_Update_Return_Reason("Accepted");
1122                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1123                         }
1124                         break;
1125                 case CCREP_REJECT:
1126                         if (developer.integer)
1127                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1128                         cls.connect_trying = false;
1129                         M_Update_Return_Reason((char *)data);
1130                         break;
1131 #if 0
1132                 case CCREP_SERVER_INFO:
1133                         if (developer.integer)
1134                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1135                         if (cls.state != ca_dedicated)
1136                         {
1137                                 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1138                                 // string we just ignore it and keep the real address
1139                                 MSG_ReadString();
1140                                 // serverlist only uses text addresses
1141                                 cname = UDP_AddrToString(readaddr);
1142                                 // search the cache for this server
1143                                 for (n = 0; n < hostCacheCount; n++)
1144                                         if (!strcmp(cname, serverlist[n].cname))
1145                                                 break;
1146                                 // add it
1147                                 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1148                                 {
1149                                         hostCacheCount++;
1150                                         memset(&serverlist[n], 0, sizeof(serverlist[n]));
1151                                         strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1152                                         strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1153                                         serverlist[n].users = MSG_ReadByte();
1154                                         serverlist[n].maxusers = MSG_ReadByte();
1155                                         c = MSG_ReadByte();
1156                                         if (c != NET_PROTOCOL_VERSION)
1157                                         {
1158                                                 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1159                                                 strcpy(serverlist[n].name, "*");
1160                                                 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1161                                         }
1162                                         strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1163                                 }
1164                         }
1165                         break;
1166                 case CCREP_PLAYER_INFO:
1167                         // we got a CCREP_PLAYER_INFO??
1168                         //if (developer.integer)
1169                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1170                         break;
1171                 case CCREP_RULE_INFO:
1172                         // we got a CCREP_RULE_INFO??
1173                         //if (developer.integer)
1174                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1175                         break;
1176 #endif
1177                 default:
1178                         break;
1179                 }
1180                 // we may not have liked the packet, but it was a valid control
1181                 // packet, so we're done processing this packet now
1182                 return true;
1183         }
1184         ret = 0;
1185         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)
1186                 CL_ParseServerMessage();
1187         return ret;
1188 }
1189
1190 void NetConn_QueryQueueFrame(void)
1191 {
1192         int index;
1193         int queries;
1194         int maxqueries;
1195         double timeouttime;
1196         static double querycounter = 0;
1197
1198         if (serverlist_querysleep)
1199                 return;
1200
1201         // each time querycounter reaches 1.0 issue a query
1202         querycounter += host_realframetime * net_slist_queriespersecond.value;
1203         maxqueries = (int)querycounter;
1204         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1205         querycounter -= maxqueries;
1206
1207         if( maxqueries == 0 ) {
1208                 return;
1209         }
1210
1211         // scan serverlist and issue queries as needed
1212     serverlist_querysleep = true;
1213
1214         timeouttime = realtime - net_slist_timeout.value;
1215         for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1216         {
1217                 serverlist_entry_t *entry = &serverlist_cache[ index ];
1218                 if( entry->query != SQS_QUERYING )
1219                 {
1220                         continue;
1221                 }
1222
1223         serverlist_querysleep = false;
1224                 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1225                 {
1226                         continue;
1227                 }
1228
1229                 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1230                 {
1231                         lhnetaddress_t address;
1232                         int socket;
1233
1234                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1235                         for (socket = 0; socket < cl_numsockets ; socket++) {
1236                                 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1237                         }
1238
1239                         entry->querytime = realtime;
1240                         entry->querycounter++;
1241
1242                         // if not in the slist menu we should print the server to console
1243                         if (serverlist_consoleoutput)
1244                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1245
1246                         queries++;
1247                 }
1248                 else
1249                 {
1250                         entry->query = SQS_TIMEDOUT;
1251                 }
1252         }
1253 }
1254
1255 void NetConn_ClientFrame(void)
1256 {
1257         int i, length;
1258         lhnetaddress_t peeraddress;
1259         NetConn_UpdateSockets();
1260         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1261         {
1262                 if (cls.connect_remainingtries == 0)
1263                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1264                 cls.connect_nextsendtime = realtime + 1;
1265                 cls.connect_remainingtries--;
1266                 if (cls.connect_remainingtries <= -10)
1267                 {
1268                         cls.connect_trying = false;
1269                         M_Update_Return_Reason("Connect: Failed");
1270                         return;
1271                 }
1272                 // try challenge first (newer server)
1273                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1274                 // then try netquake as a fallback (old server, or netquake)
1275                 SZ_Clear(&net_message);
1276                 // save space for the header, filled in later
1277                 MSG_WriteLong(&net_message, 0);
1278                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1279                 MSG_WriteString(&net_message, "QUAKE");
1280                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1281                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1282                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1283                 SZ_Clear(&net_message);
1284         }
1285         for (i = 0;i < cl_numsockets;i++)
1286                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1287                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1288         NetConn_QueryQueueFrame();
1289         if (cls.netcon && realtime > cls.netcon->timeout)
1290         {
1291                 Con_Print("Connection timed out\n");
1292                 CL_Disconnect();
1293                 Host_ShutdownServer ();
1294         }
1295 }
1296
1297 #define MAX_CHALLENGES 128
1298 struct challenge_s
1299 {
1300         lhnetaddress_t address;
1301         double time;
1302         char string[12];
1303 }
1304 challenge[MAX_CHALLENGES];
1305
1306 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1307 {
1308         int i;
1309         char c;
1310         for (i = 0;i < bufferlength - 1;i++)
1311         {
1312                 do
1313                 {
1314                         c = rand () % (127 - 33) + 33;
1315                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1316                 buffer[i] = c;
1317         }
1318         buffer[i] = 0;
1319 }
1320
1321 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1322 {
1323         unsigned int nb_clients = 0, i;
1324         int length;
1325
1326         // How many clients are there?
1327         for (i = 0;i < (unsigned int)svs.maxclients;i++)
1328                 if (svs.clients[i].active)
1329                         nb_clients++;
1330
1331         // TODO: we should add more information for the full status string
1332         length = dpsnprintf(out_msg, out_size,
1333                                                 "\377\377\377\377%s\x0A"
1334                                                 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1335                                                 "\\clients\\%d\\mapname\\%s\\hostname\\%s""\\protocol\\%d"
1336                                                 "%s%s"
1337                                                 "%s",
1338                                                 fullstatus ? "statusResponse" : "infoResponse",
1339                                                 gamename, com_modname, svs.maxclients,
1340                                                 nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1341                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1342                                                 fullstatus ? "\n" : "");
1343
1344         // Make sure it fits in the buffer
1345         if (length < 0)
1346                 return false;
1347
1348         if (fullstatus)
1349         {
1350                 char *ptr;
1351                 int left;
1352
1353                 ptr = out_msg + length;
1354                 left = (int)out_size - length;
1355
1356                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1357                 {
1358                         client_t *cl = &svs.clients[i];
1359                         if (cl->active)
1360                         {
1361                                 int nameind, cleanind;
1362                                 char curchar;
1363                                 char cleanname [sizeof(cl->name)];
1364
1365                                 // Remove all characters '"' and '\' in the player name
1366                                 nameind = 0;
1367                                 cleanind = 0;
1368                                 do
1369                                 {
1370                                         curchar = cl->name[nameind++];
1371                                         if (curchar != '"' && curchar != '\\')
1372                                         {
1373                                                 cleanname[cleanind++] = curchar;
1374                                                 if (cleanind == sizeof(cleanname) - 1)
1375                                                         break;
1376                                         }
1377                                 } while (curchar != '\0');
1378
1379                                 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1380                                                                         cl->frags,
1381                                                                         (int)(cl->ping * 1000.0f),
1382                                                                         cleanname);
1383                                 if(length < 0)
1384                                         return false;
1385                                 left -= length;
1386                                 ptr += length;
1387                         }
1388                 }
1389         }
1390
1391         return true;
1392 }
1393
1394 extern void SV_SendServerinfo (client_t *client);
1395 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1396 {
1397         int i, ret, clientnum, best;
1398         double besttime;
1399         client_t *client;
1400         netconn_t *conn;
1401         char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
1402
1403         // see if we can identify the sender as a local player
1404         // (this is necessary for rcon to send a reliable reply if the client is
1405         //  actually on the server, not sending remotely)
1406         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1407                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1408                         break;
1409         if (i == svs.maxclients)
1410                 host_client = NULL;
1411
1412         if (sv.active)
1413         {
1414                 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1415                 {
1416                         // received a command string - strip off the packaging and put it
1417                         // into our string buffer with NULL termination
1418                         data += 4;
1419                         length -= 4;
1420                         length = min(length, (int)sizeof(stringbuf) - 1);
1421                         memcpy(stringbuf, data, length);
1422                         stringbuf[length] = 0;
1423                         string = stringbuf;
1424
1425                         if (developer.integer)
1426                         {
1427                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1428                                 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1429                                 Com_HexDumpToConsole(data, length);
1430                         }
1431
1432                         if (length >= 12 && !memcmp(string, "getchallenge", 12))
1433                         {
1434                                 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1435                                 {
1436                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1437                                                 break;
1438                                         if (besttime > challenge[i].time)
1439                                                 besttime = challenge[best = i].time;
1440                                 }
1441                                 // if we did not find an exact match, choose the oldest and
1442                                 // update address and string
1443                                 if (i == MAX_CHALLENGES)
1444                                 {
1445                                         i = best;
1446                                         challenge[i].address = *peeraddress;
1447                                         NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1448                                 }
1449                                 challenge[i].time = realtime;
1450                                 // send the challenge
1451                                 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1452                                 return true;
1453                         }
1454                         if (length > 8 && !memcmp(string, "connect\\", 8))
1455                         {
1456                                 string += 7;
1457                                 length -= 7;
1458                                 if ((s = SearchInfostring(string, "challenge")))
1459                                 {
1460                                         // validate the challenge
1461                                         for (i = 0;i < MAX_CHALLENGES;i++)
1462                                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1463                                                         break;
1464                                         if (i < MAX_CHALLENGES)
1465                                         {
1466                                                 // check engine protocol
1467                                                 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1468                                                 {
1469                                                         if (developer.integer)
1470                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1471                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1472                                                 }
1473                                                 else
1474                                                 {
1475                                                         // see if this is a duplicate connection request
1476                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1477                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1478                                                                         break;
1479                                                         if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1480                                                         {
1481                                                                 // client is still trying to connect,
1482                                                                 // so we send a duplicate reply
1483                                                                 if (developer.integer)
1484                                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1485                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1486                                                         }
1487 #if 0
1488                                                         else if (clientnum < svs.maxclients)
1489                                                         {
1490                                                                 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1491                                                                 {
1492                                                                         // client crashed and is coming back, keep their stuff intact
1493                                                                         SV_SendServerinfo(client);
1494                                                                         //host_client = client;
1495                                                                         //SV_DropClient (true);
1496                                                                 }
1497                                                                 // else ignore them
1498                                                         }
1499 #endif
1500                                                         else
1501                                                         {
1502                                                                 // this is a new client, find a slot
1503                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1504                                                                         if (!client->active)
1505                                                                                 break;
1506                                                                 if (clientnum < svs.maxclients)
1507                                                                 {
1508                                                                         // prepare the client struct
1509                                                                         if ((conn = NetConn_Open(mysocket, peeraddress)))
1510                                                                         {
1511                                                                                 // allocated connection
1512                                                                                 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1513                                                                                 if (developer.integer)
1514                                                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1515                                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1516                                                                                 // now set up the client
1517                                                                                 SV_VM_Begin();
1518                                                                                 SV_ConnectClient(clientnum, conn);
1519                                                                                 SV_VM_End();
1520                                                                                 NetConn_Heartbeat(1);
1521                                                                         }
1522                                                                 }
1523                                                                 else
1524                                                                 {
1525                                                                         // server is full
1526                                                                         if (developer.integer)
1527                                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1528                                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1529                                                                 }
1530                                                         }
1531                                                 }
1532                                         }
1533                                 }
1534                                 return true;
1535                         }
1536                         if (length >= 7 && !memcmp(string, "getinfo", 7))
1537                         {
1538                                 const char *challenge = NULL;
1539
1540                                 // If there was a challenge in the getinfo message
1541                                 if (length > 8 && string[7] == ' ')
1542                                         challenge = string + 8;
1543
1544                                 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
1545                                 {
1546                                         if (developer.integer)
1547                                                 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1548                                         NetConn_WriteString(mysocket, response, peeraddress);
1549                                 }
1550                                 return true;
1551                         }
1552                         if (length >= 9 && !memcmp(string, "getstatus", 9))
1553                         {
1554                                 const char *challenge = NULL;
1555
1556                                 // If there was a challenge in the getinfo message
1557                                 if (length > 10 && string[9] == ' ')
1558                                         challenge = string + 10;
1559
1560                                 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
1561                                 {
1562                                         if (developer.integer)
1563                                                 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
1564                                         NetConn_WriteString(mysocket, response, peeraddress);
1565                                 }
1566                                 return true;
1567                         }
1568                         if (length >= 5 && !memcmp(string, "rcon ", 5))
1569                         {
1570                                 int i;
1571                                 char *s = string + 5;
1572                                 char password[64];
1573                                 for (i = 0;*s > ' ';s++)
1574                                         if (i < (int)sizeof(password) - 1)
1575                                                 password[i++] = *s;
1576                                 password[i] = 0;
1577                                 if (!strcmp(rcon_password.string, password))
1578                                 {
1579                                         // looks like a legitimate rcon command with the correct password
1580                                         Con_Printf("server received rcon command from %s:\n%s\n", host_client ? host_client->name : addressstring2, s);
1581                                         rcon_redirect = true;
1582                                         rcon_redirect_bufferpos = 0;
1583                                         Cmd_ExecuteString(s, src_command);
1584                                         rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
1585                                         rcon_redirect = false;
1586                                         // print resulting text to client
1587                                         // if client is playing, send a reliable reply instead of
1588                                         // a command packet
1589                                         if (host_client)
1590                                         {
1591                                                 // if the netconnection is loop, then this is the
1592                                                 // local player on a listen mode server, and it would
1593                                                 // result in duplicate printing to the console
1594                                                 // (not that the local player should be using rcon
1595                                                 //  when they have the console)
1596                                                 if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1597                                                         SV_ClientPrintf("%s", rcon_redirect_buffer);
1598                                         }
1599                                         else
1600                                         {
1601                                                 // qw print command
1602                                                 dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
1603                                                 NetConn_WriteString(mysocket, response, peeraddress);
1604                                         }
1605                                 }
1606                                 return true;
1607                         }
1608                         /*
1609                         if (!strncmp(string, "ping", 4))
1610                         {
1611                                 if (developer.integer)
1612                                         Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1613                                 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1614                                 return true;
1615                         }
1616                         if (!strncmp(string, "ack", 3))
1617                                 return true;
1618                         */
1619                         // we may not have liked the packet, but it was a command packet, so
1620                         // we're done processing this packet now
1621                         return true;
1622                 }
1623                 // LordHavoc: disabled netquake control packet support in server
1624 #if 0
1625                 {
1626                         int c, control;
1627                         // netquake control packets, supported for compatibility only
1628                         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1629                         {
1630                                 c = data[4];
1631                                 data += 5;
1632                                 length -= 5;
1633                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1634                                 switch (c)
1635                                 {
1636                                 case CCREQ_CONNECT:
1637                                         //if (developer.integer)
1638                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1639                                         if (length >= (int)strlen("QUAKE") + 1 + 1)
1640                                         {
1641                                                 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1642                                                 {
1643                                                         if (developer.integer)
1644                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1645                                                         SZ_Clear(&net_message);
1646                                                         // save space for the header, filled in later
1647                                                         MSG_WriteLong(&net_message, 0);
1648                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1649                                                         MSG_WriteString(&net_message, "Incompatible version.\n");
1650                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1651                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1652                                                         SZ_Clear(&net_message);
1653                                                 }
1654                                                 else
1655                                                 {
1656                                                         // see if this is a duplicate connection request
1657                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1658                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1659                                                                         break;
1660                                                         if (clientnum < svs.maxclients)
1661                                                         {
1662                                                                 // duplicate connection request
1663                                                                 if (realtime - client->connecttime < 2.0)
1664                                                                 {
1665                                                                         // client is still trying to connect,
1666                                                                         // so we send a duplicate reply
1667                                                                         if (developer.integer)
1668                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1669                                                                         SZ_Clear(&net_message);
1670                                                                         // save space for the header, filled in later
1671                                                                         MSG_WriteLong(&net_message, 0);
1672                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1673                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1674                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1675                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1676                                                                         SZ_Clear(&net_message);
1677                                                                 }
1678 #if 0
1679                                                                 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1680                                                                 {
1681                                                                         SV_SendServerinfo(client);
1682                                                                         // the old client hasn't sent us anything
1683                                                                         // in quite a while, so kick off and let
1684                                                                         // the retry take care of it...
1685                                                                         //host_client = client;
1686                                                                         //SV_DropClient (true);
1687                                                                 }
1688 #endif
1689                                                         }
1690                                                         else
1691                                                         {
1692                                                                 // this is a new client, find a slot
1693                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1694                                                                         if (!client->active)
1695                                                                                 break;
1696                                                                 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1697                                                                 {
1698                                                                         // connect to the client
1699                                                                         // everything is allocated, just fill in the details
1700                                                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
1701                                                                         if (developer.integer)
1702                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1703                                                                         // send back the info about the server connection
1704                                                                         SZ_Clear(&net_message);
1705                                                                         // save space for the header, filled in later
1706                                                                         MSG_WriteLong(&net_message, 0);
1707                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1708                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1709                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1710                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1711                                                                         SZ_Clear(&net_message);
1712                                                                         // now set up the client struct
1713                                                                         SV_VM_Begin();
1714                                                                         SV_ConnectClient(clientnum, conn);
1715                                                                         SV_VM_End();
1716                                                                         NetConn_Heartbeat(1);
1717                                                                 }
1718                                                                 else
1719                                                                 {
1720                                                                         //if (developer.integer)
1721                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1722                                                                         // no room; try to let player know
1723                                                                         SZ_Clear(&net_message);
1724                                                                         // save space for the header, filled in later
1725                                                                         MSG_WriteLong(&net_message, 0);
1726                                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1727                                                                         MSG_WriteString(&net_message, "Server is full.\n");
1728                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1729                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1730                                                                         SZ_Clear(&net_message);
1731                                                                 }
1732                                                         }
1733                                                 }
1734                                         }
1735                                         break;
1736 #if 0
1737                                 case CCREQ_SERVER_INFO:
1738                                         if (developer.integer)
1739                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1740                                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1741                                         {
1742                                                 if (developer.integer)
1743                                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1744                                                 SZ_Clear(&net_message);
1745                                                 // save space for the header, filled in later
1746                                                 MSG_WriteLong(&net_message, 0);
1747                                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1748                                                 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1749                                                 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1750                                                 MSG_WriteString(&net_message, hostname.string);
1751                                                 MSG_WriteString(&net_message, sv.name);
1752                                                 MSG_WriteByte(&net_message, net_activeconnections);
1753                                                 MSG_WriteByte(&net_message, svs.maxclients);
1754                                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1755                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1756                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1757                                                 SZ_Clear(&net_message);
1758                                         }
1759                                         break;
1760                                 case CCREQ_PLAYER_INFO:
1761                                         if (developer.integer)
1762                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1763                                         if (sv.active)
1764                                         {
1765                                                 int playerNumber, activeNumber, clientNumber;
1766                                                 client_t *client;
1767
1768                                                 playerNumber = MSG_ReadByte();
1769                                                 activeNumber = -1;
1770                                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1771                                                         if (client->active && ++activeNumber == playerNumber)
1772                                                                 break;
1773                                                 if (clientNumber != svs.maxclients)
1774                                                 {
1775                                                         SZ_Clear(&net_message);
1776                                                         // save space for the header, filled in later
1777                                                         MSG_WriteLong(&net_message, 0);
1778                                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1779                                                         MSG_WriteByte(&net_message, playerNumber);
1780                                                         MSG_WriteString(&net_message, client->name);
1781                                                         MSG_WriteLong(&net_message, client->colors);
1782                                                         MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
1783                                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1784                                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1785                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1786                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1787                                                         SZ_Clear(&net_message);
1788                                                 }
1789                                         }
1790                                         break;
1791                                 case CCREQ_RULE_INFO:
1792                                         if (developer.integer)
1793                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1794                                         if (sv.active)
1795                                         {
1796                                                 char *prevCvarName;
1797                                                 cvar_t *var;
1798
1799                                                 // find the search start location
1800                                                 prevCvarName = MSG_ReadString();
1801                                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1802
1803                                                 // send the response
1804                                                 SZ_Clear(&net_message);
1805                                                 // save space for the header, filled in later
1806                                                 MSG_WriteLong(&net_message, 0);
1807                                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1808                                                 if (var)
1809                                                 {
1810                                                         MSG_WriteString(&net_message, var->name);
1811                                                         MSG_WriteString(&net_message, var->string);
1812                                                 }
1813                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1814                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1815                                                 SZ_Clear(&net_message);
1816                                         }
1817                                         break;
1818 #endif
1819                                 default:
1820                                         break;
1821                                 }
1822                                 // we may not have liked the packet, but it was a valid control
1823                                 // packet, so we're done processing this packet now
1824                                 return true;
1825                         }
1826                 }
1827 #endif
1828                 if (host_client)
1829                 {
1830                         if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1831                         {
1832                                 SV_VM_Begin();
1833                                 SV_ReadClientMessage();
1834                                 SV_VM_End();
1835                                 return ret;
1836                         }
1837                 }
1838         }
1839         return 0;
1840 }
1841
1842 void NetConn_ServerFrame(void)
1843 {
1844         int i, length;
1845         lhnetaddress_t peeraddress;
1846         NetConn_UpdateSockets();
1847         for (i = 0;i < sv_numsockets;i++)
1848                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1849                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1850         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1851         {
1852                 // never timeout loopback connections
1853                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1854                 {
1855                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1856                         SV_DropClient(false);
1857                 }
1858         }
1859 }
1860
1861 void NetConn_QueryMasters(void)
1862 {
1863         int i;
1864         int masternum;
1865         lhnetaddress_t masteraddress;
1866         lhnetaddress_t broadcastaddress;
1867         char request[256];
1868
1869         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1870                 return;
1871
1872         // 26000 is the default quake server port, servers on other ports will not
1873         // be found
1874         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1875         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1876
1877         for (i = 0;i < cl_numsockets;i++)
1878         {
1879                 if (cl_sockets[i])
1880                 {
1881                         // search LAN for Quake servers
1882                         SZ_Clear(&net_message);
1883                         // save space for the header, filled in later
1884                         MSG_WriteLong(&net_message, 0);
1885                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1886                         MSG_WriteString(&net_message, "QUAKE");
1887                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1888                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1889                         NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1890                         SZ_Clear(&net_message);
1891
1892                         // search LAN for DarkPlaces servers
1893                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1894
1895                         // build the getservers message to send to the master servers
1896                         dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1897
1898                         // search internet
1899                         for (masternum = 0;sv_masters[masternum].name;masternum++)
1900                         {
1901                                 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1902                                 {
1903                                         masterquerycount++;
1904                                         NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1905                                 }
1906                         }
1907                 }
1908         }
1909         if (!masterquerycount)
1910         {
1911                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1912                 M_Update_Return_Reason("No network");
1913         }
1914 }
1915
1916 void NetConn_Heartbeat(int priority)
1917 {
1918         lhnetaddress_t masteraddress;
1919         int masternum;
1920         lhnetsocket_t *mysocket;
1921
1922         // if it's a state change (client connected), limit next heartbeat to no
1923         // more than 30 sec in the future
1924         if (priority == 1 && nextheartbeattime > realtime + 30.0)
1925                 nextheartbeattime = realtime + 30.0;
1926
1927         // limit heartbeatperiod to 30 to 270 second range,
1928         // lower limit is to avoid abusing master servers with excess traffic,
1929         // upper limit is to avoid timing out on the master server (which uses
1930         // 300 sec timeout)
1931         if (sv_heartbeatperiod.value < 30)
1932                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1933         if (sv_heartbeatperiod.value > 270)
1934                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1935
1936         // make advertising optional and don't advertise singleplayer games, and
1937         // only send a heartbeat as often as the admin wants
1938         if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1939         {
1940                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1941                 for (masternum = 0;sv_masters[masternum].name;masternum++)
1942                         if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1943                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1944         }
1945 }
1946
1947 static void Net_Heartbeat_f(void)
1948 {
1949         if (sv.active)
1950                 NetConn_Heartbeat(2);
1951         else
1952                 Con_Print("No server running, can not heartbeat to master server.\n");
1953 }
1954
1955 void PrintStats(netconn_t *conn)
1956 {
1957         Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1958 }
1959
1960 void Net_Stats_f(void)
1961 {
1962         netconn_t *conn;
1963         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
1964         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
1965         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
1966         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1967         Con_Printf("packetsSent                = %i\n", packetsSent);
1968         Con_Printf("packetsReSent              = %i\n", packetsReSent);
1969         Con_Printf("packetsReceived            = %i\n", packetsReceived);
1970         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
1971         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
1972         Con_Print("connections                =\n");
1973         for (conn = netconn_list;conn;conn = conn->next)
1974                 PrintStats(conn);
1975 }
1976
1977 void Net_Slist_f(void)
1978 {
1979         ServerList_ResetMasks();
1980         serverlist_sortbyfield = SLIF_PING;
1981         serverlist_sortdescending = false;
1982     if (m_state != m_slist) {
1983                 Con_Print("Sending requests to master servers\n");
1984                 ServerList_QueryList();
1985                 serverlist_consoleoutput = true;
1986                 Con_Print("Listening for replies...\n");
1987         } else
1988                 ServerList_QueryList();
1989 }
1990
1991 void NetConn_Init(void)
1992 {
1993         int i;
1994         lhnetaddress_t tempaddress;
1995         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
1996         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
1997         Cmd_AddCommand("net_slist", Net_Slist_f, "query master series and print all server information");
1998         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
1999         Cvar_RegisterVariable(&net_slist_queriespersecond);
2000         Cvar_RegisterVariable(&net_slist_queriesperframe);
2001         Cvar_RegisterVariable(&net_slist_timeout);
2002         Cvar_RegisterVariable(&net_slist_maxtries);
2003         Cvar_RegisterVariable(&net_messagetimeout);
2004         Cvar_RegisterVariable(&net_messagerejointimeout);
2005         Cvar_RegisterVariable(&net_connecttimeout);
2006         Cvar_RegisterVariable(&cl_netlocalping);
2007         Cvar_RegisterVariable(&cl_netpacketloss);
2008         Cvar_RegisterVariable(&hostname);
2009         Cvar_RegisterVariable(&developer_networking);
2010         Cvar_RegisterVariable(&cl_netport);
2011         Cvar_RegisterVariable(&sv_netport);
2012         Cvar_RegisterVariable(&net_address);
2013         //Cvar_RegisterVariable(&net_address_ipv6);
2014         Cvar_RegisterVariable(&sv_public);
2015         Cvar_RegisterVariable(&sv_heartbeatperiod);
2016         for (i = 0;sv_masters[i].name;i++)
2017                 Cvar_RegisterVariable(&sv_masters[i]);
2018 // 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.
2019         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2020         {
2021                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2022                 {
2023                         Con_Printf("-ip option used, setting net_address to \"%s\"\n");
2024                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
2025                 }
2026                 else
2027                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2028         }
2029 // 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
2030         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2031         {
2032                 i = atoi(com_argv[i + 1]);
2033                 if (i >= 0 && i < 65536)
2034                 {
2035                         Con_Printf("-port option used, setting port cvar to %i\n", i);
2036                         Cvar_SetValueQuick(&sv_netport, i);
2037                 }
2038                 else
2039                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
2040         }
2041         cl_numsockets = 0;
2042         sv_numsockets = 0;
2043         net_message.data = net_message_buf;
2044         net_message.maxsize = sizeof(net_message_buf);
2045         net_message.cursize = 0;
2046         LHNET_Init();
2047 }
2048
2049 void NetConn_Shutdown(void)
2050 {
2051         NetConn_CloseClientPorts();
2052         NetConn_CloseServerPorts();
2053         LHNET_Shutdown();
2054 }
2055