serverQuery.cpp 69 KB

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