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.
23 #include "connection.h"
24 #include "environment.h"
25 #include "irrlichttypes_bloated.h"
29 #include "inventory.h"
32 #include "serialization.h" // For SER_FMT_VER_INVALID
34 #include "inventorymanager.h"
37 #include "util/thread.h"
38 #include "util/string.h"
39 #include "rollback_interface.h" // Needed for rollbackRevertActions()
40 #include <list> // Needed for rollbackRevertActions()
42 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
45 typedef struct lua_State lua_State;
46 class IWritableItemDefManager;
47 class IWritableNodeDefManager;
48 class IWritableCraftDefManager;
51 class IRollbackManager;
54 class ServerError : public std::exception
57 ServerError(const std::string &s)
59 m_s = "ServerError: ";
62 virtual ~ServerError() throw()
64 virtual const char * what() const throw()
74 v3f findSpawnPos(ServerMap &map);
77 class MapEditEventIgnorer
80 MapEditEventIgnorer(bool *flag):
89 ~MapEditEventIgnorer()
102 class MapEditEventAreaIgnorer
105 MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
106 m_ignorevariable(ignorevariable)
108 if(m_ignorevariable->getVolume() == 0)
109 *m_ignorevariable = a;
111 m_ignorevariable = NULL;
114 ~MapEditEventAreaIgnorer()
118 assert(m_ignorevariable->getVolume() != 0);
119 *m_ignorevariable = VoxelArea();
124 VoxelArea *m_ignorevariable;
129 class ServerThread : public SimpleThread
135 ServerThread(Server *server):
147 char name[PLAYERNAME_SIZE];
153 void PrintLine(std::ostream *s);
157 Used for queueing and sorting block transfers in containers
159 Lower priority number means higher priority.
161 struct PrioritySortedBlockTransfer
163 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
165 priority = a_priority;
169 bool operator < (PrioritySortedBlockTransfer &other)
171 return priority < other.priority;
182 MediaRequest(const std::string &name_=""):
190 std::string sha1_digest;
192 MediaInfo(const std::string path_="",
193 const std::string sha1_digest_=""):
195 sha1_digest(sha1_digest_)
200 struct ServerSoundParams
203 std::string to_player;
211 float max_hear_distance;
220 max_hear_distance(32*BS),
224 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
227 struct ServerPlayingSound
229 ServerSoundParams params;
230 std::set<u16> clients; // peer ids
236 // peer_id=0 means this client has no associated peer
237 // NOTE: If client is made allowed to exist while peer doesn't,
238 // this has to be set to 0 when there is no peer.
239 // Also, the client must be moved to some other container.
241 // The serialization version to use with the client
242 u8 serialization_version;
244 u16 net_proto_version;
245 // Version is stored in here after INIT before INIT2
246 u8 pending_serialization_version;
248 bool definitions_sent;
251 m_time_from_building(9999),
252 m_excess_gotblocks(0)
255 serialization_version = SER_FMT_VER_INVALID;
256 net_proto_version = 0;
257 pending_serialization_version = SER_FMT_VER_INVALID;
258 definitions_sent = false;
259 m_nearest_unsent_d = 0;
260 m_nearest_unsent_reset_timer = 0.0;
261 m_nothing_to_send_counter = 0;
262 m_nothing_to_send_pause_timer = 0;
269 Finds block that should be sent next to the client.
270 Environment should be locked when this is called.
271 dtime is used for resetting send radius at slow interval
273 void GetNextBlocks(Server *server, float dtime,
274 core::array<PrioritySortedBlockTransfer> &dest);
276 void GotBlock(v3s16 p);
278 void SentBlock(v3s16 p);
280 void SetBlockNotSent(v3s16 p);
281 void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
285 return m_blocks_sending.size();
288 // Increments timeouts and removes timed-out blocks from list
289 // NOTE: This doesn't fix the server-not-sending-block bug
290 // because it is related to emerging, not sending.
291 //void RunSendingTimeouts(float dtime, float timeout);
293 void PrintInfo(std::ostream &o)
295 o<<"RemoteClient "<<peer_id<<": "
296 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
297 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
298 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
299 <<", m_excess_gotblocks="<<m_excess_gotblocks
301 m_excess_gotblocks = 0;
304 // Time from last placing or removing blocks
305 float m_time_from_building;
307 /*JMutex m_dig_mutex;
308 float m_dig_time_remaining;
311 v3s16 m_dig_position;*/
314 List of active objects that the client knows of.
317 core::map<u16, bool> m_known_objects;
321 Blocks that have been sent to client.
322 - These don't have to be sent again.
323 - A block is cleared from here when client says it has
324 deleted it from it's memory
326 Key is position, value is dummy.
327 No MapBlock* is stored here because the blocks can get deleted.
329 core::map<v3s16, bool> m_blocks_sent;
330 s16 m_nearest_unsent_d;
332 float m_nearest_unsent_reset_timer;
335 Blocks that are currently on the line.
336 This is used for throttling the sending of blocks.
337 - The size of this list is limited to some value
338 Block is added when it is sent with BLOCKDATA.
339 Block is removed when GOTBLOCKS is received.
340 Value is time from sending. (not used at the moment)
342 core::map<v3s16, float> m_blocks_sending;
345 Count of excess GotBlocks().
346 There is an excess amount because the client sometimes
347 gets a block so late that the server sends it again,
348 and the client then sends two GOTBLOCKs.
349 This is resetted by PrintInfo()
351 u32 m_excess_gotblocks;
353 // CPU usage optimization
354 u32 m_nothing_to_send_counter;
355 float m_nothing_to_send_pause_timer;
358 class Server : public con::PeerHandler, public MapEventReceiver,
359 public InventoryManager, public IGameDef,
360 public IBackgroundBlockEmerger
364 NOTE: Every public method should be thread-safe
368 const std::string &path_world,
369 const std::string &path_config,
370 const SubgameSpec &gamespec,
371 bool simple_singleplayer_mode
374 void start(unsigned short port);
376 // This is mainly a way to pass the time to the server.
377 // Actual processing is done in an another thread.
378 void step(float dtime);
379 // This is run by ServerThread and does the actual processing
382 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
384 core::list<PlayerInfo> getPlayerInfo();
386 // Environment must be locked when called
387 void setTimeOfDay(u32 time)
389 m_env->setTimeOfDay(time);
390 m_time_of_day_send_timer = 0;
393 bool getShutdownRequested()
395 return m_shutdown_requested;
399 Shall be called with the environment locked.
400 This is accessed by the map, which is inside the environment,
401 so it shouldn't be a problem.
403 void onMapEditEvent(MapEditEvent *event);
406 Shall be called with the environment and the connection locked.
408 Inventory* getInventory(const InventoryLocation &loc);
409 void setInventoryModified(const InventoryLocation &loc);
411 // Connection must be locked when called
412 std::wstring getStatusString();
414 void requestShutdown(void)
416 m_shutdown_requested = true;
419 // Returns -1 if failed, sound handle on success
421 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
422 void stopSound(s32 handle);
425 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
426 bool checkPriv(const std::string &name, const std::string &priv);
427 void reportPrivsModified(const std::string &name=""); // ""=all
428 void reportInventoryFormspecModified(const std::string &name);
430 // Saves g_settings to configpath given at initialization
433 void setIpBanned(const std::string &ip, const std::string &name)
435 m_banmanager.add(ip, name);
439 void unsetIpBanned(const std::string &ip_or_name)
441 m_banmanager.remove(ip_or_name);
445 std::string getBanDescription(const std::string &ip_or_name)
447 return m_banmanager.getBanDescription(ip_or_name);
450 Address getPeerAddress(u16 peer_id)
452 return m_con.GetPeerAddress(peer_id);
455 // Envlock and conlock should be locked when calling this
456 void notifyPlayer(const char *name, const std::wstring msg);
457 void notifyPlayers(const std::wstring msg);
459 void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
461 // Creates or resets inventory
462 Inventory* createDetachedInventory(const std::string &name);
464 // Envlock and conlock should be locked when using Lua
465 lua_State *getLua(){ return m_lua; }
467 // Envlock should be locked when using the rollback manager
468 IRollbackManager *getRollbackManager(){ return m_rollback; }
470 //TODO: determine what should be locked when accessing the emerge manager
471 EmergeManager *getEmergeManager(){ return m_emerge; }
473 BiomeDefManager *getBiomeDef(){ return m_biomedef; }
475 // actions: time-reversed list
476 // Return value: success/failure
477 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
478 std::list<std::string> *log);
480 // IGameDef interface
482 virtual IItemDefManager* getItemDefManager();
483 virtual INodeDefManager* getNodeDefManager();
484 virtual ICraftDefManager* getCraftDefManager();
485 virtual ITextureSource* getTextureSource();
486 virtual IShaderSource* getShaderSource();
487 virtual u16 allocateUnknownNodeId(const std::string &name);
488 virtual ISoundManager* getSoundManager();
489 virtual MtEventManager* getEventManager();
490 virtual IRollbackReportSink* getRollbackReportSink();
492 IWritableItemDefManager* getWritableItemDefManager();
493 IWritableNodeDefManager* getWritableNodeDefManager();
494 IWritableCraftDefManager* getWritableCraftDefManager();
496 const ModSpec* getModSpec(const std::string &modname);
497 void getModNames(core::list<std::string> &modlist);
498 std::string getBuiltinLuaPath();
500 std::string getWorldPath(){ return m_path_world; }
502 bool isSingleplayer(){ return m_simple_singleplayer_mode; }
504 void setAsyncFatalError(const std::string &error)
506 m_async_fatal_error.set(error);
509 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
512 // con::PeerHandler implementation.
513 // These queue stuff to be processed by handlePeerChanges().
514 // As of now, these create and remove clients and players.
515 void peerAdded(con::Peer *peer);
516 void deletingPeer(con::Peer *peer, bool timeout);
522 static void SendMovement(con::Connection &con, u16 peer_id);
523 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
524 static void SendAccessDenied(con::Connection &con, u16 peer_id,
525 const std::wstring &reason);
526 static void SendDeathscreen(con::Connection &con, u16 peer_id,
527 bool set_camera_point_target, v3f camera_point_target);
528 static void SendItemDef(con::Connection &con, u16 peer_id,
529 IItemDefManager *itemdef);
530 static void SendNodeDef(con::Connection &con, u16 peer_id,
531 INodeDefManager *nodedef, u16 protocol_version);
534 Non-static send methods.
535 Conlock should be always used.
536 Envlock usage is documented badly but it's easy to figure out
537 which ones access the environment.
540 // Envlock and conlock should be locked when calling these
541 void SendInventory(u16 peer_id);
542 void SendChatMessage(u16 peer_id, const std::wstring &message);
543 void BroadcastChatMessage(const std::wstring &message);
544 void SendPlayerHP(u16 peer_id);
545 void SendMovePlayer(u16 peer_id);
546 void SendPlayerPrivileges(u16 peer_id);
547 void SendPlayerInventoryFormspec(u16 peer_id);
548 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
550 Send a node removal/addition event to all clients except ignore_id.
551 Additionally, if far_players!=NULL, players further away than
552 far_d_nodes are ignored and their peer_ids are added to far_players
554 // Envlock and conlock should be locked when calling these
555 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
556 core::list<u16> *far_players=NULL, float far_d_nodes=100);
557 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
558 core::list<u16> *far_players=NULL, float far_d_nodes=100);
559 void setBlockNotSent(v3s16 p);
561 // Environment and Connection must be locked when called
562 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
564 // Sends blocks to clients (locks env and con on its own)
565 void SendBlocks(float dtime);
567 void fillMediaCache();
568 void sendMediaAnnouncement(u16 peer_id);
569 void sendRequestedMedia(u16 peer_id,
570 const core::list<MediaRequest> &tosend);
572 void sendDetachedInventory(const std::string &name, u16 peer_id);
573 void sendDetachedInventoryToAll(const std::string &name);
574 void sendDetachedInventories(u16 peer_id);
580 void DiePlayer(u16 peer_id);
581 void RespawnPlayer(u16 peer_id);
583 void UpdateCrafting(u16 peer_id);
585 // When called, connection mutex should be locked
586 RemoteClient* getClient(u16 peer_id);
588 // When called, environment mutex should be locked
589 std::string getPlayerName(u16 peer_id)
591 Player *player = m_env->getPlayer(peer_id);
593 return "[id="+itos(peer_id)+"]";
594 return player->getName();
597 // When called, environment mutex should be locked
598 PlayerSAO* getPlayerSAO(u16 peer_id)
600 Player *player = m_env->getPlayer(peer_id);
603 return player->getPlayerSAO();
607 Get a player from memory or creates one.
608 If player is already connected, return NULL
609 Does not verify/modify auth info and password.
611 Call with env and con locked.
613 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
615 // Locks environment and connection by its own
617 void handlePeerChange(PeerChange &c);
618 void handlePeerChanges();
625 std::string m_path_world;
626 // Path to user's configuration file ("" = no configuration file)
627 std::string m_path_config;
628 // Subgame specification
629 SubgameSpec m_gamespec;
630 // If true, do not allow multiple players and hide some multiplayer
632 bool m_simple_singleplayer_mode;
634 // Thread can set; step() will throw as ServerError
635 MutexedVariable<std::string> m_async_fatal_error;
638 float m_liquid_transform_timer;
639 float m_liquid_transform_every;
640 float m_print_info_timer;
641 float m_masterserver_timer;
642 float m_objectdata_timer;
643 float m_emergethread_trigger_timer;
644 float m_savemap_timer;
645 IntervalLimiter m_map_timer_and_unload_interval;
647 // NOTE: If connection and environment are both to be locked,
648 // environment shall be locked first.
651 ServerEnvironment *m_env;
655 con::Connection m_con;
657 // Connected clients (behind the con mutex)
658 core::map<u16, RemoteClient*> m_clients;
659 u16 m_clients_number; //for announcing masterserver
662 BanManager m_banmanager;
664 // Rollback manager (behind m_env_mutex)
665 IRollbackManager *m_rollback;
666 bool m_rollback_sink_enabled;
667 bool m_enable_rollback_recording; // Updated once in a while
670 EmergeManager *m_emerge;
672 // Biome Definition Manager
673 BiomeDefManager *m_biomedef;
676 // Envlock and conlock should be locked when using Lua
679 // Item definition manager
680 IWritableItemDefManager *m_itemdef;
682 // Node definition manager
683 IWritableNodeDefManager *m_nodedef;
685 // Craft definition manager
686 IWritableCraftDefManager *m_craftdef;
689 EventManager *m_event;
692 std::vector<ModSpec> m_mods;
698 // A buffer for time steps
699 // step() increments and AsyncRunStep() run by m_thread reads it.
701 JMutex m_step_dtime_mutex;
703 // The server mainly operates in this thread
704 ServerThread m_thread;
710 // Timer for sending time of day over network
711 float m_time_of_day_send_timer;
712 // Uptime of server in seconds
713 MutexedVariable<double> m_uptime;
717 Queues stuff from peerAdded() and deletingPeer() to
731 Queue<PeerChange> m_peer_change_queue;
737 // Mod parent directory paths
738 core::list<std::string> m_modspaths;
740 bool m_shutdown_requested;
743 Map edit event queue. Automatically receives all map edits.
744 The constructor of this class registers us to receive them through
747 NOTE: Should these be moved to actually be members of
752 Queue of map edits from the environment for sending to the clients
753 This is behind m_env_mutex
755 Queue<MapEditEvent*> m_unsent_map_edit_queue;
757 Set to true when the server itself is modifying the map and does
758 all sending of information by itself.
759 This is behind m_env_mutex
761 bool m_ignore_map_edit_events;
763 If a non-empty area, map edit events contained within are left
764 unsent. Done at map generation time to speed up editing of the
765 generated area, as it will be sent anyway.
766 This is behind m_env_mutex
768 VoxelArea m_ignore_map_edit_events_area;
770 If set to !=0, the incoming MapEditEvents are modified to have
771 this peed id as the disabled recipient
772 This is behind m_env_mutex
774 u16 m_ignore_map_edit_events_peer_id;
776 friend class EmergeThread;
777 friend class RemoteClient;
779 std::map<std::string,MediaInfo> m_media;
784 std::map<s32, ServerPlayingSound> m_playing_sounds;
788 Detached inventories (behind m_env_mutex)
791 std::map<std::string, Inventory*> m_detached_inventories;
795 Runs a simple dedicated server loop.
797 Shuts down when run is set to false.
799 void dedicated_server_loop(Server &server, bool &run);