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
28 #include "inventorymanager.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 class IRollbackManager;
57 struct RollbackAction;
59 class ServerScripting;
60 class ServerEnvironment;
61 struct SimpleSoundSpec;
64 enum ClientDeletionReason {
73 std::string sha1_digest;
75 MediaInfo(const std::string &path_="",
76 const std::string &sha1_digest_=""):
78 sha1_digest(sha1_digest_)
83 struct ServerSoundParams
94 float max_hear_distance = 32 * BS;
97 std::string to_player = "";
99 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
102 struct ServerPlayingSound
104 ServerSoundParams params;
105 SimpleSoundSpec spec;
106 std::unordered_set<session_t> clients; // peer ids
109 class Server : public con::PeerHandler, public MapEventReceiver,
110 public InventoryManager, public IGameDef
114 NOTE: Every public method should be thread-safe
118 const std::string &path_world,
119 const SubgameSpec &gamespec,
120 bool simple_singleplayer_mode,
123 ChatInterface *iface = nullptr
126 DISABLE_CLASS_COPY(Server);
130 // This is mainly a way to pass the time to the server.
131 // Actual processing is done in an another thread.
132 void step(float dtime);
133 // This is run by ServerThread and does the actual processing
134 void AsyncRunStep(bool initial_step=false);
136 PlayerSAO* StageTwoClientInit(session_t peer_id);
142 void handleCommand(NetworkPacket* pkt);
144 void handleCommand_Null(NetworkPacket* pkt) {};
145 void handleCommand_Deprecated(NetworkPacket* pkt);
146 void handleCommand_Init(NetworkPacket* pkt);
147 void handleCommand_Init2(NetworkPacket* pkt);
148 void handleCommand_ModChannelJoin(NetworkPacket *pkt);
149 void handleCommand_ModChannelLeave(NetworkPacket *pkt);
150 void handleCommand_ModChannelMsg(NetworkPacket *pkt);
151 void handleCommand_RequestMedia(NetworkPacket* pkt);
152 void handleCommand_ClientReady(NetworkPacket* pkt);
153 void handleCommand_GotBlocks(NetworkPacket* pkt);
154 void handleCommand_PlayerPos(NetworkPacket* pkt);
155 void handleCommand_DeletedBlocks(NetworkPacket* pkt);
156 void handleCommand_InventoryAction(NetworkPacket* pkt);
157 void handleCommand_ChatMessage(NetworkPacket* pkt);
158 void handleCommand_Damage(NetworkPacket* pkt);
159 void handleCommand_Password(NetworkPacket* pkt);
160 void handleCommand_PlayerItem(NetworkPacket* pkt);
161 void handleCommand_Respawn(NetworkPacket* pkt);
162 void handleCommand_Interact(NetworkPacket* pkt);
163 void handleCommand_RemovedSounds(NetworkPacket* pkt);
164 void handleCommand_NodeMetaFields(NetworkPacket* pkt);
165 void handleCommand_InventoryFields(NetworkPacket* pkt);
166 void handleCommand_FirstSrp(NetworkPacket* pkt);
167 void handleCommand_SrpBytesA(NetworkPacket* pkt);
168 void handleCommand_SrpBytesM(NetworkPacket* pkt);
170 void ProcessData(NetworkPacket *pkt);
172 void Send(NetworkPacket *pkt);
173 void Send(session_t peer_id, NetworkPacket *pkt);
175 // Helper for handleCommand_PlayerPos and handleCommand_Interact
176 void process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
179 // Both setter and getter need no envlock,
180 // can be called freely from threads
181 void setTimeOfDay(u32 time);
184 Shall be called with the environment locked.
185 This is accessed by the map, which is inside the environment,
186 so it shouldn't be a problem.
188 void onMapEditEvent(MapEditEvent *event);
191 Shall be called with the environment and the connection locked.
193 Inventory* getInventory(const InventoryLocation &loc);
194 void setInventoryModified(const InventoryLocation &loc, bool playerSend = true);
196 // Connection must be locked when called
197 std::wstring getStatusString();
198 inline double getUptime() const { return m_uptime.m_value; }
200 // read shutdown state
201 inline bool getShutdownRequested() const { return m_shutdown_requested; }
203 // request server to shutdown
204 void requestShutdown(const std::string &msg, bool reconnect, float delay = 0.0f);
206 // Returns -1 if failed, sound handle on success
208 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
209 void stopSound(s32 handle);
210 void fadeSound(s32 handle, float step, float gain);
213 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
214 bool checkPriv(const std::string &name, const std::string &priv);
215 void reportPrivsModified(const std::string &name=""); // ""=all
216 void reportInventoryFormspecModified(const std::string &name);
218 void setIpBanned(const std::string &ip, const std::string &name);
219 void unsetIpBanned(const std::string &ip_or_name);
220 std::string getBanDescription(const std::string &ip_or_name);
222 void notifyPlayer(const char *name, const std::wstring &msg);
223 void notifyPlayers(const std::wstring &msg);
224 void spawnParticle(const std::string &playername,
225 v3f pos, v3f velocity, v3f acceleration,
226 float expirationtime, float size,
227 bool collisiondetection, bool collision_removal,
228 bool vertical, const std::string &texture,
229 const struct TileAnimationParams &animation, u8 glow);
231 u32 addParticleSpawner(u16 amount, float spawntime,
232 v3f minpos, v3f maxpos,
233 v3f minvel, v3f maxvel,
234 v3f minacc, v3f maxacc,
235 float minexptime, float maxexptime,
236 float minsize, float maxsize,
237 bool collisiondetection, bool collision_removal,
238 ServerActiveObject *attached,
239 bool vertical, const std::string &texture,
240 const std::string &playername, const struct TileAnimationParams &animation,
243 void deleteParticleSpawner(const std::string &playername, u32 id);
245 // Creates or resets inventory
246 Inventory* createDetachedInventory(const std::string &name, const std::string &player="");
248 // Envlock and conlock should be locked when using scriptapi
249 ServerScripting *getScriptIface(){ return m_script; }
251 // actions: time-reversed list
252 // Return value: success/failure
253 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
254 std::list<std::string> *log);
256 // IGameDef interface
258 virtual IItemDefManager* getItemDefManager();
259 virtual const NodeDefManager* getNodeDefManager();
260 virtual ICraftDefManager* getCraftDefManager();
261 virtual u16 allocateUnknownNodeId(const std::string &name);
262 virtual MtEventManager* getEventManager();
263 IRollbackManager *getRollbackManager() { return m_rollback; }
264 virtual EmergeManager *getEmergeManager() { return m_emerge; }
266 IWritableItemDefManager* getWritableItemDefManager();
267 NodeDefManager* getWritableNodeDefManager();
268 IWritableCraftDefManager* getWritableCraftDefManager();
270 virtual const std::vector<ModSpec> &getMods() const { return m_mods; }
271 virtual const ModSpec* getModSpec(const std::string &modname) const;
272 void getModNames(std::vector<std::string> &modlist);
273 std::string getBuiltinLuaPath();
274 virtual std::string getWorldPath() const { return m_path_world; }
275 virtual std::string getModStoragePath() const;
277 inline bool isSingleplayer()
278 { return m_simple_singleplayer_mode; }
280 inline void setAsyncFatalError(const std::string &error)
281 { m_async_fatal_error.set(error); }
283 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
284 Map & getMap() { return m_env->getMap(); }
285 ServerEnvironment & getEnv() { return *m_env; }
288 u32 hudAdd(RemotePlayer *player, HudElement *element);
289 bool hudRemove(RemotePlayer *player, u32 id);
290 bool hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *value);
291 bool hudSetFlags(RemotePlayer *player, u32 flags, u32 mask);
292 bool hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount);
293 void hudSetHotbarImage(RemotePlayer *player, std::string name);
294 void hudSetHotbarSelectedImage(RemotePlayer *player, std::string name);
296 Address getPeerAddress(session_t peer_id);
298 bool setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4],
300 bool setPlayerEyeOffset(RemotePlayer *player, v3f first, v3f third);
302 bool setSky(RemotePlayer *player, const video::SColor &bgcolor,
303 const std::string &type, const std::vector<std::string> ¶ms,
305 bool setClouds(RemotePlayer *player, float density,
306 const video::SColor &color_bright,
307 const video::SColor &color_ambient,
312 bool overrideDayNightRatio(RemotePlayer *player, bool do_override, float brightness);
314 /* con::PeerHandler implementation. */
315 void peerAdded(con::Peer *peer);
316 void deletingPeer(con::Peer *peer, bool timeout);
318 void DenySudoAccess(session_t peer_id);
319 void DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, AccessDeniedCode reason,
320 const std::string &str_reason = "", bool reconnect = false);
321 void DenyAccess(session_t peer_id, AccessDeniedCode reason,
322 const std::string &custom_reason = "");
323 void acceptAuth(session_t peer_id, bool forSudoMode);
324 void DenyAccess_Legacy(session_t peer_id, const std::wstring &reason);
325 void DisconnectPeer(session_t peer_id);
326 bool getClientConInfo(session_t peer_id, con::rtt_stat_type type, float *retval);
327 bool getClientInfo(session_t peer_id, ClientState *state, u32 *uptime,
328 u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch,
329 std::string* vers_string);
331 void printToConsoleOnly(const std::string &text);
333 void SendPlayerHPOrDie(PlayerSAO *player);
334 void SendPlayerBreath(PlayerSAO *sao);
335 void SendInventory(PlayerSAO* playerSAO);
336 void SendMovePlayer(session_t peer_id);
338 virtual bool registerModStorage(ModMetadata *storage);
339 virtual void unregisterModStorage(const std::string &name);
341 bool joinModChannel(const std::string &channel);
342 bool leaveModChannel(const std::string &channel);
343 bool sendModChannelMessage(const std::string &channel, const std::string &message);
344 ModChannel *getModChannel(const std::string &channel);
349 // Environment mutex (envlock)
350 std::mutex m_env_mutex;
354 friend class EmergeThread;
355 friend class RemoteClient;
357 void SendMovement(session_t peer_id);
358 void SendHP(session_t peer_id, u16 hp);
359 void SendBreath(session_t peer_id, u16 breath);
360 void SendAccessDenied(session_t peer_id, AccessDeniedCode reason,
361 const std::string &custom_reason, bool reconnect = false);
362 void SendAccessDenied_Legacy(session_t peer_id, const std::wstring &reason);
363 void SendDeathscreen(session_t peer_id, bool set_camera_point_target,
364 v3f camera_point_target);
365 void SendItemDef(session_t peer_id, IItemDefManager *itemdef, u16 protocol_version);
366 void SendNodeDef(session_t peer_id, const NodeDefManager *nodedef,
367 u16 protocol_version);
369 /* mark blocks not sent for all clients */
370 void SetBlocksNotSent(std::map<v3s16, MapBlock *>& block);
373 void SendChatMessage(session_t peer_id, const ChatMessage &message);
374 void SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed);
375 void SendPlayerHP(session_t peer_id);
377 void SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4],
378 f32 animation_speed);
379 void SendEyeOffset(session_t peer_id, v3f first, v3f third);
380 void SendPlayerPrivileges(session_t peer_id);
381 void SendPlayerInventoryFormspec(session_t peer_id);
382 void SendShowFormspecMessage(session_t peer_id, const std::string &formspec,
383 const std::string &formname);
384 void SendHUDAdd(session_t peer_id, u32 id, HudElement *form);
385 void SendHUDRemove(session_t peer_id, u32 id);
386 void SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value);
387 void SendHUDSetFlags(session_t peer_id, u32 flags, u32 mask);
388 void SendHUDSetParam(session_t peer_id, u16 param, const std::string &value);
389 void SendSetSky(session_t peer_id, const video::SColor &bgcolor,
390 const std::string &type, const std::vector<std::string> ¶ms,
392 void SendCloudParams(session_t peer_id, float density,
393 const video::SColor &color_bright,
394 const video::SColor &color_ambient,
398 void SendOverrideDayNightRatio(session_t peer_id, bool do_override, float ratio);
399 void broadcastModChannelMessage(const std::string &channel,
400 const std::string &message, session_t from_peer);
403 Send a node removal/addition event to all clients except ignore_id.
404 Additionally, if far_players!=NULL, players further away than
405 far_d_nodes are ignored and their peer_ids are added to far_players
407 // Envlock and conlock should be locked when calling these
408 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
409 std::vector<u16> *far_players=NULL, float far_d_nodes=100);
410 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
411 std::vector<u16> *far_players=NULL, float far_d_nodes=100,
412 bool remove_metadata=true);
413 void setBlockNotSent(v3s16 p);
415 // Environment and Connection must be locked when called
416 void SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
418 // Sends blocks to clients (locks env and con on its own)
419 void SendBlocks(float dtime);
421 void fillMediaCache();
422 void sendMediaAnnouncement(session_t peer_id, const std::string &lang_code);
423 void sendRequestedMedia(session_t peer_id,
424 const std::vector<std::string> &tosend);
426 void sendDetachedInventory(const std::string &name, session_t peer_id);
427 void sendDetachedInventories(session_t peer_id);
429 // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all)
430 void SendAddParticleSpawner(session_t peer_id, u16 protocol_version,
431 u16 amount, float spawntime,
432 v3f minpos, v3f maxpos,
433 v3f minvel, v3f maxvel,
434 v3f minacc, v3f maxacc,
435 float minexptime, float maxexptime,
436 float minsize, float maxsize,
437 bool collisiondetection, bool collision_removal,
439 bool vertical, const std::string &texture, u32 id,
440 const struct TileAnimationParams &animation, u8 glow);
442 void SendDeleteParticleSpawner(session_t peer_id, u32 id);
444 // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all)
445 void SendSpawnParticle(session_t peer_id, u16 protocol_version,
446 v3f pos, v3f velocity, v3f acceleration,
447 float expirationtime, float size,
448 bool collisiondetection, bool collision_removal,
449 bool vertical, const std::string &texture,
450 const struct TileAnimationParams &animation, u8 glow);
452 u32 SendActiveObjectRemoveAdd(session_t peer_id, const std::string &datas);
453 void SendActiveObjectMessages(session_t peer_id, const std::string &datas,
454 bool reliable = true);
455 void SendCSMFlavourLimits(session_t peer_id);
461 void DiePlayer(session_t peer_id);
462 void RespawnPlayer(session_t peer_id);
463 void DeleteClient(session_t peer_id, ClientDeletionReason reason);
464 void UpdateCrafting(RemotePlayer *player);
465 bool checkInteractDistance(RemotePlayer *player, const f32 d, const std::string what);
467 void handleChatInterfaceEvent(ChatEvent *evt);
469 // This returns the answer to the sender of wmessage, or "" if there is none
470 std::wstring handleChat(const std::string &name, const std::wstring &wname,
471 std::wstring wmessage_input,
472 bool check_shout_priv = false,
473 RemotePlayer *player = NULL);
474 void handleAdminChat(const ChatEventChat *evt);
476 // When called, connection mutex should be locked
477 RemoteClient* getClient(session_t peer_id, ClientState state_min = CS_Active);
478 RemoteClient* getClientNoEx(session_t peer_id, ClientState state_min = CS_Active);
480 // When called, environment mutex should be locked
481 std::string getPlayerName(session_t peer_id);
482 PlayerSAO *getPlayerSAO(session_t peer_id);
485 Get a player from memory or creates one.
486 If player is already connected, return NULL
487 Does not verify/modify auth info and password.
489 Call with env and con locked.
491 PlayerSAO *emergePlayer(const char *name, session_t peer_id, u16 proto_version);
493 void handlePeerChanges();
500 std::string m_path_world;
501 // Subgame specification
502 SubgameSpec m_gamespec;
503 // If true, do not allow multiple players and hide some multiplayer
505 bool m_simple_singleplayer_mode;
506 u16 m_max_chatmessage_length;
507 // For "dedicated" server list flag
510 // Thread can set; step() will throw as ServerError
511 MutexedVariable<std::string> m_async_fatal_error;
514 float m_liquid_transform_timer = 0.0f;
515 float m_liquid_transform_every = 1.0f;
516 float m_masterserver_timer = 0.0f;
517 float m_emergethread_trigger_timer = 0.0f;
518 float m_savemap_timer = 0.0f;
519 IntervalLimiter m_map_timer_and_unload_interval;
522 ServerEnvironment *m_env = nullptr;
525 std::shared_ptr<con::Connection> m_con;
528 BanManager *m_banmanager = nullptr;
530 // Rollback manager (behind m_env_mutex)
531 IRollbackManager *m_rollback = nullptr;
532 bool m_enable_rollback_recording = false; // Updated once in a while
535 EmergeManager *m_emerge = nullptr;
538 // Envlock and conlock should be locked when using Lua
539 ServerScripting *m_script = nullptr;
541 // Item definition manager
542 IWritableItemDefManager *m_itemdef;
544 // Node definition manager
545 NodeDefManager *m_nodedef;
547 // Craft definition manager
548 IWritableCraftDefManager *m_craftdef;
551 EventManager *m_event;
554 std::vector<ModSpec> m_mods;
560 // A buffer for time steps
561 // step() increments and AsyncRunStep() run by m_thread reads it.
562 float m_step_dtime = 0.0f;
563 std::mutex m_step_dtime_mutex;
565 // current server step lag counter
568 // The server mainly operates in this thread
569 ServerThread *m_thread = nullptr;
575 // Timer for sending time of day over network
576 float m_time_of_day_send_timer = 0.0f;
577 // Uptime of server in seconds
578 MutexedVariable<double> m_uptime;
582 ClientInterface m_clients;
586 Queues stuff from peerAdded() and deletingPeer() to
589 std::queue<con::PeerChange> m_peer_change_queue;
591 std::unordered_map<session_t, std::string> m_formspec_state_data;
597 bool m_shutdown_requested = false;
598 std::string m_shutdown_msg;
599 bool m_shutdown_ask_reconnect = false;
600 float m_shutdown_timer = 0.0f;
602 ChatInterface *m_admin_chat;
603 std::string m_admin_nick;
606 Map edit event queue. Automatically receives all map edits.
607 The constructor of this class registers us to receive them through
610 NOTE: Should these be moved to actually be members of
615 Queue of map edits from the environment for sending to the clients
616 This is behind m_env_mutex
618 std::queue<MapEditEvent*> m_unsent_map_edit_queue;
620 Set to true when the server itself is modifying the map and does
621 all sending of information by itself.
622 This is behind m_env_mutex
624 bool m_ignore_map_edit_events = false;
626 If a non-empty area, map edit events contained within are left
627 unsent. Done at map generation time to speed up editing of the
628 generated area, as it will be sent anyway.
629 This is behind m_env_mutex
631 VoxelArea m_ignore_map_edit_events_area;
633 If set to !=0, the incoming MapEditEvents are modified to have
634 this peed id as the disabled recipient
635 This is behind m_env_mutex
637 session_t m_ignore_map_edit_events_peer_id = 0;
639 // media files known to server
640 std::unordered_map<std::string, MediaInfo> m_media;
645 std::unordered_map<s32, ServerPlayingSound> m_playing_sounds;
646 s32 m_next_sound_id = 0;
649 Detached inventories (behind m_env_mutex)
652 std::map<std::string, Inventory*> m_detached_inventories;
653 // value = "" (visible to all players) or player name
654 std::map<std::string, std::string> m_detached_inventories_player;
656 std::unordered_map<std::string, ModMetadata *> m_mod_storages;
657 float m_mod_storage_save_timer = 10.0f;
659 // CSM flavour limits byteflag
660 u64 m_csm_flavour_limits = CSMFlavourLimit::CSM_FL_NONE;
661 u32 m_csm_noderange_limit = 8;
663 // ModChannel manager
664 std::unique_ptr<ModChannelMgr> m_modchannel_mgr;
668 Runs a simple dedicated server loop.
670 Shuts down when kill is set to true.
672 void dedicated_server_loop(Server &server, bool &kill);