serverQuery.cpp 66 KB

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