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