server.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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. // Envlock
  212. std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
  213. bool checkPriv(const std::string &name, const std::string &priv);
  214. void reportPrivsModified(const std::string &name=""); // ""=all
  215. void reportInventoryFormspecModified(const std::string &name);
  216. void reportFormspecPrependModified(const std::string &name);
  217. void setIpBanned(const std::string &ip, const std::string &name);
  218. void unsetIpBanned(const std::string &ip_or_name);
  219. std::string getBanDescription(const std::string &ip_or_name);
  220. bool denyIfBanned(session_t peer_id);
  221. void notifyPlayer(const char *name, const std::wstring &msg);
  222. void notifyPlayers(const std::wstring &msg);
  223. void spawnParticle(const std::string &playername,
  224. const ParticleParameters &p);
  225. u32 addParticleSpawner(const ParticleSpawnerParameters &p,
  226. ServerActiveObject *attached, const std::string &playername);
  227. void deleteParticleSpawner(const std::string &playername, u32 id);
  228. struct DynamicMediaArgs {
  229. std::string filename;
  230. std::optional<std::string> filepath;
  231. std::optional<std::string_view> data;
  232. u32 token;
  233. std::string to_player;
  234. bool ephemeral = false;
  235. };
  236. bool dynamicAddMedia(const DynamicMediaArgs &args);
  237. ServerInventoryManager *getInventoryMgr() const { return m_inventory_mgr.get(); }
  238. void sendDetachedInventory(Inventory *inventory, const std::string &name, session_t peer_id);
  239. // Envlock and conlock should be locked when using scriptapi
  240. ServerScripting *getScriptIface(){ return m_script; }
  241. // actions: time-reversed list
  242. // Return value: success/failure
  243. bool rollbackRevertActions(const std::list<RollbackAction> &actions,
  244. std::list<std::string> *log);
  245. // IGameDef interface
  246. // Under envlock
  247. virtual IItemDefManager* getItemDefManager();
  248. virtual const NodeDefManager* getNodeDefManager();
  249. virtual ICraftDefManager* getCraftDefManager();
  250. virtual u16 allocateUnknownNodeId(const std::string &name);
  251. IRollbackManager *getRollbackManager() { return m_rollback; }
  252. virtual EmergeManager *getEmergeManager() { return m_emerge; }
  253. virtual ModStorageDatabase *getModStorageDatabase() { return m_mod_storage_database; }
  254. IWritableItemDefManager* getWritableItemDefManager();
  255. NodeDefManager* getWritableNodeDefManager();
  256. IWritableCraftDefManager* getWritableCraftDefManager();
  257. virtual const std::vector<ModSpec> &getMods() const;
  258. virtual const ModSpec* getModSpec(const std::string &modname) const;
  259. virtual const SubgameSpec* getGameSpec() const { return &m_gamespec; }
  260. static std::string getBuiltinLuaPath();
  261. virtual std::string getWorldPath() const { return m_path_world; }
  262. inline bool isSingleplayer() const
  263. { return m_simple_singleplayer_mode; }
  264. struct StepSettings {
  265. float steplen;
  266. bool pause;
  267. };
  268. void setStepSettings(StepSettings spdata) { m_step_settings.store(spdata); }
  269. StepSettings getStepSettings() { return m_step_settings.load(); }
  270. inline void setAsyncFatalError(const std::string &error)
  271. { m_async_fatal_error.set(error); }
  272. inline void setAsyncFatalError(const LuaError &e)
  273. {
  274. setAsyncFatalError(std::string("Lua: ") + e.what());
  275. }
  276. // Not thread-safe.
  277. void addShutdownError(const ModError &e);
  278. bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
  279. Map & getMap() { return m_env->getMap(); }
  280. ServerEnvironment & getEnv() { return *m_env; }
  281. v3f findSpawnPos();
  282. u32 hudAdd(RemotePlayer *player, HudElement *element);
  283. bool hudRemove(RemotePlayer *player, u32 id);
  284. bool hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *value);
  285. bool hudSetFlags(RemotePlayer *player, u32 flags, u32 mask);
  286. bool hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount);
  287. void hudSetHotbarImage(RemotePlayer *player, const std::string &name);
  288. void hudSetHotbarSelectedImage(RemotePlayer *player, const std::string &name);
  289. Address getPeerAddress(session_t peer_id);
  290. void setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4],
  291. f32 frame_speed);
  292. void setPlayerEyeOffset(RemotePlayer *player, const v3f &first, const v3f &third, const v3f &third_front);
  293. void setSky(RemotePlayer *player, const SkyboxParams &params);
  294. void setSun(RemotePlayer *player, const SunParams &params);
  295. void setMoon(RemotePlayer *player, const MoonParams &params);
  296. void setStars(RemotePlayer *player, const StarParams &params);
  297. void setClouds(RemotePlayer *player, const CloudParams &params);
  298. void overrideDayNightRatio(RemotePlayer *player, bool do_override, float brightness);
  299. void setLighting(RemotePlayer *player, const Lighting &lighting);
  300. void RespawnPlayer(session_t peer_id);
  301. /* con::PeerHandler implementation. */
  302. void peerAdded(con::Peer *peer);
  303. void deletingPeer(con::Peer *peer, bool timeout);
  304. void DenySudoAccess(session_t peer_id);
  305. void DenyAccess(session_t peer_id, AccessDeniedCode reason,
  306. const std::string &custom_reason = "", bool reconnect = false);
  307. void kickAllPlayers(AccessDeniedCode reason,
  308. const std::string &str_reason, bool reconnect);
  309. void acceptAuth(session_t peer_id, bool forSudoMode);
  310. void DisconnectPeer(session_t peer_id);
  311. bool getClientConInfo(session_t peer_id, con::rtt_stat_type type, float *retval);
  312. bool getClientInfo(session_t peer_id, ClientInfo &ret);
  313. const ClientDynamicInfo *getClientDynamicInfo(session_t peer_id);
  314. void printToConsoleOnly(const std::string &text);
  315. void HandlePlayerHPChange(PlayerSAO *sao, const PlayerHPChangeReason &reason);
  316. void SendPlayerHP(PlayerSAO *sao, bool effect);
  317. void SendPlayerBreath(PlayerSAO *sao);
  318. void SendInventory(RemotePlayer *player, bool incremental);
  319. void SendMovePlayer(PlayerSAO *sao);
  320. void SendMovePlayerRel(session_t peer_id, const v3f &added_pos);
  321. void SendPlayerSpeed(session_t peer_id, const v3f &added_vel);
  322. void SendPlayerFov(session_t peer_id);
  323. void SendMinimapModes(session_t peer_id,
  324. std::vector<MinimapMode> &modes,
  325. size_t wanted_mode);
  326. void sendDetachedInventories(session_t peer_id, bool incremental);
  327. bool joinModChannel(const std::string &channel);
  328. bool leaveModChannel(const std::string &channel);
  329. bool sendModChannelMessage(const std::string &channel, const std::string &message);
  330. ModChannel *getModChannel(const std::string &channel);
  331. // Send block to specific player only
  332. bool SendBlock(session_t peer_id, const v3s16 &blockpos);
  333. // Get or load translations for a language
  334. Translations *getTranslationLanguage(const std::string &lang_code);
  335. // Returns all media files the server knows about
  336. // map key = binary sha1, map value = file path
  337. std::unordered_map<std::string, std::string> getMediaList();
  338. static ModStorageDatabase *openModStorageDatabase(const std::string &world_path);
  339. static ModStorageDatabase *openModStorageDatabase(const std::string &backend,
  340. const std::string &world_path, const Settings &world_mt);
  341. static bool migrateModStorageDatabase(const GameParams &game_params,
  342. const Settings &cmd_args);
  343. static u16 getProtocolVersionMin();
  344. static u16 getProtocolVersionMax();
  345. // Lua files registered for init of async env, pair of modname + path
  346. std::vector<std::pair<std::string, std::string>> m_async_init_files;
  347. // Identical but for mapgen env
  348. std::vector<std::pair<std::string, std::string>> m_mapgen_init_files;
  349. // Data transferred into other Lua envs at init time
  350. std::unique_ptr<PackedValue> m_lua_globals_data;
  351. // Bind address
  352. Address m_bind_addr;
  353. // Environment mutex (envlock)
  354. std::mutex m_env_mutex;
  355. private:
  356. friend class EmergeThread;
  357. friend class RemoteClient;
  358. friend class TestServerShutdownState;
  359. struct ShutdownState {
  360. friend class TestServerShutdownState;
  361. public:
  362. bool is_requested = false;
  363. bool should_reconnect = false;
  364. std::string message;
  365. void reset();
  366. void trigger(float delay, const std::string &msg, bool reconnect);
  367. void tick(float dtime, Server *server);
  368. std::wstring getShutdownTimerMessage() const;
  369. bool isTimerRunning() const { return m_timer > 0.0f; }
  370. private:
  371. float m_timer = 0.0f;
  372. };
  373. struct PendingDynamicMediaCallback {
  374. std::string filename; // only set if media entry and file is to be deleted
  375. float expiry_timer;
  376. std::unordered_set<session_t> waiting_players;
  377. };
  378. // The standard library does not implement std::hash for pairs so we have this:
  379. struct SBCHash {
  380. size_t operator() (const std::pair<v3s16, u16> &p) const {
  381. return std::hash<v3s16>()(p.first) ^ p.second;
  382. }
  383. };
  384. typedef std::unordered_map<std::pair<v3s16, u16>, std::string, SBCHash> SerializedBlockCache;
  385. void init();
  386. void SendMovement(session_t peer_id);
  387. void SendHP(session_t peer_id, u16 hp, bool effect);
  388. void SendBreath(session_t peer_id, u16 breath);
  389. void SendAccessDenied(session_t peer_id, AccessDeniedCode reason,
  390. const std::string &custom_reason, bool reconnect = false);
  391. void SendAccessDenied_Legacy(session_t peer_id, const std::wstring &reason);
  392. void SendDeathscreen(session_t peer_id, bool set_camera_point_target,
  393. v3f camera_point_target);
  394. void SendItemDef(session_t peer_id, IItemDefManager *itemdef, u16 protocol_version);
  395. void SendNodeDef(session_t peer_id, const NodeDefManager *nodedef,
  396. u16 protocol_version);
  397. virtual void SendChatMessage(session_t peer_id, const ChatMessage &message);
  398. void SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed);
  399. void SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4],
  400. f32 animation_speed);
  401. void SendEyeOffset(session_t peer_id, v3f first, v3f third, v3f third_front);
  402. void SendPlayerPrivileges(session_t peer_id);
  403. void SendPlayerInventoryFormspec(session_t peer_id);
  404. void SendPlayerFormspecPrepend(session_t peer_id);
  405. void SendShowFormspecMessage(session_t peer_id, const std::string &formspec,
  406. const std::string &formname);
  407. void SendHUDAdd(session_t peer_id, u32 id, HudElement *form);
  408. void SendHUDRemove(session_t peer_id, u32 id);
  409. void SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value);
  410. void SendHUDSetFlags(session_t peer_id, u32 flags, u32 mask);
  411. void SendHUDSetParam(session_t peer_id, u16 param, const std::string &value);
  412. void SendSetSky(session_t peer_id, const SkyboxParams &params);
  413. void SendSetSun(session_t peer_id, const SunParams &params);
  414. void SendSetMoon(session_t peer_id, const MoonParams &params);
  415. void SendSetStars(session_t peer_id, const StarParams &params);
  416. void SendCloudParams(session_t peer_id, const CloudParams &params);
  417. void SendOverrideDayNightRatio(session_t peer_id, bool do_override, float ratio);
  418. void SendSetLighting(session_t peer_id, const Lighting &lighting);
  419. void broadcastModChannelMessage(const std::string &channel,
  420. const std::string &message, session_t from_peer);
  421. /*
  422. Send a node removal/addition event to all clients except ignore_id.
  423. Additionally, if far_players!=NULL, players further away than
  424. far_d_nodes are ignored and their peer_ids are added to far_players
  425. */
  426. // Envlock and conlock should be locked when calling these
  427. void sendRemoveNode(v3s16 p, std::unordered_set<u16> *far_players = nullptr,
  428. float far_d_nodes = 100);
  429. void sendAddNode(v3s16 p, MapNode n,
  430. std::unordered_set<u16> *far_players = nullptr,
  431. float far_d_nodes = 100, bool remove_metadata = true);
  432. void sendNodeChangePkt(NetworkPacket &pkt, v3s16 block_pos,
  433. v3f p, float far_d_nodes, std::unordered_set<u16> *far_players);
  434. void sendMetadataChanged(const std::unordered_set<v3s16> &positions,
  435. float far_d_nodes = 100);
  436. // Environment and Connection must be locked when called
  437. // `cache` may only be very short lived! (invalidation not handeled)
  438. void SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver,
  439. u16 net_proto_version, SerializedBlockCache *cache = nullptr);
  440. // Sends blocks to clients (locks env and con on its own)
  441. void SendBlocks(float dtime);
  442. bool addMediaFile(const std::string &filename, const std::string &filepath,
  443. std::string *filedata = nullptr, std::string *digest = nullptr);
  444. void fillMediaCache();
  445. void sendMediaAnnouncement(session_t peer_id, const std::string &lang_code);
  446. void sendRequestedMedia(session_t peer_id,
  447. const std::unordered_set<std::string> &tosend);
  448. void stepPendingDynMediaCallbacks(float dtime);
  449. // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all)
  450. void SendAddParticleSpawner(session_t peer_id, u16 protocol_version,
  451. const ParticleSpawnerParameters &p, u16 attached_id, u32 id);
  452. void SendDeleteParticleSpawner(session_t peer_id, u32 id);
  453. // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all)
  454. void SendSpawnParticle(session_t peer_id, u16 protocol_version,
  455. const ParticleParameters &p);
  456. void SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersao);
  457. void SendActiveObjectMessages(session_t peer_id, const std::string &datas,
  458. bool reliable = true);
  459. void SendCSMRestrictionFlags(session_t peer_id);
  460. /*
  461. Something random
  462. */
  463. void HandlePlayerDeath(PlayerSAO* sao, const PlayerHPChangeReason &reason);
  464. void DeleteClient(session_t peer_id, ClientDeletionReason reason);
  465. void UpdateCrafting(RemotePlayer *player);
  466. bool checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what);
  467. void handleChatInterfaceEvent(ChatEvent *evt);
  468. // This returns the answer to the sender of wmessage, or "" if there is none
  469. std::wstring handleChat(const std::string &name, std::wstring wmessage_input,
  470. bool check_shout_priv = false, RemotePlayer *player = nullptr);
  471. void handleAdminChat(const ChatEventChat *evt);
  472. // When called, connection mutex should be locked
  473. RemoteClient* getClient(session_t peer_id, ClientState state_min = CS_Active);
  474. RemoteClient* getClientNoEx(session_t peer_id, ClientState state_min = CS_Active);
  475. // When called, environment mutex should be locked
  476. std::string getPlayerName(session_t peer_id);
  477. PlayerSAO *getPlayerSAO(session_t peer_id);
  478. /*
  479. Get a player from memory or creates one.
  480. If player is already connected, return NULL
  481. Does not verify/modify auth info and password.
  482. Call with env and con locked.
  483. */
  484. PlayerSAO *emergePlayer(const char *name, session_t peer_id, u16 proto_version);
  485. void handlePeerChanges();
  486. /*
  487. Variables
  488. */
  489. // World directory
  490. std::string m_path_world;
  491. // Subgame specification
  492. SubgameSpec m_gamespec;
  493. // If true, do not allow multiple players and hide some multiplayer
  494. // functionality
  495. bool m_simple_singleplayer_mode;
  496. u16 m_max_chatmessage_length;
  497. // For "dedicated" server list flag
  498. bool m_dedicated;
  499. Settings *m_game_settings = nullptr;
  500. // Thread can set; step() will throw as ServerError
  501. MutexedVariable<std::string> m_async_fatal_error;
  502. // Some timers
  503. float m_liquid_transform_timer = 0.0f;
  504. float m_liquid_transform_every = 1.0f;
  505. float m_masterserver_timer = 0.0f;
  506. float m_emergethread_trigger_timer = 0.0f;
  507. float m_savemap_timer = 0.0f;
  508. IntervalLimiter m_map_timer_and_unload_interval;
  509. // Environment
  510. ServerEnvironment *m_env = nullptr;
  511. // Reference to the server map until ServerEnvironment is initialized
  512. // after that this variable must be a nullptr
  513. ServerMap *m_startup_server_map = nullptr;
  514. // server connection
  515. std::shared_ptr<con::Connection> m_con;
  516. // Ban checking
  517. BanManager *m_banmanager = nullptr;
  518. // Rollback manager (behind m_env_mutex)
  519. IRollbackManager *m_rollback = nullptr;
  520. // Emerge manager
  521. EmergeManager *m_emerge = nullptr;
  522. // Scripting
  523. // Envlock and conlock should be locked when using Lua
  524. ServerScripting *m_script = nullptr;
  525. // Item definition manager
  526. IWritableItemDefManager *m_itemdef;
  527. // Node definition manager
  528. NodeDefManager *m_nodedef;
  529. // Craft definition manager
  530. IWritableCraftDefManager *m_craftdef;
  531. // Mods
  532. std::unique_ptr<ServerModManager> m_modmgr;
  533. std::unordered_map<std::string, Translations> server_translations;
  534. /*
  535. Threads
  536. */
  537. // Set by Game
  538. std::atomic<StepSettings> m_step_settings{{0.1f, false}};
  539. // The server mainly operates in this thread
  540. ServerThread *m_thread = nullptr;
  541. /*
  542. Time related stuff
  543. */
  544. // Timer for sending time of day over network
  545. float m_time_of_day_send_timer = 0.0f;
  546. /*
  547. Client interface
  548. */
  549. ClientInterface m_clients;
  550. /*
  551. Peer change queue.
  552. Queues stuff from peerAdded() and deletingPeer() to
  553. handlePeerChanges()
  554. */
  555. std::queue<con::PeerChange> m_peer_change_queue;
  556. std::unordered_map<session_t, std::string> m_formspec_state_data;
  557. /*
  558. Random stuff
  559. */
  560. ShutdownState m_shutdown_state;
  561. ChatInterface *m_admin_chat;
  562. std::string m_admin_nick;
  563. // If a mod error occurs while shutting down, the error message will be
  564. // written into this.
  565. std::string *const m_shutdown_errmsg;
  566. /*
  567. Map edit event queue. Automatically receives all map edits.
  568. The constructor of this class registers us to receive them through
  569. onMapEditEvent
  570. NOTE: Should these be moved to actually be members of
  571. ServerEnvironment?
  572. */
  573. /*
  574. Queue of map edits from the environment for sending to the clients
  575. This is behind m_env_mutex
  576. */
  577. std::queue<MapEditEvent*> m_unsent_map_edit_queue;
  578. /*
  579. If a non-empty area, map edit events contained within are left
  580. unsent. Done at map generation time to speed up editing of the
  581. generated area, as it will be sent anyway.
  582. This is behind m_env_mutex
  583. */
  584. VoxelArea m_ignore_map_edit_events_area;
  585. // media files known to server
  586. std::unordered_map<std::string, MediaInfo> m_media;
  587. // pending dynamic media callbacks, clients inform the server when they have a file fetched
  588. std::unordered_map<u32, PendingDynamicMediaCallback> m_pending_dyn_media;
  589. float m_step_pending_dyn_media_timer = 0.0f;
  590. /*
  591. Sounds
  592. */
  593. std::unordered_map<s32, ServerPlayingSound> m_playing_sounds;
  594. s32 m_playing_sounds_id_last_used = 0; // positive values only
  595. s32 nextSoundId();
  596. ModStorageDatabase *m_mod_storage_database = nullptr;
  597. float m_mod_storage_save_timer = 10.0f;
  598. // CSM restrictions byteflag
  599. u64 m_csm_restriction_flags = CSMRestrictionFlags::CSM_RF_NONE;
  600. u32 m_csm_restriction_noderange = 8;
  601. // ModChannel manager
  602. std::unique_ptr<ModChannelMgr> m_modchannel_mgr;
  603. // Inventory manager
  604. std::unique_ptr<ServerInventoryManager> m_inventory_mgr;
  605. // Global server metrics backend
  606. std::unique_ptr<MetricsBackend> m_metrics_backend;
  607. // Server metrics
  608. MetricCounterPtr m_uptime_counter;
  609. MetricGaugePtr m_player_gauge;
  610. MetricGaugePtr m_timeofday_gauge;
  611. MetricGaugePtr m_lag_gauge;
  612. MetricCounterPtr m_aom_buffer_counter[2]; // [0] = rel, [1] = unrel
  613. MetricCounterPtr m_packet_recv_counter;
  614. MetricCounterPtr m_packet_recv_processed_counter;
  615. MetricCounterPtr m_map_edit_event_counter;
  616. };
  617. /*
  618. Runs a simple dedicated server loop.
  619. Shuts down when kill is set to true.
  620. */
  621. void dedicated_server_loop(Server &server, bool &kill);