serverQuery.cpp 69 KB

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