3 Copyright (C) 2010-2011 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
15 You should have received a copy of the GNU 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 "common_irrlicht.h"
29 #include "inventory.h"
33 #include "serialization.h" // For SER_FMT_VER_INVALID
34 #include "serverremoteplayer.h"
36 #include "inventorymanager.h"
40 typedef struct lua_State lua_State;
41 class IWritableItemDefManager;
42 class IWritableNodeDefManager;
43 class IWritableCraftDefManager;
46 class ServerError : public std::exception
49 ServerError(const std::string &s)
51 m_s = "ServerError: ";
54 virtual ~ServerError() throw()
56 virtual const char * what() const throw()
66 v3f findSpawnPos(ServerMap &map);
69 A structure containing the data needed for queueing the fetching
72 struct QueuedBlockEmerge
75 // key = peer_id, value = flags
76 core::map<u16, u8> peer_ids;
80 This is a thread-safe class.
82 class BlockEmergeQueue
92 JMutexAutoLock lock(m_mutex);
94 core::list<QueuedBlockEmerge*>::Iterator i;
95 for(i=m_queue.begin(); i!=m_queue.end(); i++)
97 QueuedBlockEmerge *q = *i;
103 peer_id=0 adds with nobody to send to
105 void addBlock(u16 peer_id, v3s16 pos, u8 flags)
107 DSTACK(__FUNCTION_NAME);
109 JMutexAutoLock lock(m_mutex);
114 Find if block is already in queue.
115 If it is, update the peer to it and quit.
117 core::list<QueuedBlockEmerge*>::Iterator i;
118 for(i=m_queue.begin(); i!=m_queue.end(); i++)
120 QueuedBlockEmerge *q = *i;
123 q->peer_ids[peer_id] = flags;
132 QueuedBlockEmerge *q = new QueuedBlockEmerge;
135 q->peer_ids[peer_id] = flags;
136 m_queue.push_back(q);
139 // Returned pointer must be deleted
140 // Returns NULL if queue is empty
141 QueuedBlockEmerge * pop()
143 JMutexAutoLock lock(m_mutex);
145 core::list<QueuedBlockEmerge*>::Iterator i = m_queue.begin();
146 if(i == m_queue.end())
148 QueuedBlockEmerge *q = *i;
155 JMutexAutoLock lock(m_mutex);
156 return m_queue.size();
159 u32 peerItemCount(u16 peer_id)
161 JMutexAutoLock lock(m_mutex);
165 core::list<QueuedBlockEmerge*>::Iterator i;
166 for(i=m_queue.begin(); i!=m_queue.end(); i++)
168 QueuedBlockEmerge *q = *i;
169 if(q->peer_ids.find(peer_id) != NULL)
177 core::list<QueuedBlockEmerge*> m_queue;
183 class ServerThread : public SimpleThread
189 ServerThread(Server *server):
198 class EmergeThread : public SimpleThread
204 EmergeThread(Server *server):
215 if(IsRunning() == false)
225 char name[PLAYERNAME_SIZE];
231 void PrintLine(std::ostream *s);
235 Used for queueing and sorting block transfers in containers
237 Lower priority number means higher priority.
239 struct PrioritySortedBlockTransfer
241 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
243 priority = a_priority;
247 bool operator < (PrioritySortedBlockTransfer &other)
249 return priority < other.priority;
256 struct TextureRequest
260 TextureRequest(const std::string &name_=""):
265 struct TextureInformation
268 std::string sha1_digest;
270 TextureInformation(const std::string path_="",
271 const std::string sha1_digest_=""):
273 sha1_digest(sha1_digest_)
278 struct ServerSoundParams
281 std::string to_player;
289 float max_hear_distance;
298 max_hear_distance(32*BS),
302 v3f getPos(ServerEnvironment *env, bool *pos_exists) const
304 if(pos_exists) *pos_exists = false;
309 if(pos_exists) *pos_exists = true;
314 ServerActiveObject *sao = env->getActiveObject(object);
317 if(pos_exists) *pos_exists = true;
318 return sao->getBasePosition(); }
324 struct ServerPlayingSound
326 ServerSoundParams params;
327 std::set<u16> clients; // peer ids
333 // peer_id=0 means this client has no associated peer
334 // NOTE: If client is made allowed to exist while peer doesn't,
335 // this has to be set to 0 when there is no peer.
336 // Also, the client must be moved to some other container.
338 // The serialization version to use with the client
339 u8 serialization_version;
341 u16 net_proto_version;
342 // Version is stored in here after INIT before INIT2
343 u8 pending_serialization_version;
345 bool definitions_sent;
348 m_time_from_building(9999),
349 m_excess_gotblocks(0)
352 serialization_version = SER_FMT_VER_INVALID;
353 net_proto_version = 0;
354 pending_serialization_version = SER_FMT_VER_INVALID;
355 definitions_sent = false;
356 m_nearest_unsent_d = 0;
357 m_nearest_unsent_reset_timer = 0.0;
358 m_nothing_to_send_counter = 0;
359 m_nothing_to_send_pause_timer = 0;
366 Finds block that should be sent next to the client.
367 Environment should be locked when this is called.
368 dtime is used for resetting send radius at slow interval
370 void GetNextBlocks(Server *server, float dtime,
371 core::array<PrioritySortedBlockTransfer> &dest);
373 void GotBlock(v3s16 p);
375 void SentBlock(v3s16 p);
377 void SetBlockNotSent(v3s16 p);
378 void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
382 return m_blocks_sending.size();
385 // Increments timeouts and removes timed-out blocks from list
386 // NOTE: This doesn't fix the server-not-sending-block bug
387 // because it is related to emerging, not sending.
388 //void RunSendingTimeouts(float dtime, float timeout);
390 void PrintInfo(std::ostream &o)
392 o<<"RemoteClient "<<peer_id<<": "
393 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
394 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
395 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
396 <<", m_excess_gotblocks="<<m_excess_gotblocks
398 m_excess_gotblocks = 0;
401 // Time from last placing or removing blocks
402 float m_time_from_building;
404 /*JMutex m_dig_mutex;
405 float m_dig_time_remaining;
408 v3s16 m_dig_position;*/
411 List of active objects that the client knows of.
414 core::map<u16, bool> m_known_objects;
418 Blocks that have been sent to client.
419 - These don't have to be sent again.
420 - A block is cleared from here when client says it has
421 deleted it from it's memory
423 Key is position, value is dummy.
424 No MapBlock* is stored here because the blocks can get deleted.
426 core::map<v3s16, bool> m_blocks_sent;
427 s16 m_nearest_unsent_d;
429 float m_nearest_unsent_reset_timer;
432 Blocks that are currently on the line.
433 This is used for throttling the sending of blocks.
434 - The size of this list is limited to some value
435 Block is added when it is sent with BLOCKDATA.
436 Block is removed when GOTBLOCKS is received.
437 Value is time from sending. (not used at the moment)
439 core::map<v3s16, float> m_blocks_sending;
442 Count of excess GotBlocks().
443 There is an excess amount because the client sometimes
444 gets a block so late that the server sends it again,
445 and the client then sends two GOTBLOCKs.
446 This is resetted by PrintInfo()
448 u32 m_excess_gotblocks;
450 // CPU usage optimization
451 u32 m_nothing_to_send_counter;
452 float m_nothing_to_send_pause_timer;
455 class Server : public con::PeerHandler, public MapEventReceiver,
456 public InventoryManager, public IGameDef,
457 public IBackgroundBlockEmerger
461 NOTE: Every public method should be thread-safe
465 const std::string &path_world,
466 const std::string &path_config,
467 const SubgameSpec &gamespec,
468 bool simple_singleplayer_mode
471 void start(unsigned short port);
473 // This is mainly a way to pass the time to the server.
474 // Actual processing is done in an another thread.
475 void step(float dtime);
476 // This is run by ServerThread and does the actual processing
479 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
481 core::list<PlayerInfo> getPlayerInfo();
483 // Environment must be locked when called
484 void setTimeOfDay(u32 time)
486 m_env->setTimeOfDay(time);
487 m_time_of_day_send_timer = 0;
490 bool getShutdownRequested()
492 return m_shutdown_requested;
496 Shall be called with the environment locked.
497 This is accessed by the map, which is inside the environment,
498 so it shouldn't be a problem.
500 void onMapEditEvent(MapEditEvent *event);
503 Shall be called with the environment and the connection locked.
505 Inventory* getInventory(const InventoryLocation &loc);
506 std::string getInventoryOwner(const InventoryLocation &loc);
507 void setInventoryModified(const InventoryLocation &loc);
509 // Connection must be locked when called
510 std::wstring getStatusString();
512 void requestShutdown(void)
514 m_shutdown_requested = true;
517 // Envlock and conlock should be locked when calling this
518 void SendMovePlayer(Player *player);
520 // Returns -1 if failed, sound handle on success
522 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
523 void stopSound(s32 handle);
526 u64 getPlayerAuthPrivs(const std::string &name);
527 void setPlayerAuthPrivs(const std::string &name, u64 privs);
528 u64 getPlayerEffectivePrivs(const std::string &name);
530 // Changes a player's password, password must be given as plaintext
531 // If the player doesn't exist, a new entry is added to the auth manager
532 void setPlayerPassword(const std::string &name, const std::wstring &password);
534 // Saves g_settings to configpath given at initialization
537 void setIpBanned(const std::string &ip, const std::string &name)
539 m_banmanager.add(ip, name);
543 void unsetIpBanned(const std::string &ip_or_name)
545 m_banmanager.remove(ip_or_name);
549 std::string getBanDescription(const std::string &ip_or_name)
551 return m_banmanager.getBanDescription(ip_or_name);
554 Address getPeerAddress(u16 peer_id)
556 return m_con.GetPeerAddress(peer_id);
559 // Envlock and conlock should be locked when calling this
560 void notifyPlayer(const char *name, const std::wstring msg);
561 void notifyPlayers(const std::wstring msg);
563 void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
565 // Envlock and conlock should be locked when using Lua
566 lua_State *getLua(){ return m_lua; }
568 // IGameDef interface
570 virtual IItemDefManager* getItemDefManager();
571 virtual INodeDefManager* getNodeDefManager();
572 virtual ICraftDefManager* getCraftDefManager();
573 virtual ITextureSource* getTextureSource();
574 virtual u16 allocateUnknownNodeId(const std::string &name);
575 virtual ISoundManager* getSoundManager();
576 virtual MtEventManager* getEventManager();
578 IWritableItemDefManager* getWritableItemDefManager();
579 IWritableNodeDefManager* getWritableNodeDefManager();
580 IWritableCraftDefManager* getWritableCraftDefManager();
582 const ModSpec* getModSpec(const std::string &modname);
584 std::string getWorldPath(){ return m_path_world; }
586 void setAsyncFatalError(const std::string &error)
588 m_async_fatal_error.set(error);
593 // con::PeerHandler implementation.
594 // These queue stuff to be processed by handlePeerChanges().
595 // As of now, these create and remove clients and players.
596 void peerAdded(con::Peer *peer);
597 void deletingPeer(con::Peer *peer, bool timeout);
603 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
604 static void SendAccessDenied(con::Connection &con, u16 peer_id,
605 const std::wstring &reason);
606 static void SendDeathscreen(con::Connection &con, u16 peer_id,
607 bool set_camera_point_target, v3f camera_point_target);
608 static void SendItemDef(con::Connection &con, u16 peer_id,
609 IItemDefManager *itemdef);
610 static void SendNodeDef(con::Connection &con, u16 peer_id,
611 INodeDefManager *nodedef);
614 Non-static send methods.
615 Conlock should be always used.
616 Envlock usage is documented badly but it's easy to figure out
617 which ones access the environment.
620 // Envlock and conlock should be locked when calling these
621 void SendInventory(u16 peer_id);
622 // send wielded item info about player to all
623 void SendWieldedItem(const ServerRemotePlayer *srp);
624 // send wielded item info about all players to all players
625 void SendPlayerItems();
626 void SendChatMessage(u16 peer_id, const std::wstring &message);
627 void BroadcastChatMessage(const std::wstring &message);
628 void SendPlayerHP(Player *player);
630 Send a node removal/addition event to all clients except ignore_id.
631 Additionally, if far_players!=NULL, players further away than
632 far_d_nodes are ignored and their peer_ids are added to far_players
634 // Envlock and conlock should be locked when calling these
635 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
636 core::list<u16> *far_players=NULL, float far_d_nodes=100);
637 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
638 core::list<u16> *far_players=NULL, float far_d_nodes=100);
639 void setBlockNotSent(v3s16 p);
641 // Environment and Connection must be locked when called
642 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
644 // Sends blocks to clients (locks env and con on its own)
645 void SendBlocks(float dtime);
647 void PrepareTextures();
649 void SendTextureAnnouncement(u16 peer_id);
651 void SendTexturesRequested(u16 peer_id,core::list<TextureRequest> tosend);
657 void DiePlayer(Player *player);
658 void RespawnPlayer(Player *player);
660 void UpdateCrafting(u16 peer_id);
662 // When called, connection mutex should be locked
663 RemoteClient* getClient(u16 peer_id);
665 // When called, environment mutex should be locked
666 std::string getPlayerName(u16 peer_id)
668 Player *player = m_env->getPlayer(peer_id);
670 return "[id="+itos(peer_id)+"]";
671 return player->getName();
675 Get a player from memory or creates one.
676 If player is already connected, return NULL
677 Does not verify/modify auth info and password.
679 Call with env and con locked.
681 ServerRemotePlayer *emergePlayer(const char *name, u16 peer_id);
683 // Locks environment and connection by its own
685 void handlePeerChange(PeerChange &c);
686 void handlePeerChanges();
688 u64 getPlayerPrivs(Player *player);
695 std::string m_path_world;
696 // Path to user's configuration file ("" = no configuration file)
697 std::string m_path_config;
698 // Subgame specification
699 SubgameSpec m_gamespec;
700 // If true, do not allow multiple players and hide some multiplayer
702 bool m_simple_singleplayer_mode;
704 // Thread can set; step() will throw as ServerError
705 MutexedVariable<std::string> m_async_fatal_error;
708 float m_liquid_transform_timer;
709 float m_print_info_timer;
710 float m_objectdata_timer;
711 float m_emergethread_trigger_timer;
712 float m_savemap_timer;
713 IntervalLimiter m_map_timer_and_unload_interval;
715 // NOTE: If connection and environment are both to be locked,
716 // environment shall be locked first.
719 ServerEnvironment *m_env;
723 con::Connection m_con;
725 // Connected clients (behind the con mutex)
726 core::map<u16, RemoteClient*> m_clients;
728 // User authentication
729 AuthManager m_authmanager;
732 BanManager m_banmanager;
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 core::list<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 set to !=0, the incoming MapEditEvents are modified to have
827 this peed id as the disabled recipient
828 This is behind m_env_mutex
830 u16 m_ignore_map_edit_events_peer_id;
832 friend class EmergeThread;
833 friend class RemoteClient;
835 std::map<std::string,TextureInformation> m_Textures;
840 std::map<s32, ServerPlayingSound> m_playing_sounds;
845 Runs a simple dedicated server loop.
847 Shuts down when run is set to false.
849 void dedicated_server_loop(Server &server, bool &run);