serverQuery.cpp 69 KB

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