serverQuery.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //-----------------------------------------------------------------------------
  23. // Server Query States:
  24. // 1: Master server query status -> wait for master response
  25. // 2: Master server packet status -> wait for master packets to arrive
  26. // 3: Server ping status -> wait for servers to respond to pings
  27. // 4: Server query status -> wait for servers to respond to queries
  28. // 5: Done
  29. // Master Server Packets:
  30. // Header
  31. // message Message id
  32. // flags Query flags
  33. // sequenceNumber Packet sequence id
  34. // Server Query Filter Packet
  35. // packetIndex Request specific page # (rest empty)
  36. // gameType Game type string
  37. // missionType Mission type string
  38. // minPlayers At least this many players
  39. // maxPlayers No more than this many
  40. // regions Region mask, 0 = all
  41. // version Server version, 0 = any
  42. // filterFlags Server flags (dedicated, etc), 0 = any
  43. // maxBots No more than maxBots
  44. // minCPUSpeed At least this fast
  45. // playerCount Buddy list search
  46. // playerList[playerCount]
  47. // Master Server Info Packet
  48. // gameType Game type string
  49. // missionType Mission type string
  50. // maxPlayers Max allowed
  51. // regions Region mask
  52. // version Server version #
  53. // infoFlags Server flags (dedicated, etc)
  54. // numBots Current bot count
  55. // CPUSpeed Server CPU speed
  56. // playerCount Current player count
  57. // playerList[playerCount]
  58. // Game Info Query Packet
  59. // gameType Game type string
  60. // missionType Mission type string
  61. // missionName You get one guess...
  62. // satusFlags Dedicated, etc.
  63. // playerCount Current player count
  64. // maxPlayers Max allowed
  65. // numBots Current bot count
  66. // CPUSpeed Server CPU speed
  67. // statusString Server info message
  68. // statusString Server status message
  69. // Accessed Environment Vars
  70. // Server::MissionType
  71. // Server::MissionName
  72. // Server::GameType
  73. // Server::ServerType
  74. // Server::PlayerCount
  75. // Server::BotCount
  76. // Server::GuidList[playerCount]
  77. // Server::Dedicated
  78. // Server::Status
  79. // Pref::Server::Name
  80. // Pref::Server::Password
  81. // Pref::Server::Info
  82. // Pref::Server::MaxPlayers
  83. // Pref::Server::RegionMask
  84. // Pref::Net::RegionMask
  85. // Pref::Client::Master[n]
  86. // Pref::Client::ServerFavoriteCount
  87. // Pref::Client::ServerFavorite[ServerFavoriteCount]
  88. //-----------------------------------------------------------------------------
  89. #include "app/net/serverQuery.h"
  90. #include "platform/platform.h"
  91. #include "core/dnet.h"
  92. #include "core/util/tVector.h"
  93. #include "core/stream/bitStream.h"
  94. #include "console/console.h"
  95. #include "console/simBase.h"
  96. #include "app/banList.h"
  97. #include "app/auth.h"
  98. #include "sim/netConnection.h"
  99. #include "sim/netInterface.h"
  100. // cafTODO: breaks T2D
  101. #include "T3D/gameBase/gameConnection.h"
  102. // This is basically the server query protocol version now:
  103. static const char* versionString = "VER1";
  104. struct MasterInfo
  105. {
  106. NetAddress address;
  107. U32 region;
  108. };
  109. Vector<ServerInfo> gServerList(__FILE__, __LINE__);
  110. static Vector<MasterInfo> gMasterServerList(__FILE__, __LINE__);
  111. static Vector<NetAddress> gFinishedList(__FILE__, __LINE__); // timed out servers and finished servers go here
  112. NetAddress gMasterServerQueryAddress;
  113. bool gServerBrowserDirty = false;
  114. static const U32 gHeartbeatInterval = 120000;
  115. static const S32 gMasterServerRetryCount = 3;
  116. static const S32 gMasterServerTimeout = 2000;
  117. static const S32 gPacketRetryCount = 4;
  118. static const S32 gPacketTimeout = 1000;
  119. static const S32 gMaxConcurrentPings = 10;
  120. static const S32 gMaxConcurrentQueries = 2;
  121. static const S32 gPingRetryCount = 4;
  122. static const S32 gPingTimeout = 800;
  123. static const S32 gQueryRetryCount = 4;
  124. static const S32 gQueryTimeout = 1000;
  125. // State variables:
  126. static bool sgServerQueryActive = false;
  127. static S32 gPingSession = 0;
  128. static S32 gKey = 0;
  129. static bool gGotFirstListPacket = false;
  130. // Variables used for the interface:
  131. static U32 gServerPingCount = 0;
  132. static U32 gServerQueryCount = 0;
  133. static U32 gHeartbeatSeq = 0;
  134. class DemoNetInterface : public NetInterface
  135. {
  136. public:
  137. void handleInfoPacket(const NetAddress *address, U8 packetType, BitStream *stream);
  138. };
  139. DemoNetInterface gNetInterface;
  140. ConsoleFunctionGroupBegin( ServerQuery, "Functions which allow you to query the LAN or a master server for online games.");
  141. //-----------------------------------------------------------------------------
  142. struct Ping
  143. {
  144. NetAddress address;
  145. S32 session;
  146. S32 key;
  147. U32 time;
  148. U32 tryCount;
  149. bool broadcast;
  150. };
  151. static Ping gMasterServerPing;
  152. static Vector<Ping> gPingList(__FILE__, __LINE__);
  153. static Vector<Ping> gQueryList(__FILE__, __LINE__);
  154. //-----------------------------------------------------------------------------
  155. struct PacketStatus
  156. {
  157. U8 index;
  158. S32 key;
  159. U32 time;
  160. U32 tryCount;
  161. PacketStatus() : index( 0 ), key(-1), time(0), tryCount( gPacketRetryCount ) {};
  162. PacketStatus( U8 _index, S32 _key, U32 _time )
  163. {
  164. index = _index;
  165. key = _key;
  166. time = _time;
  167. tryCount = gPacketRetryCount;
  168. }
  169. };
  170. static Vector<PacketStatus> gPacketStatusList(__FILE__, __LINE__);
  171. //-----------------------------------------------------------------------------
  172. struct ServerFilter
  173. {
  174. enum Type
  175. {
  176. Normal = 0,
  177. Buddy = 1,
  178. Offline = 2,
  179. Favorites = 3,
  180. };
  181. enum // Query Flags
  182. {
  183. OnlineQuery = 0, // Authenticated with master
  184. OfflineQuery = BIT(0), // On our own
  185. NoStringCompress = BIT(1),
  186. };
  187. enum // Filter flags:
  188. {
  189. Dedicated = BIT(0),
  190. NotPassworded = BIT(1),
  191. Linux = BIT(2),
  192. CurrentVersion = BIT(7),
  193. NotXenon = BIT(6)
  194. };
  195. //Rearranging the fields according to their sizes
  196. char* gameType;
  197. char* missionType;
  198. U8 queryFlags;
  199. U8 minPlayers;
  200. U8 maxPlayers;
  201. U8 maxBots;
  202. U8 filterFlags;
  203. U8 buddyCount;
  204. U16 minCPU;
  205. U32 regionMask;
  206. U32 maxPing;
  207. U32* buddyList;
  208. Type type;
  209. ServerFilter()
  210. {
  211. queryFlags = 0;
  212. gameType = NULL;
  213. missionType = NULL;
  214. minPlayers = 0;
  215. maxPlayers = 255;
  216. maxBots = 16;
  217. regionMask = 0xFFFFFFFF;
  218. maxPing = 0;
  219. filterFlags = 0;
  220. minCPU = 0;
  221. buddyCount = 0;
  222. buddyList = NULL;
  223. }
  224. ~ServerFilter()
  225. {
  226. if ( gameType )
  227. dFree( gameType );
  228. if ( missionType )
  229. dFree( missionType );
  230. if ( buddyList )
  231. dFree( buddyList );
  232. }
  233. };
  234. static ServerFilter sActiveFilter;
  235. //-----------------------------------------------------------------------------
  236. // Forward function declarations:
  237. //-----------------------------------------------------------------------------
  238. static void pushPingRequest( const NetAddress *addr );
  239. static void pushPingBroadcast( const NetAddress *addr );
  240. static void pushServerFavorites();
  241. static bool pickMasterServer();
  242. static S32 findPingEntry( Vector<Ping> &v, const NetAddress* addr );
  243. static bool addressFinished( const NetAddress* addr );
  244. static ServerInfo* findServerInfo( const NetAddress* addr );
  245. static ServerInfo* findOrCreateServerInfo( const NetAddress* addr );
  246. static void removeServerInfo( const NetAddress* addr );
  247. static void sendPacket( U8 pType, const NetAddress* addr, U32 key, U32 session, U8 flags );
  248. static void writeCString( BitStream* stream, const char* string );
  249. static void readCString( BitStream* stream, char* buffer );
  250. static void writeLongCString( BitStream* stream, const char* string );
  251. static void readLongCString( BitStream* stream, char* buffer );
  252. static void processMasterServerQuery( U32 session );
  253. static void processPingsAndQueries( U32 session, bool schedule = true);
  254. static void processServerListPackets( U32 session );
  255. static void processHeartbeat(U32);
  256. static void updatePingProgress();
  257. static void updateQueryProgress();
  258. Vector<MasterInfo>* getMasterServerList();
  259. bool pickMasterServer();
  260. void clearServerList();
  261. //-----------------------------------------------------------------------------
  262. // Events
  263. //-----------------------------------------------------------------------------
  264. //----------------------------------------------------------------
  265. class ProcessMasterQueryEvent : public SimEvent
  266. {
  267. U32 session;
  268. public:
  269. ProcessMasterQueryEvent( U32 _session )
  270. {
  271. session = _session;
  272. }
  273. void process( SimObject *object )
  274. {
  275. processMasterServerQuery( session );
  276. }
  277. };
  278. //----------------------------------------------------------------
  279. class ProcessPingEvent : public SimEvent
  280. {
  281. U32 session;
  282. public:
  283. ProcessPingEvent( U32 _session )
  284. {
  285. session = _session;
  286. }
  287. void process( SimObject *object )
  288. {
  289. processPingsAndQueries( session );
  290. }
  291. };
  292. //----------------------------------------------------------------
  293. class ProcessPacketEvent : public SimEvent
  294. {
  295. U32 session;
  296. public:
  297. ProcessPacketEvent( U32 _session )
  298. {
  299. session = _session;
  300. }
  301. void process( SimObject *object )
  302. {
  303. processServerListPackets( session );
  304. }
  305. };
  306. //----------------------------------------------------------------
  307. class HeartbeatEvent : public SimEvent
  308. {
  309. U32 mSeq;
  310. public:
  311. HeartbeatEvent(U32 seq)
  312. {
  313. mSeq = seq;
  314. }
  315. void process( SimObject *object )
  316. {
  317. processHeartbeat(mSeq);
  318. }
  319. };
  320. //-----------------------------------------------------------------------------
  321. // Public query methods
  322. //-----------------------------------------------------------------------------
  323. //-----------------------------------------------------------------------------
  324. void queryLanServers(U32 port, U8 flags, const char* gameType, const char* missionType,
  325. U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing, U16 minCPU,
  326. U8 filterFlags)
  327. {
  328. sgServerQueryActive = true;
  329. pushServerFavorites();
  330. sActiveFilter.type = ServerFilter::Offline;
  331. // Clear the filter:
  332. if ( !sActiveFilter.gameType || dStricmp( sActiveFilter.gameType, "Any" ) != 0 )
  333. {
  334. sActiveFilter.gameType = (char*) dRealloc( sActiveFilter.gameType, 4 );
  335. dStrcpy( sActiveFilter.gameType, "Any" );
  336. }
  337. if ( !sActiveFilter.missionType || dStricmp( sActiveFilter.missionType, "Any" ) != 0 )
  338. {
  339. sActiveFilter.missionType = (char*) dRealloc( sActiveFilter.missionType, 4 );
  340. dStrcpy( sActiveFilter.missionType, "Any" );
  341. }
  342. sActiveFilter.queryFlags = 0;
  343. sActiveFilter.minPlayers = minPlayers;
  344. sActiveFilter.maxPlayers = maxPlayers;
  345. sActiveFilter.maxBots = maxBots;
  346. sActiveFilter.regionMask = regionMask;
  347. sActiveFilter.maxPing = maxPing;
  348. sActiveFilter.minCPU = minCPU;
  349. sActiveFilter.filterFlags = filterFlags;
  350. NetAddress addr;
  351. char addrText[256];
  352. dSprintf( addrText, sizeof( addrText ), "IP:BROADCAST:%d", port );
  353. Net::stringToAddress( addrText, &addr );
  354. pushPingBroadcast( &addr );
  355. Con::executef("onServerQueryStatus", "start", "Querying LAN servers", "0");
  356. processPingsAndQueries( gPingSession );
  357. }
  358. //-----------------------------------------------------------------------------
  359. ConsoleFunction( queryAllServers, void, 12, 12, "queryAllServers(...);" )
  360. {
  361. TORQUE_UNUSED(argc);
  362. U32 lanPort = dAtoi(argv[1]);
  363. U8 flags = dAtoi(argv[2]);
  364. // It's not a good idea to hold onto args, recursive calls to
  365. // console exec will trash them.
  366. char* gameType = dStrdup(argv[3]);
  367. char* missionType = dStrdup(argv[4]);
  368. U8 minPlayers = dAtoi(argv[5]);
  369. U8 maxPlayers = dAtoi(argv[6]);
  370. U8 maxBots = dAtoi(argv[7]);
  371. U32 regionMask = dAtoi(argv[8]);
  372. U32 maxPing = dAtoi(argv[9]);
  373. U16 minCPU = dAtoi(argv[10]);
  374. U8 filterFlags = dAtoi(argv[11]);
  375. U32 buddyList = 0;
  376. clearServerList();
  377. queryMasterServer(flags,gameType,missionType,minPlayers,maxPlayers,
  378. maxBots,regionMask,maxPing,minCPU,filterFlags,0,&buddyList);
  379. queryLanServers(lanPort, flags, gameType, missionType, minPlayers, maxPlayers, maxBots,
  380. regionMask, maxPing, minCPU, filterFlags);
  381. dFree(gameType);
  382. dFree(missionType);
  383. }
  384. ConsoleFunction( queryLanServers, void, 12, 12, "queryLanServers(...);" )
  385. {
  386. TORQUE_UNUSED(argc);
  387. U32 lanPort = dAtoi(argv[1]);
  388. U8 flags = dAtoi(argv[2]);
  389. // It's not a good idea to hold onto args, recursive calls to
  390. // console exec will trash them.
  391. char* gameType = dStrdup(argv[3]);
  392. char* missionType = dStrdup(argv[4]);
  393. U8 minPlayers = dAtoi(argv[5]);
  394. U8 maxPlayers = dAtoi(argv[6]);
  395. U8 maxBots = dAtoi(argv[7]);
  396. U32 regionMask = dAtoi(argv[8]);
  397. U32 maxPing = dAtoi(argv[9]);
  398. U16 minCPU = dAtoi(argv[10]);
  399. U8 filterFlags = dAtoi(argv[11]);
  400. clearServerList();
  401. queryLanServers(lanPort, flags, gameType, missionType, minPlayers, maxPlayers, maxBots,
  402. regionMask, maxPing, minCPU, filterFlags);
  403. dFree(gameType);
  404. dFree(missionType);
  405. }
  406. //-----------------------------------------------------------------------------
  407. void queryMasterGameTypes()
  408. {
  409. Vector<MasterInfo> *masterList = getMasterServerList();
  410. if ( masterList->size() != 0 )
  411. {
  412. U32 master = Sim::getCurrentTime() % masterList->size();
  413. // Send a request to the master server for the game types:
  414. Con::printf( "Requesting game types from the master server..." );
  415. sendPacket( NetInterface::MasterServerGameTypesRequest, &(*masterList)[master].address, gKey, gPingSession, 0 );
  416. }
  417. }
  418. //-----------------------------------------------------------------------------
  419. void queryMasterServer(U8 flags, const char* gameType, const char* missionType,
  420. U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing,
  421. U16 minCPU, U8 filterFlags, U8 buddyCount, U32* buddyList )
  422. {
  423. // Reset the list packet flag:
  424. gGotFirstListPacket = false;
  425. sgServerQueryActive = true;
  426. Con::executef( "onServerQueryStatus", "start", "Querying master server", "0");
  427. if ( buddyCount == 0 )
  428. {
  429. sActiveFilter.type = ServerFilter::Normal;
  430. // Update the active filter:
  431. if ( !sActiveFilter.gameType || dStrcmp( sActiveFilter.gameType, gameType ) != 0 )
  432. {
  433. sActiveFilter.gameType = (char*) dRealloc( sActiveFilter.gameType, dStrlen( gameType ) + 1 );
  434. dStrcpy( sActiveFilter.gameType, gameType );
  435. }
  436. if ( !sActiveFilter.missionType || dStrcmp( sActiveFilter.missionType, missionType ) != 0 )
  437. {
  438. sActiveFilter.missionType = (char*) dRealloc( sActiveFilter.missionType, dStrlen( missionType ) + 1 );
  439. dStrcpy( sActiveFilter.missionType, missionType );
  440. }
  441. sActiveFilter.queryFlags = flags;
  442. sActiveFilter.minPlayers = minPlayers;
  443. sActiveFilter.maxPlayers = maxPlayers;
  444. sActiveFilter.maxBots = maxBots;
  445. sActiveFilter.regionMask = regionMask;
  446. sActiveFilter.maxPing = maxPing;
  447. sActiveFilter.minCPU = minCPU;
  448. sActiveFilter.filterFlags = filterFlags;
  449. sActiveFilter.buddyCount = buddyCount;
  450. dFree( sActiveFilter.buddyList );
  451. sActiveFilter.buddyList = NULL;
  452. }
  453. else
  454. {
  455. sActiveFilter.type = ServerFilter::Buddy;
  456. sActiveFilter.buddyCount = buddyCount;
  457. sActiveFilter.buddyList = (U32*) dRealloc( sActiveFilter.buddyList, buddyCount * 4 );
  458. dMemcpy( sActiveFilter.buddyList, buddyList, buddyCount * 4 );
  459. clearServerList();
  460. }
  461. // Pick a random master server from the list:
  462. gMasterServerList.clear();
  463. Vector<MasterInfo> *masterList = getMasterServerList();
  464. for ( U32 i = 0; i < masterList->size(); i++ )
  465. gMasterServerList.push_back( (*masterList)[i] );
  466. // Clear the master server ping:
  467. gMasterServerPing.time = 0;
  468. gMasterServerPing.tryCount = gMasterServerRetryCount;
  469. if ( !pickMasterServer() )
  470. Con::errorf( "No master servers found!" );
  471. else
  472. processMasterServerQuery( gPingSession );
  473. }
  474. ConsoleFunction( queryMasterServer, void, 11, 11, "queryMasterServer(...);" )
  475. {
  476. TORQUE_UNUSED(argc);
  477. U8 flags = dAtoi(argv[1]);
  478. // It's not a good idea to hold onto args, recursive calls to
  479. // console exec will trash them.
  480. char* gameType = dStrdup(argv[2]);
  481. char* missionType = dStrdup(argv[3]);
  482. U8 minPlayers = dAtoi(argv[4]);
  483. U8 maxPlayers = dAtoi(argv[5]);
  484. U8 maxBots = dAtoi(argv[6]);
  485. U32 regionMask = dAtoi(argv[7]);
  486. U32 maxPing = dAtoi(argv[8]);
  487. U16 minCPU = dAtoi(argv[9]);
  488. U8 filterFlags = dAtoi(argv[10]);
  489. U32 buddyList = 0;
  490. clearServerList();
  491. queryMasterServer(flags,gameType,missionType,minPlayers,maxPlayers,
  492. maxBots,regionMask,maxPing,minCPU,filterFlags,0,&buddyList);
  493. dFree(gameType);
  494. dFree(missionType);
  495. }
  496. //-----------------------------------------------------------------------------
  497. ConsoleFunction( querySingleServer, void, 3, 3, "querySingleServer(address, flags);" )
  498. {
  499. TORQUE_UNUSED(argc);
  500. NetAddress addr;
  501. char* addrText;
  502. addrText = dStrdup(argv[1]);
  503. U8 flags = dAtoi(argv[2]);
  504. Net::stringToAddress( addrText, &addr );
  505. querySingleServer(&addr,flags);
  506. }
  507. //-----------------------------------------------------------------------------
  508. void queryFavoriteServers( U8 /*flags*/ )
  509. {
  510. sgServerQueryActive = true;
  511. clearServerList();
  512. sActiveFilter.type = ServerFilter::Favorites;
  513. pushServerFavorites();
  514. Con::executef( "onServerQueryStatus", "start", "Query favorites...", "0" );
  515. processPingsAndQueries( gPingSession );
  516. }
  517. //-----------------------------------------------------------------------------
  518. void querySingleServer( const NetAddress* addr, U8 /*flags*/ )
  519. {
  520. sgServerQueryActive = true;
  521. ServerInfo* si = findServerInfo( addr );
  522. if ( si )
  523. si->status = ServerInfo::Status_New | ServerInfo::Status_Updating;
  524. // Remove the server from the finished list (if it's there):
  525. for ( U32 i = 0; i < gFinishedList.size(); i++ )
  526. {
  527. if ( Net::compareAddresses( addr, &gFinishedList[i] ) )
  528. {
  529. gFinishedList.erase( i );
  530. break;
  531. }
  532. }
  533. Con::executef( "onServerQueryStatus", "start", "Refreshing server...", "0" );
  534. gServerPingCount = gServerQueryCount = 0;
  535. pushPingRequest( addr );
  536. processPingsAndQueries( gPingSession );
  537. }
  538. //-----------------------------------------------------------------------------
  539. void cancelServerQuery()
  540. {
  541. // Cancel the current query, if there is anything left
  542. // on the ping list, it's dropped.
  543. if ( sgServerQueryActive )
  544. {
  545. Con::printf( "Server query canceled." );
  546. ServerInfo* si;
  547. // Clear the master server packet list:
  548. gPacketStatusList.clear();
  549. // Clear the ping list:
  550. while ( gPingList.size() )
  551. {
  552. si = findServerInfo( &gPingList[0].address );
  553. if ( si && !si->status.test( ServerInfo::Status_Responded ) )
  554. si->status = ServerInfo::Status_TimedOut;
  555. gPingList.erase( U32( 0 ) );
  556. }
  557. // Clear the query list:
  558. while ( gQueryList.size() )
  559. {
  560. si = findServerInfo( &gQueryList[0].address );
  561. if ( si && !si->status.test( ServerInfo::Status_Responded ) )
  562. si->status = ServerInfo::Status_TimedOut;
  563. gQueryList.erase( U32( 0 ) );
  564. }
  565. sgServerQueryActive = false;
  566. gServerBrowserDirty = true;
  567. }
  568. }
  569. ConsoleFunction( cancelServerQuery, void, 1, 1, "cancelServerQuery()" )
  570. {
  571. TORQUE_UNUSED(argc); TORQUE_UNUSED(argv);
  572. cancelServerQuery();
  573. }
  574. //-----------------------------------------------------------------------------
  575. void stopServerQuery()
  576. {
  577. // Cancel the current query, anything left on the ping
  578. // list is moved to the finished list as "done".
  579. if ( sgServerQueryActive )
  580. {
  581. gPacketStatusList.clear();
  582. if ( gPingList.size() )
  583. {
  584. while ( gPingList.size() )
  585. {
  586. gFinishedList.push_back( gPingList[0].address );
  587. gPingList.erase( U32( 0 ) );
  588. }
  589. }
  590. else
  591. cancelServerQuery();
  592. }
  593. }
  594. ConsoleFunction( stopServerQuery, void, 1, 1, "stopServerQuery()" )
  595. {
  596. TORQUE_UNUSED(argc); TORQUE_UNUSED(argv);
  597. stopServerQuery();
  598. }
  599. //-----------------------------------------------------------------------------
  600. ConsoleFunction(startHeartbeat, void, 1, 1, "startHeartbeat()")
  601. {
  602. TORQUE_UNUSED(argc); TORQUE_UNUSED(argv);
  603. if (validateAuthenticatedServer()) {
  604. gHeartbeatSeq++;
  605. processHeartbeat(gHeartbeatSeq); // thump-thump...
  606. }
  607. }
  608. ConsoleFunction(stopHeartbeat, void, 1, 1, "stopHeartbeat();")
  609. {
  610. TORQUE_UNUSED(argc); TORQUE_UNUSED(argv);
  611. gHeartbeatSeq++;
  612. }
  613. //-----------------------------------------------------------------------------
  614. ConsoleFunction( getServerCount, int, 1, 1, "getServerCount();" )
  615. {
  616. TORQUE_UNUSED(argv); TORQUE_UNUSED(argc);
  617. return gServerList.size();
  618. }
  619. ConsoleFunction( setServerInfo, bool, 2, 2, "setServerInfo(index);" )
  620. {
  621. TORQUE_UNUSED(argc);
  622. U32 index = dAtoi(argv[1]);
  623. if (index >= 0 && index < gServerList.size()) {
  624. ServerInfo& info = gServerList[index];
  625. char addrString[256];
  626. Net::addressToString( &info.address, addrString );
  627. Con::setIntVariable("ServerInfo::Status",info.status);
  628. Con::setVariable("ServerInfo::Address",addrString);
  629. Con::setVariable("ServerInfo::Name",info.name);
  630. Con::setVariable("ServerInfo::GameType",info.gameType);
  631. Con::setVariable("ServerInfo::MissionName",info.missionName);
  632. Con::setVariable("ServerInfo::MissionType",info.missionType);
  633. Con::setVariable("ServerInfo::State",info.statusString);
  634. Con::setVariable("ServerInfo::Info",info.infoString);
  635. Con::setIntVariable("ServerInfo::PlayerCount",info.numPlayers);
  636. Con::setIntVariable("ServerInfo::MaxPlayers",info.maxPlayers);
  637. Con::setIntVariable("ServerInfo::BotCount",info.numBots);
  638. Con::setIntVariable("ServerInfo::Version",info.version);
  639. Con::setIntVariable("ServerInfo::Ping",info.ping);
  640. Con::setIntVariable("ServerInfo::CPUSpeed",info.cpuSpeed);
  641. Con::setBoolVariable("ServerInfo::Favorite",info.isFavorite);
  642. Con::setBoolVariable("ServerInfo::Dedicated",info.isDedicated());
  643. Con::setBoolVariable("ServerInfo::Password",info.isPassworded());
  644. return true;
  645. }
  646. return false;
  647. }
  648. //-----------------------------------------------------------------------------
  649. // Internal
  650. //-----------------------------------------------------------------------------
  651. //-----------------------------------------------------------------------------
  652. ServerInfo::~ServerInfo()
  653. {
  654. if ( name )
  655. dFree( name );
  656. if ( gameType )
  657. dFree( gameType );
  658. if ( missionType )
  659. dFree( missionType );
  660. if( missionName )
  661. dFree( missionName );
  662. if ( statusString )
  663. dFree( statusString );
  664. if ( infoString )
  665. dFree( infoString );
  666. }
  667. //-----------------------------------------------------------------------------
  668. Vector<MasterInfo>* getMasterServerList()
  669. {
  670. // This code used to get the master server list from the
  671. // WON.net directory.
  672. static Vector<MasterInfo> masterList;
  673. masterList.clear();
  674. for (U32 i = 0; i < 10; i++) {
  675. char buffer[50];
  676. dSprintf(buffer,sizeof(buffer),"pref::Master%d",i);
  677. const char* master = Con::getVariable(buffer);
  678. if (master && *master) {
  679. NetAddress address;
  680. // Format for master server variable:
  681. // regionMask:netAddress
  682. U32 region = 1; // needs to default to something > 0
  683. dSscanf(master,"%d:",&region);
  684. const char* madd = dStrchr(master,':') + 1;
  685. if (region && Net::stringToAddress(madd,&address)) {
  686. masterList.increment();
  687. MasterInfo& info = masterList.last();
  688. info.address = address;
  689. info.region = region;
  690. }
  691. else
  692. Con::errorf("Bad master server address: %s",master);
  693. }
  694. }
  695. if (!masterList.size())
  696. Con::errorf("No master servers found");
  697. return &masterList;
  698. }
  699. //-----------------------------------------------------------------------------
  700. bool pickMasterServer()
  701. {
  702. // Reset the master server ping:
  703. gMasterServerPing.time = 0;
  704. gMasterServerPing.key = 0;
  705. gMasterServerPing.tryCount = gMasterServerRetryCount;
  706. gMasterServerPing.session = gPingSession;
  707. char addrString[256];
  708. U32 serverCount = gMasterServerList.size();
  709. if ( !serverCount )
  710. {
  711. // There are no more servers left to try...:(
  712. return( false );
  713. }
  714. U32 region = Con::getIntVariable( "$pref::Net::RegionMask" );
  715. U32 index = Sim::getCurrentTime() % serverCount;
  716. // First try to find a master server in the same region:
  717. for ( U32 i = 0; i < serverCount; i++ )
  718. {
  719. if ( gMasterServerList[index].region == region )
  720. {
  721. Net::addressToString( &gMasterServerList[index].address, addrString );
  722. Con::printf( "Found master server %s in same region.", addrString );
  723. gMasterServerPing.address = gMasterServerList[index].address;
  724. return( true );
  725. }
  726. index = index < serverCount - 1 ? index + 1 : 0;
  727. }
  728. // Settle for the one we first picked:
  729. Net::addressToString( &gMasterServerList[index].address, addrString );
  730. Con::printf( "No master servers found in this region, trying %s.", addrString );
  731. gMasterServerPing.address = gMasterServerList[index].address;
  732. return( true );
  733. }
  734. //-----------------------------------------------------------------------------
  735. void clearServerList()
  736. {
  737. gPacketStatusList.clear();
  738. gServerList.clear();
  739. gFinishedList.clear();
  740. gPingList.clear();
  741. gQueryList.clear();
  742. gServerPingCount = gServerQueryCount = 0;
  743. gPingSession++;
  744. }
  745. //-----------------------------------------------------------------------------
  746. void sendHeartbeat( U8 flags )
  747. {
  748. // send heartbeats to all of the master servers:
  749. Vector<MasterInfo> *masterList = getMasterServerList();
  750. for(U32 i = 0; i < masterList->size(); i++)
  751. {
  752. char buffer[256];
  753. Net::addressToString(&(*masterList)[i].address, buffer);
  754. // Send a request to the master server for the game types:
  755. Con::printf( "Sending heartbeat to master server [%s]", buffer );
  756. sendPacket( NetInterface::GameHeartbeat, &(*masterList)[i].address, 0, gPingSession, flags );
  757. }
  758. }
  759. //-----------------------------------------------------------------------------
  760. static void pushPingRequest( const NetAddress* addr )
  761. {
  762. if( addressFinished( addr ) )
  763. return;
  764. Ping p;
  765. p.address = *addr;
  766. p.session = gPingSession;
  767. p.key = 0;
  768. p.time = 0;
  769. p.tryCount = gPingRetryCount;
  770. p.broadcast = false;
  771. gPingList.push_back( p );
  772. gServerPingCount++;
  773. }
  774. //-----------------------------------------------------------------------------
  775. static void pushPingBroadcast( const NetAddress* addr )
  776. {
  777. if( addressFinished( addr ) )
  778. return;
  779. Ping p;
  780. p.address = *addr;
  781. p.session = gPingSession;
  782. p.key = 0;
  783. p.time = 0;
  784. p.tryCount = 1; // only try this once
  785. p.broadcast = true;
  786. gPingList.push_back( p );
  787. // Don't increment gServerPingCount, broadcasts are not
  788. // counted as requests.
  789. }
  790. //-----------------------------------------------------------------------------
  791. static S32 countPingRequests()
  792. {
  793. // Need a function here because the ping list also includes
  794. // broadcast pings we don't want counted.
  795. U32 pSize = gPingList.size(), count = pSize;
  796. for (U32 i = 0; i < pSize; i++)
  797. if (gPingList[i].broadcast)
  798. count--;
  799. return count;
  800. }
  801. //-----------------------------------------------------------------------------
  802. static void pushServerFavorites()
  803. {
  804. S32 count = Con::getIntVariable( "$pref::Client::ServerFavoriteCount" );
  805. if ( count < 0 )
  806. {
  807. Con::setIntVariable( "$pref::Client::ServerFavoriteCount", 0 );
  808. return;
  809. }
  810. NetAddress addr;
  811. const char* server = NULL;
  812. char buf[256], serverName[25], addrString[256];
  813. U32 sz, len;
  814. for ( S32 i = 0; i < count; i++ )
  815. {
  816. dSprintf( buf, sizeof( buf ), "pref::Client::ServerFavorite%d", i );
  817. server = Con::getVariable( buf );
  818. if ( server )
  819. {
  820. sz = dStrcspn( server, "\t" );
  821. if ( sz > 0 )
  822. {
  823. len = sz > 24 ? 24 : sz;
  824. dStrncpy( serverName, server, len );
  825. serverName[len] = 0;
  826. dStrncpy( addrString, server + ( sz + 1 ), 255 );
  827. //Con::errorf( "Pushing server favorite \"%s\" - %s...", serverName, addrString );
  828. Net::stringToAddress( addrString, &addr );
  829. ServerInfo* si = findOrCreateServerInfo( &addr );
  830. AssertFatal(si, "pushServerFavorites - failed to create Server Info!" );
  831. si->name = (char*) dRealloc( (void*) si->name, dStrlen( serverName ) + 1 );
  832. dStrcpy( si->name, serverName );
  833. si->isFavorite = true;
  834. pushPingRequest( &addr );
  835. }
  836. }
  837. }
  838. }
  839. //-----------------------------------------------------------------------------
  840. static S32 findPingEntry( Vector<Ping> &v, const NetAddress* addr )
  841. {
  842. for ( U32 i = 0; i < v.size(); i++ )
  843. if ( Net::compareAddresses( addr, &v[i].address ) )
  844. return S32( i );
  845. return -1;
  846. }
  847. //-----------------------------------------------------------------------------
  848. static bool addressFinished( const NetAddress* addr )
  849. {
  850. for ( U32 i = 0; i < gFinishedList.size(); i++ )
  851. if ( Net::compareAddresses( addr, &gFinishedList[i] ) )
  852. return true;
  853. return false;
  854. }
  855. //-----------------------------------------------------------------------------
  856. static ServerInfo* findServerInfo( const NetAddress* addr )
  857. {
  858. for ( U32 i = 0; i < gServerList.size(); i++ )
  859. if ( Net::compareAddresses( addr, &gServerList[i].address ) )
  860. return &gServerList[i];
  861. return NULL;
  862. }
  863. //-----------------------------------------------------------------------------
  864. static ServerInfo* findOrCreateServerInfo( const NetAddress* addr )
  865. {
  866. ServerInfo* ret = findServerInfo( addr );
  867. if ( ret )
  868. return ret;
  869. ServerInfo si;
  870. si.address = *addr;
  871. gServerList.push_back( si );
  872. return &gServerList.last();
  873. }
  874. //-----------------------------------------------------------------------------
  875. static void removeServerInfo( const NetAddress* addr )
  876. {
  877. for ( U32 i = 0; i < gServerList.size(); i++ )
  878. {
  879. if ( Net::compareAddresses( addr, &gServerList[i].address ) )
  880. {
  881. gServerList.erase( i );
  882. gServerBrowserDirty = true;
  883. }
  884. }
  885. }
  886. //-----------------------------------------------------------------------------
  887. #if defined(TORQUE_DEBUG)
  888. // This function is solely for testing the functionality of the server browser
  889. // with more servers in the list.
  890. void addFakeServers( S32 howMany )
  891. {
  892. static S32 sNumFakeServers = 1;
  893. ServerInfo newServer;
  894. for ( S32 i = 0; i < howMany; i++ )
  895. {
  896. newServer.numPlayers = (U8)(Platform::getRandom() * 64.0f);
  897. newServer.maxPlayers = 64;
  898. char buf[256];
  899. dSprintf( buf, 255, "Fake server #%d", sNumFakeServers );
  900. newServer.name = (char*) dMalloc( dStrlen( buf ) + 1 );
  901. dStrcpy( newServer.name, buf );
  902. newServer.gameType = (char*) dMalloc( 5 );
  903. dStrcpy( newServer.gameType, "Fake" );
  904. newServer.missionType = (char*) dMalloc( 4 );
  905. dStrcpy( newServer.missionType, "FakeMissionType" );
  906. newServer.missionName = (char*) dMalloc( 14 );
  907. dStrcpy( newServer.missionName, "FakeMapName" );
  908. Net::stringToAddress( "IP:198.74.33.35:28000", &newServer.address );
  909. newServer.ping = (U32)( Platform::getRandom() * 200.0f );
  910. newServer.cpuSpeed = 470;
  911. newServer.status = ServerInfo::Status_Responded;
  912. gServerList.push_back( newServer );
  913. sNumFakeServers++;
  914. }
  915. gServerBrowserDirty = true;
  916. }
  917. #endif // DEBUG
  918. //-----------------------------------------------------------------------------
  919. static void sendPacket( U8 pType, const NetAddress* addr, U32 key, U32 session, U8 flags )
  920. {
  921. BitStream *out = BitStream::getPacketStream();
  922. out->clearStringBuffer();
  923. out->write( pType );
  924. out->write( flags );
  925. out->write( U32( ( session << 16 ) | ( key & 0xFFFF ) ) );
  926. BitStream::sendPacketStream(addr);
  927. }
  928. //-----------------------------------------------------------------------------
  929. static void writeCString( BitStream* stream, const char* string )
  930. {
  931. U8 strLen = ( string != NULL ) ? dStrlen( string ) : 0;
  932. stream->write( strLen );
  933. for ( U32 i = 0; i < strLen; i++ )
  934. stream->write( U8( string[i] ) );
  935. }
  936. //-----------------------------------------------------------------------------
  937. static void readCString( BitStream* stream, char* buffer )
  938. {
  939. U32 i;
  940. U8 strLen;
  941. stream->read( &strLen );
  942. for ( i = 0; i < strLen; i++ )
  943. {
  944. U8* ptr = (U8*) buffer;
  945. stream->read( &ptr[i] );
  946. }
  947. buffer[i] = 0;
  948. }
  949. //-----------------------------------------------------------------------------
  950. static void writeLongCString( BitStream* stream, const char* string )
  951. {
  952. U16 strLen = ( string != NULL ) ? dStrlen( string ) : 0;
  953. stream->write( strLen );
  954. for ( U32 i = 0; i < strLen; i++ )
  955. stream->write( U8( string[i] ) );
  956. }
  957. //-----------------------------------------------------------------------------
  958. static void readLongCString( BitStream* stream, char* buffer )
  959. {
  960. U32 i;
  961. U16 strLen;
  962. stream->read( &strLen );
  963. for ( i = 0; i < strLen; i++ )
  964. {
  965. U8* ptr = (U8*) buffer;
  966. stream->read( &ptr[i] );
  967. }
  968. buffer[i] = 0;
  969. }
  970. //-----------------------------------------------------------------------------
  971. // Event processing
  972. //-----------------------------------------------------------------------------
  973. //-----------------------------------------------------------------------------
  974. static void processMasterServerQuery( U32 session )
  975. {
  976. if ( session != gPingSession || !sgServerQueryActive )
  977. return;
  978. if ( !gGotFirstListPacket )
  979. {
  980. bool keepGoing = true;
  981. U32 time = Platform::getVirtualMilliseconds();
  982. char addressString[256];
  983. if ( gMasterServerPing.time + gMasterServerTimeout < time )
  984. {
  985. Net::addressToString( &gMasterServerPing.address, addressString );
  986. if ( !gMasterServerPing.tryCount )
  987. {
  988. // The query timed out.
  989. Con::printf( "Server list request to %s timed out.", addressString );
  990. // Remove this server from the list:
  991. for ( U32 i = 0; i < gMasterServerList.size(); i++ )
  992. {
  993. if ( Net::compareAddresses( &gMasterServerList[i].address, &gMasterServerPing.address ) )
  994. {
  995. gMasterServerList.erase( i );
  996. break;
  997. }
  998. }
  999. // Pick a new master server to try:
  1000. keepGoing = pickMasterServer();
  1001. if ( keepGoing )
  1002. {
  1003. Con::executef( "onServerQueryStatus", "update", "Switching master servers...", "0" );
  1004. Net::addressToString( &gMasterServerPing.address, addressString );
  1005. }
  1006. }
  1007. if ( keepGoing )
  1008. {
  1009. gMasterServerPing.tryCount--;
  1010. gMasterServerPing.time = time;
  1011. gMasterServerPing.key = gKey++;
  1012. // Send a request to the master server for the server list:
  1013. BitStream *out = BitStream::getPacketStream();
  1014. out->clearStringBuffer();
  1015. out->write( U8( NetInterface::MasterServerListRequest ) );
  1016. out->write( U8( sActiveFilter.queryFlags) );
  1017. out->write( ( gMasterServerPing.session << 16 ) | ( gMasterServerPing.key & 0xFFFF ) );
  1018. out->write( U8( 255 ) );
  1019. writeCString( out, sActiveFilter.gameType );
  1020. writeCString( out, sActiveFilter.missionType );
  1021. out->write( sActiveFilter.minPlayers );
  1022. out->write( sActiveFilter.maxPlayers );
  1023. out->write( sActiveFilter.regionMask );
  1024. U32 version = ( sActiveFilter.filterFlags & ServerFilter::CurrentVersion ) ? getVersionNumber() : 0;
  1025. out->write( version );
  1026. out->write( sActiveFilter.filterFlags );
  1027. out->write( sActiveFilter.maxBots );
  1028. out->write( sActiveFilter.minCPU );
  1029. out->write( sActiveFilter.buddyCount );
  1030. for ( U32 i = 0; i < sActiveFilter.buddyCount; i++ )
  1031. out->write( sActiveFilter.buddyList[i] );
  1032. BitStream::sendPacketStream( &gMasterServerPing.address );
  1033. Con::printf( "Requesting the server list from master server %s (%d tries left)...", addressString, gMasterServerPing.tryCount );
  1034. if ( gMasterServerPing.tryCount < gMasterServerRetryCount - 1 )
  1035. Con::executef( "onServerQueryStatus", "update", "Retrying the master server...", "0" );
  1036. }
  1037. }
  1038. if ( keepGoing )
  1039. {
  1040. // schedule another check:
  1041. Sim::postEvent( Sim::getRootGroup(), new ProcessMasterQueryEvent( session ), Sim::getTargetTime() + 1 );
  1042. }
  1043. else
  1044. {
  1045. Con::errorf( "There are no more master servers to try!" );
  1046. Con::executef( "onServerQueryStatus", "done", "No master servers found.", "0" );
  1047. }
  1048. }
  1049. }
  1050. //-----------------------------------------------------------------------------
  1051. static void processPingsAndQueries( U32 session, bool schedule )
  1052. {
  1053. if( session != gPingSession )
  1054. return;
  1055. U32 i = 0;
  1056. U32 time = Platform::getVirtualMilliseconds();
  1057. char addressString[256];
  1058. U8 flags = ServerFilter::OnlineQuery;
  1059. bool waitingForMaster = ( sActiveFilter.type == ServerFilter::Normal ) && !gGotFirstListPacket && sgServerQueryActive;
  1060. for ( i = 0; i < gPingList.size() && i < gMaxConcurrentPings; )
  1061. {
  1062. Ping &p = gPingList[i];
  1063. if ( p.time + gPingTimeout < time )
  1064. {
  1065. if ( !p.tryCount )
  1066. {
  1067. // it's timed out.
  1068. if (!p.broadcast)
  1069. {
  1070. Net::addressToString( &p.address, addressString );
  1071. Con::printf( "Ping to server %s timed out.", addressString );
  1072. }
  1073. // If server info is in list (favorite), set its status:
  1074. ServerInfo* si = findServerInfo( &p.address );
  1075. if ( si )
  1076. {
  1077. si->status = ServerInfo::Status_TimedOut;
  1078. gServerBrowserDirty = true;
  1079. }
  1080. gFinishedList.push_back( p.address );
  1081. gPingList.erase( i );
  1082. if ( !waitingForMaster )
  1083. updatePingProgress();
  1084. }
  1085. else
  1086. {
  1087. p.tryCount--;
  1088. p.time = time;
  1089. p.key = gKey++;
  1090. Net::addressToString( &p.address, addressString );
  1091. if (p.broadcast)
  1092. Con::printf( "LAN server ping: %s...", addressString );
  1093. else
  1094. Con::printf( "Pinging Server %s (%d)...", addressString, p.tryCount );
  1095. sendPacket( NetInterface::GamePingRequest, &p.address, p.key, p.session, flags );
  1096. i++;
  1097. }
  1098. }
  1099. else
  1100. i++;
  1101. }
  1102. if ( !gPingList.size() && !waitingForMaster )
  1103. {
  1104. // Start the query phase:
  1105. for ( U32 i = 0; i < gQueryList.size() && i < gMaxConcurrentQueries; )
  1106. {
  1107. Ping &p = gQueryList[i];
  1108. if ( p.time + gPingTimeout < time )
  1109. {
  1110. ServerInfo* si = findServerInfo( &p.address );
  1111. if ( !si )
  1112. {
  1113. // Server info not found, so remove the query:
  1114. gQueryList.erase( i );
  1115. gServerBrowserDirty = true;
  1116. continue;
  1117. }
  1118. Net::addressToString( &p.address, addressString );
  1119. if ( !p.tryCount )
  1120. {
  1121. Con::printf( "Query to server %s timed out.", addressString );
  1122. si->status = ServerInfo::Status_TimedOut;
  1123. gQueryList.erase( i );
  1124. gServerBrowserDirty = true;
  1125. }
  1126. else
  1127. {
  1128. p.tryCount--;
  1129. p.time = time;
  1130. p.key = gKey++;
  1131. Con::printf( "Querying Server %s (%d)...", addressString, p.tryCount );
  1132. sendPacket( NetInterface::GameInfoRequest, &p.address, p.key, p.session, flags );
  1133. if ( !si->isQuerying() )
  1134. {
  1135. si->status |= ServerInfo::Status_Querying;
  1136. gServerBrowserDirty = true;
  1137. }
  1138. i++;
  1139. }
  1140. }
  1141. else
  1142. i++;
  1143. }
  1144. }
  1145. if ( gPingList.size() || gQueryList.size() || waitingForMaster )
  1146. {
  1147. // The LAN query function doesn't always want to schedule
  1148. // the next ping.
  1149. if (schedule)
  1150. Sim::postEvent( Sim::getRootGroup(), new ProcessPingEvent( session ), Sim::getTargetTime() + 1 );
  1151. }
  1152. else
  1153. {
  1154. // All done!
  1155. char msg[64];
  1156. U32 foundCount = gServerList.size();
  1157. if ( foundCount == 0 )
  1158. dStrcpy( msg, "No servers found." );
  1159. else if ( foundCount == 1 )
  1160. dStrcpy( msg, "One server found." );
  1161. else
  1162. dSprintf( msg, sizeof( msg ), "%d servers found.", foundCount );
  1163. Con::executef( "onServerQueryStatus", "done", msg, "1");
  1164. }
  1165. }
  1166. //-----------------------------------------------------------------------------
  1167. static void processServerListPackets( U32 session )
  1168. {
  1169. if ( session != gPingSession || !sgServerQueryActive )
  1170. return;
  1171. U32 currentTime = Platform::getVirtualMilliseconds();
  1172. // Loop through the packet status list and resend packet requests where necessary:
  1173. for ( U32 i = 0; i < gPacketStatusList.size(); i++ )
  1174. {
  1175. PacketStatus &p = gPacketStatusList[i];
  1176. if ( p.time + gPacketTimeout < currentTime )
  1177. {
  1178. if ( !p.tryCount )
  1179. {
  1180. // Packet timed out :(
  1181. Con::printf( "Server list packet #%d timed out.", p.index + 1 );
  1182. gPacketStatusList.erase( i );
  1183. }
  1184. else
  1185. {
  1186. // Try again...
  1187. Con::printf( "Rerequesting server list packet #%d...", p.index + 1 );
  1188. p.tryCount--;
  1189. p.time = currentTime;
  1190. p.key = gKey++;
  1191. BitStream *out = BitStream::getPacketStream();
  1192. out->clearStringBuffer();
  1193. out->write( U8( NetInterface::MasterServerListRequest ) );
  1194. out->write( U8( sActiveFilter.queryFlags ) ); // flags
  1195. out->write( ( session << 16) | ( p.key & 0xFFFF ) );
  1196. out->write( p.index ); // packet index
  1197. out->write( U8( 0 ) ); // game type
  1198. out->write( U8( 0 ) ); // mission type
  1199. out->write( U8( 0 ) ); // minPlayers
  1200. out->write( U8( 0 ) ); // maxPlayers
  1201. out->write( U32( 0 ) ); // region mask
  1202. out->write( U32( 0 ) ); // version
  1203. out->write( U8( 0 ) ); // filter flags
  1204. out->write( U8( 0 ) ); // max bots
  1205. out->write( U16( 0 ) ); // min CPU
  1206. out->write( U8( 0 ) ); // buddy count
  1207. BitStream::sendPacketStream(&gMasterServerQueryAddress);
  1208. }
  1209. }
  1210. }
  1211. if ( gPacketStatusList.size() )
  1212. Sim::postEvent( Sim::getRootGroup(), new ProcessPacketEvent( session ), Sim::getCurrentTime() + 30 );
  1213. else
  1214. processPingsAndQueries( gPingSession );
  1215. }
  1216. //-----------------------------------------------------------------------------
  1217. static void processHeartbeat(U32 seq)
  1218. {
  1219. if(seq != gHeartbeatSeq)
  1220. return;
  1221. sendHeartbeat( 0 );
  1222. Sim::postEvent( Sim::getRootGroup(), new HeartbeatEvent(seq), Sim::getCurrentTime() + gHeartbeatInterval );
  1223. }
  1224. //-----------------------------------------------------------------------------
  1225. static void updatePingProgress()
  1226. {
  1227. if ( !gPingList.size() )
  1228. {
  1229. updateQueryProgress();
  1230. return;
  1231. }
  1232. char msg[64];
  1233. U32 pingsLeft = countPingRequests();
  1234. dSprintf( msg, sizeof(msg),
  1235. (!pingsLeft && gPingList.size())?
  1236. "Waiting for lan servers...":
  1237. "Pinging servers: %d left...",
  1238. pingsLeft );
  1239. // Ping progress is 0 -> 0.5
  1240. F32 progress = 0.0f;
  1241. if ( gServerPingCount )
  1242. progress = F32( gServerPingCount - pingsLeft ) / F32( gServerPingCount * 2 );
  1243. //Con::errorf( ConsoleLogEntry::General, "Ping progress - %d of %d left - progress = %.2f", pingsLeft, gServerPingCount, progress );
  1244. Con::executef( "onServerQueryStatus", "ping", msg, Con::getFloatArg( progress ) );
  1245. }
  1246. //-----------------------------------------------------------------------------
  1247. static void updateQueryProgress()
  1248. {
  1249. if ( gPingList.size() )
  1250. return;
  1251. char msg[64];
  1252. U32 queriesLeft = gQueryList.size();
  1253. dSprintf( msg, sizeof( msg ), "Querying servers: %d left...", queriesLeft );
  1254. // Query progress is 0.5 -> 1
  1255. F32 progress = 0.5f;
  1256. if ( gServerQueryCount )
  1257. progress += ( F32( gServerQueryCount - queriesLeft ) / F32( gServerQueryCount * 2 ) );
  1258. //Con::errorf( ConsoleLogEntry::General, "Query progress - %d of %d left - progress = %.2f", queriesLeft, gServerQueryCount, progress );
  1259. Con::executef( "onServerQueryStatus", "query", msg, Con::getFloatArg( progress ) );
  1260. }
  1261. //-----------------------------------------------------------------------------
  1262. // Server packet handlers:
  1263. //-----------------------------------------------------------------------------
  1264. //-----------------------------------------------------------------------------
  1265. static void handleMasterServerGameTypesResponse( BitStream* stream, U32 /*key*/, U8 /*flags*/ )
  1266. {
  1267. Con::printf( "Received game type list from the master server." );
  1268. U32 i;
  1269. U8 temp;
  1270. char stringBuf[256];
  1271. stream->read( &temp );
  1272. Con::executef("onClearGameTypes");
  1273. for ( i = 0; i < U32( temp ); i++ )
  1274. {
  1275. readCString( stream, stringBuf );
  1276. Con::executef("onAddGameType", stringBuf);
  1277. }
  1278. stream->read( &temp );
  1279. Con::executef("onClearMissionTypes");
  1280. for ( i = 0; i < U32( temp ); i++ )
  1281. {
  1282. readCString( stream, stringBuf );
  1283. Con::executef("onAddMissionType", stringBuf);
  1284. }
  1285. }
  1286. //-----------------------------------------------------------------------------
  1287. static void handleMasterServerListResponse( BitStream* stream, U32 key, U8 /*flags*/ )
  1288. {
  1289. U8 packetIndex, packetTotal;
  1290. U32 i;
  1291. U16 serverCount, port;
  1292. U8 netNum[4];
  1293. char addressBuffer[256];
  1294. NetAddress addr;
  1295. stream->read( &packetIndex );
  1296. // Validate the packet key:
  1297. U32 packetKey = gMasterServerPing.key;
  1298. if ( gGotFirstListPacket )
  1299. {
  1300. for ( i = 0; i < gPacketStatusList.size(); i++ )
  1301. {
  1302. if ( gPacketStatusList[i].index == packetIndex )
  1303. {
  1304. packetKey = gPacketStatusList[i].key;
  1305. break;
  1306. }
  1307. }
  1308. }
  1309. U32 testKey = ( gPingSession << 16 ) | ( packetKey & 0xFFFF );
  1310. if ( testKey != key )
  1311. return;
  1312. stream->read( &packetTotal );
  1313. stream->read( &serverCount );
  1314. Con::printf( "Received server list packet %d of %d from the master server (%d servers).", ( packetIndex + 1 ), packetTotal, serverCount );
  1315. // Enter all of the servers in this packet into the ping list:
  1316. for ( i = 0; i < serverCount; i++ )
  1317. {
  1318. stream->read( &netNum[0] );
  1319. stream->read( &netNum[1] );
  1320. stream->read( &netNum[2] );
  1321. stream->read( &netNum[3] );
  1322. stream->read( &port );
  1323. dSprintf( addressBuffer, sizeof( addressBuffer ), "IP:%d.%d.%d.%d:%d", netNum[0], netNum[1], netNum[2], netNum[3], port );
  1324. Net::stringToAddress( addressBuffer, &addr );
  1325. pushPingRequest( &addr );
  1326. }
  1327. // If this is the first list packet we have received, fill the packet status list
  1328. // and start processing:
  1329. if ( !gGotFirstListPacket )
  1330. {
  1331. gGotFirstListPacket = true;
  1332. gMasterServerQueryAddress = gMasterServerPing.address;
  1333. U32 currentTime = Platform::getVirtualMilliseconds();
  1334. for ( i = 0; i < packetTotal; i++ )
  1335. {
  1336. if ( i != packetIndex )
  1337. {
  1338. PacketStatus* p = new PacketStatus( i, gMasterServerPing.key, currentTime );
  1339. gPacketStatusList.push_back( *p );
  1340. }
  1341. }
  1342. processServerListPackets( gPingSession );
  1343. }
  1344. else
  1345. {
  1346. // Remove the packet we just received from the status list:
  1347. for ( i = 0; i < gPacketStatusList.size(); i++ )
  1348. {
  1349. if ( gPacketStatusList[i].index == packetIndex )
  1350. {
  1351. gPacketStatusList.erase( i );
  1352. break;
  1353. }
  1354. }
  1355. }
  1356. }
  1357. //-----------------------------------------------------------------------------
  1358. static void handleGameMasterInfoRequest( const NetAddress* address, U32 key, U8 flags )
  1359. {
  1360. if ( GNet->doesAllowConnections() )
  1361. {
  1362. U8 temp8;
  1363. U32 temp32;
  1364. char netString[256];
  1365. Net::addressToString(address, netString);
  1366. Vector<MasterInfo> *masterList = getMasterServerList();
  1367. const NetAddress *masterAddr;
  1368. bool fromMaster = false;
  1369. for(U32 i = 0; i < masterList->size(); i++)
  1370. {
  1371. masterAddr = &(*masterList)[i].address;
  1372. if (*(U32*)(masterAddr->netNum) == *(U32*)(address->netNum))
  1373. {
  1374. fromMaster = true;
  1375. break;
  1376. }
  1377. }
  1378. Con::printf( "Received info request from %s [%s].", fromMaster?"a master server":"a machine", netString);
  1379. BitStream *out = BitStream::getPacketStream();
  1380. out->clearStringBuffer();
  1381. out->write( U8( NetInterface::GameMasterInfoResponse ) );
  1382. out->write( U8( flags ) );
  1383. out->write( key );
  1384. writeCString( out, Con::getVariable( "Server::GameType" ) );
  1385. writeCString( out, Con::getVariable( "Server::MissionType" ) );
  1386. temp8 = U8( Con::getIntVariable( "pref::Server::MaxPlayers" ) );
  1387. out->write( temp8 );
  1388. temp32 = Con::getIntVariable( "pref::Server::RegionMask" );
  1389. out->write( temp32 );
  1390. temp32 = getVersionNumber();
  1391. out->write( temp32 );
  1392. temp8 = 0;
  1393. #if defined(TORQUE_OS_LINUX) || defined(TORQUE_OS_OPENBSD)
  1394. temp8 |= ServerInfo::Status_Linux;
  1395. #endif
  1396. #if defined(TORQUE_OS_XENON)
  1397. temp8 |= ServerInfo::Status_Xenon;
  1398. #endif
  1399. if ( Con::getBoolVariable( "Server::Dedicated" ) )
  1400. temp8 |= ServerInfo::Status_Dedicated;
  1401. if ( dStrlen( Con::getVariable( "pref::Server::Password" ) ) > 0 )
  1402. temp8 |= ServerInfo::Status_Passworded;
  1403. out->write( temp8 );
  1404. temp8 = U8( Con::getIntVariable( "Server::BotCount" ) );
  1405. out->write( temp8 );
  1406. out->write( Platform::SystemInfo.processor.mhz );
  1407. U8 playerCount = U8( Con::getIntVariable( "Server::PlayerCount" ) );
  1408. out->write( playerCount );
  1409. const char* guidList = Con::getVariable( "Server::GuidList" );
  1410. char* buf = new char[dStrlen( guidList ) + 1];
  1411. dStrcpy( buf, guidList );
  1412. char* temp = dStrtok( buf, "\t" );
  1413. temp8 = 0;
  1414. for ( ; temp && temp8 < playerCount; temp8++ )
  1415. {
  1416. out->write( U32( dAtoi( temp ) ) );
  1417. temp = dStrtok( NULL, "\t" );
  1418. temp8++;
  1419. }
  1420. for ( ; temp8 < playerCount; temp8++ )
  1421. out->write( U32( 0 ) );
  1422. delete [] buf;
  1423. BitStream::sendPacketStream(address);
  1424. }
  1425. }
  1426. //-----------------------------------------------------------------------------
  1427. static void handleGamePingRequest( const NetAddress* address, U32 key, U8 flags )
  1428. {
  1429. // Do not respond if a mission is not running:
  1430. if ( GNet->doesAllowConnections() )
  1431. {
  1432. // Do not respond if this is a single-player game:
  1433. if ( dStricmp( Con::getVariable( "Server::ServerType" ), "SinglePlayer" ) == 0 )
  1434. return;
  1435. // Do not respond to offline queries if this is an online server:
  1436. if ( flags & ServerFilter::OfflineQuery )
  1437. return;
  1438. // some banning code here (?)
  1439. BitStream *out = BitStream::getPacketStream();
  1440. out->clearStringBuffer();
  1441. out->write( U8( NetInterface::GamePingResponse ) );
  1442. out->write( flags );
  1443. out->write( key );
  1444. if ( flags & ServerFilter::NoStringCompress )
  1445. writeCString( out, versionString );
  1446. else
  1447. out->writeString( versionString );
  1448. out->write( GameConnection::CurrentProtocolVersion );
  1449. out->write( GameConnection::MinRequiredProtocolVersion );
  1450. out->write( getVersionNumber() );
  1451. // Enforce a 24-character limit on the server name:
  1452. char serverName[25];
  1453. dStrncpy( serverName, Con::getVariable( "pref::Server::Name" ), 24 );
  1454. serverName[24] = 0;
  1455. if ( flags & ServerFilter::NoStringCompress )
  1456. writeCString( out, serverName );
  1457. else
  1458. out->writeString( serverName );
  1459. BitStream::sendPacketStream(address);
  1460. }
  1461. }
  1462. //-----------------------------------------------------------------------------
  1463. static void handleGamePingResponse( const NetAddress* address, BitStream* stream, U32 key, U8 /*flags*/ )
  1464. {
  1465. // Broadcast has timed out or query has been cancelled:
  1466. if( !gPingList.size() )
  1467. return;
  1468. S32 index = findPingEntry( gPingList, address );
  1469. if( index == -1 )
  1470. {
  1471. // an anonymous ping response - if it's not already timed
  1472. // out or finished, ping it. Probably from a broadcast
  1473. if( !addressFinished( address ) )
  1474. pushPingRequest( address );
  1475. return;
  1476. }
  1477. Ping &p = gPingList[index];
  1478. U32 infoKey = ( p.session << 16 ) | ( p.key & 0xFFFF );
  1479. if( infoKey != key )
  1480. return;
  1481. // Find if the server info already exists (favorite or refreshing):
  1482. ServerInfo* si = findServerInfo( address );
  1483. bool applyFilter = false;
  1484. if ( sActiveFilter.type == ServerFilter::Normal )
  1485. applyFilter = si ? !si->isUpdating() : true;
  1486. char addrString[256];
  1487. Net::addressToString( address, addrString );
  1488. bool waitingForMaster = ( sActiveFilter.type == ServerFilter::Normal ) && !gGotFirstListPacket;
  1489. // Verify the version:
  1490. char buf[256];
  1491. stream->readString( buf );
  1492. if ( dStrcmp( buf, versionString ) != 0 )
  1493. {
  1494. // Version is different, so remove it from consideration:
  1495. Con::printf( "Server %s is a different version.", addrString );
  1496. Con::printf( "Wanted version %s, got version %s", versionString, buf);
  1497. gFinishedList.push_back( *address );
  1498. gPingList.erase( index );
  1499. if ( si )
  1500. {
  1501. si->status = ServerInfo::Status_TimedOut;
  1502. gServerBrowserDirty = true;
  1503. }
  1504. if ( !waitingForMaster )
  1505. updatePingProgress();
  1506. return;
  1507. }
  1508. // See if the server meets our minimum protocol:
  1509. U32 temp32;
  1510. stream->read( &temp32 );
  1511. if ( temp32 < GameConnection::MinRequiredProtocolVersion )
  1512. {
  1513. Con::printf( "Protocol for server %s does not meet minimum protocol.", addrString );
  1514. gFinishedList.push_back( *address );
  1515. gPingList.erase( index );
  1516. if ( si )
  1517. {
  1518. si->status = ServerInfo::Status_TimedOut;
  1519. gServerBrowserDirty = true;
  1520. }
  1521. if ( !waitingForMaster )
  1522. updatePingProgress();
  1523. return;
  1524. }
  1525. // See if we meet the server's minimum protocol:
  1526. stream->read( &temp32 );
  1527. if ( GameConnection::CurrentProtocolVersion < temp32 )
  1528. {
  1529. Con::printf( "You do not meet the minimum protocol for server %s.", addrString );
  1530. gFinishedList.push_back( *address );
  1531. gPingList.erase( index );
  1532. if ( si )
  1533. {
  1534. si->status = ServerInfo::Status_TimedOut;
  1535. gServerBrowserDirty = true;
  1536. }
  1537. if ( !waitingForMaster )
  1538. updatePingProgress();
  1539. return;
  1540. }
  1541. // Calculate the ping:
  1542. U32 time = Platform::getVirtualMilliseconds();
  1543. U32 ping = ( time > p.time ) ? time - p.time : 0;
  1544. // Check for max ping filter:
  1545. if ( applyFilter && sActiveFilter.maxPing > 0 && ping > sActiveFilter.maxPing )
  1546. {
  1547. // Ping is too high, so remove this server from consideration:
  1548. Con::printf( "Server %s filtered out by maximum ping.", addrString );
  1549. gFinishedList.push_back( *address );
  1550. gPingList.erase( index );
  1551. if ( si )
  1552. removeServerInfo( address );
  1553. if ( !waitingForMaster )
  1554. updatePingProgress();
  1555. return;
  1556. }
  1557. // Get the server build version:
  1558. stream->read( &temp32 );
  1559. if ( applyFilter
  1560. && ( sActiveFilter.filterFlags & ServerFilter::CurrentVersion )
  1561. && ( temp32 != getVersionNumber() ) )
  1562. {
  1563. Con::printf( "Server %s filtered out by version number.", addrString );
  1564. gFinishedList.push_back( *address );
  1565. gPingList.erase( index );
  1566. if ( si )
  1567. removeServerInfo( address );
  1568. if ( !waitingForMaster )
  1569. updatePingProgress();
  1570. return;
  1571. }
  1572. // OK, we can finally create the server info structure:
  1573. if ( !si )
  1574. si = findOrCreateServerInfo( address );
  1575. si->ping = ping;
  1576. si->version = temp32;
  1577. // Get the server name:
  1578. stream->readString( buf );
  1579. if ( !si->name )
  1580. {
  1581. si->name = (char*) dMalloc( dStrlen( buf ) + 1 );
  1582. dStrcpy( si->name, buf );
  1583. }
  1584. // Set the server up to be queried:
  1585. gFinishedList.push_back( *address );
  1586. p.key = 0;
  1587. p.time = 0;
  1588. p.tryCount = gQueryRetryCount;
  1589. gQueryList.push_back( p );
  1590. gServerQueryCount++;
  1591. gPingList.erase( index );
  1592. if ( !waitingForMaster )
  1593. updatePingProgress();
  1594. // Update the server browser gui!
  1595. gServerBrowserDirty = true;
  1596. }
  1597. //-----------------------------------------------------------------------------
  1598. static void handleGameInfoRequest( const NetAddress* address, U32 key, U8 flags )
  1599. {
  1600. // Do not respond unless there is a server running:
  1601. if ( GNet->doesAllowConnections() )
  1602. {
  1603. // Do not respond to offline queries if this is an online server:
  1604. if ( flags & ServerFilter::OfflineQuery )
  1605. return;
  1606. bool compressStrings = !( flags & ServerFilter::NoStringCompress );
  1607. BitStream *out = BitStream::getPacketStream();
  1608. out->clearStringBuffer();
  1609. out->write( U8( NetInterface::GameInfoResponse ) );
  1610. out->write( flags );
  1611. out->write( key );
  1612. if ( compressStrings ) {
  1613. out->writeString( Con::getVariable( "Server::GameType" ) );
  1614. out->writeString( Con::getVariable( "Server::MissionType" ) );
  1615. out->writeString( Con::getVariable( "Server::MissionName" ) );
  1616. }
  1617. else {
  1618. writeCString( out, Con::getVariable( "Server::GameType" ) );
  1619. writeCString( out, Con::getVariable( "Server::MissionType" ) );
  1620. writeCString( out, Con::getVariable( "Server::MissionName" ) );
  1621. }
  1622. U8 status = 0;
  1623. #if defined(TORQUE_OS_LINUX) || defined(TORQUE_OS_OPENBSD)
  1624. status |= ServerInfo::Status_Linux;
  1625. #endif
  1626. #if defined(TORQUE_OS_XENON)
  1627. status |= ServerInfo::Status_Xenon;
  1628. #endif
  1629. if ( Con::getBoolVariable( "Server::Dedicated" ) )
  1630. status |= ServerInfo::Status_Dedicated;
  1631. if ( dStrlen( Con::getVariable( "pref::Server::Password" ) ) )
  1632. status |= ServerInfo::Status_Passworded;
  1633. out->write( status );
  1634. out->write( U8( Con::getIntVariable( "Server::PlayerCount" ) ) );
  1635. out->write( U8( Con::getIntVariable( "pref::Server::MaxPlayers" ) ) );
  1636. out->write( U8( Con::getIntVariable( "Server::BotCount" ) ) );
  1637. out->write( U16( Platform::SystemInfo.processor.mhz ) );
  1638. if ( compressStrings )
  1639. out->writeString( Con::getVariable( "pref::Server::Info" ) );
  1640. else
  1641. writeCString( out, Con::getVariable( "pref::Server::Info" ) );
  1642. writeLongCString( out, Con::evaluate( "onServerInfoQuery();" ) );
  1643. BitStream::sendPacketStream(address);
  1644. }
  1645. }
  1646. //-----------------------------------------------------------------------------
  1647. static void handleGameInfoResponse( const NetAddress* address, BitStream* stream, U32 /*key*/, U8 /*flags*/ )
  1648. {
  1649. if ( !gQueryList.size() )
  1650. return;
  1651. S32 index = findPingEntry( gQueryList, address );
  1652. if ( index == -1 )
  1653. return;
  1654. // Remove the server from the query list since it has been so kind as to respond:
  1655. gQueryList.erase( index );
  1656. updateQueryProgress();
  1657. ServerInfo *si = findServerInfo( address );
  1658. if ( !si )
  1659. return;
  1660. bool isUpdate = si->isUpdating();
  1661. bool applyFilter = !isUpdate && ( sActiveFilter.type == ServerFilter::Normal );
  1662. char addrString[256];
  1663. Net::addressToString( address, addrString );
  1664. // Get the rules set:
  1665. char stringBuf[2048]; // Who knows how big this should be?
  1666. stream->readString( stringBuf );
  1667. if ( !si->gameType || dStricmp( si->gameType, stringBuf ) != 0 )
  1668. {
  1669. si->gameType = (char*) dRealloc( (void*) si->gameType, dStrlen( stringBuf ) + 1 );
  1670. dStrcpy( si->gameType, stringBuf );
  1671. // Test against the active filter:
  1672. if ( applyFilter && dStricmp( sActiveFilter.gameType, "any" ) != 0
  1673. && dStricmp( si->gameType, sActiveFilter.gameType ) != 0 )
  1674. {
  1675. Con::printf( "Server %s filtered out by rules set. (%s:%s)", addrString, sActiveFilter.gameType, si->gameType );
  1676. removeServerInfo( address );
  1677. return;
  1678. }
  1679. }
  1680. // Get the mission type:
  1681. stream->readString( stringBuf );
  1682. if ( !si->missionType || dStrcmp( si->missionType, stringBuf ) != 0 )
  1683. {
  1684. si->missionType = (char*) dRealloc( (void*) si->missionType, dStrlen( stringBuf ) + 1 );
  1685. dStrcpy( si->missionType, stringBuf );
  1686. // Test against the active filter:
  1687. if ( applyFilter && dStricmp( sActiveFilter.missionType, "any" ) != 0
  1688. && dStricmp( si->missionType, sActiveFilter.missionType ) != 0 )
  1689. {
  1690. Con::printf( "Server %s filtered out by mission type. (%s:%s)", addrString, sActiveFilter.missionType, si->missionType );
  1691. removeServerInfo( address );
  1692. return;
  1693. }
  1694. }
  1695. // Get the mission name:
  1696. stream->readString( stringBuf );
  1697. // Clip the file extension off:
  1698. char* temp = dStrstr( static_cast<char*>( stringBuf ), const_cast<char*>( ".mis" ) );
  1699. if ( temp )
  1700. *temp = '\0';
  1701. if ( !si->missionName || dStrcmp( si->missionName, stringBuf ) != 0 )
  1702. {
  1703. si->missionName = (char*) dRealloc( (void*) si->missionName, dStrlen( stringBuf ) + 1 );
  1704. dStrcpy( si->missionName, stringBuf );
  1705. }
  1706. // Get the server status:
  1707. U8 temp_U8;
  1708. stream->read( &temp_U8 );
  1709. si->status = temp_U8;
  1710. // Filter by the flags:
  1711. if ( applyFilter )
  1712. {
  1713. if ( sActiveFilter.filterFlags & ServerFilter::Dedicated && !si->isDedicated() )
  1714. {
  1715. Con::printf( "Server %s filtered out by dedicated flag.", addrString );
  1716. removeServerInfo( address );
  1717. return;
  1718. }
  1719. if ( sActiveFilter.filterFlags & ServerFilter::NotPassworded && si->isPassworded() )
  1720. {
  1721. Con::printf( "Server %s filtered out by no-password flag.", addrString );
  1722. removeServerInfo( address );
  1723. return;
  1724. }
  1725. if ( sActiveFilter.filterFlags & ServerFilter::NotXenon && si->isXenon() )
  1726. {
  1727. Con::printf( "Server %s filtered out by no-xenon flag.", addrString );
  1728. removeServerInfo( address );
  1729. return;
  1730. }
  1731. }
  1732. si->status.set( ServerInfo::Status_Responded );
  1733. // Get the player count:
  1734. stream->read( &si->numPlayers );
  1735. // Test player count against active filter:
  1736. if ( applyFilter && ( si->numPlayers < sActiveFilter.minPlayers || si->numPlayers > sActiveFilter.maxPlayers ) )
  1737. {
  1738. Con::printf( "Server %s filtered out by player count.", addrString );
  1739. removeServerInfo( address );
  1740. return;
  1741. }
  1742. // Get the max players and bot count:
  1743. stream->read( &si->maxPlayers );
  1744. stream->read( &si->numBots );
  1745. // Test bot count against active filter:
  1746. if ( applyFilter && ( si->numBots > sActiveFilter.maxBots ) )
  1747. {
  1748. Con::printf( "Server %s filtered out by maximum bot count.", addrString );
  1749. removeServerInfo( address );
  1750. return;
  1751. }
  1752. // Get the CPU speed;
  1753. U16 temp_U16;
  1754. stream->read( &temp_U16 );
  1755. si->cpuSpeed = temp_U16;
  1756. // Test CPU speed against active filter:
  1757. if ( applyFilter && ( si->cpuSpeed < sActiveFilter.minCPU ) )
  1758. {
  1759. Con::printf( "Server %s filtered out by minimum CPU speed.", addrString );
  1760. removeServerInfo( address );
  1761. return;
  1762. }
  1763. // Get the server info:
  1764. stream->readString( stringBuf );
  1765. if ( !si->statusString || ( isUpdate && dStrcmp( si->statusString, stringBuf ) != 0 ) )
  1766. {
  1767. si->infoString = (char*) dRealloc( (void*) si->infoString, dStrlen( stringBuf ) + 1 );
  1768. dStrcpy( si->infoString, stringBuf );
  1769. }
  1770. // Get the content string:
  1771. readLongCString( stream, stringBuf );
  1772. if ( !si->statusString || ( isUpdate && dStrcmp( si->statusString, stringBuf ) != 0 ) )
  1773. {
  1774. si->statusString = (char*) dRealloc( (void*) si->statusString, dStrlen( stringBuf ) + 1 );
  1775. dStrcpy( si->statusString, stringBuf );
  1776. }
  1777. // Update the server browser gui!
  1778. gServerBrowserDirty = true;
  1779. }
  1780. //-----------------------------------------------------------------------------
  1781. // Packet Dispatch
  1782. void DemoNetInterface::handleInfoPacket( const NetAddress* address, U8 packetType, BitStream* stream )
  1783. {
  1784. U8 flags;
  1785. U32 key;
  1786. stream->read( &flags );
  1787. stream->read( &key );
  1788. stream->clearStringBuffer();
  1789. switch( packetType )
  1790. {
  1791. case GamePingRequest:
  1792. handleGamePingRequest( address, key, flags );
  1793. break;
  1794. case GamePingResponse:
  1795. handleGamePingResponse( address, stream, key, flags );
  1796. break;
  1797. case GameInfoRequest:
  1798. handleGameInfoRequest( address, key, flags );
  1799. break;
  1800. case GameInfoResponse:
  1801. handleGameInfoResponse( address, stream, key, flags );
  1802. break;
  1803. case MasterServerGameTypesResponse:
  1804. handleMasterServerGameTypesResponse( stream, key, flags );
  1805. break;
  1806. case MasterServerListResponse:
  1807. handleMasterServerListResponse( stream, key, flags );
  1808. break;
  1809. case GameMasterInfoRequest:
  1810. handleGameMasterInfoRequest( address, key, flags );
  1811. break;
  1812. }
  1813. }
  1814. ConsoleFunctionGroupEnd( ServerQuery );