3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
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"
46 #include <unordered_set>
51 class IWritableItemDefManager;
53 class IWritableCraftDefManager;
60 struct PlayerHPChangeReason;
61 class IRollbackManager;
62 struct RollbackAction;
64 class ServerScripting;
65 class ServerEnvironment;
66 struct SimpleSoundSpec;
74 class ServerModManager;
75 class ServerInventoryManager;
77 enum ClientDeletionReason {
86 std::string sha1_digest; // base64-encoded
87 bool no_announce; // true: not announced in TOCLIENT_ANNOUNCE_MEDIA (at player join)
89 MediaInfo(const std::string &path_="",
90 const std::string &sha1_digest_=""):
92 sha1_digest(sha1_digest_),
98 struct ServerSoundParams
109 float max_hear_distance = 32 * BS;
112 std::string to_player = "";
113 std::string exclude_player = "";
115 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
118 struct ServerPlayingSound
120 ServerSoundParams params;
121 SimpleSoundSpec spec;
122 std::unordered_set<session_t> clients; // peer ids
126 MinimapType type = MINIMAP_TYPE_OFF;
133 // structure for everything getClientInfo returns, for convenience
140 u8 major, minor, patch;
141 std::string vers_string, lang_code;
144 class Server : public con::PeerHandler, public MapEventReceiver,
149 NOTE: Every public method should be thread-safe
153 const std::string &path_world,
154 const SubgameSpec &gamespec,
155 bool simple_singleplayer_mode,
158 ChatInterface *iface = nullptr,
159 std::string *on_shutdown_errmsg = nullptr
162 DISABLE_CLASS_COPY(Server);
166 // This is mainly a way to pass the time to the server.
167 // Actual processing is done in an another thread.
168 void step(float dtime);
169 // This is run by ServerThread and does the actual processing
170 void AsyncRunStep(bool initial_step=false);
172 PlayerSAO* StageTwoClientInit(session_t peer_id);
178 void handleCommand(NetworkPacket* pkt);
180 void handleCommand_Null(NetworkPacket* pkt) {};
181 void handleCommand_Deprecated(NetworkPacket* pkt);
182 void handleCommand_Init(NetworkPacket* pkt);
183 void handleCommand_Init2(NetworkPacket* pkt);
184 void handleCommand_ModChannelJoin(NetworkPacket *pkt);
185 void handleCommand_ModChannelLeave(NetworkPacket *pkt);
186 void handleCommand_ModChannelMsg(NetworkPacket *pkt);
187 void handleCommand_RequestMedia(NetworkPacket* pkt);
188 void handleCommand_ClientReady(NetworkPacket* pkt);
189 void handleCommand_GotBlocks(NetworkPacket* pkt);
190 void handleCommand_PlayerPos(NetworkPacket* pkt);
191 void handleCommand_DeletedBlocks(NetworkPacket* pkt);
192 void handleCommand_InventoryAction(NetworkPacket* pkt);
193 void handleCommand_ChatMessage(NetworkPacket* pkt);
194 void handleCommand_Damage(NetworkPacket* pkt);
195 void handleCommand_PlayerItem(NetworkPacket* pkt);
196 void handleCommand_Respawn(NetworkPacket* pkt);
197 void handleCommand_Interact(NetworkPacket* pkt);
198 void handleCommand_RemovedSounds(NetworkPacket* pkt);
199 void handleCommand_NodeMetaFields(NetworkPacket* pkt);
200 void handleCommand_InventoryFields(NetworkPacket* pkt);
201 void handleCommand_FirstSrp(NetworkPacket* pkt);
202 void handleCommand_SrpBytesA(NetworkPacket* pkt);
203 void handleCommand_SrpBytesM(NetworkPacket* pkt);
204 void handleCommand_HaveMedia(NetworkPacket *pkt);
206 void ProcessData(NetworkPacket *pkt);
208 void Send(NetworkPacket *pkt);
209 void Send(session_t peer_id, NetworkPacket *pkt);
211 // Helper for handleCommand_PlayerPos and handleCommand_Interact
212 void process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
215 // Both setter and getter need no envlock,
216 // can be called freely from threads
217 void setTimeOfDay(u32 time);
220 Shall be called with the environment locked.
221 This is accessed by the map, which is inside the environment,
222 so it shouldn't be a problem.
224 void onMapEditEvent(const MapEditEvent &event);
226 // Connection must be locked when called
227 std::string getStatusString();
228 inline double getUptime() const { return m_uptime_counter->get(); }
230 // read shutdown state
231 inline bool isShutdownRequested() const { return m_shutdown_state.is_requested; }
233 // request server to shutdown
234 void requestShutdown(const std::string &msg, bool reconnect, float delay = 0.0f);
236 // Returns -1 if failed, sound handle on success
238 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms,
239 bool ephemeral=false);
240 void stopSound(s32 handle);
241 void fadeSound(s32 handle, float step, float gain);
244 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
245 bool checkPriv(const std::string &name, const std::string &priv);
246 void reportPrivsModified(const std::string &name=""); // ""=all
247 void reportInventoryFormspecModified(const std::string &name);
248 void reportFormspecPrependModified(const std::string &name);
250 void setIpBanned(const std::string &ip, const std::string &name);
251 void unsetIpBanned(const std::string &ip_or_name);
252 std::string getBanDescription(const std::string &ip_or_name);
254 void notifyPlayer(const char *name, const std::wstring &msg);
255 void notifyPlayers(const std::wstring &msg);
257 void spawnParticle(const std::string &playername,
258 const ParticleParameters &p);
260 u32 addParticleSpawner(const ParticleSpawnerParameters &p,
261 ServerActiveObject *attached, const std::string &playername);
263 void deleteParticleSpawner(const std::string &playername, u32 id);
265 bool dynamicAddMedia(std::string filepath, u32 token,
266 const std::string &to_player, bool ephemeral);
268 ServerInventoryManager *getInventoryMgr() const { return m_inventory_mgr.get(); }
269 void sendDetachedInventory(Inventory *inventory, const std::string &name, session_t peer_id);
271 // Envlock and conlock should be locked when using scriptapi
272 ServerScripting *getScriptIface(){ return m_script; }
274 // actions: time-reversed list
275 // Return value: success/failure
276 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
277 std::list<std::string> *log);
279 // IGameDef interface
281 virtual IItemDefManager* getItemDefManager();
282 virtual const NodeDefManager* getNodeDefManager();
283 virtual ICraftDefManager* getCraftDefManager();
284 virtual u16 allocateUnknownNodeId(const std::string &name);
285 IRollbackManager *getRollbackManager() { return m_rollback; }
286 virtual EmergeManager *getEmergeManager() { return m_emerge; }
287 virtual ModMetadataDatabase *getModStorageDatabase() { return m_mod_storage_database; }
289 IWritableItemDefManager* getWritableItemDefManager();
290 NodeDefManager* getWritableNodeDefManager();
291 IWritableCraftDefManager* getWritableCraftDefManager();
293 virtual const std::vector<ModSpec> &getMods() const;
294 virtual const ModSpec* getModSpec(const std::string &modname) const;
295 static std::string getBuiltinLuaPath();
296 virtual std::string getWorldPath() const { return m_path_world; }
298 inline bool isSingleplayer() const
299 { return m_simple_singleplayer_mode; }
301 inline void setAsyncFatalError(const std::string &error)
302 { m_async_fatal_error.set(error); }
303 inline void setAsyncFatalError(const LuaError &e)
305 setAsyncFatalError(std::string("Lua: ") + e.what());
308 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
309 Map & getMap() { return m_env->getMap(); }
310 ServerEnvironment & getEnv() { return *m_env; }
313 u32 hudAdd(RemotePlayer *player, HudElement *element);
314 bool hudRemove(RemotePlayer *player, u32 id);
315 bool hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *value);
316 bool hudSetFlags(RemotePlayer *player, u32 flags, u32 mask);
317 bool hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount);
318 void hudSetHotbarImage(RemotePlayer *player, const std::string &name);
319 void hudSetHotbarSelectedImage(RemotePlayer *player, const std::string &name);
321 Address getPeerAddress(session_t peer_id);
323 void setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4],
325 void setPlayerEyeOffset(RemotePlayer *player, const v3f &first, const v3f &third);
327 void setSky(RemotePlayer *player, const SkyboxParams ¶ms);
328 void setSun(RemotePlayer *player, const SunParams ¶ms);
329 void setMoon(RemotePlayer *player, const MoonParams ¶ms);
330 void setStars(RemotePlayer *player, const StarParams ¶ms);
332 void setClouds(RemotePlayer *player, const CloudParams ¶ms);
334 void overrideDayNightRatio(RemotePlayer *player, bool do_override, float brightness);
336 void setLighting(RemotePlayer *player, const Lighting &lighting);
338 /* con::PeerHandler implementation. */
339 void peerAdded(con::Peer *peer);
340 void deletingPeer(con::Peer *peer, bool timeout);
342 void DenySudoAccess(session_t peer_id);
343 void DenyAccess(session_t peer_id, AccessDeniedCode reason,
344 const std::string &custom_reason = "", bool reconnect = false);
345 void acceptAuth(session_t peer_id, bool forSudoMode);
346 void DisconnectPeer(session_t peer_id);
347 bool getClientConInfo(session_t peer_id, con::rtt_stat_type type, float *retval);
348 bool getClientInfo(session_t peer_id, ClientInfo &ret);
350 void printToConsoleOnly(const std::string &text);
352 void HandlePlayerHPChange(PlayerSAO *sao, const PlayerHPChangeReason &reason);
353 void SendPlayerHP(PlayerSAO *sao);
354 void SendPlayerBreath(PlayerSAO *sao);
355 void SendInventory(PlayerSAO *playerSAO, bool incremental);
356 void SendMovePlayer(session_t peer_id);
357 void SendPlayerSpeed(session_t peer_id, const v3f &added_vel);
358 void SendPlayerFov(session_t peer_id);
360 void SendMinimapModes(session_t peer_id,
361 std::vector<MinimapMode> &modes,
364 void sendDetachedInventories(session_t peer_id, bool incremental);
366 virtual bool registerModStorage(ModMetadata *storage);
367 virtual void unregisterModStorage(const std::string &name);
369 bool joinModChannel(const std::string &channel);
370 bool leaveModChannel(const std::string &channel);
371 bool sendModChannelMessage(const std::string &channel, const std::string &message);
372 ModChannel *getModChannel(const std::string &channel);
374 // Send block to specific player only
375 bool SendBlock(session_t peer_id, const v3s16 &blockpos);
377 // Get or load translations for a language
378 Translations *getTranslationLanguage(const std::string &lang_code);
380 static ModMetadataDatabase *openModStorageDatabase(const std::string &world_path);
382 static ModMetadataDatabase *openModStorageDatabase(const std::string &backend,
383 const std::string &world_path, const Settings &world_mt);
385 static bool migrateModStorageDatabase(const GameParams &game_params,
386 const Settings &cmd_args);
388 // Lua files registered for init of async env, pair of modname + path
389 std::vector<std::pair<std::string, std::string>> m_async_init_files;
391 // Serialized data transferred into async envs at init time
392 MutexedVariable<std::string> m_async_globals_data;
397 // Environment mutex (envlock)
398 std::mutex m_env_mutex;
401 friend class EmergeThread;
402 friend class RemoteClient;
403 friend class TestServerShutdownState;
405 struct ShutdownState {
406 friend class TestServerShutdownState;
408 bool is_requested = false;
409 bool should_reconnect = false;
413 void trigger(float delay, const std::string &msg, bool reconnect);
414 void tick(float dtime, Server *server);
415 std::wstring getShutdownTimerMessage() const;
416 bool isTimerRunning() const { return m_timer > 0.0f; }
418 float m_timer = 0.0f;
421 struct PendingDynamicMediaCallback {
422 std::string filename; // only set if media entry and file is to be deleted
424 std::unordered_set<session_t> waiting_players;
429 void SendMovement(session_t peer_id);
430 void SendHP(session_t peer_id, u16 hp);
431 void SendBreath(session_t peer_id, u16 breath);
432 void SendAccessDenied(session_t peer_id, AccessDeniedCode reason,
433 const std::string &custom_reason, bool reconnect = false);
434 void SendAccessDenied_Legacy(session_t peer_id, const std::wstring &reason);
435 void SendDeathscreen(session_t peer_id, bool set_camera_point_target,
436 v3f camera_point_target);
437 void SendItemDef(session_t peer_id, IItemDefManager *itemdef, u16 protocol_version);
438 void SendNodeDef(session_t peer_id, const NodeDefManager *nodedef,
439 u16 protocol_version);
441 /* mark blocks not sent for all clients */
442 void SetBlocksNotSent(std::map<v3s16, MapBlock *>& block);
445 virtual void SendChatMessage(session_t peer_id, const ChatMessage &message);
446 void SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed);
448 void SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4],
449 f32 animation_speed);
450 void SendEyeOffset(session_t peer_id, v3f first, v3f third);
451 void SendPlayerPrivileges(session_t peer_id);
452 void SendPlayerInventoryFormspec(session_t peer_id);
453 void SendPlayerFormspecPrepend(session_t peer_id);
454 void SendShowFormspecMessage(session_t peer_id, const std::string &formspec,
455 const std::string &formname);
456 void SendHUDAdd(session_t peer_id, u32 id, HudElement *form);
457 void SendHUDRemove(session_t peer_id, u32 id);
458 void SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value);
459 void SendHUDSetFlags(session_t peer_id, u32 flags, u32 mask);
460 void SendHUDSetParam(session_t peer_id, u16 param, const std::string &value);
461 void SendSetSky(session_t peer_id, const SkyboxParams ¶ms);
462 void SendSetSun(session_t peer_id, const SunParams ¶ms);
463 void SendSetMoon(session_t peer_id, const MoonParams ¶ms);
464 void SendSetStars(session_t peer_id, const StarParams ¶ms);
465 void SendCloudParams(session_t peer_id, const CloudParams ¶ms);
466 void SendOverrideDayNightRatio(session_t peer_id, bool do_override, float ratio);
467 void SendSetLighting(session_t peer_id, const Lighting &lighting);
468 void broadcastModChannelMessage(const std::string &channel,
469 const std::string &message, session_t from_peer);
472 Send a node removal/addition event to all clients except ignore_id.
473 Additionally, if far_players!=NULL, players further away than
474 far_d_nodes are ignored and their peer_ids are added to far_players
476 // Envlock and conlock should be locked when calling these
477 void sendRemoveNode(v3s16 p, std::unordered_set<u16> *far_players = nullptr,
478 float far_d_nodes = 100);
479 void sendAddNode(v3s16 p, MapNode n,
480 std::unordered_set<u16> *far_players = nullptr,
481 float far_d_nodes = 100, bool remove_metadata = true);
483 void sendMetadataChanged(const std::list<v3s16> &meta_updates,
484 float far_d_nodes = 100);
486 // Environment and Connection must be locked when called
487 void SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
489 // Sends blocks to clients (locks env and con on its own)
490 void SendBlocks(float dtime);
492 bool addMediaFile(const std::string &filename, const std::string &filepath,
493 std::string *filedata = nullptr, std::string *digest = nullptr);
494 void fillMediaCache();
495 void sendMediaAnnouncement(session_t peer_id, const std::string &lang_code);
496 void sendRequestedMedia(session_t peer_id,
497 const std::vector<std::string> &tosend);
498 void stepPendingDynMediaCallbacks(float dtime);
500 // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all)
501 void SendAddParticleSpawner(session_t peer_id, u16 protocol_version,
502 const ParticleSpawnerParameters &p, u16 attached_id, u32 id);
504 void SendDeleteParticleSpawner(session_t peer_id, u32 id);
506 // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all)
507 void SendSpawnParticle(session_t peer_id, u16 protocol_version,
508 const ParticleParameters &p);
510 void SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersao);
511 void SendActiveObjectMessages(session_t peer_id, const std::string &datas,
512 bool reliable = true);
513 void SendCSMRestrictionFlags(session_t peer_id);
519 void HandlePlayerDeath(PlayerSAO* sao, const PlayerHPChangeReason &reason);
520 void RespawnPlayer(session_t peer_id);
521 void DeleteClient(session_t peer_id, ClientDeletionReason reason);
522 void UpdateCrafting(RemotePlayer *player);
523 bool checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what);
525 void handleChatInterfaceEvent(ChatEvent *evt);
527 // This returns the answer to the sender of wmessage, or "" if there is none
528 std::wstring handleChat(const std::string &name, std::wstring wmessage_input,
529 bool check_shout_priv = false, RemotePlayer *player = nullptr);
530 void handleAdminChat(const ChatEventChat *evt);
532 // When called, connection mutex should be locked
533 RemoteClient* getClient(session_t peer_id, ClientState state_min = CS_Active);
534 RemoteClient* getClientNoEx(session_t peer_id, ClientState state_min = CS_Active);
536 // When called, environment mutex should be locked
537 std::string getPlayerName(session_t peer_id);
538 PlayerSAO *getPlayerSAO(session_t peer_id);
541 Get a player from memory or creates one.
542 If player is already connected, return NULL
543 Does not verify/modify auth info and password.
545 Call with env and con locked.
547 PlayerSAO *emergePlayer(const char *name, session_t peer_id, u16 proto_version);
549 void handlePeerChanges();
555 std::string m_path_world;
556 // Subgame specification
557 SubgameSpec m_gamespec;
558 // If true, do not allow multiple players and hide some multiplayer
560 bool m_simple_singleplayer_mode;
561 u16 m_max_chatmessage_length;
562 // For "dedicated" server list flag
564 Settings *m_game_settings = nullptr;
566 // Thread can set; step() will throw as ServerError
567 MutexedVariable<std::string> m_async_fatal_error;
570 float m_liquid_transform_timer = 0.0f;
571 float m_liquid_transform_every = 1.0f;
572 float m_masterserver_timer = 0.0f;
573 float m_emergethread_trigger_timer = 0.0f;
574 float m_savemap_timer = 0.0f;
575 IntervalLimiter m_map_timer_and_unload_interval;
578 ServerEnvironment *m_env = nullptr;
580 // Reference to the server map until ServerEnvironment is initialized
581 // after that this variable must be a nullptr
582 ServerMap *m_startup_server_map = nullptr;
585 std::shared_ptr<con::Connection> m_con;
588 BanManager *m_banmanager = nullptr;
590 // Rollback manager (behind m_env_mutex)
591 IRollbackManager *m_rollback = nullptr;
594 EmergeManager *m_emerge = nullptr;
597 // Envlock and conlock should be locked when using Lua
598 ServerScripting *m_script = nullptr;
600 // Item definition manager
601 IWritableItemDefManager *m_itemdef;
603 // Node definition manager
604 NodeDefManager *m_nodedef;
606 // Craft definition manager
607 IWritableCraftDefManager *m_craftdef;
610 std::unique_ptr<ServerModManager> m_modmgr;
612 std::unordered_map<std::string, Translations> server_translations;
617 // A buffer for time steps
618 // step() increments and AsyncRunStep() run by m_thread reads it.
619 float m_step_dtime = 0.0f;
620 std::mutex m_step_dtime_mutex;
622 // The server mainly operates in this thread
623 ServerThread *m_thread = nullptr;
628 // Timer for sending time of day over network
629 float m_time_of_day_send_timer = 0.0f;
634 ClientInterface m_clients;
638 Queues stuff from peerAdded() and deletingPeer() to
641 std::queue<con::PeerChange> m_peer_change_queue;
643 std::unordered_map<session_t, std::string> m_formspec_state_data;
649 ShutdownState m_shutdown_state;
651 ChatInterface *m_admin_chat;
652 std::string m_admin_nick;
654 // if a mod-error occurs in the on_shutdown callback, the error message will
655 // be written into this
656 std::string *const m_on_shutdown_errmsg;
659 Map edit event queue. Automatically receives all map edits.
660 The constructor of this class registers us to receive them through
663 NOTE: Should these be moved to actually be members of
668 Queue of map edits from the environment for sending to the clients
669 This is behind m_env_mutex
671 std::queue<MapEditEvent*> m_unsent_map_edit_queue;
673 If a non-empty area, map edit events contained within are left
674 unsent. Done at map generation time to speed up editing of the
675 generated area, as it will be sent anyway.
676 This is behind m_env_mutex
678 VoxelArea m_ignore_map_edit_events_area;
680 // media files known to server
681 std::unordered_map<std::string, MediaInfo> m_media;
683 // pending dynamic media callbacks, clients inform the server when they have a file fetched
684 std::unordered_map<u32, PendingDynamicMediaCallback> m_pending_dyn_media;
685 float m_step_pending_dyn_media_timer = 0.0f;
690 std::unordered_map<s32, ServerPlayingSound> m_playing_sounds;
691 s32 m_next_sound_id = 0; // positive values only
694 std::unordered_map<std::string, ModMetadata *> m_mod_storages;
695 ModMetadataDatabase *m_mod_storage_database = nullptr;
696 float m_mod_storage_save_timer = 10.0f;
698 // CSM restrictions byteflag
699 u64 m_csm_restriction_flags = CSMRestrictionFlags::CSM_RF_NONE;
700 u32 m_csm_restriction_noderange = 8;
702 // ModChannel manager
703 std::unique_ptr<ModChannelMgr> m_modchannel_mgr;
706 std::unique_ptr<ServerInventoryManager> m_inventory_mgr;
708 // Global server metrics backend
709 std::unique_ptr<MetricsBackend> m_metrics_backend;
712 MetricCounterPtr m_uptime_counter;
713 MetricGaugePtr m_player_gauge;
714 MetricGaugePtr m_timeofday_gauge;
715 // current server step lag
716 MetricGaugePtr m_lag_gauge;
717 MetricCounterPtr m_aom_buffer_counter;
718 MetricCounterPtr m_packet_recv_counter;
719 MetricCounterPtr m_packet_recv_processed_counter;
723 Runs a simple dedicated server loop.
725 Shuts down when kill is set to true.
727 void dedicated_server_loop(Server &server, bool &kill);