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