server.h 24 KB

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