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"
34 typedef struct lua_State lua_State;
35 class IWritableToolDefManager;
36 class IWritableNodeDefManager;
41 v3f findSpawnPos(ServerMap &map);
44 A structure containing the data needed for queueing the fetching
47 struct QueuedBlockEmerge
50 // key = peer_id, value = flags
51 core::map<u16, u8> peer_ids;
55 This is a thread-safe class.
57 class BlockEmergeQueue
67 JMutexAutoLock lock(m_mutex);
69 core::list<QueuedBlockEmerge*>::Iterator i;
70 for(i=m_queue.begin(); i!=m_queue.end(); i++)
72 QueuedBlockEmerge *q = *i;
78 peer_id=0 adds with nobody to send to
80 void addBlock(u16 peer_id, v3s16 pos, u8 flags)
82 DSTACK(__FUNCTION_NAME);
84 JMutexAutoLock lock(m_mutex);
89 Find if block is already in queue.
90 If it is, update the peer to it and quit.
92 core::list<QueuedBlockEmerge*>::Iterator i;
93 for(i=m_queue.begin(); i!=m_queue.end(); i++)
95 QueuedBlockEmerge *q = *i;
98 q->peer_ids[peer_id] = flags;
107 QueuedBlockEmerge *q = new QueuedBlockEmerge;
110 q->peer_ids[peer_id] = flags;
111 m_queue.push_back(q);
114 // Returned pointer must be deleted
115 // Returns NULL if queue is empty
116 QueuedBlockEmerge * pop()
118 JMutexAutoLock lock(m_mutex);
120 core::list<QueuedBlockEmerge*>::Iterator i = m_queue.begin();
121 if(i == m_queue.end())
123 QueuedBlockEmerge *q = *i;
130 JMutexAutoLock lock(m_mutex);
131 return m_queue.size();
134 u32 peerItemCount(u16 peer_id)
136 JMutexAutoLock lock(m_mutex);
140 core::list<QueuedBlockEmerge*>::Iterator i;
141 for(i=m_queue.begin(); i!=m_queue.end(); i++)
143 QueuedBlockEmerge *q = *i;
144 if(q->peer_ids.find(peer_id) != NULL)
152 core::list<QueuedBlockEmerge*> m_queue;
158 class ServerThread : public SimpleThread
164 ServerThread(Server *server):
173 class EmergeThread : public SimpleThread
179 EmergeThread(Server *server):
190 if(IsRunning() == false)
200 char name[PLAYERNAME_SIZE];
206 void PrintLine(std::ostream *s);
209 u32 PIChecksum(core::list<PlayerInfo> &l);
212 Used for queueing and sorting block transfers in containers
214 Lower priority number means higher priority.
216 struct PrioritySortedBlockTransfer
218 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
220 priority = a_priority;
224 bool operator < (PrioritySortedBlockTransfer &other)
226 return priority < other.priority;
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;
249 m_time_from_building(9999),
250 m_excess_gotblocks(0)
253 serialization_version = SER_FMT_VER_INVALID;
254 net_proto_version = 0;
255 pending_serialization_version = SER_FMT_VER_INVALID;
256 m_nearest_unsent_d = 0;
257 m_nearest_unsent_reset_timer = 0.0;
258 m_nothing_to_send_counter = 0;
259 m_nothing_to_send_pause_timer = 0;
266 Finds block that should be sent next to the client.
267 Environment should be locked when this is called.
268 dtime is used for resetting send radius at slow interval
270 void GetNextBlocks(Server *server, float dtime,
271 core::array<PrioritySortedBlockTransfer> &dest);
274 Connection and environment should be locked when this is called.
275 steps() objects of blocks not found in active_blocks, then
276 adds those blocks to active_blocks
281 core::map<v3s16, bool> &stepped_blocks
284 void GotBlock(v3s16 p);
286 void SentBlock(v3s16 p);
288 void SetBlockNotSent(v3s16 p);
289 void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
293 return m_blocks_sending.size();
296 // Increments timeouts and removes timed-out blocks from list
297 // NOTE: This doesn't fix the server-not-sending-block bug
298 // because it is related to emerging, not sending.
299 //void RunSendingTimeouts(float dtime, float timeout);
301 void PrintInfo(std::ostream &o)
303 o<<"RemoteClient "<<peer_id<<": "
304 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
305 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
306 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
307 <<", m_excess_gotblocks="<<m_excess_gotblocks
309 m_excess_gotblocks = 0;
312 // Time from last placing or removing blocks
313 float m_time_from_building;
315 /*JMutex m_dig_mutex;
316 float m_dig_time_remaining;
319 v3s16 m_dig_position;*/
322 List of active objects that the client knows of.
325 core::map<u16, bool> m_known_objects;
329 Blocks that have been sent to client.
330 - These don't have to be sent again.
331 - A block is cleared from here when client says it has
332 deleted it from it's memory
334 Key is position, value is dummy.
335 No MapBlock* is stored here because the blocks can get deleted.
337 core::map<v3s16, bool> m_blocks_sent;
338 s16 m_nearest_unsent_d;
340 float m_nearest_unsent_reset_timer;
343 Blocks that are currently on the line.
344 This is used for throttling the sending of blocks.
345 - The size of this list is limited to some value
346 Block is added when it is sent with BLOCKDATA.
347 Block is removed when GOTBLOCKS is received.
348 Value is time from sending. (not used at the moment)
350 core::map<v3s16, float> m_blocks_sending;
353 Count of excess GotBlocks().
354 There is an excess amount because the client sometimes
355 gets a block so late that the server sends it again,
356 and the client then sends two GOTBLOCKs.
357 This is resetted by PrintInfo()
359 u32 m_excess_gotblocks;
361 // CPU usage optimization
362 u32 m_nothing_to_send_counter;
363 float m_nothing_to_send_pause_timer;
366 class Server : public con::PeerHandler, public MapEventReceiver,
367 public InventoryManager, public IGameDef
371 NOTE: Every public method should be thread-safe
375 std::string mapsavedir,
376 std::string configpath
379 void start(unsigned short port);
381 // This is mainly a way to pass the time to the server.
382 // Actual processing is done in an another thread.
383 void step(float dtime);
384 // This is run by ServerThread and does the actual processing
387 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
389 core::list<PlayerInfo> getPlayerInfo();
391 /*u32 getDayNightRatio()
393 return time_to_daynight_ratio(m_time_of_day.get());
396 // Environment must be locked when called
397 void setTimeOfDay(u32 time)
399 m_env->setTimeOfDay(time);
400 m_time_of_day_send_timer = 0;
403 bool getShutdownRequested()
405 return m_shutdown_requested;
409 Shall be called with the environment locked.
410 This is accessed by the map, which is inside the environment,
411 so it shouldn't be a problem.
413 void onMapEditEvent(MapEditEvent *event);
416 Shall be called with the environment and the connection locked.
418 Inventory* getInventory(InventoryContext *c, std::string id);
419 void inventoryModified(InventoryContext *c, std::string id);
421 // Connection must be locked when called
422 std::wstring getStatusString();
424 void requestShutdown(void)
426 m_shutdown_requested = true;
430 // Envlock and conlock should be locked when calling this
431 void SendMovePlayer(Player *player);
433 u64 getPlayerAuthPrivs(const std::string &name)
436 return m_authmanager.getPrivs(name);
438 catch(AuthNotFoundException &e)
440 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
445 void setPlayerAuthPrivs(const std::string &name, u64 privs)
448 return m_authmanager.setPrivs(name, privs);
450 catch(AuthNotFoundException &e)
452 dstream<<"WARNING: Auth not found for "<<name<<std::endl;
456 // Saves g_settings to configpath given at initialization
459 void setIpBanned(const std::string &ip, const std::string &name)
461 m_banmanager.add(ip, name);
465 void unsetIpBanned(const std::string &ip_or_name)
467 m_banmanager.remove(ip_or_name);
471 std::string getBanDescription(const std::string &ip_or_name)
473 return m_banmanager.getBanDescription(ip_or_name);
476 Address getPeerAddress(u16 peer_id)
478 return m_con.GetPeerAddress(peer_id);
481 // Envlock and conlock should be locked when calling this
482 void notifyPlayer(const char *name, const std::wstring msg);
483 void notifyPlayers(const std::wstring msg);
485 // Envlock and conlock should be locked when using Lua
486 lua_State *getLua(){ return m_lua; }
488 // IGameDef interface
490 virtual IToolDefManager* getToolDefManager();
491 virtual INodeDefManager* getNodeDefManager();
492 virtual ITextureSource* getTextureSource();
496 // con::PeerHandler implementation.
497 // These queue stuff to be processed by handlePeerChanges().
498 // As of now, these create and remove clients and players.
499 void peerAdded(con::Peer *peer);
500 void deletingPeer(con::Peer *peer, bool timeout);
506 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
507 static void SendAccessDenied(con::Connection &con, u16 peer_id,
508 const std::wstring &reason);
509 static void SendDeathscreen(con::Connection &con, u16 peer_id,
510 bool set_camera_point_target, v3f camera_point_target);
511 static void SendToolDef(con::Connection &con, u16 peer_id,
512 IToolDefManager *tooldef);
515 Non-static send methods
518 // Envlock and conlock should be locked when calling these
519 void SendObjectData(float dtime);
520 void SendPlayerInfos();
521 void SendInventory(u16 peer_id);
522 // send wielded item info about player to all
523 void SendWieldedItem(const Player *player);
524 // send wielded item info about all players to all players
525 void SendPlayerItems();
526 void SendChatMessage(u16 peer_id, const std::wstring &message);
527 void BroadcastChatMessage(const std::wstring &message);
528 void SendPlayerHP(Player *player);
530 Send a node removal/addition event to all clients except ignore_id.
531 Additionally, if far_players!=NULL, players further away than
532 far_d_nodes are ignored and their peer_ids are added to far_players
534 // Envlock and conlock should be locked when calling these
535 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
536 core::list<u16> *far_players=NULL, float far_d_nodes=100);
537 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
538 core::list<u16> *far_players=NULL, float far_d_nodes=100);
539 void setBlockNotSent(v3s16 p);
541 // Environment and Connection must be locked when called
542 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
544 // Sends blocks to clients (locks env and con on its own)
545 void SendBlocks(float dtime);
551 void HandlePlayerHP(Player *player, s16 damage);
552 void RespawnPlayer(Player *player);
554 void UpdateCrafting(u16 peer_id);
556 // When called, connection mutex should be locked
557 RemoteClient* getClient(u16 peer_id);
559 // When called, environment mutex should be locked
560 std::string getPlayerName(u16 peer_id)
562 Player *player = m_env->getPlayer(peer_id);
564 return "[id="+itos(peer_id);
565 return player->getName();
569 Get a player from memory or creates one.
570 If player is already connected, return NULL
571 The password is not checked here - it is only used to
572 set the password if a new player is created.
574 Call with env and con locked.
576 Player *emergePlayer(const char *name, const char *password, u16 peer_id);
578 // Locks environment and connection by its own
580 void handlePeerChange(PeerChange &c);
581 void handlePeerChanges();
583 u64 getPlayerPrivs(Player *player);
590 float m_liquid_transform_timer;
591 float m_print_info_timer;
592 float m_objectdata_timer;
593 float m_emergethread_trigger_timer;
594 float m_savemap_timer;
595 IntervalLimiter m_map_timer_and_unload_interval;
597 // NOTE: If connection and environment are both to be locked,
598 // environment shall be locked first.
601 ServerEnvironment *m_env;
605 con::Connection m_con;
607 // Connected clients (behind the con mutex)
608 core::map<u16, RemoteClient*> m_clients;
610 // User authentication
611 AuthManager m_authmanager;
614 BanManager m_banmanager;
617 // Envlock and conlock should be locked when using Lua
620 // Tool definition manager
621 IWritableToolDefManager *m_toolmgr;
623 // Node definition manager
624 IWritableNodeDefManager *m_nodemgr;
630 // A buffer for time steps
631 // step() increments and AsyncRunStep() run by m_thread reads it.
633 JMutex m_step_dtime_mutex;
635 // The server mainly operates in this thread
636 ServerThread m_thread;
637 // This thread fetches and generates map
638 EmergeThread m_emergethread;
639 // Queue of block coordinates to be processed by the emerge thread
640 BlockEmergeQueue m_emerge_queue;
647 //MutexedVariable<u32> m_time_of_day;
648 // Used to buffer dtime for adding to m_time_of_day
649 float m_time_counter;
650 // Timer for sending time of day over network
651 float m_time_of_day_send_timer;
652 // Uptime of server in seconds
653 MutexedVariable<double> m_uptime;
657 Queues stuff from peerAdded() and deletingPeer() to
671 Queue<PeerChange> m_peer_change_queue;
678 std::string m_mapsavedir;
680 // Configuration path ("" = no configuration file)
681 std::string m_configpath;
683 bool m_shutdown_requested;
686 Map edit event queue. Automatically receives all map edits.
687 The constructor of this class registers us to receive them through
690 NOTE: Should these be moved to actually be members of
695 Queue of map edits from the environment for sending to the clients
696 This is behind m_env_mutex
698 Queue<MapEditEvent*> m_unsent_map_edit_queue;
700 Set to true when the server itself is modifying the map and does
701 all sending of information by itself.
702 This is behind m_env_mutex
704 bool m_ignore_map_edit_events;
706 If set to !=0, the incoming MapEditEvents are modified to have
707 this peed id as the disabled recipient
708 This is behind m_env_mutex
710 u16 m_ignore_map_edit_events_peer_id;
712 friend class EmergeThread;
713 friend class RemoteClient;
717 Runs a simple dedicated server loop.
719 Shuts down when run is set to false.
721 void dedicated_server_loop(Server &server, bool &run);