serverQuery.cpp 69 KB

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