server.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 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. #pragma once
  17. #include "irr_v3d.h"
  18. #include "map.h"
  19. #include "hud.h"
  20. #include "gamedef.h"
  21. #include "serialization.h" // For SER_FMT_VER_INVALID
  22. #include "content/mods.h"
  23. #include "inventorymanager.h"
  24. #include "content/subgames.h"
  25. #include "network/peerhandler.h"
  26. #include "network/address.h"
  27. #include "util/numeric.h"
  28. #include "util/thread.h"
  29. #include "util/basic_macros.h"
  30. #include "util/metricsbackend.h"
  31. #include "serverenvironment.h"
  32. #include "server/clientiface.h"
  33. #include "chatmessage.h"
  34. #include "sound.h"
  35. #include "translation.h"
  36. #include <atomic>
  37. #include <string>
  38. #include <list>
  39. #include <map>
  40. #include <vector>
  41. #include <unordered_set>
  42. #include <optional>
  43. #include <string_view>
  44. class ChatEvent;
  45. struct ChatEventChat;
  46. struct ChatInterface;
  47. class IWritableItemDefManager;
  48. class NodeDefManager;
  49. class IWritableCraftDefManager;
  50. class BanManager;
  51. class Inventory;
  52. class ModChannelMgr;
  53. class RemotePlayer;
  54. class PlayerSAO;
  55. struct PlayerHPChangeReason;
  56. class IRollbackManager;
  57. struct RollbackAction;
  58. class EmergeManager;
  59. class ServerScripting;
  60. class ServerEnvironment;
  61. struct SoundSpec;
  62. struct CloudParams;
  63. struct SkyboxParams;
  64. struct SunParams;
  65. struct MoonParams;
  66. struct StarParams;
  67. struct Lighting;
  68. class ServerThread;
  69. class ServerModManager;
  70. class ServerInventoryManager;
  71. struct PackedValue;
  72. struct ParticleParameters;
  73. struct ParticleSpawnerParameters;
  74. enum ClientDeletionReason {
  75. CDR_LEAVE,
  76. CDR_TIMEOUT,
  77. CDR_DENY
  78. };
  79. struct MediaInfo
  80. {
  81. std::string path;
  82. std::string sha1_digest; // base64-encoded
  83. // true = not announced in TOCLIENT_ANNOUNCE_MEDIA (at player join)
  84. bool no_announce;
  85. // does what it says. used by some cases of dynamic media.
  86. bool delete_at_shutdown;
  87. MediaInfo(std::string_view path_ = "",
  88. std::string_view sha1_digest_ = ""):
  89. path(path_),
  90. sha1_digest(sha1_digest_),
  91. no_announce(false),
  92. delete_at_shutdown(false)
  93. {
  94. }
  95. };
  96. // Combines the pure sound (SoundSpec) with positional information
  97. struct ServerPlayingSound
  98. {
  99. SoundLocation type = SoundLocation::Local;
  100. float gain = 1.0f; // for amplification of the base sound
  101. float max_hear_distance = 32 * BS;
  102. v3f pos;
  103. u16 object = 0;
  104. std::string to_player;
  105. std::string exclude_player;
  106. v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
  107. SoundSpec spec;
  108. std::unordered_set<session_t> clients; // peer ids
  109. };
  110. struct MinimapMode {
  111. MinimapType type = MINIMAP_TYPE_OFF;
  112. std::string label;
  113. u16 size = 0;
  114. std::string texture;
  115. u16 scale = 1;
  116. };
  117. // structure for everything getClientInfo returns, for convenience
  118. struct ClientInfo {
  119. ClientState state;
  120. Address addr;
  121. u32 uptime;
  122. u8 ser_vers;
  123. u16 prot_vers;
  124. u8 major, minor, patch;
  125. std::string vers_string, lang_code;
  126. };
  127. class Server : public con::PeerHandler, public MapEventReceiver,
  128. public IGameDef
  129. {
  130. public:
  131. /*
  132. NOTE: Every public method should be thread-safe
  133. */
  134. Server(
  135. const std::string &path_world,
  136. const SubgameSpec &gamespec,
  137. bool simple_singleplayer_mode,
  138. Address bind_addr,
  139. bool dedicated,
  140. ChatInterface *iface = nullptr,
  141. std::string *shutdown_errmsg = nullptr
  142. );
  143. ~Server();
  144. DISABLE_CLASS_COPY(Server);
  145. void start();
  146. void stop();
  147. // Actual processing is done in another thread.
  148. // This just checks if there was an error in that thread.
  149. void step();
  150. // This is run by ServerThread and does the actual processing
  151. void AsyncRunStep(float dtime, bool initial_step = false);
  152. void Receive(float timeout);
  153. PlayerSAO* StageTwoClientInit(session_t peer_id);
  154. /*
  155. * Command Handlers
  156. */
  157. void handleCommand(NetworkPacket* pkt);
  158. void handleCommand_Null(NetworkPacket* pkt) {};
  159. void handleCommand_Deprecated(NetworkPacket* pkt);
  160. void handleCommand_Init(NetworkPacket* pkt);
  161. void handleCommand_Init2(NetworkPacket* pkt);
  162. void handleCommand_ModChannelJoin(NetworkPacket *pkt);
  163. void handleCommand_ModChannelLeave(NetworkPacket *pkt);
  164. void handleCommand_ModChannelMsg(NetworkPacket *pkt);
  165. void handleCommand_RequestMedia(NetworkPacket* pkt);
  166. void handleCommand_ClientReady(NetworkPacket* pkt);
  167. void handleCommand_GotBlocks(NetworkPacket* pkt);
  168. void handleCommand_PlayerPos(NetworkPacket* pkt);
  169. void handleCommand_DeletedBlocks(NetworkPacket* pkt);
  170. void handleCommand_InventoryAction(NetworkPacket* pkt);
  171. void handleCommand_ChatMessage(NetworkPacket* pkt);
  172. void handleCommand_Damage(NetworkPacket* pkt);
  173. void handleCommand_PlayerItem(NetworkPacket* pkt);
  174. void handleCommand_Respawn(NetworkPacket* pkt);
  175. void handleCommand_Interact(NetworkPacket* pkt);
  176. void handleCommand_RemovedSounds(NetworkPacket* pkt);
  177. void handleCommand_NodeMetaFields(NetworkPacket* pkt);
  178. void handleCommand_InventoryFields(NetworkPacket* pkt);
  179. void handleCommand_FirstSrp(NetworkPacket* pkt);
  180. void handleCommand_SrpBytesA(NetworkPacket* pkt);
  181. void handleCommand_SrpBytesM(NetworkPacket* pkt);
  182. void handleCommand_HaveMedia(NetworkPacket *pkt);
  183. void handleCommand_UpdateClientInfo(NetworkPacket *pkt);
  184. void ProcessData(NetworkPacket *pkt);
  185. void Send(NetworkPacket *pkt);
  186. void Send(session_t peer_id, NetworkPacket *pkt);
  187. // Helper for handleCommand_PlayerPos and handleCommand_Interact
  188. void process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
  189. NetworkPacket *pkt);
  190. // Both setter and getter need no envlock,
  191. // can be called freely from threads
  192. void setTimeOfDay(u32 time);
  193. /*
  194. Shall be called with the environment locked.
  195. This is accessed by the map, which is inside the environment,
  196. so it shouldn't be a problem.
  197. */
  198. void onMapEditEvent(const MapEditEvent &event);
  199. // Connection must be locked when called
  200. std::string getStatusString();
  201. inline double getUptime() const { return m_uptime_counter->get(); }
  202. // read shutdown state
  203. inline bool isShutdownRequested() const { return m_shutdown_state.is_requested; }
  204. // request server to shutdown
  205. void requestShutdown(const std::string &msg, bool reconnect, float delay = 0.0f);
  206. // Returns -1 if failed, sound handle on success
  207. // Envlock
  208. s32 playSound(ServerPlayingSound &params, bool ephemeral=false);
  209. void stopSound(s32 handle);
  210. void fadeSound(s32 handle, float step, float gain);
  211. // Stop all sounds attached to given objects, for a certain client
  212. void stopAttachedSounds(session_t peer_id,
  213. const std::vector<u16> &object_ids);
  214. // Envlock
  215. std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
  216. bool checkPriv(const std::string &name, const std::string &priv);
  217. void reportPrivsModified(const std::string &name=""); // ""=all
  218. void reportInventoryFormspecModified(const std::string &name);
  219. void reportFormspecPrependModified(const std::string &name);
  220. void setIpBanned(const std::string &ip, const std::string &name);
  221. void unsetIpBanned(const std::string &ip_or_name);
  222. std::string getBanDescription(const std::string &ip_or_name);
  223. bool denyIfBanned(session_t peer_id);
  224. void notifyPlayer(const char *name, const std::wstring &msg);
  225. void notifyPlayers(const std::wstring &msg);
  226. void spawnParticle(const std::string &playername,
  227. const ParticleParameters &p);
  228. u32 addParticleSpawner(const ParticleSpawnerParameters &p,
  229. ServerActiveObject *attached, const std::string &playername);
  230. void deleteParticleSpawner(const std::string &playername, u32 id);
  231. struct DynamicMediaArgs {
  232. std::string filename;
  233. std::optional<std::string> filepath;
  234. std::optional<std::string_view> data;
  235. u32 token;
  236. std::string to_player;
  237. bool ephemeral = false;
  238. };
  239. bool dynamicAddMedia(const DynamicMediaArgs &args);
  240. ServerInventoryManager *getInventoryMgr() const { return m_inventory_mgr.get(); }
  241. void sendDetachedInventory(Inventory *inventory, const std::string &name, session_t peer_id);
  242. // Envlock and conlock should be locked when using scriptapi
  243. inline ServerScripting *getScriptIface() { return m_script.get(); }
  244. // actions: time-reversed list
  245. // Return value: success/failure
  246. bool rollbackRevertActions(const std::list<RollbackAction> &actions,
  247. std::list<std::string> *log);
  248. // IGameDef interface
  249. // Under envlock
  250. virtual IItemDefManager* getItemDefManager();
  251. virtual const NodeDefManager* getNodeDefManager();
  252. virtual ICraftDefManager* getCraftDefManager();
  253. virtual u16 allocateUnknownNodeId(const std::string &name);
  254. IRollbackManager *getRollbackManager() { return m_rollback; }
  255. virtual EmergeManager *getEmergeManager() { return m_emerge.get(); }
  256. virtual ModStorageDatabase *getModStorageDatabase() { return m_mod_storage_database; }
  257. IWritableItemDefManager* getWritableItemDefManager();
  258. NodeDefManager* getWritableNodeDefManager();
  259. IWritableCraftDefManager* getWritableCraftDefManager();
  260. virtual const std::vector<ModSpec> &getMods() const;
  261. virtual const ModSpec* getModSpec(const std::string &modname) const;
  262. virtual const SubgameSpec* getGameSpec() const { return &m_gamespec; }
  263. static std::string getBuiltinLuaPath();
  264. virtual std::string getWorldPath() const { return m_path_world; }
  265. virtual std::string getModDataPath() const { return m_path_mod_data; }
  266. inline bool isSingleplayer() const
  267. { return m_simple_singleplayer_mode; }
  268. struct StepSettings {
  269. float steplen;
  270. bool pause;
  271. };
  272. void setStepSettings(StepSettings spdata) { m_step_settings.store(spdata); }
  273. StepSettings getStepSettings() { return m_step_settings.load(); }
  274. inline void setAsyncFatalError(const std::string &error)
  275. { m_async_fatal_error.set(error); }
  276. inline void setAsyncFatalError(const LuaError &e)
  277. {
  278. setAsyncFatalError(std::string("Lua: ") + e.what());
  279. }
  280. // Not thread-safe.
  281. void addShutdownError(const ModError &e);
  282. bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
  283. Map & getMap() { return m_env->getMap(); }
  284. ServerEnvironment & getEnv() { return *m_env; }
  285. v3f findSpawnPos();
  286. u32 hudAdd(RemotePlayer *player, HudElement *element);
  287. bool hudRemove(RemotePlayer *player, u32 id);
  288. bool hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *value);
  289. bool hudSetFlags(RemotePlayer *player, u32 flags, u32 mask);
  290. bool hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount);
  291. void hudSetHotbarImage(RemotePlayer *player, const std::string &name);
  292. void hudSetHotbarSelectedImage(RemotePlayer *player, const std::string &name);
  293. Address getPeerAddress(session_t peer_id);
  294. void setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4],
  295. f32 frame_speed);
  296. void setPlayerEyeOffset(RemotePlayer *player, v3f first, v3f third, v3f third_front);
  297. void setSky(RemotePlayer *player, const SkyboxParams &params);
  298. void setSun(RemotePlayer *player, const SunParams &params);
  299. void setMoon(RemotePlayer *player, const MoonParams &params);
  300. void setStars(RemotePlayer *player, const StarParams &params);
  301. void setClouds(RemotePlayer *player, const CloudParams &params);
  302. void overrideDayNightRatio(RemotePlayer *player, bool do_override, float brightness);
  303. void setLighting(RemotePlayer *player, const Lighting &lighting);
  304. void RespawnPlayer(session_t peer_id);
  305. /* con::PeerHandler implementation. */
  306. void peerAdded(con::Peer *peer);
  307. void deletingPeer(con::Peer *peer, bool timeout);
  308. void DenySudoAccess(session_t peer_id);
  309. void DenyAccess(session_t peer_id, AccessDeniedCode reason,
  310. const std::string &custom_reason = "", bool reconnect = false);
  311. void kickAllPlayers(AccessDeniedCode reason,
  312. const std::string &str_reason, bool reconnect);
  313. void acceptAuth(session_t peer_id, bool forSudoMode);
  314. void DisconnectPeer(session_t peer_id);
  315. bool getClientConInfo(session_t peer_id, con::rtt_stat_type type, float *retval);
  316. bool getClientInfo(session_t peer_id, ClientInfo &ret);
  317. const ClientDynamicInfo *getClientDynamicInfo(session_t peer_id);
  318. void printToConsoleOnly(const std::string &text);
  319. void HandlePlayerHPChange(PlayerSAO *sao, const PlayerHPChangeReason &reason);
  320. void SendPlayerHP(PlayerSAO *sao, bool effect);
  321. void SendPlayerBreath(PlayerSAO *sao);
  322. void SendInventory(RemotePlayer *player, bool incremental);
  323. void SendMovePlayer(PlayerSAO *sao);
  324. void SendMovePlayerRel(session_t peer_id, const v3f &added_pos);
  325. void SendPlayerSpeed(session_t peer_id, const v3f &added_vel);
  326. void SendPlayerFov(session_t peer_id);
  327. void SendMinimapModes(session_t peer_id,
  328. std::vector<MinimapMode> &modes,
  329. size_t wanted_mode);
  330. void sendDetachedInventories(session_t peer_id, bool incremental);
  331. bool joinModChannel(const std::string &channel);
  332. bool leaveModChannel(const std::string &channel);
  333. bool sendModChannelMessage(const std::string &channel, const std::string &message);
  334. ModChannel *getModChannel(const std::string &channel);
  335. // Send block to specific player only
  336. bool SendBlock(session_t peer_id, const v3s16 &blockpos);
  337. // Get or load translations for a language
  338. Translations *getTranslationLanguage(const std::string &lang_code);
  339. // Returns all media files the server knows about
  340. // map key = binary sha1, map value = file path
  341. std::unordered_map<std::string, std::string> getMediaList();
  342. static ModStorageDatabase *openModStorageDatabase(const std::string &world_path);
  343. static ModStorageDatabase *openModStorageDatabase(const std::string &backend,
  344. const std::string &world_path, const Settings &world_mt);
  345. static bool migrateModStorageDatabase(const GameParams &game_params,
  346. const Settings &cmd_args);
  347. static u16 getProtocolVersionMin();
  348. static u16 getProtocolVersionMax();
  349. // Lua files registered for init of async env, pair of modname + path
  350. std::vector<std::pair<std::string, std::string>> m_async_init_files;
  351. // Identical but for mapgen env
  352. std::vector<std::pair<std::string, std::string>> m_mapgen_init_files;
  353. // Data transferred into other Lua envs at init time
  354. std::unique_ptr<PackedValue> m_lua_globals_data;
  355. // Bind address
  356. Address m_bind_addr;
  357. // Environment mutex (envlock)
  358. std::mutex m_env_mutex;
  359. protected:
  360. /* Do not add more members here, this is only required to make unit tests work. */
  361. // Scripting
  362. // Envlock and conlock should be locked when using Lua
  363. std::unique_ptr<ServerScripting> m_script;
  364. // Mods
  365. std::unique_ptr<ServerModManager> m_modmgr;
  366. private:
  367. friend class EmergeThread;
  368. friend class RemoteClient;
  369. // unittest classes
  370. friend class TestServerShutdownState;
  371. friend class TestMoveAction;
  372. struct ShutdownState {
  373. friend class TestServerShutdownState;
  374. public:
  375. bool is_requested = false;
  376. bool should_reconnect = false;
  377. std::string message;
  378. void reset();
  379. void trigger(float delay, const std::string &msg, bool reconnect);
  380. void tick(float dtime, Server *server);
  381. std::wstring getShutdownTimerMessage() const;
  382. bool isTimerRunning() const { return m_timer > 0.0f; }
  383. private:
  384. float m_timer = 0.0f;
  385. };
  386. struct PendingDynamicMediaCallback {
  387. std::string filename; // only set if media entry and file is to be deleted
  388. float expiry_timer;
  389. std::unordered_set<session_t> waiting_players;
  390. };
  391. // The standard library does not implement std::hash for pairs so we have this:
  392. struct SBCHash {
  393. size_t operator() (const std::pair<v3s16, u16> &p) const {
  394. return std::hash<v3s16>()(p.first) ^ p.second;
  395. }
  396. };
  397. typedef std::unordered_map<std::pair<v3s16, u16>, std::string, SBCHash> SerializedBlockCache;
  398. void init();
  399. void SendMovement(session_t peer_id);
  400. void SendHP(session_t peer_id, u16 hp, bool effect);
  401. void SendBreath(session_t peer_id, u16 breath);
  402. void SendAccessDenied(session_t peer_id, AccessDeniedCode reason,
  403. const std::string &custom_reason, bool reconnect = false);
  404. void SendDeathscreen(session_t peer_id, bool set_camera_point_target,
  405. v3f camera_point_target);
  406. void SendItemDef(session_t peer_id, IItemDefManager *itemdef, u16 protocol_version);
  407. void SendNodeDef(session_t peer_id, const NodeDefManager *nodedef,
  408. u16 protocol_version);
  409. virtual void SendChatMessage(session_t peer_id, const ChatMessage &message);
  410. void SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed);
  411. void SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4],
  412. f32 animation_speed);
  413. void SendEyeOffset(session_t peer_id, v3f first, v3f third, v3f third_front);
  414. void SendPlayerPrivileges(session_t peer_id);
  415. void SendPlayerInventoryFormspec(session_t peer_id);
  416. void SendPlayerFormspecPrepend(session_t peer_id);
  417. void SendShowFormspecMessage(session_t peer_id, const std::string &formspec,
  418. const std::string &formname);
  419. void SendHUDAdd(session_t peer_id, u32 id, HudElement *form);
  420. void SendHUDRemove(session_t peer_id, u32 id);
  421. void SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value);
  422. void SendHUDSetFlags(session_t peer_id, u32 flags, u32 mask);
  423. void SendHUDSetParam(session_t peer_id, u16 param, std::string_view value);
  424. void SendSetSky(session_t peer_id, const SkyboxParams &params);
  425. void SendSetSun(session_t peer_id, const SunParams &params);
  426. void SendSetMoon(session_t peer_id, const MoonParams &params);
  427. void SendSetStars(session_t peer_id, const StarParams &params);
  428. void SendCloudParams(session_t peer_id, const CloudParams &params);
  429. void SendOverrideDayNightRatio(session_t peer_id, bool do_override, float ratio);
  430. void SendSetLighting(session_t peer_id, const Lighting &lighting);
  431. void broadcastModChannelMessage(const std::string &channel,
  432. const std::string &message, session_t from_peer);
  433. /*
  434. Send a node removal/addition event to all clients except ignore_id.
  435. Additionally, if far_players!=NULL, players further away than
  436. far_d_nodes are ignored and their peer_ids are added to far_players
  437. */
  438. // Envlock and conlock should be locked when calling these
  439. void sendRemoveNode(v3s16 p, std::unordered_set<u16> *far_players = nullptr,
  440. float far_d_nodes = 100);
  441. void sendAddNode(v3s16 p, MapNode n,
  442. std::unordered_set<u16> *far_players = nullptr,
  443. float far_d_nodes = 100, bool remove_metadata = true);
  444. void sendNodeChangePkt(NetworkPacket &pkt, v3s16 block_pos,
  445. v3f p, float far_d_nodes, std::unordered_set<u16> *far_players);
  446. void sendMetadataChanged(const std::unordered_set<v3s16> &positions,
  447. float far_d_nodes = 100);
  448. // Environment and Connection must be locked when called
  449. // `cache` may only be very short lived! (invalidation not handeled)
  450. void SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver,
  451. u16 net_proto_version, SerializedBlockCache *cache = nullptr);
  452. // Sends blocks to clients (locks env and con on its own)
  453. void SendBlocks(float dtime);
  454. bool addMediaFile(const std::string &filename, const std::string &filepath,
  455. std::string *filedata = nullptr, std::string *digest = nullptr);
  456. void fillMediaCache();
  457. void sendMediaAnnouncement(session_t peer_id, const std::string &lang_code);
  458. void sendRequestedMedia(session_t peer_id,
  459. const std::unordered_set<std::string> &tosend);
  460. void stepPendingDynMediaCallbacks(float dtime);
  461. // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all)
  462. void SendAddParticleSpawner(session_t peer_id, u16 protocol_version,
  463. const ParticleSpawnerParameters &p, u16 attached_id, u32 id);
  464. void SendDeleteParticleSpawner(session_t peer_id, u32 id);
  465. // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all)
  466. void SendSpawnParticle(session_t peer_id, u16 protocol_version,
  467. const ParticleParameters &p);
  468. void SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersao);
  469. void SendActiveObjectMessages(session_t peer_id, const std::string &datas,
  470. bool reliable = true);
  471. void SendCSMRestrictionFlags(session_t peer_id);
  472. /*
  473. Something random
  474. */
  475. void HandlePlayerDeath(PlayerSAO* sao, const PlayerHPChangeReason &reason);
  476. void DeleteClient(session_t peer_id, ClientDeletionReason reason);
  477. void UpdateCrafting(RemotePlayer *player);
  478. bool checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what);
  479. void handleChatInterfaceEvent(ChatEvent *evt);
  480. // This returns the answer to the sender of wmessage, or "" if there is none
  481. std::wstring handleChat(const std::string &name, std::wstring wmessage_input,
  482. bool check_shout_priv = false, RemotePlayer *player = nullptr);
  483. void handleAdminChat(const ChatEventChat *evt);
  484. // When called, connection mutex should be locked
  485. RemoteClient* getClient(session_t peer_id, ClientState state_min = CS_Active);
  486. RemoteClient* getClientNoEx(session_t peer_id, ClientState state_min = CS_Active);
  487. // When called, environment mutex should be locked
  488. std::string getPlayerName(session_t peer_id);
  489. PlayerSAO *getPlayerSAO(session_t peer_id);
  490. /*
  491. Get a player from memory or creates one.
  492. If player is already connected, return NULL
  493. Does not verify/modify auth info and password.
  494. Call with env and con locked.
  495. */
  496. PlayerSAO *emergePlayer(const char *name, session_t peer_id, u16 proto_version);
  497. void handlePeerChanges();
  498. /*
  499. Variables
  500. */
  501. // World directory
  502. std::string m_path_world;
  503. std::string m_path_mod_data;
  504. // Subgame specification
  505. SubgameSpec m_gamespec;
  506. // If true, do not allow multiple players and hide some multiplayer
  507. // functionality
  508. bool m_simple_singleplayer_mode;
  509. u16 m_max_chatmessage_length;
  510. // For "dedicated" server list flag
  511. bool m_dedicated;
  512. // Game settings layer
  513. Settings *m_game_settings = nullptr;
  514. // Thread can set; step() will throw as ServerError
  515. MutexedVariable<std::string> m_async_fatal_error;
  516. // Some timers
  517. float m_time_of_day_send_timer = 0.0f;
  518. float m_liquid_transform_timer = 0.0f;
  519. float m_liquid_transform_every = 1.0f;
  520. float m_masterserver_timer = 0.0f;
  521. float m_emergethread_trigger_timer = 0.0f;
  522. float m_savemap_timer = 0.0f;
  523. IntervalLimiter m_map_timer_and_unload_interval;
  524. IntervalLimiter m_max_lag_decrease;
  525. // Environment
  526. ServerEnvironment *m_env = nullptr;
  527. // server connection
  528. std::shared_ptr<con::Connection> m_con;
  529. // Ban checking
  530. BanManager *m_banmanager = nullptr;
  531. // Rollback manager (behind m_env_mutex)
  532. IRollbackManager *m_rollback = nullptr;
  533. // Emerge manager
  534. std::unique_ptr<EmergeManager> m_emerge;
  535. // Item definition manager
  536. IWritableItemDefManager *m_itemdef;
  537. // Node definition manager
  538. NodeDefManager *m_nodedef;
  539. // Craft definition manager
  540. IWritableCraftDefManager *m_craftdef;
  541. std::unordered_map<std::string, Translations> server_translations;
  542. /*
  543. Threads
  544. */
  545. // Set by Game
  546. std::atomic<StepSettings> m_step_settings{{0.1f, false}};
  547. // The server mainly operates in this thread
  548. ServerThread *m_thread = nullptr;
  549. /*
  550. Client interface
  551. */
  552. ClientInterface m_clients;
  553. /*
  554. Peer change queue.
  555. Queues stuff from peerAdded() and deletingPeer() to
  556. handlePeerChanges()
  557. */
  558. std::queue<con::PeerChange> m_peer_change_queue;
  559. std::unordered_map<session_t, std::string> m_formspec_state_data;
  560. /*
  561. Random stuff
  562. */
  563. ShutdownState m_shutdown_state;
  564. ChatInterface *m_admin_chat;
  565. std::string m_admin_nick;
  566. // If a mod error occurs while shutting down, the error message will be
  567. // written into this.
  568. std::string *const m_shutdown_errmsg;
  569. /*
  570. Map edit event queue. Automatically receives all map edits.
  571. The constructor of this class registers us to receive them through
  572. onMapEditEvent
  573. NOTE: Should these be moved to actually be members of
  574. ServerEnvironment?
  575. */
  576. /*
  577. Queue of map edits from the environment for sending to the clients
  578. This is behind m_env_mutex
  579. */
  580. std::queue<MapEditEvent*> m_unsent_map_edit_queue;
  581. /*
  582. If a non-empty area, map edit events contained within are left
  583. unsent. Done at map generation time to speed up editing of the
  584. generated area, as it will be sent anyway.
  585. This is behind m_env_mutex
  586. */
  587. VoxelArea m_ignore_map_edit_events_area;
  588. // media files known to server
  589. std::unordered_map<std::string, MediaInfo> m_media;
  590. // pending dynamic media callbacks, clients inform the server when they have a file fetched
  591. std::unordered_map<u32, PendingDynamicMediaCallback> m_pending_dyn_media;
  592. float m_step_pending_dyn_media_timer = 0.0f;
  593. /*
  594. Sounds
  595. */
  596. std::unordered_map<s32, ServerPlayingSound> m_playing_sounds;
  597. s32 m_playing_sounds_id_last_used = 0; // positive values only
  598. s32 nextSoundId();
  599. ModStorageDatabase *m_mod_storage_database = nullptr;
  600. float m_mod_storage_save_timer = 10.0f;
  601. // CSM restrictions byteflag
  602. u64 m_csm_restriction_flags = CSMRestrictionFlags::CSM_RF_NONE;
  603. u32 m_csm_restriction_noderange = 8;
  604. // ModChannel manager
  605. std::unique_ptr<ModChannelMgr> m_modchannel_mgr;
  606. // Inventory manager
  607. std::unique_ptr<ServerInventoryManager> m_inventory_mgr;
  608. // Global server metrics backend
  609. std::unique_ptr<MetricsBackend> m_metrics_backend;
  610. // Server metrics
  611. MetricCounterPtr m_uptime_counter;
  612. MetricGaugePtr m_player_gauge;
  613. MetricGaugePtr m_timeofday_gauge;
  614. MetricGaugePtr m_lag_gauge;
  615. MetricCounterPtr m_aom_buffer_counter[2]; // [0] = rel, [1] = unrel
  616. MetricCounterPtr m_packet_recv_counter;
  617. MetricCounterPtr m_packet_recv_processed_counter;
  618. MetricCounterPtr m_map_edit_event_counter;
  619. };
  620. /*
  621. Runs a simple dedicated server loop.
  622. Shuts down when kill is set to true.
  623. */
  624. void dedicated_server_loop(Server &server, bool &kill);