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"
39 typedef struct lua_State lua_State;
40 class IWritableItemDefManager;
41 class IWritableNodeDefManager;
42 class IWritableCraftDefManager;
44 class ServerError : public std::exception
47 ServerError(const std::string &s)
49 m_s = "ServerError: ";
52 virtual ~ServerError() throw()
54 virtual const char * what() const throw()
64 v3f findSpawnPos(ServerMap &map);
67 A structure containing the data needed for queueing the fetching
70 struct QueuedBlockEmerge
73 // key = peer_id, value = flags
74 core::map<u16, u8> peer_ids;
78 This is a thread-safe class.
80 class BlockEmergeQueue
90 JMutexAutoLock lock(m_mutex);
92 core::list<QueuedBlockEmerge*>::Iterator i;
93 for(i=m_queue.begin(); i!=m_queue.end(); i++)
95 QueuedBlockEmerge *q = *i;
101 peer_id=0 adds with nobody to send to
103 void addBlock(u16 peer_id, v3s16 pos, u8 flags)
105 DSTACK(__FUNCTION_NAME);
107 JMutexAutoLock lock(m_mutex);
112 Find if block is already in queue.
113 If it is, update the peer to it and quit.
115 core::list<QueuedBlockEmerge*>::Iterator i;
116 for(i=m_queue.begin(); i!=m_queue.end(); i++)
118 QueuedBlockEmerge *q = *i;
121 q->peer_ids[peer_id] = flags;
130 QueuedBlockEmerge *q = new QueuedBlockEmerge;
133 q->peer_ids[peer_id] = flags;
134 m_queue.push_back(q);
137 // Returned pointer must be deleted
138 // Returns NULL if queue is empty
139 QueuedBlockEmerge * pop()
141 JMutexAutoLock lock(m_mutex);
143 core::list<QueuedBlockEmerge*>::Iterator i = m_queue.begin();
144 if(i == m_queue.end())
146 QueuedBlockEmerge *q = *i;
153 JMutexAutoLock lock(m_mutex);
154 return m_queue.size();
157 u32 peerItemCount(u16 peer_id)
159 JMutexAutoLock lock(m_mutex);
163 core::list<QueuedBlockEmerge*>::Iterator i;
164 for(i=m_queue.begin(); i!=m_queue.end(); i++)
166 QueuedBlockEmerge *q = *i;
167 if(q->peer_ids.find(peer_id) != NULL)
175 core::list<QueuedBlockEmerge*> m_queue;
181 class ServerThread : public SimpleThread
187 ServerThread(Server *server):
196 class EmergeThread : public SimpleThread
202 EmergeThread(Server *server):
213 if(IsRunning() == false)
223 char name[PLAYERNAME_SIZE];
229 void PrintLine(std::ostream *s);
233 Used for queueing and sorting block transfers in containers
235 Lower priority number means higher priority.
237 struct PrioritySortedBlockTransfer
239 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
241 priority = a_priority;
245 bool operator < (PrioritySortedBlockTransfer &other)
247 return priority < other.priority;
254 struct TextureRequest
258 TextureRequest(const std::string &name_=""):
263 struct TextureInformation
266 std::string sha1_digest;
268 TextureInformation(const std::string path_="",
269 const std::string sha1_digest_=""):
271 sha1_digest(sha1_digest_)
279 // peer_id=0 means this client has no associated peer
280 // NOTE: If client is made allowed to exist while peer doesn't,
281 // this has to be set to 0 when there is no peer.
282 // Also, the client must be moved to some other container.
284 // The serialization version to use with the client
285 u8 serialization_version;
287 u16 net_proto_version;
288 // Version is stored in here after INIT before INIT2
289 u8 pending_serialization_version;
291 bool definitions_sent;
294 m_time_from_building(9999),
295 m_excess_gotblocks(0)
298 serialization_version = SER_FMT_VER_INVALID;
299 net_proto_version = 0;
300 pending_serialization_version = SER_FMT_VER_INVALID;
301 definitions_sent = false;
302 m_nearest_unsent_d = 0;
303 m_nearest_unsent_reset_timer = 0.0;
304 m_nothing_to_send_counter = 0;
305 m_nothing_to_send_pause_timer = 0;
312 Finds block that should be sent next to the client.
313 Environment should be locked when this is called.
314 dtime is used for resetting send radius at slow interval
316 void GetNextBlocks(Server *server, float dtime,
317 core::array<PrioritySortedBlockTransfer> &dest);
319 void GotBlock(v3s16 p);
321 void SentBlock(v3s16 p);
323 void SetBlockNotSent(v3s16 p);
324 void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
328 return m_blocks_sending.size();
331 // Increments timeouts and removes timed-out blocks from list
332 // NOTE: This doesn't fix the server-not-sending-block bug
333 // because it is related to emerging, not sending.
334 //void RunSendingTimeouts(float dtime, float timeout);
336 void PrintInfo(std::ostream &o)
338 o<<"RemoteClient "<<peer_id<<": "
339 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
340 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
341 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
342 <<", m_excess_gotblocks="<<m_excess_gotblocks
344 m_excess_gotblocks = 0;
347 // Time from last placing or removing blocks
348 float m_time_from_building;
350 /*JMutex m_dig_mutex;
351 float m_dig_time_remaining;
354 v3s16 m_dig_position;*/
357 List of active objects that the client knows of.
360 core::map<u16, bool> m_known_objects;
364 Blocks that have been sent to client.
365 - These don't have to be sent again.
366 - A block is cleared from here when client says it has
367 deleted it from it's memory
369 Key is position, value is dummy.
370 No MapBlock* is stored here because the blocks can get deleted.
372 core::map<v3s16, bool> m_blocks_sent;
373 s16 m_nearest_unsent_d;
375 float m_nearest_unsent_reset_timer;
378 Blocks that are currently on the line.
379 This is used for throttling the sending of blocks.
380 - The size of this list is limited to some value
381 Block is added when it is sent with BLOCKDATA.
382 Block is removed when GOTBLOCKS is received.
383 Value is time from sending. (not used at the moment)
385 core::map<v3s16, float> m_blocks_sending;
388 Count of excess GotBlocks().
389 There is an excess amount because the client sometimes
390 gets a block so late that the server sends it again,
391 and the client then sends two GOTBLOCKs.
392 This is resetted by PrintInfo()
394 u32 m_excess_gotblocks;
396 // CPU usage optimization
397 u32 m_nothing_to_send_counter;
398 float m_nothing_to_send_pause_timer;
401 class Server : public con::PeerHandler, public MapEventReceiver,
402 public InventoryManager, public IGameDef,
403 public IBackgroundBlockEmerger
407 NOTE: Every public method should be thread-safe
411 const std::string &path_world,
412 const std::string &path_config,
413 const SubgameSpec &gamespec
416 void start(unsigned short port);
418 // This is mainly a way to pass the time to the server.
419 // Actual processing is done in an another thread.
420 void step(float dtime);
421 // This is run by ServerThread and does the actual processing
424 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
426 core::list<PlayerInfo> getPlayerInfo();
428 /*u32 getDayNightRatio()
430 return time_to_daynight_ratio(m_time_of_day.get());
433 // Environment must be locked when called
434 void setTimeOfDay(u32 time)
436 m_env->setTimeOfDay(time);
437 m_time_of_day_send_timer = 0;
440 bool getShutdownRequested()
442 return m_shutdown_requested;
446 Shall be called with the environment locked.
447 This is accessed by the map, which is inside the environment,
448 so it shouldn't be a problem.
450 void onMapEditEvent(MapEditEvent *event);
453 Shall be called with the environment and the connection locked.
455 Inventory* getInventory(const InventoryLocation &loc);
456 std::string getInventoryOwner(const InventoryLocation &loc);
457 void setInventoryModified(const InventoryLocation &loc);
459 // Connection must be locked when called
460 std::wstring getStatusString();
462 void requestShutdown(void)
464 m_shutdown_requested = true;
468 // Envlock and conlock should be locked when calling this
469 void SendMovePlayer(Player *player);
471 u64 getPlayerAuthPrivs(const std::string &name)
474 return m_authmanager.getPrivs(name);
476 catch(AuthNotFoundException &e)
478 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
483 void setPlayerAuthPrivs(const std::string &name, u64 privs)
486 return m_authmanager.setPrivs(name, privs);
488 catch(AuthNotFoundException &e)
490 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
494 // Changes a player's password, password must be given as plaintext
495 // If the player doesn't exist, a new entry is added to the auth manager
496 void setPlayerPassword(const std::string &name, const std::wstring &password);
498 // Saves g_settings to configpath given at initialization
501 void setIpBanned(const std::string &ip, const std::string &name)
503 m_banmanager.add(ip, name);
507 void unsetIpBanned(const std::string &ip_or_name)
509 m_banmanager.remove(ip_or_name);
513 std::string getBanDescription(const std::string &ip_or_name)
515 return m_banmanager.getBanDescription(ip_or_name);
518 Address getPeerAddress(u16 peer_id)
520 return m_con.GetPeerAddress(peer_id);
523 // Envlock and conlock should be locked when calling this
524 void notifyPlayer(const char *name, const std::wstring msg);
525 void notifyPlayers(const std::wstring msg);
527 void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
529 // Envlock and conlock should be locked when using Lua
530 lua_State *getLua(){ return m_lua; }
532 // IGameDef interface
534 virtual IItemDefManager* getItemDefManager();
535 virtual INodeDefManager* getNodeDefManager();
536 virtual ICraftDefManager* getCraftDefManager();
537 virtual ITextureSource* getTextureSource();
538 virtual u16 allocateUnknownNodeId(const std::string &name);
540 IWritableItemDefManager* getWritableItemDefManager();
541 IWritableNodeDefManager* getWritableNodeDefManager();
542 IWritableCraftDefManager* getWritableCraftDefManager();
544 const ModSpec* getModSpec(const std::string &modname);
546 std::string getWorldPath(){ return m_path_world; }
548 void setAsyncFatalError(const std::string &error)
550 m_async_fatal_error.set(error);
555 // con::PeerHandler implementation.
556 // These queue stuff to be processed by handlePeerChanges().
557 // As of now, these create and remove clients and players.
558 void peerAdded(con::Peer *peer);
559 void deletingPeer(con::Peer *peer, bool timeout);
565 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
566 static void SendAccessDenied(con::Connection &con, u16 peer_id,
567 const std::wstring &reason);
568 static void SendDeathscreen(con::Connection &con, u16 peer_id,
569 bool set_camera_point_target, v3f camera_point_target);
570 static void SendItemDef(con::Connection &con, u16 peer_id,
571 IItemDefManager *itemdef);
572 static void SendNodeDef(con::Connection &con, u16 peer_id,
573 INodeDefManager *nodedef);
576 Non-static send methods.
577 Conlock should be always used.
578 Envlock usage is documented badly but it's easy to figure out
579 which ones access the environment.
582 // Envlock and conlock should be locked when calling these
583 void SendInventory(u16 peer_id);
584 // send wielded item info about player to all
585 void SendWieldedItem(const ServerRemotePlayer *srp);
586 // send wielded item info about all players to all players
587 void SendPlayerItems();
588 void SendChatMessage(u16 peer_id, const std::wstring &message);
589 void BroadcastChatMessage(const std::wstring &message);
590 void SendPlayerHP(Player *player);
592 Send a node removal/addition event to all clients except ignore_id.
593 Additionally, if far_players!=NULL, players further away than
594 far_d_nodes are ignored and their peer_ids are added to far_players
596 // Envlock and conlock should be locked when calling these
597 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
598 core::list<u16> *far_players=NULL, float far_d_nodes=100);
599 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
600 core::list<u16> *far_players=NULL, float far_d_nodes=100);
601 void setBlockNotSent(v3s16 p);
603 // Environment and Connection must be locked when called
604 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
606 // Sends blocks to clients (locks env and con on its own)
607 void SendBlocks(float dtime);
609 void PrepareTextures();
611 void SendTextureAnnouncement(u16 peer_id);
613 void SendTexturesRequested(u16 peer_id,core::list<TextureRequest> tosend);
619 void DiePlayer(Player *player);
620 void RespawnPlayer(Player *player);
622 void UpdateCrafting(u16 peer_id);
624 // When called, connection mutex should be locked
625 RemoteClient* getClient(u16 peer_id);
627 // When called, environment mutex should be locked
628 std::string getPlayerName(u16 peer_id)
630 Player *player = m_env->getPlayer(peer_id);
632 return "[id="+itos(peer_id)+"]";
633 return player->getName();
637 Get a player from memory or creates one.
638 If player is already connected, return NULL
639 Does not verify/modify auth info and password.
641 Call with env and con locked.
643 ServerRemotePlayer *emergePlayer(const char *name, u16 peer_id);
645 // Locks environment and connection by its own
647 void handlePeerChange(PeerChange &c);
648 void handlePeerChanges();
650 u64 getPlayerPrivs(Player *player);
657 std::string m_path_world;
658 // Path to user's configuration file ("" = no configuration file)
659 std::string m_path_config;
660 // Subgame specification
661 SubgameSpec m_gamespec;
663 // Equivalent of /usr/share/minetest/server
664 std::string m_path_share;
666 // Thread can set; step() will throw as ServerError
667 MutexedVariable<std::string> m_async_fatal_error;
670 float m_liquid_transform_timer;
671 float m_print_info_timer;
672 float m_objectdata_timer;
673 float m_emergethread_trigger_timer;
674 float m_savemap_timer;
675 IntervalLimiter m_map_timer_and_unload_interval;
677 // NOTE: If connection and environment are both to be locked,
678 // environment shall be locked first.
681 ServerEnvironment *m_env;
685 con::Connection m_con;
687 // Connected clients (behind the con mutex)
688 core::map<u16, RemoteClient*> m_clients;
690 // User authentication
691 AuthManager m_authmanager;
694 BanManager m_banmanager;
697 // Envlock and conlock should be locked when using Lua
700 // Item definition manager
701 IWritableItemDefManager *m_itemdef;
703 // Node definition manager
704 IWritableNodeDefManager *m_nodedef;
706 // Craft definition manager
707 IWritableCraftDefManager *m_craftdef;
710 core::list<ModSpec> m_mods;
716 // A buffer for time steps
717 // step() increments and AsyncRunStep() run by m_thread reads it.
719 JMutex m_step_dtime_mutex;
721 // The server mainly operates in this thread
722 ServerThread m_thread;
723 // This thread fetches and generates map
724 EmergeThread m_emergethread;
725 // Queue of block coordinates to be processed by the emerge thread
726 BlockEmergeQueue m_emerge_queue;
733 //MutexedVariable<u32> m_time_of_day;
734 // Used to buffer dtime for adding to m_time_of_day
735 float m_time_counter;
736 // Timer for sending time of day over network
737 float m_time_of_day_send_timer;
738 // Uptime of server in seconds
739 MutexedVariable<double> m_uptime;
743 Queues stuff from peerAdded() and deletingPeer() to
757 Queue<PeerChange> m_peer_change_queue;
763 // Mod parent directory paths
764 core::list<std::string> m_modspaths;
766 bool m_shutdown_requested;
769 Map edit event queue. Automatically receives all map edits.
770 The constructor of this class registers us to receive them through
773 NOTE: Should these be moved to actually be members of
778 Queue of map edits from the environment for sending to the clients
779 This is behind m_env_mutex
781 Queue<MapEditEvent*> m_unsent_map_edit_queue;
783 Set to true when the server itself is modifying the map and does
784 all sending of information by itself.
785 This is behind m_env_mutex
787 bool m_ignore_map_edit_events;
789 If set to !=0, the incoming MapEditEvents are modified to have
790 this peed id as the disabled recipient
791 This is behind m_env_mutex
793 u16 m_ignore_map_edit_events_peer_id;
795 friend class EmergeThread;
796 friend class RemoteClient;
798 std::map<std::string,TextureInformation> m_Textures;
802 Runs a simple dedicated server loop.
804 Shuts down when run is set to false.
806 void dedicated_server_loop(Server &server, bool &run);