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