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"
38 typedef struct lua_State lua_State;
39 class IWritableItemDefManager;
40 class IWritableNodeDefManager;
41 class IWritableCraftDefManager;
43 class ServerError : public std::exception
46 ServerError(const std::string &s)
48 m_s = "ServerError: ";
51 virtual ~ServerError() throw()
53 virtual const char * what() const throw()
63 v3f findSpawnPos(ServerMap &map);
66 A structure containing the data needed for queueing the fetching
69 struct QueuedBlockEmerge
72 // key = peer_id, value = flags
73 core::map<u16, u8> peer_ids;
77 This is a thread-safe class.
79 class BlockEmergeQueue
89 JMutexAutoLock lock(m_mutex);
91 core::list<QueuedBlockEmerge*>::Iterator i;
92 for(i=m_queue.begin(); i!=m_queue.end(); i++)
94 QueuedBlockEmerge *q = *i;
100 peer_id=0 adds with nobody to send to
102 void addBlock(u16 peer_id, v3s16 pos, u8 flags)
104 DSTACK(__FUNCTION_NAME);
106 JMutexAutoLock lock(m_mutex);
111 Find if block is already in queue.
112 If it is, update the peer to it and quit.
114 core::list<QueuedBlockEmerge*>::Iterator i;
115 for(i=m_queue.begin(); i!=m_queue.end(); i++)
117 QueuedBlockEmerge *q = *i;
120 q->peer_ids[peer_id] = flags;
129 QueuedBlockEmerge *q = new QueuedBlockEmerge;
132 q->peer_ids[peer_id] = flags;
133 m_queue.push_back(q);
136 // Returned pointer must be deleted
137 // Returns NULL if queue is empty
138 QueuedBlockEmerge * pop()
140 JMutexAutoLock lock(m_mutex);
142 core::list<QueuedBlockEmerge*>::Iterator i = m_queue.begin();
143 if(i == m_queue.end())
145 QueuedBlockEmerge *q = *i;
152 JMutexAutoLock lock(m_mutex);
153 return m_queue.size();
156 u32 peerItemCount(u16 peer_id)
158 JMutexAutoLock lock(m_mutex);
162 core::list<QueuedBlockEmerge*>::Iterator i;
163 for(i=m_queue.begin(); i!=m_queue.end(); i++)
165 QueuedBlockEmerge *q = *i;
166 if(q->peer_ids.find(peer_id) != NULL)
174 core::list<QueuedBlockEmerge*> m_queue;
180 class ServerThread : public SimpleThread
186 ServerThread(Server *server):
195 class EmergeThread : public SimpleThread
201 EmergeThread(Server *server):
212 if(IsRunning() == false)
222 char name[PLAYERNAME_SIZE];
228 void PrintLine(std::ostream *s);
232 Used for queueing and sorting block transfers in containers
234 Lower priority number means higher priority.
236 struct PrioritySortedBlockTransfer
238 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
240 priority = a_priority;
244 bool operator < (PrioritySortedBlockTransfer &other)
246 return priority < other.priority;
253 struct TextureRequest
257 TextureRequest(const std::string &name_=""):
262 struct TextureInformation
265 std::string sha1_digest;
267 TextureInformation(const std::string path_="",
268 const std::string sha1_digest_=""):
270 sha1_digest(sha1_digest_)
278 // peer_id=0 means this client has no associated peer
279 // NOTE: If client is made allowed to exist while peer doesn't,
280 // this has to be set to 0 when there is no peer.
281 // Also, the client must be moved to some other container.
283 // The serialization version to use with the client
284 u8 serialization_version;
286 u16 net_proto_version;
287 // Version is stored in here after INIT before INIT2
288 u8 pending_serialization_version;
290 bool definitions_sent;
293 m_time_from_building(9999),
294 m_excess_gotblocks(0)
297 serialization_version = SER_FMT_VER_INVALID;
298 net_proto_version = 0;
299 pending_serialization_version = SER_FMT_VER_INVALID;
300 definitions_sent = false;
301 m_nearest_unsent_d = 0;
302 m_nearest_unsent_reset_timer = 0.0;
303 m_nothing_to_send_counter = 0;
304 m_nothing_to_send_pause_timer = 0;
311 Finds block that should be sent next to the client.
312 Environment should be locked when this is called.
313 dtime is used for resetting send radius at slow interval
315 void GetNextBlocks(Server *server, float dtime,
316 core::array<PrioritySortedBlockTransfer> &dest);
318 void GotBlock(v3s16 p);
320 void SentBlock(v3s16 p);
322 void SetBlockNotSent(v3s16 p);
323 void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
327 return m_blocks_sending.size();
330 // Increments timeouts and removes timed-out blocks from list
331 // NOTE: This doesn't fix the server-not-sending-block bug
332 // because it is related to emerging, not sending.
333 //void RunSendingTimeouts(float dtime, float timeout);
335 void PrintInfo(std::ostream &o)
337 o<<"RemoteClient "<<peer_id<<": "
338 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
339 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
340 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
341 <<", m_excess_gotblocks="<<m_excess_gotblocks
343 m_excess_gotblocks = 0;
346 // Time from last placing or removing blocks
347 float m_time_from_building;
349 /*JMutex m_dig_mutex;
350 float m_dig_time_remaining;
353 v3s16 m_dig_position;*/
356 List of active objects that the client knows of.
359 core::map<u16, bool> m_known_objects;
363 Blocks that have been sent to client.
364 - These don't have to be sent again.
365 - A block is cleared from here when client says it has
366 deleted it from it's memory
368 Key is position, value is dummy.
369 No MapBlock* is stored here because the blocks can get deleted.
371 core::map<v3s16, bool> m_blocks_sent;
372 s16 m_nearest_unsent_d;
374 float m_nearest_unsent_reset_timer;
377 Blocks that are currently on the line.
378 This is used for throttling the sending of blocks.
379 - The size of this list is limited to some value
380 Block is added when it is sent with BLOCKDATA.
381 Block is removed when GOTBLOCKS is received.
382 Value is time from sending. (not used at the moment)
384 core::map<v3s16, float> m_blocks_sending;
387 Count of excess GotBlocks().
388 There is an excess amount because the client sometimes
389 gets a block so late that the server sends it again,
390 and the client then sends two GOTBLOCKs.
391 This is resetted by PrintInfo()
393 u32 m_excess_gotblocks;
395 // CPU usage optimization
396 u32 m_nothing_to_send_counter;
397 float m_nothing_to_send_pause_timer;
400 class Server : public con::PeerHandler, public MapEventReceiver,
401 public InventoryManager, public IGameDef,
402 public IBackgroundBlockEmerger
406 NOTE: Every public method should be thread-safe
410 std::string gamename,
411 std::string mapsavedir,
412 std::string configpath
415 void start(unsigned short port);
417 // This is mainly a way to pass the time to the server.
418 // Actual processing is done in an another thread.
419 void step(float dtime);
420 // This is run by ServerThread and does the actual processing
423 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
425 core::list<PlayerInfo> getPlayerInfo();
427 /*u32 getDayNightRatio()
429 return time_to_daynight_ratio(m_time_of_day.get());
432 // Environment must be locked when called
433 void setTimeOfDay(u32 time)
435 m_env->setTimeOfDay(time);
436 m_time_of_day_send_timer = 0;
439 bool getShutdownRequested()
441 return m_shutdown_requested;
445 Shall be called with the environment locked.
446 This is accessed by the map, which is inside the environment,
447 so it shouldn't be a problem.
449 void onMapEditEvent(MapEditEvent *event);
452 Shall be called with the environment and the connection locked.
454 Inventory* getInventory(const InventoryLocation &loc);
455 std::string getInventoryOwner(const InventoryLocation &loc);
456 void setInventoryModified(const InventoryLocation &loc);
458 // Connection must be locked when called
459 std::wstring getStatusString();
461 void requestShutdown(void)
463 m_shutdown_requested = true;
467 // Envlock and conlock should be locked when calling this
468 void SendMovePlayer(Player *player);
470 u64 getPlayerAuthPrivs(const std::string &name)
473 return m_authmanager.getPrivs(name);
475 catch(AuthNotFoundException &e)
477 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
482 void setPlayerAuthPrivs(const std::string &name, u64 privs)
485 return m_authmanager.setPrivs(name, privs);
487 catch(AuthNotFoundException &e)
489 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
493 // Changes a player's password, password must be given as plaintext
494 // If the player doesn't exist, a new entry is added to the auth manager
495 void setPlayerPassword(const std::string &name, const std::wstring &password);
497 // Saves g_settings to configpath given at initialization
500 void setIpBanned(const std::string &ip, const std::string &name)
502 m_banmanager.add(ip, name);
506 void unsetIpBanned(const std::string &ip_or_name)
508 m_banmanager.remove(ip_or_name);
512 std::string getBanDescription(const std::string &ip_or_name)
514 return m_banmanager.getBanDescription(ip_or_name);
517 Address getPeerAddress(u16 peer_id)
519 return m_con.GetPeerAddress(peer_id);
522 // Envlock and conlock should be locked when calling this
523 void notifyPlayer(const char *name, const std::wstring msg);
524 void notifyPlayers(const std::wstring msg);
526 void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
528 // Envlock and conlock should be locked when using Lua
529 lua_State *getLua(){ return m_lua; }
531 // IGameDef interface
533 virtual IItemDefManager* getItemDefManager();
534 virtual INodeDefManager* getNodeDefManager();
535 virtual ICraftDefManager* getCraftDefManager();
536 virtual ITextureSource* getTextureSource();
537 virtual u16 allocateUnknownNodeId(const std::string &name);
539 IWritableItemDefManager* getWritableItemDefManager();
540 IWritableNodeDefManager* getWritableNodeDefManager();
541 IWritableCraftDefManager* getWritableCraftDefManager();
543 const ModSpec* getModSpec(const std::string &modname);
545 std::string getWorldPath(){ return m_path_world; }
549 // con::PeerHandler implementation.
550 // These queue stuff to be processed by handlePeerChanges().
551 // As of now, these create and remove clients and players.
552 void peerAdded(con::Peer *peer);
553 void deletingPeer(con::Peer *peer, bool timeout);
559 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
560 static void SendAccessDenied(con::Connection &con, u16 peer_id,
561 const std::wstring &reason);
562 static void SendDeathscreen(con::Connection &con, u16 peer_id,
563 bool set_camera_point_target, v3f camera_point_target);
564 static void SendItemDef(con::Connection &con, u16 peer_id,
565 IItemDefManager *itemdef);
566 static void SendNodeDef(con::Connection &con, u16 peer_id,
567 INodeDefManager *nodedef);
570 Non-static send methods.
571 Conlock should be always used.
572 Envlock usage is documented badly but it's easy to figure out
573 which ones access the environment.
576 // Envlock and conlock should be locked when calling these
577 void SendInventory(u16 peer_id);
578 // send wielded item info about player to all
579 void SendWieldedItem(const ServerRemotePlayer *srp);
580 // send wielded item info about all players to all players
581 void SendPlayerItems();
582 void SendChatMessage(u16 peer_id, const std::wstring &message);
583 void BroadcastChatMessage(const std::wstring &message);
584 void SendPlayerHP(Player *player);
586 Send a node removal/addition event to all clients except ignore_id.
587 Additionally, if far_players!=NULL, players further away than
588 far_d_nodes are ignored and their peer_ids are added to far_players
590 // Envlock and conlock should be locked when calling these
591 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
592 core::list<u16> *far_players=NULL, float far_d_nodes=100);
593 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
594 core::list<u16> *far_players=NULL, float far_d_nodes=100);
595 void setBlockNotSent(v3s16 p);
597 // Environment and Connection must be locked when called
598 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
600 // Sends blocks to clients (locks env and con on its own)
601 void SendBlocks(float dtime);
603 void PrepareTextures();
605 void SendTextureAnnouncement(u16 peer_id);
607 void SendTexturesRequested(u16 peer_id,core::list<TextureRequest> tosend);
613 void DiePlayer(Player *player);
614 void RespawnPlayer(Player *player);
616 void UpdateCrafting(u16 peer_id);
618 // When called, connection mutex should be locked
619 RemoteClient* getClient(u16 peer_id);
621 // When called, environment mutex should be locked
622 std::string getPlayerName(u16 peer_id)
624 Player *player = m_env->getPlayer(peer_id);
626 return "[id="+itos(peer_id)+"]";
627 return player->getName();
631 Get a player from memory or creates one.
632 If player is already connected, return NULL
633 Does not verify/modify auth info and password.
635 Call with env and con locked.
637 ServerRemotePlayer *emergePlayer(const char *name, u16 peer_id);
639 // Locks environment and connection by its own
641 void handlePeerChange(PeerChange &c);
642 void handlePeerChanges();
644 u64 getPlayerPrivs(Player *player);
651 std::string m_gamename;
653 std::string m_path_world;
654 // Path to user's configuration file ("" = no configuration file)
655 std::string m_path_config;
657 // Equivalent of /usr/share/minetest/server
658 std::string m_path_share;
659 // Equivalent of /usr/share/minetest/server/games/gamename
660 std::string m_path_game;
661 // Equivalent of /usr/share/minetest/server/addons/gamename
662 // and ~/.minetest/server/addons/gamename
663 std::set<std::string> m_path_addons;
666 float m_liquid_transform_timer;
667 float m_print_info_timer;
668 float m_objectdata_timer;
669 float m_emergethread_trigger_timer;
670 float m_savemap_timer;
671 IntervalLimiter m_map_timer_and_unload_interval;
673 // NOTE: If connection and environment are both to be locked,
674 // environment shall be locked first.
677 ServerEnvironment *m_env;
681 con::Connection m_con;
683 // Connected clients (behind the con mutex)
684 core::map<u16, RemoteClient*> m_clients;
686 // User authentication
687 AuthManager m_authmanager;
690 BanManager m_banmanager;
693 // Envlock and conlock should be locked when using Lua
696 // Item definition manager
697 IWritableItemDefManager *m_itemdef;
699 // Node definition manager
700 IWritableNodeDefManager *m_nodedef;
702 // Craft definition manager
703 IWritableCraftDefManager *m_craftdef;
706 core::list<ModSpec> m_mods;
712 // A buffer for time steps
713 // step() increments and AsyncRunStep() run by m_thread reads it.
715 JMutex m_step_dtime_mutex;
717 // The server mainly operates in this thread
718 ServerThread m_thread;
719 // This thread fetches and generates map
720 EmergeThread m_emergethread;
721 // Queue of block coordinates to be processed by the emerge thread
722 BlockEmergeQueue m_emerge_queue;
729 //MutexedVariable<u32> m_time_of_day;
730 // Used to buffer dtime for adding to m_time_of_day
731 float m_time_counter;
732 // Timer for sending time of day over network
733 float m_time_of_day_send_timer;
734 // Uptime of server in seconds
735 MutexedVariable<double> m_uptime;
739 Queues stuff from peerAdded() and deletingPeer() to
753 Queue<PeerChange> m_peer_change_queue;
759 // Mod parent directory paths
760 core::list<std::string> m_modspaths;
762 bool m_shutdown_requested;
765 Map edit event queue. Automatically receives all map edits.
766 The constructor of this class registers us to receive them through
769 NOTE: Should these be moved to actually be members of
774 Queue of map edits from the environment for sending to the clients
775 This is behind m_env_mutex
777 Queue<MapEditEvent*> m_unsent_map_edit_queue;
779 Set to true when the server itself is modifying the map and does
780 all sending of information by itself.
781 This is behind m_env_mutex
783 bool m_ignore_map_edit_events;
785 If set to !=0, the incoming MapEditEvents are modified to have
786 this peed id as the disabled recipient
787 This is behind m_env_mutex
789 u16 m_ignore_map_edit_events_peer_id;
791 friend class EmergeThread;
792 friend class RemoteClient;
794 std::map<std::string,TextureInformation> m_Textures;
798 Runs a simple dedicated server loop.
800 Shuts down when run is set to false.
802 void dedicated_server_loop(Server &server, bool &run);