serverQuery.cpp 69 KB

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