clientiface.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include <sstream>
  17. #include "clientiface.h"
  18. #include "network/connection.h"
  19. #include "network/serveropcodes.h"
  20. #include "remoteplayer.h"
  21. #include "settings.h"
  22. #include "mapblock.h"
  23. #include "serverenvironment.h"
  24. #include "map.h"
  25. #include "emerge.h"
  26. #include "content_sao.h" // TODO this is used for cleanup of only
  27. #include "log.h"
  28. #include "util/srp.h"
  29. #include "face_position_cache.h"
  30. const char *ClientInterface::statenames[] = {
  31. "Invalid",
  32. "Disconnecting",
  33. "Denied",
  34. "Created",
  35. "AwaitingInit2",
  36. "HelloSent",
  37. "InitDone",
  38. "DefinitionsSent",
  39. "Active",
  40. "SudoMode",
  41. };
  42. std::string ClientInterface::state2Name(ClientState state)
  43. {
  44. return statenames[state];
  45. }
  46. RemoteClient::RemoteClient() :
  47. m_max_simul_sends(g_settings->getU16("max_simultaneous_block_sends_per_client")),
  48. m_min_time_from_building(
  49. g_settings->getFloat("full_block_send_enable_min_time_from_building")),
  50. m_max_send_distance(g_settings->getS16("max_block_send_distance")),
  51. m_block_optimize_distance(g_settings->getS16("block_send_optimize_distance")),
  52. m_max_gen_distance(g_settings->getS16("max_block_generate_distance")),
  53. m_occ_cull(g_settings->getBool("server_side_occlusion_culling"))
  54. {
  55. }
  56. void RemoteClient::ResendBlockIfOnWire(v3s16 p)
  57. {
  58. // if this block is on wire, mark it for sending again as soon as possible
  59. if (m_blocks_sending.find(p) != m_blocks_sending.end()) {
  60. SetBlockNotSent(p);
  61. }
  62. }
  63. LuaEntitySAO *getAttachedObject(PlayerSAO *sao, ServerEnvironment *env)
  64. {
  65. if (!sao->isAttached())
  66. return nullptr;
  67. int id;
  68. std::string bone;
  69. v3f dummy;
  70. sao->getAttachment(&id, &bone, &dummy, &dummy);
  71. ServerActiveObject *ao = env->getActiveObject(id);
  72. while (id && ao) {
  73. ao->getAttachment(&id, &bone, &dummy, &dummy);
  74. if (id)
  75. ao = env->getActiveObject(id);
  76. }
  77. return dynamic_cast<LuaEntitySAO *>(ao);
  78. }
  79. void RemoteClient::GetNextBlocks (
  80. ServerEnvironment *env,
  81. EmergeManager * emerge,
  82. float dtime,
  83. std::vector<PrioritySortedBlockTransfer> &dest)
  84. {
  85. // Increment timers
  86. m_nothing_to_send_pause_timer -= dtime;
  87. m_nearest_unsent_reset_timer += dtime;
  88. if (m_nothing_to_send_pause_timer >= 0)
  89. return;
  90. RemotePlayer *player = env->getPlayer(peer_id);
  91. // This can happen sometimes; clients and players are not in perfect sync.
  92. if (!player)
  93. return;
  94. PlayerSAO *sao = player->getPlayerSAO();
  95. if (!sao)
  96. return;
  97. // Won't send anything if already sending
  98. if (m_blocks_sending.size() >= m_max_simul_sends) {
  99. //infostream<<"Not sending any blocks, Queue full."<<std::endl;
  100. return;
  101. }
  102. v3f playerpos = sao->getBasePosition();
  103. // if the player is attached, get the velocity from the attached object
  104. LuaEntitySAO *lsao = getAttachedObject(sao, env);
  105. const v3f &playerspeed = lsao? lsao->getVelocity() : player->getSpeed();
  106. v3f playerspeeddir(0,0,0);
  107. if (playerspeed.getLength() > 1.0f * BS)
  108. playerspeeddir = playerspeed / playerspeed.getLength();
  109. // Predict to next block
  110. v3f playerpos_predicted = playerpos + playerspeeddir * (MAP_BLOCKSIZE * BS);
  111. v3s16 center_nodepos = floatToInt(playerpos_predicted, BS);
  112. v3s16 center = getNodeBlockPos(center_nodepos);
  113. // Camera position and direction
  114. v3f camera_pos = sao->getEyePosition();
  115. v3f camera_dir = v3f(0,0,1);
  116. camera_dir.rotateYZBy(sao->getPitch());
  117. camera_dir.rotateXZBy(sao->getYaw());
  118. /*infostream<<"camera_dir=("<<camera_dir.X<<","<<camera_dir.Y<<","
  119. <<camera_dir.Z<<")"<<std::endl;*/
  120. /*
  121. Get the starting value of the block finder radius.
  122. */
  123. if (m_last_center != center) {
  124. m_nearest_unsent_d = 0;
  125. m_last_center = center;
  126. }
  127. /*infostream<<"m_nearest_unsent_reset_timer="
  128. <<m_nearest_unsent_reset_timer<<std::endl;*/
  129. // Reset periodically to workaround for some bugs or stuff
  130. if (m_nearest_unsent_reset_timer > 20.0f) {
  131. m_nearest_unsent_reset_timer = 0.0f;
  132. m_nearest_unsent_d = 0;
  133. //infostream<<"Resetting m_nearest_unsent_d for "
  134. // <<server->getPlayerName(peer_id)<<std::endl;
  135. }
  136. //s16 last_nearest_unsent_d = m_nearest_unsent_d;
  137. s16 d_start = m_nearest_unsent_d;
  138. //infostream<<"d_start="<<d_start<<std::endl;
  139. u16 max_simul_sends_usually = m_max_simul_sends;
  140. /*
  141. Check the time from last addNode/removeNode.
  142. Decrease send rate if player is building stuff.
  143. */
  144. m_time_from_building += dtime;
  145. if (m_time_from_building < m_min_time_from_building) {
  146. max_simul_sends_usually
  147. = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
  148. }
  149. /*
  150. Number of blocks sending + number of blocks selected for sending
  151. */
  152. u32 num_blocks_selected = m_blocks_sending.size();
  153. /*
  154. next time d will be continued from the d from which the nearest
  155. unsent block was found this time.
  156. This is because not necessarily any of the blocks found this
  157. time are actually sent.
  158. */
  159. s32 new_nearest_unsent_d = -1;
  160. // Get view range and camera fov (radians) from the client
  161. s16 wanted_range = sao->getWantedRange() + 1;
  162. float camera_fov = sao->getFov();
  163. // Distrust client-sent FOV and get server-set player object property
  164. // zoom FOV (degrees) as a check to avoid hacked clients using FOV to load
  165. // distant world.
  166. float prop_zoom_fov = sao->getZoomFOV() * core::DEGTORAD;
  167. const s16 full_d_max = std::min(adjustDist(m_max_send_distance, prop_zoom_fov),
  168. wanted_range);
  169. const s16 d_opt = std::min(adjustDist(m_block_optimize_distance, prop_zoom_fov),
  170. wanted_range);
  171. const s16 d_blocks_in_sight = full_d_max * BS * MAP_BLOCKSIZE;
  172. s16 d_max = full_d_max;
  173. s16 d_max_gen = std::min(adjustDist(m_max_gen_distance, prop_zoom_fov),
  174. wanted_range);
  175. // Don't loop very much at a time, adjust with distance,
  176. // do more work per RTT with greater distances.
  177. s16 max_d_increment_at_time = full_d_max / 9 + 1;
  178. if (d_max > d_start + max_d_increment_at_time)
  179. d_max = d_start + max_d_increment_at_time;
  180. // cos(angle between velocity and camera) * |velocity|
  181. // Limit to 0.0f in case player moves backwards.
  182. f32 dot = rangelim(camera_dir.dotProduct(playerspeed), 0.0f, 300.0f);
  183. // Reduce the field of view when a player moves and looks forward.
  184. // limit max fov effect to 50%, 60% at 20n/s fly speed
  185. camera_fov = camera_fov / (1 + dot / 300.0f);
  186. s32 nearest_emerged_d = -1;
  187. s32 nearest_emergefull_d = -1;
  188. s32 nearest_sent_d = -1;
  189. //bool queue_is_full = false;
  190. const v3s16 cam_pos_nodes = floatToInt(camera_pos, BS);
  191. s16 d;
  192. for (d = d_start; d <= d_max; d++) {
  193. /*
  194. Get the border/face dot coordinates of a "d-radiused"
  195. box
  196. */
  197. std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
  198. std::vector<v3s16>::iterator li;
  199. for (li = list.begin(); li != list.end(); ++li) {
  200. v3s16 p = *li + center;
  201. /*
  202. Send throttling
  203. - Don't allow too many simultaneous transfers
  204. - EXCEPT when the blocks are very close
  205. Also, don't send blocks that are already flying.
  206. */
  207. // Start with the usual maximum
  208. u16 max_simul_dynamic = max_simul_sends_usually;
  209. // If block is very close, allow full maximum
  210. if (d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
  211. max_simul_dynamic = m_max_simul_sends;
  212. // Don't select too many blocks for sending
  213. if (num_blocks_selected >= max_simul_dynamic) {
  214. //queue_is_full = true;
  215. goto queue_full_break;
  216. }
  217. // Don't send blocks that are currently being transferred
  218. if (m_blocks_sending.find(p) != m_blocks_sending.end())
  219. continue;
  220. /*
  221. Do not go over max mapgen limit
  222. */
  223. if (blockpos_over_max_limit(p))
  224. continue;
  225. // If this is true, inexistent block will be made from scratch
  226. bool generate = d <= d_max_gen;
  227. /*
  228. Don't generate or send if not in sight
  229. FIXME This only works if the client uses a small enough
  230. FOV setting. The default of 72 degrees is fine.
  231. Also retrieve a smaller view cone in the direction of the player's
  232. movement.
  233. (0.1 is about 4 degrees)
  234. */
  235. f32 dist;
  236. if (!(isBlockInSight(p, camera_pos, camera_dir, camera_fov,
  237. d_blocks_in_sight, &dist) ||
  238. (playerspeed.getLength() > 1.0f * BS &&
  239. isBlockInSight(p, camera_pos, playerspeeddir, 0.1f,
  240. d_blocks_in_sight)))) {
  241. continue;
  242. }
  243. /*
  244. Don't send already sent blocks
  245. */
  246. if (m_blocks_sent.find(p) != m_blocks_sent.end())
  247. continue;
  248. /*
  249. Check if map has this block
  250. */
  251. MapBlock *block = env->getMap().getBlockNoCreateNoEx(p);
  252. bool surely_not_found_on_disk = false;
  253. bool block_is_invalid = false;
  254. if (block) {
  255. // Reset usage timer, this block will be of use in the future.
  256. block->resetUsageTimer();
  257. // Block is dummy if data doesn't exist.
  258. // It means it has been not found from disk and not generated
  259. if (block->isDummy()) {
  260. surely_not_found_on_disk = true;
  261. }
  262. if (!block->isGenerated())
  263. block_is_invalid = true;
  264. /*
  265. If block is not close, don't send it unless it is near
  266. ground level.
  267. Block is near ground level if night-time mesh
  268. differs from day-time mesh.
  269. */
  270. if (d >= d_opt) {
  271. if (!block->getDayNightDiff())
  272. continue;
  273. }
  274. if (m_occ_cull && !block_is_invalid &&
  275. env->getMap().isBlockOccluded(block, cam_pos_nodes)) {
  276. continue;
  277. }
  278. }
  279. /*
  280. If block has been marked to not exist on disk (dummy)
  281. and generating new ones is not wanted, skip block.
  282. */
  283. if (!generate && surely_not_found_on_disk) {
  284. // get next one.
  285. continue;
  286. }
  287. /*
  288. Add inexistent block to emerge queue.
  289. */
  290. if (block == NULL || surely_not_found_on_disk || block_is_invalid) {
  291. if (emerge->enqueueBlockEmerge(peer_id, p, generate)) {
  292. if (nearest_emerged_d == -1)
  293. nearest_emerged_d = d;
  294. } else {
  295. if (nearest_emergefull_d == -1)
  296. nearest_emergefull_d = d;
  297. goto queue_full_break;
  298. }
  299. // get next one.
  300. continue;
  301. }
  302. if (nearest_sent_d == -1)
  303. nearest_sent_d = d;
  304. /*
  305. Add block to send queue
  306. */
  307. PrioritySortedBlockTransfer q((float)dist, p, peer_id);
  308. dest.push_back(q);
  309. num_blocks_selected += 1;
  310. }
  311. }
  312. queue_full_break:
  313. // If nothing was found for sending and nothing was queued for
  314. // emerging, continue next time browsing from here
  315. if (nearest_emerged_d != -1) {
  316. new_nearest_unsent_d = nearest_emerged_d;
  317. } else if (nearest_emergefull_d != -1) {
  318. new_nearest_unsent_d = nearest_emergefull_d;
  319. } else {
  320. if (d > full_d_max) {
  321. new_nearest_unsent_d = 0;
  322. m_nothing_to_send_pause_timer = 2.0f;
  323. } else {
  324. if (nearest_sent_d != -1)
  325. new_nearest_unsent_d = nearest_sent_d;
  326. else
  327. new_nearest_unsent_d = d;
  328. }
  329. }
  330. if (new_nearest_unsent_d != -1)
  331. m_nearest_unsent_d = new_nearest_unsent_d;
  332. }
  333. void RemoteClient::GotBlock(v3s16 p)
  334. {
  335. if (m_blocks_modified.find(p) == m_blocks_modified.end()) {
  336. if (m_blocks_sending.find(p) != m_blocks_sending.end())
  337. m_blocks_sending.erase(p);
  338. else
  339. m_excess_gotblocks++;
  340. m_blocks_sent.insert(p);
  341. }
  342. }
  343. void RemoteClient::SentBlock(v3s16 p)
  344. {
  345. if (m_blocks_modified.find(p) != m_blocks_modified.end())
  346. m_blocks_modified.erase(p);
  347. if (m_blocks_sending.find(p) == m_blocks_sending.end())
  348. m_blocks_sending[p] = 0.0f;
  349. else
  350. infostream<<"RemoteClient::SentBlock(): Sent block"
  351. " already in m_blocks_sending"<<std::endl;
  352. }
  353. void RemoteClient::SetBlockNotSent(v3s16 p)
  354. {
  355. m_nearest_unsent_d = 0;
  356. m_nothing_to_send_pause_timer = 0;
  357. if (m_blocks_sending.find(p) != m_blocks_sending.end())
  358. m_blocks_sending.erase(p);
  359. if (m_blocks_sent.find(p) != m_blocks_sent.end())
  360. m_blocks_sent.erase(p);
  361. m_blocks_modified.insert(p);
  362. }
  363. void RemoteClient::SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks)
  364. {
  365. m_nearest_unsent_d = 0;
  366. m_nothing_to_send_pause_timer = 0;
  367. for (auto &block : blocks) {
  368. v3s16 p = block.first;
  369. m_blocks_modified.insert(p);
  370. if (m_blocks_sending.find(p) != m_blocks_sending.end())
  371. m_blocks_sending.erase(p);
  372. if (m_blocks_sent.find(p) != m_blocks_sent.end())
  373. m_blocks_sent.erase(p);
  374. }
  375. }
  376. void RemoteClient::notifyEvent(ClientStateEvent event)
  377. {
  378. std::ostringstream myerror;
  379. switch (m_state)
  380. {
  381. case CS_Invalid:
  382. //intentionally do nothing
  383. break;
  384. case CS_Created:
  385. switch (event) {
  386. case CSE_Hello:
  387. m_state = CS_HelloSent;
  388. break;
  389. case CSE_InitLegacy:
  390. m_state = CS_AwaitingInit2;
  391. break;
  392. case CSE_Disconnect:
  393. m_state = CS_Disconnecting;
  394. break;
  395. case CSE_SetDenied:
  396. m_state = CS_Denied;
  397. break;
  398. /* GotInit2 SetDefinitionsSent SetMediaSent */
  399. default:
  400. myerror << "Created: Invalid client state transition! " << event;
  401. throw ClientStateError(myerror.str());
  402. }
  403. break;
  404. case CS_Denied:
  405. /* don't do anything if in denied state */
  406. break;
  407. case CS_HelloSent:
  408. switch(event)
  409. {
  410. case CSE_AuthAccept:
  411. m_state = CS_AwaitingInit2;
  412. if (chosen_mech == AUTH_MECHANISM_SRP ||
  413. chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD)
  414. srp_verifier_delete((SRPVerifier *) auth_data);
  415. chosen_mech = AUTH_MECHANISM_NONE;
  416. break;
  417. case CSE_Disconnect:
  418. m_state = CS_Disconnecting;
  419. break;
  420. case CSE_SetDenied:
  421. m_state = CS_Denied;
  422. if (chosen_mech == AUTH_MECHANISM_SRP ||
  423. chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD)
  424. srp_verifier_delete((SRPVerifier *) auth_data);
  425. chosen_mech = AUTH_MECHANISM_NONE;
  426. break;
  427. default:
  428. myerror << "HelloSent: Invalid client state transition! " << event;
  429. throw ClientStateError(myerror.str());
  430. }
  431. break;
  432. case CS_AwaitingInit2:
  433. switch(event)
  434. {
  435. case CSE_GotInit2:
  436. confirmSerializationVersion();
  437. m_state = CS_InitDone;
  438. break;
  439. case CSE_Disconnect:
  440. m_state = CS_Disconnecting;
  441. break;
  442. case CSE_SetDenied:
  443. m_state = CS_Denied;
  444. break;
  445. /* Init SetDefinitionsSent SetMediaSent */
  446. default:
  447. myerror << "InitSent: Invalid client state transition! " << event;
  448. throw ClientStateError(myerror.str());
  449. }
  450. break;
  451. case CS_InitDone:
  452. switch(event)
  453. {
  454. case CSE_SetDefinitionsSent:
  455. m_state = CS_DefinitionsSent;
  456. break;
  457. case CSE_Disconnect:
  458. m_state = CS_Disconnecting;
  459. break;
  460. case CSE_SetDenied:
  461. m_state = CS_Denied;
  462. break;
  463. /* Init GotInit2 SetMediaSent */
  464. default:
  465. myerror << "InitDone: Invalid client state transition! " << event;
  466. throw ClientStateError(myerror.str());
  467. }
  468. break;
  469. case CS_DefinitionsSent:
  470. switch(event)
  471. {
  472. case CSE_SetClientReady:
  473. m_state = CS_Active;
  474. break;
  475. case CSE_Disconnect:
  476. m_state = CS_Disconnecting;
  477. break;
  478. case CSE_SetDenied:
  479. m_state = CS_Denied;
  480. break;
  481. /* Init GotInit2 SetDefinitionsSent */
  482. default:
  483. myerror << "DefinitionsSent: Invalid client state transition! " << event;
  484. throw ClientStateError(myerror.str());
  485. }
  486. break;
  487. case CS_Active:
  488. switch(event)
  489. {
  490. case CSE_SetDenied:
  491. m_state = CS_Denied;
  492. break;
  493. case CSE_Disconnect:
  494. m_state = CS_Disconnecting;
  495. break;
  496. case CSE_SudoSuccess:
  497. m_state = CS_SudoMode;
  498. if (chosen_mech == AUTH_MECHANISM_SRP)
  499. srp_verifier_delete((SRPVerifier *) auth_data);
  500. chosen_mech = AUTH_MECHANISM_NONE;
  501. break;
  502. /* Init GotInit2 SetDefinitionsSent SetMediaSent SetDenied */
  503. default:
  504. myerror << "Active: Invalid client state transition! " << event;
  505. throw ClientStateError(myerror.str());
  506. break;
  507. }
  508. break;
  509. case CS_SudoMode:
  510. switch(event)
  511. {
  512. case CSE_SetDenied:
  513. m_state = CS_Denied;
  514. break;
  515. case CSE_Disconnect:
  516. m_state = CS_Disconnecting;
  517. break;
  518. case CSE_SudoLeave:
  519. m_state = CS_Active;
  520. break;
  521. default:
  522. myerror << "Active: Invalid client state transition! " << event;
  523. throw ClientStateError(myerror.str());
  524. break;
  525. }
  526. break;
  527. case CS_Disconnecting:
  528. /* we are already disconnecting */
  529. break;
  530. }
  531. }
  532. u64 RemoteClient::uptime() const
  533. {
  534. return porting::getTimeS() - m_connection_time;
  535. }
  536. ClientInterface::ClientInterface(const std::shared_ptr<con::Connection> & con)
  537. :
  538. m_con(con),
  539. m_env(NULL),
  540. m_print_info_timer(0.0f)
  541. {
  542. }
  543. ClientInterface::~ClientInterface()
  544. {
  545. /*
  546. Delete clients
  547. */
  548. {
  549. MutexAutoLock clientslock(m_clients_mutex);
  550. for (auto &client_it : m_clients) {
  551. // Delete client
  552. delete client_it.second;
  553. }
  554. }
  555. }
  556. std::vector<session_t> ClientInterface::getClientIDs(ClientState min_state)
  557. {
  558. std::vector<session_t> reply;
  559. MutexAutoLock clientslock(m_clients_mutex);
  560. for (const auto &m_client : m_clients) {
  561. if (m_client.second->getState() >= min_state)
  562. reply.push_back(m_client.second->peer_id);
  563. }
  564. return reply;
  565. }
  566. void ClientInterface::markBlockposAsNotSent(const v3s16 &pos)
  567. {
  568. MutexAutoLock clientslock(m_clients_mutex);
  569. for (const auto &client : m_clients) {
  570. if (client.second->getState() >= CS_Active)
  571. client.second->SetBlockNotSent(pos);
  572. }
  573. }
  574. /**
  575. * Verify if user limit was reached.
  576. * User limit count all clients from HelloSent state (MT protocol user) to Active state
  577. * @return true if user limit was reached
  578. */
  579. bool ClientInterface::isUserLimitReached()
  580. {
  581. return getClientIDs(CS_HelloSent).size() >= g_settings->getU16("max_users");
  582. }
  583. void ClientInterface::step(float dtime)
  584. {
  585. m_print_info_timer += dtime;
  586. if (m_print_info_timer >= 30.0f) {
  587. m_print_info_timer = 0.0f;
  588. UpdatePlayerList();
  589. }
  590. }
  591. void ClientInterface::UpdatePlayerList()
  592. {
  593. if (m_env) {
  594. std::vector<session_t> clients = getClientIDs();
  595. m_clients_names.clear();
  596. if (!clients.empty())
  597. infostream<<"Players:"<<std::endl;
  598. for (session_t i : clients) {
  599. RemotePlayer *player = m_env->getPlayer(i);
  600. if (player == NULL)
  601. continue;
  602. infostream << "* " << player->getName() << "\t";
  603. {
  604. MutexAutoLock clientslock(m_clients_mutex);
  605. RemoteClient* client = lockedGetClientNoEx(i);
  606. if (client)
  607. client->PrintInfo(infostream);
  608. }
  609. m_clients_names.emplace_back(player->getName());
  610. }
  611. }
  612. }
  613. void ClientInterface::send(session_t peer_id, u8 channelnum,
  614. NetworkPacket *pkt, bool reliable)
  615. {
  616. m_con->Send(peer_id, channelnum, pkt, reliable);
  617. }
  618. void ClientInterface::sendToAll(NetworkPacket *pkt)
  619. {
  620. MutexAutoLock clientslock(m_clients_mutex);
  621. for (auto &client_it : m_clients) {
  622. RemoteClient *client = client_it.second;
  623. if (client->net_proto_version != 0) {
  624. m_con->Send(client->peer_id,
  625. clientCommandFactoryTable[pkt->getCommand()].channel, pkt,
  626. clientCommandFactoryTable[pkt->getCommand()].reliable);
  627. }
  628. }
  629. }
  630. void ClientInterface::sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacypkt,
  631. u16 min_proto_ver)
  632. {
  633. MutexAutoLock clientslock(m_clients_mutex);
  634. for (auto &client_it : m_clients) {
  635. RemoteClient *client = client_it.second;
  636. NetworkPacket *pkt_to_send = nullptr;
  637. if (client->net_proto_version >= min_proto_ver) {
  638. pkt_to_send = pkt;
  639. } else if (client->net_proto_version != 0) {
  640. pkt_to_send = legacypkt;
  641. } else {
  642. warningstream << "Client with unhandled version to handle: '"
  643. << client->net_proto_version << "'";
  644. continue;
  645. }
  646. m_con->Send(client->peer_id,
  647. clientCommandFactoryTable[pkt_to_send->getCommand()].channel,
  648. pkt_to_send,
  649. clientCommandFactoryTable[pkt_to_send->getCommand()].reliable);
  650. }
  651. }
  652. RemoteClient* ClientInterface::getClientNoEx(session_t peer_id, ClientState state_min)
  653. {
  654. MutexAutoLock clientslock(m_clients_mutex);
  655. RemoteClientMap::const_iterator n = m_clients.find(peer_id);
  656. // The client may not exist; clients are immediately removed if their
  657. // access is denied, and this event occurs later then.
  658. if (n == m_clients.end())
  659. return NULL;
  660. if (n->second->getState() >= state_min)
  661. return n->second;
  662. return NULL;
  663. }
  664. RemoteClient* ClientInterface::lockedGetClientNoEx(session_t peer_id, ClientState state_min)
  665. {
  666. RemoteClientMap::const_iterator n = m_clients.find(peer_id);
  667. // The client may not exist; clients are immediately removed if their
  668. // access is denied, and this event occurs later then.
  669. if (n == m_clients.end())
  670. return NULL;
  671. if (n->second->getState() >= state_min)
  672. return n->second;
  673. return NULL;
  674. }
  675. ClientState ClientInterface::getClientState(session_t peer_id)
  676. {
  677. MutexAutoLock clientslock(m_clients_mutex);
  678. RemoteClientMap::const_iterator n = m_clients.find(peer_id);
  679. // The client may not exist; clients are immediately removed if their
  680. // access is denied, and this event occurs later then.
  681. if (n == m_clients.end())
  682. return CS_Invalid;
  683. return n->second->getState();
  684. }
  685. void ClientInterface::setPlayerName(session_t peer_id, const std::string &name)
  686. {
  687. MutexAutoLock clientslock(m_clients_mutex);
  688. RemoteClientMap::iterator n = m_clients.find(peer_id);
  689. // The client may not exist; clients are immediately removed if their
  690. // access is denied, and this event occurs later then.
  691. if (n != m_clients.end())
  692. n->second->setName(name);
  693. }
  694. void ClientInterface::DeleteClient(session_t peer_id)
  695. {
  696. MutexAutoLock conlock(m_clients_mutex);
  697. // Error check
  698. RemoteClientMap::iterator n = m_clients.find(peer_id);
  699. // The client may not exist; clients are immediately removed if their
  700. // access is denied, and this event occurs later then.
  701. if (n == m_clients.end())
  702. return;
  703. /*
  704. Mark objects to be not known by the client
  705. */
  706. //TODO this should be done by client destructor!!!
  707. RemoteClient *client = n->second;
  708. // Handle objects
  709. for (u16 id : client->m_known_objects) {
  710. // Get object
  711. ServerActiveObject* obj = m_env->getActiveObject(id);
  712. if(obj && obj->m_known_by_count > 0)
  713. obj->m_known_by_count--;
  714. }
  715. // Delete client
  716. delete m_clients[peer_id];
  717. m_clients.erase(peer_id);
  718. }
  719. void ClientInterface::CreateClient(session_t peer_id)
  720. {
  721. MutexAutoLock conlock(m_clients_mutex);
  722. // Error check
  723. RemoteClientMap::iterator n = m_clients.find(peer_id);
  724. // The client shouldn't already exist
  725. if (n != m_clients.end()) return;
  726. // Create client
  727. RemoteClient *client = new RemoteClient();
  728. client->peer_id = peer_id;
  729. m_clients[client->peer_id] = client;
  730. }
  731. void ClientInterface::event(session_t peer_id, ClientStateEvent event)
  732. {
  733. {
  734. MutexAutoLock clientlock(m_clients_mutex);
  735. // Error check
  736. RemoteClientMap::iterator n = m_clients.find(peer_id);
  737. // No client to deliver event
  738. if (n == m_clients.end())
  739. return;
  740. n->second->notifyEvent(event);
  741. }
  742. if ((event == CSE_SetClientReady) ||
  743. (event == CSE_Disconnect) ||
  744. (event == CSE_SetDenied))
  745. {
  746. UpdatePlayerList();
  747. }
  748. }
  749. u16 ClientInterface::getProtocolVersion(session_t peer_id)
  750. {
  751. MutexAutoLock conlock(m_clients_mutex);
  752. // Error check
  753. RemoteClientMap::iterator n = m_clients.find(peer_id);
  754. // No client to get version
  755. if (n == m_clients.end())
  756. return 0;
  757. return n->second->net_proto_version;
  758. }
  759. void ClientInterface::setClientVersion(session_t peer_id, u8 major, u8 minor, u8 patch,
  760. const std::string &full)
  761. {
  762. MutexAutoLock conlock(m_clients_mutex);
  763. // Error check
  764. RemoteClientMap::iterator n = m_clients.find(peer_id);
  765. // No client to set versions
  766. if (n == m_clients.end())
  767. return;
  768. n->second->setVersionInfo(major, minor, patch, full);
  769. }