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