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 A structure containing the data needed for queueing the fetching
80 struct QueuedBlockEmerge
83 // key = peer_id, value = flags
84 core::map<u16, u8> peer_ids;
88 This is a thread-safe class.
90 class BlockEmergeQueue
100 JMutexAutoLock lock(m_mutex);
102 core::list<QueuedBlockEmerge*>::Iterator i;
103 for(i=m_queue.begin(); i!=m_queue.end(); i++)
105 QueuedBlockEmerge *q = *i;
111 peer_id=0 adds with nobody to send to
113 void addBlock(u16 peer_id, v3s16 pos, u8 flags)
115 DSTACK(__FUNCTION_NAME);
117 JMutexAutoLock lock(m_mutex);
122 Find if block is already in queue.
123 If it is, update the peer to it and quit.
125 core::list<QueuedBlockEmerge*>::Iterator i;
126 for(i=m_queue.begin(); i!=m_queue.end(); i++) {
127 QueuedBlockEmerge *q = *i;
129 q->peer_ids[peer_id] = flags;
138 QueuedBlockEmerge *q = new QueuedBlockEmerge;
141 q->peer_ids[peer_id] = flags;
142 m_queue.push_back(q);
145 // Returned pointer must be deleted
146 // Returns NULL if queue is empty
147 QueuedBlockEmerge * pop()
149 JMutexAutoLock lock(m_mutex);
151 core::list<QueuedBlockEmerge*>::Iterator i = m_queue.begin();
152 if(i == m_queue.end())
154 QueuedBlockEmerge *q = *i;
161 JMutexAutoLock lock(m_mutex);
162 return m_queue.size();
165 u32 peerItemCount(u16 peer_id)
167 JMutexAutoLock lock(m_mutex);
171 core::list<QueuedBlockEmerge*>::Iterator i;
172 for(i=m_queue.begin(); i!=m_queue.end(); i++)
174 QueuedBlockEmerge *q = *i;
175 if(q->peer_ids.find(peer_id) != NULL)
183 core::list<QueuedBlockEmerge*> m_queue;
189 class ServerThread : public SimpleThread
195 ServerThread(Server *server):
207 char name[PLAYERNAME_SIZE];
213 void PrintLine(std::ostream *s);
217 Used for queueing and sorting block transfers in containers
219 Lower priority number means higher priority.
221 struct PrioritySortedBlockTransfer
223 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
225 priority = a_priority;
229 bool operator < (PrioritySortedBlockTransfer &other)
231 return priority < other.priority;
242 MediaRequest(const std::string &name_=""):
250 std::string sha1_digest;
252 MediaInfo(const std::string path_="",
253 const std::string sha1_digest_=""):
255 sha1_digest(sha1_digest_)
260 struct ServerSoundParams
263 std::string to_player;
271 float max_hear_distance;
280 max_hear_distance(32*BS),
284 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
287 struct ServerPlayingSound
289 ServerSoundParams params;
290 std::set<u16> clients; // peer ids
296 // peer_id=0 means this client has no associated peer
297 // NOTE: If client is made allowed to exist while peer doesn't,
298 // this has to be set to 0 when there is no peer.
299 // Also, the client must be moved to some other container.
301 // The serialization version to use with the client
302 u8 serialization_version;
304 u16 net_proto_version;
305 // Version is stored in here after INIT before INIT2
306 u8 pending_serialization_version;
308 bool definitions_sent;
311 m_time_from_building(9999),
312 m_excess_gotblocks(0)
315 serialization_version = SER_FMT_VER_INVALID;
316 net_proto_version = 0;
317 pending_serialization_version = SER_FMT_VER_INVALID;
318 definitions_sent = false;
319 m_nearest_unsent_d = 0;
320 m_nearest_unsent_reset_timer = 0.0;
321 m_nothing_to_send_counter = 0;
322 m_nothing_to_send_pause_timer = 0;
329 Finds block that should be sent next to the client.
330 Environment should be locked when this is called.
331 dtime is used for resetting send radius at slow interval
333 void GetNextBlocks(Server *server, float dtime,
334 core::array<PrioritySortedBlockTransfer> &dest);
336 void GotBlock(v3s16 p);
338 void SentBlock(v3s16 p);
340 void SetBlockNotSent(v3s16 p);
341 void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
345 return m_blocks_sending.size();
348 // Increments timeouts and removes timed-out blocks from list
349 // NOTE: This doesn't fix the server-not-sending-block bug
350 // because it is related to emerging, not sending.
351 //void RunSendingTimeouts(float dtime, float timeout);
353 void PrintInfo(std::ostream &o)
355 o<<"RemoteClient "<<peer_id<<": "
356 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
357 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
358 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
359 <<", m_excess_gotblocks="<<m_excess_gotblocks
361 m_excess_gotblocks = 0;
364 // Time from last placing or removing blocks
365 float m_time_from_building;
367 /*JMutex m_dig_mutex;
368 float m_dig_time_remaining;
371 v3s16 m_dig_position;*/
374 List of active objects that the client knows of.
377 core::map<u16, bool> m_known_objects;
381 Blocks that have been sent to client.
382 - These don't have to be sent again.
383 - A block is cleared from here when client says it has
384 deleted it from it's memory
386 Key is position, value is dummy.
387 No MapBlock* is stored here because the blocks can get deleted.
389 core::map<v3s16, bool> m_blocks_sent;
390 s16 m_nearest_unsent_d;
392 float m_nearest_unsent_reset_timer;
395 Blocks that are currently on the line.
396 This is used for throttling the sending of blocks.
397 - The size of this list is limited to some value
398 Block is added when it is sent with BLOCKDATA.
399 Block is removed when GOTBLOCKS is received.
400 Value is time from sending. (not used at the moment)
402 core::map<v3s16, float> m_blocks_sending;
405 Count of excess GotBlocks().
406 There is an excess amount because the client sometimes
407 gets a block so late that the server sends it again,
408 and the client then sends two GOTBLOCKs.
409 This is resetted by PrintInfo()
411 u32 m_excess_gotblocks;
413 // CPU usage optimization
414 u32 m_nothing_to_send_counter;
415 float m_nothing_to_send_pause_timer;
418 class Server : public con::PeerHandler, public MapEventReceiver,
419 public InventoryManager, public IGameDef,
420 public IBackgroundBlockEmerger
424 NOTE: Every public method should be thread-safe
428 const std::string &path_world,
429 const std::string &path_config,
430 const SubgameSpec &gamespec,
431 bool simple_singleplayer_mode
434 void start(unsigned short port);
436 // This is mainly a way to pass the time to the server.
437 // Actual processing is done in an another thread.
438 void step(float dtime);
439 // This is run by ServerThread and does the actual processing
442 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
444 core::list<PlayerInfo> getPlayerInfo();
446 // Environment must be locked when called
447 void setTimeOfDay(u32 time)
449 m_env->setTimeOfDay(time);
450 m_time_of_day_send_timer = 0;
453 bool getShutdownRequested()
455 return m_shutdown_requested;
459 Shall be called with the environment locked.
460 This is accessed by the map, which is inside the environment,
461 so it shouldn't be a problem.
463 void onMapEditEvent(MapEditEvent *event);
466 Shall be called with the environment and the connection locked.
468 Inventory* getInventory(const InventoryLocation &loc);
469 void setInventoryModified(const InventoryLocation &loc);
471 // Connection must be locked when called
472 std::wstring getStatusString();
474 void requestShutdown(void)
476 m_shutdown_requested = true;
479 // Returns -1 if failed, sound handle on success
481 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
482 void stopSound(s32 handle);
485 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
486 bool checkPriv(const std::string &name, const std::string &priv);
487 void reportPrivsModified(const std::string &name=""); // ""=all
488 void reportInventoryFormspecModified(const std::string &name);
490 // Saves g_settings to configpath given at initialization
493 void setIpBanned(const std::string &ip, const std::string &name)
495 m_banmanager.add(ip, name);
499 void unsetIpBanned(const std::string &ip_or_name)
501 m_banmanager.remove(ip_or_name);
505 std::string getBanDescription(const std::string &ip_or_name)
507 return m_banmanager.getBanDescription(ip_or_name);
510 Address getPeerAddress(u16 peer_id)
512 return m_con.GetPeerAddress(peer_id);
515 // Envlock and conlock should be locked when calling this
516 void notifyPlayer(const char *name, const std::wstring msg);
517 void notifyPlayers(const std::wstring msg);
519 void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
521 // Creates or resets inventory
522 Inventory* createDetachedInventory(const std::string &name);
524 // Envlock and conlock should be locked when using Lua
525 lua_State *getLua(){ return m_lua; }
527 // Envlock should be locked when using the rollback manager
528 IRollbackManager *getRollbackManager(){ return m_rollback; }
530 //TODO: determine what should be locked when accessing the emerge manager
531 EmergeManager *getEmergeManager(){ return m_emerge; }
533 BiomeDefManager *getBiomeDef(){ return m_biomedef; }
535 // actions: time-reversed list
536 // Return value: success/failure
537 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
538 std::list<std::string> *log);
540 // IGameDef interface
542 virtual IItemDefManager* getItemDefManager();
543 virtual INodeDefManager* getNodeDefManager();
544 virtual ICraftDefManager* getCraftDefManager();
545 virtual ITextureSource* getTextureSource();
546 virtual IShaderSource* getShaderSource();
547 virtual u16 allocateUnknownNodeId(const std::string &name);
548 virtual ISoundManager* getSoundManager();
549 virtual MtEventManager* getEventManager();
550 virtual IRollbackReportSink* getRollbackReportSink();
552 IWritableItemDefManager* getWritableItemDefManager();
553 IWritableNodeDefManager* getWritableNodeDefManager();
554 IWritableCraftDefManager* getWritableCraftDefManager();
556 const ModSpec* getModSpec(const std::string &modname);
557 void getModNames(core::list<std::string> &modlist);
558 std::string getBuiltinLuaPath();
560 std::string getWorldPath(){ return m_path_world; }
562 bool isSingleplayer(){ return m_simple_singleplayer_mode; }
564 void setAsyncFatalError(const std::string &error)
566 m_async_fatal_error.set(error);
569 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
572 // con::PeerHandler implementation.
573 // These queue stuff to be processed by handlePeerChanges().
574 // As of now, these create and remove clients and players.
575 void peerAdded(con::Peer *peer);
576 void deletingPeer(con::Peer *peer, bool timeout);
582 static void SendMovement(con::Connection &con, u16 peer_id);
583 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
584 static void SendAccessDenied(con::Connection &con, u16 peer_id,
585 const std::wstring &reason);
586 static void SendDeathscreen(con::Connection &con, u16 peer_id,
587 bool set_camera_point_target, v3f camera_point_target);
588 static void SendItemDef(con::Connection &con, u16 peer_id,
589 IItemDefManager *itemdef);
590 static void SendNodeDef(con::Connection &con, u16 peer_id,
591 INodeDefManager *nodedef, u16 protocol_version);
594 Non-static send methods.
595 Conlock should be always used.
596 Envlock usage is documented badly but it's easy to figure out
597 which ones access the environment.
600 // Envlock and conlock should be locked when calling these
601 void SendInventory(u16 peer_id);
602 void SendChatMessage(u16 peer_id, const std::wstring &message);
603 void BroadcastChatMessage(const std::wstring &message);
604 void SendPlayerHP(u16 peer_id);
605 void SendMovePlayer(u16 peer_id);
606 void SendPlayerPrivileges(u16 peer_id);
607 void SendPlayerInventoryFormspec(u16 peer_id);
608 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
610 Send a node removal/addition event to all clients except ignore_id.
611 Additionally, if far_players!=NULL, players further away than
612 far_d_nodes are ignored and their peer_ids are added to far_players
614 // Envlock and conlock should be locked when calling these
615 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
616 core::list<u16> *far_players=NULL, float far_d_nodes=100);
617 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
618 core::list<u16> *far_players=NULL, float far_d_nodes=100);
619 void setBlockNotSent(v3s16 p);
621 // Environment and Connection must be locked when called
622 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
624 // Sends blocks to clients (locks env and con on its own)
625 void SendBlocks(float dtime);
627 void fillMediaCache();
628 void sendMediaAnnouncement(u16 peer_id);
629 void sendRequestedMedia(u16 peer_id,
630 const core::list<MediaRequest> &tosend);
632 void sendDetachedInventory(const std::string &name, u16 peer_id);
633 void sendDetachedInventoryToAll(const std::string &name);
634 void sendDetachedInventories(u16 peer_id);
640 void DiePlayer(u16 peer_id);
641 void RespawnPlayer(u16 peer_id);
643 void UpdateCrafting(u16 peer_id);
645 // When called, connection mutex should be locked
646 RemoteClient* getClient(u16 peer_id);
648 // When called, environment mutex should be locked
649 std::string getPlayerName(u16 peer_id)
651 Player *player = m_env->getPlayer(peer_id);
653 return "[id="+itos(peer_id)+"]";
654 return player->getName();
657 // When called, environment mutex should be locked
658 PlayerSAO* getPlayerSAO(u16 peer_id)
660 Player *player = m_env->getPlayer(peer_id);
663 return player->getPlayerSAO();
667 Get a player from memory or creates one.
668 If player is already connected, return NULL
669 Does not verify/modify auth info and password.
671 Call with env and con locked.
673 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
675 // Locks environment and connection by its own
677 void handlePeerChange(PeerChange &c);
678 void handlePeerChanges();
685 std::string m_path_world;
686 // Path to user's configuration file ("" = no configuration file)
687 std::string m_path_config;
688 // Subgame specification
689 SubgameSpec m_gamespec;
690 // If true, do not allow multiple players and hide some multiplayer
692 bool m_simple_singleplayer_mode;
694 // Thread can set; step() will throw as ServerError
695 MutexedVariable<std::string> m_async_fatal_error;
698 float m_liquid_transform_timer;
699 float m_print_info_timer;
700 float m_masterserver_timer;
701 float m_objectdata_timer;
702 float m_emergethread_trigger_timer;
703 float m_savemap_timer;
704 IntervalLimiter m_map_timer_and_unload_interval;
706 // NOTE: If connection and environment are both to be locked,
707 // environment shall be locked first.
710 ServerEnvironment *m_env;
714 con::Connection m_con;
716 // Connected clients (behind the con mutex)
717 core::map<u16, RemoteClient*> m_clients;
718 u16 m_clients_number; //for announcing masterserver
721 BanManager m_banmanager;
723 // Rollback manager (behind m_env_mutex)
724 IRollbackManager *m_rollback;
725 bool m_rollback_sink_enabled;
726 bool m_enable_rollback_recording; // Updated once in a while
729 EmergeManager *m_emerge;
731 // Biome Definition Manager
732 BiomeDefManager *m_biomedef;
735 // Envlock and conlock should be locked when using Lua
738 // Item definition manager
739 IWritableItemDefManager *m_itemdef;
741 // Node definition manager
742 IWritableNodeDefManager *m_nodedef;
744 // Craft definition manager
745 IWritableCraftDefManager *m_craftdef;
748 EventManager *m_event;
751 std::vector<ModSpec> m_mods;
757 // A buffer for time steps
758 // step() increments and AsyncRunStep() run by m_thread reads it.
760 JMutex m_step_dtime_mutex;
762 // The server mainly operates in this thread
763 ServerThread m_thread;
764 // This thread fetches and generates map
765 //EmergeThread m_emergethread;
766 // Queue of block coordinates to be processed by the emerge thread
767 //BlockEmergeQueue m_emerge_queue;
773 // Timer for sending time of day over network
774 float m_time_of_day_send_timer;
775 // Uptime of server in seconds
776 MutexedVariable<double> m_uptime;
780 Queues stuff from peerAdded() and deletingPeer() to
794 Queue<PeerChange> m_peer_change_queue;
800 // Mod parent directory paths
801 core::list<std::string> m_modspaths;
803 bool m_shutdown_requested;
806 Map edit event queue. Automatically receives all map edits.
807 The constructor of this class registers us to receive them through
810 NOTE: Should these be moved to actually be members of
815 Queue of map edits from the environment for sending to the clients
816 This is behind m_env_mutex
818 Queue<MapEditEvent*> m_unsent_map_edit_queue;
820 Set to true when the server itself is modifying the map and does
821 all sending of information by itself.
822 This is behind m_env_mutex
824 bool m_ignore_map_edit_events;
826 If a non-empty area, map edit events contained within are left
827 unsent. Done at map generation time to speed up editing of the
828 generated area, as it will be sent anyway.
829 This is behind m_env_mutex
831 VoxelArea m_ignore_map_edit_events_area;
833 If set to !=0, the incoming MapEditEvents are modified to have
834 this peed id as the disabled recipient
835 This is behind m_env_mutex
837 u16 m_ignore_map_edit_events_peer_id;
839 friend class EmergeThread;
840 friend class RemoteClient;
842 std::map<std::string,MediaInfo> m_media;
847 std::map<s32, ServerPlayingSound> m_playing_sounds;
851 Detached inventories (behind m_env_mutex)
854 std::map<std::string, Inventory*> m_detached_inventories;
858 Runs a simple dedicated server loop.
860 Shuts down when run is set to false.
862 void dedicated_server_loop(Server &server, bool &run);