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 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()
43 typedef struct lua_State lua_State;
44 class IWritableItemDefManager;
45 class IWritableNodeDefManager;
46 class IWritableCraftDefManager;
49 class IRollbackManager;
51 class ServerError : public std::exception
54 ServerError(const std::string &s)
56 m_s = "ServerError: ";
59 virtual ~ServerError() throw()
61 virtual const char * what() const throw()
71 v3f findSpawnPos(ServerMap &map);
74 A structure containing the data needed for queueing the fetching
77 struct QueuedBlockEmerge
80 // key = peer_id, value = flags
81 core::map<u16, u8> peer_ids;
85 This is a thread-safe class.
87 class BlockEmergeQueue
97 JMutexAutoLock lock(m_mutex);
99 core::list<QueuedBlockEmerge*>::Iterator i;
100 for(i=m_queue.begin(); i!=m_queue.end(); i++)
102 QueuedBlockEmerge *q = *i;
108 peer_id=0 adds with nobody to send to
110 void addBlock(u16 peer_id, v3s16 pos, u8 flags)
112 DSTACK(__FUNCTION_NAME);
114 JMutexAutoLock lock(m_mutex);
119 Find if block is already in queue.
120 If it is, update the peer to it and quit.
122 core::list<QueuedBlockEmerge*>::Iterator i;
123 for(i=m_queue.begin(); i!=m_queue.end(); i++)
125 QueuedBlockEmerge *q = *i;
128 q->peer_ids[peer_id] = flags;
137 QueuedBlockEmerge *q = new QueuedBlockEmerge;
140 q->peer_ids[peer_id] = flags;
141 m_queue.push_back(q);
144 // Returned pointer must be deleted
145 // Returns NULL if queue is empty
146 QueuedBlockEmerge * pop()
148 JMutexAutoLock lock(m_mutex);
150 core::list<QueuedBlockEmerge*>::Iterator i = m_queue.begin();
151 if(i == m_queue.end())
153 QueuedBlockEmerge *q = *i;
160 JMutexAutoLock lock(m_mutex);
161 return m_queue.size();
164 u32 peerItemCount(u16 peer_id)
166 JMutexAutoLock lock(m_mutex);
170 core::list<QueuedBlockEmerge*>::Iterator i;
171 for(i=m_queue.begin(); i!=m_queue.end(); i++)
173 QueuedBlockEmerge *q = *i;
174 if(q->peer_ids.find(peer_id) != NULL)
182 core::list<QueuedBlockEmerge*> m_queue;
188 class ServerThread : public SimpleThread
194 ServerThread(Server *server):
203 class EmergeThread : public SimpleThread
209 EmergeThread(Server *server):
220 if(IsRunning() == false)
230 char name[PLAYERNAME_SIZE];
236 void PrintLine(std::ostream *s);
240 Used for queueing and sorting block transfers in containers
242 Lower priority number means higher priority.
244 struct PrioritySortedBlockTransfer
246 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
248 priority = a_priority;
252 bool operator < (PrioritySortedBlockTransfer &other)
254 return priority < other.priority;
265 MediaRequest(const std::string &name_=""):
273 std::string sha1_digest;
275 MediaInfo(const std::string path_="",
276 const std::string sha1_digest_=""):
278 sha1_digest(sha1_digest_)
283 struct ServerSoundParams
286 std::string to_player;
294 float max_hear_distance;
303 max_hear_distance(32*BS),
307 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
310 struct ServerPlayingSound
312 ServerSoundParams params;
313 std::set<u16> clients; // peer ids
319 // peer_id=0 means this client has no associated peer
320 // NOTE: If client is made allowed to exist while peer doesn't,
321 // this has to be set to 0 when there is no peer.
322 // Also, the client must be moved to some other container.
324 // The serialization version to use with the client
325 u8 serialization_version;
327 u16 net_proto_version;
328 // Version is stored in here after INIT before INIT2
329 u8 pending_serialization_version;
331 bool definitions_sent;
334 m_time_from_building(9999),
335 m_excess_gotblocks(0)
338 serialization_version = SER_FMT_VER_INVALID;
339 net_proto_version = 0;
340 pending_serialization_version = SER_FMT_VER_INVALID;
341 definitions_sent = false;
342 m_nearest_unsent_d = 0;
343 m_nearest_unsent_reset_timer = 0.0;
344 m_nothing_to_send_counter = 0;
345 m_nothing_to_send_pause_timer = 0;
352 Finds block that should be sent next to the client.
353 Environment should be locked when this is called.
354 dtime is used for resetting send radius at slow interval
356 void GetNextBlocks(Server *server, float dtime,
357 core::array<PrioritySortedBlockTransfer> &dest);
359 void GotBlock(v3s16 p);
361 void SentBlock(v3s16 p);
363 void SetBlockNotSent(v3s16 p);
364 void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
368 return m_blocks_sending.size();
371 // Increments timeouts and removes timed-out blocks from list
372 // NOTE: This doesn't fix the server-not-sending-block bug
373 // because it is related to emerging, not sending.
374 //void RunSendingTimeouts(float dtime, float timeout);
376 void PrintInfo(std::ostream &o)
378 o<<"RemoteClient "<<peer_id<<": "
379 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
380 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
381 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
382 <<", m_excess_gotblocks="<<m_excess_gotblocks
384 m_excess_gotblocks = 0;
387 // Time from last placing or removing blocks
388 float m_time_from_building;
390 /*JMutex m_dig_mutex;
391 float m_dig_time_remaining;
394 v3s16 m_dig_position;*/
397 List of active objects that the client knows of.
400 core::map<u16, bool> m_known_objects;
404 Blocks that have been sent to client.
405 - These don't have to be sent again.
406 - A block is cleared from here when client says it has
407 deleted it from it's memory
409 Key is position, value is dummy.
410 No MapBlock* is stored here because the blocks can get deleted.
412 core::map<v3s16, bool> m_blocks_sent;
413 s16 m_nearest_unsent_d;
415 float m_nearest_unsent_reset_timer;
418 Blocks that are currently on the line.
419 This is used for throttling the sending of blocks.
420 - The size of this list is limited to some value
421 Block is added when it is sent with BLOCKDATA.
422 Block is removed when GOTBLOCKS is received.
423 Value is time from sending. (not used at the moment)
425 core::map<v3s16, float> m_blocks_sending;
428 Count of excess GotBlocks().
429 There is an excess amount because the client sometimes
430 gets a block so late that the server sends it again,
431 and the client then sends two GOTBLOCKs.
432 This is resetted by PrintInfo()
434 u32 m_excess_gotblocks;
436 // CPU usage optimization
437 u32 m_nothing_to_send_counter;
438 float m_nothing_to_send_pause_timer;
441 class Server : public con::PeerHandler, public MapEventReceiver,
442 public InventoryManager, public IGameDef,
443 public IBackgroundBlockEmerger
447 NOTE: Every public method should be thread-safe
451 const std::string &path_world,
452 const std::string &path_config,
453 const SubgameSpec &gamespec,
454 bool simple_singleplayer_mode
457 void start(unsigned short port);
459 // This is mainly a way to pass the time to the server.
460 // Actual processing is done in an another thread.
461 void step(float dtime);
462 // This is run by ServerThread and does the actual processing
465 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
467 core::list<PlayerInfo> getPlayerInfo();
469 // Environment must be locked when called
470 void setTimeOfDay(u32 time)
472 m_env->setTimeOfDay(time);
473 m_time_of_day_send_timer = 0;
476 bool getShutdownRequested()
478 return m_shutdown_requested;
482 Shall be called with the environment locked.
483 This is accessed by the map, which is inside the environment,
484 so it shouldn't be a problem.
486 void onMapEditEvent(MapEditEvent *event);
489 Shall be called with the environment and the connection locked.
491 Inventory* getInventory(const InventoryLocation &loc);
492 void setInventoryModified(const InventoryLocation &loc);
494 // Connection must be locked when called
495 std::wstring getStatusString();
497 void requestShutdown(void)
499 m_shutdown_requested = true;
502 // Returns -1 if failed, sound handle on success
504 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
505 void stopSound(s32 handle);
508 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
509 bool checkPriv(const std::string &name, const std::string &priv);
510 void reportPrivsModified(const std::string &name=""); // ""=all
511 void reportInventoryFormspecModified(const std::string &name);
513 // Saves g_settings to configpath given at initialization
516 void setIpBanned(const std::string &ip, const std::string &name)
518 m_banmanager.add(ip, name);
522 void unsetIpBanned(const std::string &ip_or_name)
524 m_banmanager.remove(ip_or_name);
528 std::string getBanDescription(const std::string &ip_or_name)
530 return m_banmanager.getBanDescription(ip_or_name);
533 Address getPeerAddress(u16 peer_id)
535 return m_con.GetPeerAddress(peer_id);
538 // Envlock and conlock should be locked when calling this
539 void notifyPlayer(const char *name, const std::wstring msg);
540 void notifyPlayers(const std::wstring msg);
542 void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
544 // Creates or resets inventory
545 Inventory* createDetachedInventory(const std::string &name);
547 // Envlock and conlock should be locked when using Lua
548 lua_State *getLua(){ return m_lua; }
550 // Envlock should be locked when using the rollback manager
551 IRollbackManager *getRollbackManager(){ return m_rollback; }
552 // actions: time-reversed list
553 // Return value: success/failure
554 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
555 std::list<std::string> *log);
557 // IGameDef interface
559 virtual IItemDefManager* getItemDefManager();
560 virtual INodeDefManager* getNodeDefManager();
561 virtual ICraftDefManager* getCraftDefManager();
562 virtual ITextureSource* getTextureSource();
563 virtual u16 allocateUnknownNodeId(const std::string &name);
564 virtual ISoundManager* getSoundManager();
565 virtual MtEventManager* getEventManager();
566 virtual IRollbackReportSink* getRollbackReportSink();
568 IWritableItemDefManager* getWritableItemDefManager();
569 IWritableNodeDefManager* getWritableNodeDefManager();
570 IWritableCraftDefManager* getWritableCraftDefManager();
572 const ModSpec* getModSpec(const std::string &modname);
573 void getModNames(core::list<std::string> &modlist);
574 std::string getBuiltinLuaPath();
576 std::string getWorldPath(){ return m_path_world; }
578 bool isSingleplayer(){ return m_simple_singleplayer_mode; }
580 void setAsyncFatalError(const std::string &error)
582 m_async_fatal_error.set(error);
587 // con::PeerHandler implementation.
588 // These queue stuff to be processed by handlePeerChanges().
589 // As of now, these create and remove clients and players.
590 void peerAdded(con::Peer *peer);
591 void deletingPeer(con::Peer *peer, bool timeout);
597 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
598 static void SendAccessDenied(con::Connection &con, u16 peer_id,
599 const std::wstring &reason);
600 static void SendDeathscreen(con::Connection &con, u16 peer_id,
601 bool set_camera_point_target, v3f camera_point_target);
602 static void SendItemDef(con::Connection &con, u16 peer_id,
603 IItemDefManager *itemdef);
604 static void SendNodeDef(con::Connection &con, u16 peer_id,
605 INodeDefManager *nodedef);
608 Non-static send methods.
609 Conlock should be always used.
610 Envlock usage is documented badly but it's easy to figure out
611 which ones access the environment.
614 // Envlock and conlock should be locked when calling these
615 void SendInventory(u16 peer_id);
616 void SendChatMessage(u16 peer_id, const std::wstring &message);
617 void BroadcastChatMessage(const std::wstring &message);
618 void SendPlayerHP(u16 peer_id);
619 void SendMovePlayer(u16 peer_id);
620 void SendPlayerPrivileges(u16 peer_id);
621 void SendPlayerInventoryFormspec(u16 peer_id);
623 Send a node removal/addition event to all clients except ignore_id.
624 Additionally, if far_players!=NULL, players further away than
625 far_d_nodes are ignored and their peer_ids are added to far_players
627 // Envlock and conlock should be locked when calling these
628 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
629 core::list<u16> *far_players=NULL, float far_d_nodes=100);
630 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
631 core::list<u16> *far_players=NULL, float far_d_nodes=100);
632 void setBlockNotSent(v3s16 p);
634 // Environment and Connection must be locked when called
635 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
637 // Sends blocks to clients (locks env and con on its own)
638 void SendBlocks(float dtime);
640 void fillMediaCache();
641 void sendMediaAnnouncement(u16 peer_id);
642 void sendRequestedMedia(u16 peer_id,
643 const core::list<MediaRequest> &tosend);
645 void sendDetachedInventory(const std::string &name, u16 peer_id);
646 void sendDetachedInventoryToAll(const std::string &name);
647 void sendDetachedInventories(u16 peer_id);
653 void DiePlayer(u16 peer_id);
654 void RespawnPlayer(u16 peer_id);
656 void UpdateCrafting(u16 peer_id);
658 // When called, connection mutex should be locked
659 RemoteClient* getClient(u16 peer_id);
661 // When called, environment mutex should be locked
662 std::string getPlayerName(u16 peer_id)
664 Player *player = m_env->getPlayer(peer_id);
666 return "[id="+itos(peer_id)+"]";
667 return player->getName();
670 // When called, environment mutex should be locked
671 PlayerSAO* getPlayerSAO(u16 peer_id)
673 Player *player = m_env->getPlayer(peer_id);
676 return player->getPlayerSAO();
680 Get a player from memory or creates one.
681 If player is already connected, return NULL
682 Does not verify/modify auth info and password.
684 Call with env and con locked.
686 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
688 // Locks environment and connection by its own
690 void handlePeerChange(PeerChange &c);
691 void handlePeerChanges();
698 std::string m_path_world;
699 // Path to user's configuration file ("" = no configuration file)
700 std::string m_path_config;
701 // Subgame specification
702 SubgameSpec m_gamespec;
703 // If true, do not allow multiple players and hide some multiplayer
705 bool m_simple_singleplayer_mode;
707 // Thread can set; step() will throw as ServerError
708 MutexedVariable<std::string> m_async_fatal_error;
711 float m_liquid_transform_timer;
712 float m_print_info_timer;
713 float m_objectdata_timer;
714 float m_emergethread_trigger_timer;
715 float m_savemap_timer;
716 IntervalLimiter m_map_timer_and_unload_interval;
718 // NOTE: If connection and environment are both to be locked,
719 // environment shall be locked first.
722 ServerEnvironment *m_env;
726 con::Connection m_con;
728 // Connected clients (behind the con mutex)
729 core::map<u16, RemoteClient*> m_clients;
732 BanManager m_banmanager;
734 // Rollback manager (behind m_env_mutex)
735 IRollbackManager *m_rollback;
736 bool m_rollback_sink_enabled;
737 bool m_enable_rollback_recording; // Updated once in a while
740 // Envlock and conlock should be locked when using Lua
743 // Item definition manager
744 IWritableItemDefManager *m_itemdef;
746 // Node definition manager
747 IWritableNodeDefManager *m_nodedef;
749 // Craft definition manager
750 IWritableCraftDefManager *m_craftdef;
753 EventManager *m_event;
756 core::list<ModSpec> m_mods;
762 // A buffer for time steps
763 // step() increments and AsyncRunStep() run by m_thread reads it.
765 JMutex m_step_dtime_mutex;
767 // The server mainly operates in this thread
768 ServerThread m_thread;
769 // This thread fetches and generates map
770 EmergeThread m_emergethread;
771 // Queue of block coordinates to be processed by the emerge thread
772 BlockEmergeQueue m_emerge_queue;
778 // Timer for sending time of day over network
779 float m_time_of_day_send_timer;
780 // Uptime of server in seconds
781 MutexedVariable<double> m_uptime;
785 Queues stuff from peerAdded() and deletingPeer() to
799 Queue<PeerChange> m_peer_change_queue;
805 // Mod parent directory paths
806 core::list<std::string> m_modspaths;
808 bool m_shutdown_requested;
811 Map edit event queue. Automatically receives all map edits.
812 The constructor of this class registers us to receive them through
815 NOTE: Should these be moved to actually be members of
820 Queue of map edits from the environment for sending to the clients
821 This is behind m_env_mutex
823 Queue<MapEditEvent*> m_unsent_map_edit_queue;
825 Set to true when the server itself is modifying the map and does
826 all sending of information by itself.
827 This is behind m_env_mutex
829 bool m_ignore_map_edit_events;
831 If a non-empty area, map edit events contained within are left
832 unsent. Done at map generation time to speed up editing of the
833 generated area, as it will be sent anyway.
834 This is behind m_env_mutex
836 VoxelArea m_ignore_map_edit_events_area;
838 If set to !=0, the incoming MapEditEvents are modified to have
839 this peed id as the disabled recipient
840 This is behind m_env_mutex
842 u16 m_ignore_map_edit_events_peer_id;
844 friend class EmergeThread;
845 friend class RemoteClient;
847 std::map<std::string,MediaInfo> m_media;
852 std::map<s32, ServerPlayingSound> m_playing_sounds;
856 Detached inventories (behind m_env_mutex)
859 std::map<std::string, Inventory*> m_detached_inventories;
863 Runs a simple dedicated server loop.
865 Shuts down when run is set to false.
867 void dedicated_server_loop(Server &server, bool &run);