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" // struct TileAnimationParams
31 #include "network/peerhandler.h"
32 #include "network/address.h"
33 #include "util/numeric.h"
34 #include "util/thread.h"
35 #include "util/basic_macros.h"
36 #include "serverenvironment.h"
37 #include "clientiface.h"
38 #include "chatmessage.h"
47 class IWritableItemDefManager;
49 class IWritableCraftDefManager;
56 struct PlayerHPChangeReason;
57 class IRollbackManager;
58 struct RollbackAction;
60 class ServerScripting;
61 class ServerEnvironment;
62 struct SimpleSoundSpec;
65 class ServerModManager;
67 enum ClientDeletionReason {
76 std::string sha1_digest;
78 MediaInfo(const std::string &path_="",
79 const std::string &sha1_digest_=""):
81 sha1_digest(sha1_digest_)
86 struct ServerSoundParams
97 float max_hear_distance = 32 * BS;
100 std::string to_player = "";
102 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
105 struct ServerPlayingSound
107 ServerSoundParams params;
108 SimpleSoundSpec spec;
109 std::unordered_set<session_t> clients; // peer ids
112 class Server : public con::PeerHandler, public MapEventReceiver,
113 public InventoryManager, public IGameDef
117 NOTE: Every public method should be thread-safe
121 const std::string &path_world,
122 const SubgameSpec &gamespec,
123 bool simple_singleplayer_mode,
126 ChatInterface *iface = nullptr
129 DISABLE_CLASS_COPY(Server);
134 // This is mainly a way to pass the time to the server.
135 // Actual processing is done in an another thread.
136 void step(float dtime);
137 // This is run by ServerThread and does the actual processing
138 void AsyncRunStep(bool initial_step=false);
140 PlayerSAO* StageTwoClientInit(session_t peer_id);
146 void handleCommand(NetworkPacket* pkt);
148 void handleCommand_Null(NetworkPacket* pkt) {};
149 void handleCommand_Deprecated(NetworkPacket* pkt);
150 void handleCommand_Init(NetworkPacket* pkt);
151 void handleCommand_Init2(NetworkPacket* pkt);
152 void handleCommand_ModChannelJoin(NetworkPacket *pkt);
153 void handleCommand_ModChannelLeave(NetworkPacket *pkt);
154 void handleCommand_ModChannelMsg(NetworkPacket *pkt);
155 void handleCommand_RequestMedia(NetworkPacket* pkt);
156 void handleCommand_ClientReady(NetworkPacket* pkt);
157 void handleCommand_GotBlocks(NetworkPacket* pkt);
158 void handleCommand_PlayerPos(NetworkPacket* pkt);
159 void handleCommand_DeletedBlocks(NetworkPacket* pkt);
160 void handleCommand_InventoryAction(NetworkPacket* pkt);
161 void handleCommand_ChatMessage(NetworkPacket* pkt);
162 void handleCommand_Damage(NetworkPacket* pkt);
163 void handleCommand_Password(NetworkPacket* pkt);
164 void handleCommand_PlayerItem(NetworkPacket* pkt);
165 void handleCommand_Respawn(NetworkPacket* pkt);
166 void handleCommand_Interact(NetworkPacket* pkt);
167 void handleCommand_RemovedSounds(NetworkPacket* pkt);
168 void handleCommand_NodeMetaFields(NetworkPacket* pkt);
169 void handleCommand_InventoryFields(NetworkPacket* pkt);
170 void handleCommand_FirstSrp(NetworkPacket* pkt);
171 void handleCommand_SrpBytesA(NetworkPacket* pkt);
172 void handleCommand_SrpBytesM(NetworkPacket* pkt);
174 void ProcessData(NetworkPacket *pkt);
176 void Send(NetworkPacket *pkt);
177 void Send(session_t peer_id, NetworkPacket *pkt);
179 // Helper for handleCommand_PlayerPos and handleCommand_Interact
180 void process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
183 // Both setter and getter need no envlock,
184 // can be called freely from threads
185 void setTimeOfDay(u32 time);
188 Shall be called with the environment locked.
189 This is accessed by the map, which is inside the environment,
190 so it shouldn't be a problem.
192 void onMapEditEvent(MapEditEvent *event);
195 Shall be called with the environment and the connection locked.
197 Inventory* getInventory(const InventoryLocation &loc);
198 void setInventoryModified(const InventoryLocation &loc);
200 // Connection must be locked when called
201 std::wstring getStatusString();
202 inline double getUptime() const { return m_uptime.m_value; }
204 // read shutdown state
205 inline bool isShutdownRequested() const { return m_shutdown_state.is_requested; }
207 // request server to shutdown
208 void requestShutdown(const std::string &msg, bool reconnect, float delay = 0.0f);
210 // Returns -1 if failed, sound handle on success
212 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
213 void stopSound(s32 handle);
214 void fadeSound(s32 handle, float step, float gain);
217 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
218 bool checkPriv(const std::string &name, const std::string &priv);
219 void reportPrivsModified(const std::string &name=""); // ""=all
220 void reportInventoryFormspecModified(const std::string &name);
221 void reportFormspecPrependModified(const std::string &name);
223 void setIpBanned(const std::string &ip, const std::string &name);
224 void unsetIpBanned(const std::string &ip_or_name);
225 std::string getBanDescription(const std::string &ip_or_name);
227 void notifyPlayer(const char *name, const std::wstring &msg);
228 void notifyPlayers(const std::wstring &msg);
229 void spawnParticle(const std::string &playername,
230 v3f pos, v3f velocity, v3f acceleration,
231 float expirationtime, float size,
232 bool collisiondetection, bool collision_removal, bool object_collision,
233 bool vertical, const std::string &texture,
234 const struct TileAnimationParams &animation, u8 glow);
236 u32 addParticleSpawner(u16 amount, float spawntime,
237 v3f minpos, v3f maxpos,
238 v3f minvel, v3f maxvel,
239 v3f minacc, v3f maxacc,
240 float minexptime, float maxexptime,
241 float minsize, float maxsize,
242 bool collisiondetection, bool collision_removal, bool object_collision,
243 ServerActiveObject *attached,
244 bool vertical, const std::string &texture,
245 const std::string &playername, const struct TileAnimationParams &animation,
248 void deleteParticleSpawner(const std::string &playername, u32 id);
250 // Creates or resets inventory
251 Inventory *createDetachedInventory(const std::string &name,
252 const std::string &player = "");
253 bool removeDetachedInventory(const std::string &name);
255 // Envlock and conlock should be locked when using scriptapi
256 ServerScripting *getScriptIface(){ return m_script; }
258 // actions: time-reversed list
259 // Return value: success/failure
260 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
261 std::list<std::string> *log);
263 // IGameDef interface
265 virtual IItemDefManager* getItemDefManager();
266 virtual const NodeDefManager* getNodeDefManager();
267 virtual ICraftDefManager* getCraftDefManager();
268 virtual u16 allocateUnknownNodeId(const std::string &name);
269 IRollbackManager *getRollbackManager() { return m_rollback; }
270 virtual EmergeManager *getEmergeManager() { return m_emerge; }
272 IWritableItemDefManager* getWritableItemDefManager();
273 NodeDefManager* getWritableNodeDefManager();
274 IWritableCraftDefManager* getWritableCraftDefManager();
276 virtual const std::vector<ModSpec> &getMods() const;
277 virtual const ModSpec* getModSpec(const std::string &modname) const;
278 void getModNames(std::vector<std::string> &modlist);
279 std::string getBuiltinLuaPath();
280 virtual std::string getWorldPath() const { return m_path_world; }
281 virtual std::string getModStoragePath() const;
283 inline bool isSingleplayer()
284 { return m_simple_singleplayer_mode; }
286 inline void setAsyncFatalError(const std::string &error)
287 { m_async_fatal_error.set(error); }
289 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
290 Map & getMap() { return m_env->getMap(); }
291 ServerEnvironment & getEnv() { return *m_env; }
294 u32 hudAdd(RemotePlayer *player, HudElement *element);
295 bool hudRemove(RemotePlayer *player, u32 id);
296 bool hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *value);
297 bool hudSetFlags(RemotePlayer *player, u32 flags, u32 mask);
298 bool hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount);
299 void hudSetHotbarImage(RemotePlayer *player, const std::string &name);
300 void hudSetHotbarSelectedImage(RemotePlayer *player, const std::string &name);
302 Address getPeerAddress(session_t peer_id);
304 void setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4],
306 void setPlayerEyeOffset(RemotePlayer *player, const v3f &first, const v3f &third);
308 void setSky(RemotePlayer *player, const video::SColor &bgcolor,
309 const std::string &type, const std::vector<std::string> ¶ms,
311 void setClouds(RemotePlayer *player, const CloudParams ¶ms);
313 bool overrideDayNightRatio(RemotePlayer *player, bool do_override, float brightness);
315 /* con::PeerHandler implementation. */
316 void peerAdded(con::Peer *peer);
317 void deletingPeer(con::Peer *peer, bool timeout);
319 void DenySudoAccess(session_t peer_id);
320 void DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, AccessDeniedCode reason,
321 const std::string &str_reason = "", bool reconnect = false);
322 void DenyAccess(session_t peer_id, AccessDeniedCode reason,
323 const std::string &custom_reason = "");
324 void acceptAuth(session_t peer_id, bool forSudoMode);
325 void DenyAccess_Legacy(session_t peer_id, const std::wstring &reason);
326 void DisconnectPeer(session_t peer_id);
327 bool getClientConInfo(session_t peer_id, con::rtt_stat_type type, float *retval);
328 bool getClientInfo(session_t peer_id, ClientState *state, u32 *uptime,
329 u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch,
330 std::string* vers_string);
332 void printToConsoleOnly(const std::string &text);
334 void SendPlayerHPOrDie(PlayerSAO *player, const PlayerHPChangeReason &reason);
335 void SendPlayerBreath(PlayerSAO *sao);
336 void SendInventory(PlayerSAO *playerSAO, bool incremental);
337 void SendMovePlayer(session_t peer_id);
338 void SendPlayerSpeed(session_t peer_id, const v3f &added_vel);
340 void sendDetachedInventories(session_t peer_id, bool incremental);
342 virtual bool registerModStorage(ModMetadata *storage);
343 virtual void unregisterModStorage(const std::string &name);
345 bool joinModChannel(const std::string &channel);
346 bool leaveModChannel(const std::string &channel);
347 bool sendModChannelMessage(const std::string &channel, const std::string &message);
348 ModChannel *getModChannel(const std::string &channel);
350 // Send block to specific player only
351 bool SendBlock(session_t peer_id, const v3s16 &blockpos);
356 // Environment mutex (envlock)
357 std::mutex m_env_mutex;
360 friend class EmergeThread;
361 friend class RemoteClient;
362 friend class TestServerShutdownState;
364 struct ShutdownState {
365 friend class TestServerShutdownState;
367 bool is_requested = false;
368 bool should_reconnect = false;
372 void trigger(float delay, const std::string &msg, bool reconnect);
373 void tick(float dtime, Server *server);
374 std::wstring getShutdownTimerMessage() const;
375 bool isTimerRunning() const { return m_timer > 0.0f; }
377 float m_timer = 0.0f;
380 void SendMovement(session_t peer_id);
381 void SendHP(session_t peer_id, u16 hp);
382 void SendBreath(session_t peer_id, u16 breath);
383 void SendAccessDenied(session_t peer_id, AccessDeniedCode reason,
384 const std::string &custom_reason, bool reconnect = false);
385 void SendAccessDenied_Legacy(session_t peer_id, const std::wstring &reason);
386 void SendDeathscreen(session_t peer_id, bool set_camera_point_target,
387 v3f camera_point_target);
388 void SendItemDef(session_t peer_id, IItemDefManager *itemdef, u16 protocol_version);
389 void SendNodeDef(session_t peer_id, const NodeDefManager *nodedef,
390 u16 protocol_version);
392 /* mark blocks not sent for all clients */
393 void SetBlocksNotSent(std::map<v3s16, MapBlock *>& block);
396 virtual void SendChatMessage(session_t peer_id, const ChatMessage &message);
397 void SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed);
398 void SendPlayerHP(session_t peer_id);
400 void SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4],
401 f32 animation_speed);
402 void SendEyeOffset(session_t peer_id, v3f first, v3f third);
403 void SendPlayerPrivileges(session_t peer_id);
404 void SendPlayerInventoryFormspec(session_t peer_id);
405 void SendPlayerFormspecPrepend(session_t peer_id);
406 void SendShowFormspecMessage(session_t peer_id, const std::string &formspec,
407 const std::string &formname);
408 void SendHUDAdd(session_t peer_id, u32 id, HudElement *form);
409 void SendHUDRemove(session_t peer_id, u32 id);
410 void SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value);
411 void SendHUDSetFlags(session_t peer_id, u32 flags, u32 mask);
412 void SendHUDSetParam(session_t peer_id, u16 param, const std::string &value);
413 void SendSetSky(session_t peer_id, const video::SColor &bgcolor,
414 const std::string &type, const std::vector<std::string> ¶ms,
416 void SendCloudParams(session_t peer_id, const CloudParams ¶ms);
417 void SendOverrideDayNightRatio(session_t peer_id, bool do_override, float ratio);
418 void broadcastModChannelMessage(const std::string &channel,
419 const std::string &message, session_t from_peer);
422 Send a node removal/addition event to all clients except ignore_id.
423 Additionally, if far_players!=NULL, players further away than
424 far_d_nodes are ignored and their peer_ids are added to far_players
426 // Envlock and conlock should be locked when calling these
427 void sendRemoveNode(v3s16 p, std::unordered_set<u16> *far_players = nullptr,
428 float far_d_nodes = 100);
429 void sendAddNode(v3s16 p, MapNode n,
430 std::unordered_set<u16> *far_players = nullptr,
431 float far_d_nodes = 100, bool remove_metadata = true);
433 void sendMetadataChanged(const std::list<v3s16> &meta_updates,
434 float far_d_nodes = 100);
436 // Environment and Connection must be locked when called
437 void SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
439 // Sends blocks to clients (locks env and con on its own)
440 void SendBlocks(float dtime);
442 void fillMediaCache();
443 void sendMediaAnnouncement(session_t peer_id, const std::string &lang_code);
444 void sendRequestedMedia(session_t peer_id,
445 const std::vector<std::string> &tosend);
447 void sendDetachedInventory(const std::string &name, session_t peer_id);
449 // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all)
450 void SendAddParticleSpawner(session_t peer_id, u16 protocol_version,
451 u16 amount, float spawntime,
452 v3f minpos, v3f maxpos,
453 v3f minvel, v3f maxvel,
454 v3f minacc, v3f maxacc,
455 float minexptime, float maxexptime,
456 float minsize, float maxsize,
457 bool collisiondetection, bool collision_removal, bool object_collision,
459 bool vertical, const std::string &texture, u32 id,
460 const struct TileAnimationParams &animation, u8 glow);
462 void SendDeleteParticleSpawner(session_t peer_id, u32 id);
464 // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all)
465 void SendSpawnParticle(session_t peer_id, u16 protocol_version,
466 v3f pos, v3f velocity, v3f acceleration,
467 float expirationtime, float size,
468 bool collisiondetection, bool collision_removal, bool object_collision,
469 bool vertical, const std::string &texture,
470 const struct TileAnimationParams &animation, u8 glow);
472 void SendActiveObjectRemoveAdd(RemoteClient *client, PlayerSAO *playersao);
473 void SendActiveObjectMessages(session_t peer_id, const std::string &datas,
474 bool reliable = true);
475 void SendCSMRestrictionFlags(session_t peer_id);
481 void DiePlayer(session_t peer_id, const PlayerHPChangeReason &reason);
482 void RespawnPlayer(session_t peer_id);
483 void DeleteClient(session_t peer_id, ClientDeletionReason reason);
484 void UpdateCrafting(RemotePlayer *player);
485 bool checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what);
487 void handleChatInterfaceEvent(ChatEvent *evt);
489 // This returns the answer to the sender of wmessage, or "" if there is none
490 std::wstring handleChat(const std::string &name, const std::wstring &wname,
491 std::wstring wmessage_input,
492 bool check_shout_priv = false,
493 RemotePlayer *player = NULL);
494 void handleAdminChat(const ChatEventChat *evt);
496 // When called, connection mutex should be locked
497 RemoteClient* getClient(session_t peer_id, ClientState state_min = CS_Active);
498 RemoteClient* getClientNoEx(session_t peer_id, ClientState state_min = CS_Active);
500 // When called, environment mutex should be locked
501 std::string getPlayerName(session_t peer_id);
502 PlayerSAO *getPlayerSAO(session_t peer_id);
505 Get a player from memory or creates one.
506 If player is already connected, return NULL
507 Does not verify/modify auth info and password.
509 Call with env and con locked.
511 PlayerSAO *emergePlayer(const char *name, session_t peer_id, u16 proto_version);
513 void handlePeerChanges();
520 std::string m_path_world;
521 // Subgame specification
522 SubgameSpec m_gamespec;
523 // If true, do not allow multiple players and hide some multiplayer
525 bool m_simple_singleplayer_mode;
526 u16 m_max_chatmessage_length;
527 // For "dedicated" server list flag
530 // Thread can set; step() will throw as ServerError
531 MutexedVariable<std::string> m_async_fatal_error;
534 float m_liquid_transform_timer = 0.0f;
535 float m_liquid_transform_every = 1.0f;
536 float m_masterserver_timer = 0.0f;
537 float m_emergethread_trigger_timer = 0.0f;
538 float m_savemap_timer = 0.0f;
539 IntervalLimiter m_map_timer_and_unload_interval;
542 ServerEnvironment *m_env = nullptr;
545 std::shared_ptr<con::Connection> m_con;
548 BanManager *m_banmanager = nullptr;
550 // Rollback manager (behind m_env_mutex)
551 IRollbackManager *m_rollback = nullptr;
554 EmergeManager *m_emerge = nullptr;
557 // Envlock and conlock should be locked when using Lua
558 ServerScripting *m_script = nullptr;
560 // Item definition manager
561 IWritableItemDefManager *m_itemdef;
563 // Node definition manager
564 NodeDefManager *m_nodedef;
566 // Craft definition manager
567 IWritableCraftDefManager *m_craftdef;
570 EventManager *m_event;
573 std::unique_ptr<ServerModManager> m_modmgr;
579 // A buffer for time steps
580 // step() increments and AsyncRunStep() run by m_thread reads it.
581 float m_step_dtime = 0.0f;
582 std::mutex m_step_dtime_mutex;
584 // current server step lag counter
587 // The server mainly operates in this thread
588 ServerThread *m_thread = nullptr;
594 // Timer for sending time of day over network
595 float m_time_of_day_send_timer = 0.0f;
596 // Uptime of server in seconds
597 MutexedVariable<double> m_uptime;
601 ClientInterface m_clients;
605 Queues stuff from peerAdded() and deletingPeer() to
608 std::queue<con::PeerChange> m_peer_change_queue;
610 std::unordered_map<session_t, std::string> m_formspec_state_data;
616 ShutdownState m_shutdown_state;
618 ChatInterface *m_admin_chat;
619 std::string m_admin_nick;
622 Map edit event queue. Automatically receives all map edits.
623 The constructor of this class registers us to receive them through
626 NOTE: Should these be moved to actually be members of
631 Queue of map edits from the environment for sending to the clients
632 This is behind m_env_mutex
634 std::queue<MapEditEvent*> m_unsent_map_edit_queue;
636 If a non-empty area, map edit events contained within are left
637 unsent. Done at map generation time to speed up editing of the
638 generated area, as it will be sent anyway.
639 This is behind m_env_mutex
641 VoxelArea m_ignore_map_edit_events_area;
643 // media files known to server
644 std::unordered_map<std::string, MediaInfo> m_media;
649 std::unordered_map<s32, ServerPlayingSound> m_playing_sounds;
650 s32 m_next_sound_id = 0;
653 Detached inventories (behind m_env_mutex)
656 std::map<std::string, Inventory*> m_detached_inventories;
657 // value = "" (visible to all players) or player name
658 std::map<std::string, std::string> m_detached_inventories_player;
660 std::unordered_map<std::string, ModMetadata *> m_mod_storages;
661 float m_mod_storage_save_timer = 10.0f;
663 // CSM restrictions byteflag
664 u64 m_csm_restriction_flags = CSMRestrictionFlags::CSM_RF_NONE;
665 u32 m_csm_restriction_noderange = 8;
667 // ModChannel manager
668 std::unique_ptr<ModChannelMgr> m_modchannel_mgr;
672 Runs a simple dedicated server loop.
674 Shuts down when kill is set to true.
676 void dedicated_server_loop(Server &server, bool &kill);