3 Copyright (C) 2010-2013 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 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
46 typedef struct lua_State lua_State;
47 class IWritableItemDefManager;
48 class IWritableNodeDefManager;
49 class IWritableCraftDefManager;
52 class IRollbackManager;
55 class ServerError : public std::exception
58 ServerError(const std::string &s)
60 m_s = "ServerError: ";
63 virtual ~ServerError() throw()
65 virtual const char * what() const throw()
75 v3f findSpawnPos(ServerMap &map);
78 class MapEditEventIgnorer
81 MapEditEventIgnorer(bool *flag):
90 ~MapEditEventIgnorer()
103 class MapEditEventAreaIgnorer
106 MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
107 m_ignorevariable(ignorevariable)
109 if(m_ignorevariable->getVolume() == 0)
110 *m_ignorevariable = a;
112 m_ignorevariable = NULL;
115 ~MapEditEventAreaIgnorer()
119 assert(m_ignorevariable->getVolume() != 0);
120 *m_ignorevariable = VoxelArea();
125 VoxelArea *m_ignorevariable;
130 class ServerThread : public SimpleThread
136 ServerThread(Server *server):
148 char name[PLAYERNAME_SIZE];
154 void PrintLine(std::ostream *s);
158 Used for queueing and sorting block transfers in containers
160 Lower priority number means higher priority.
162 struct PrioritySortedBlockTransfer
164 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
166 priority = a_priority;
170 bool operator < (const PrioritySortedBlockTransfer &other) const
172 return priority < other.priority;
183 MediaRequest(const std::string &name_=""):
191 std::string sha1_digest;
193 MediaInfo(const std::string path_="",
194 const std::string sha1_digest_=""):
196 sha1_digest(sha1_digest_)
201 struct ServerSoundParams
204 std::string to_player;
212 float max_hear_distance;
221 max_hear_distance(32*BS),
225 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
228 struct ServerPlayingSound
230 ServerSoundParams params;
231 std::set<u16> clients; // peer ids
237 // peer_id=0 means this client has no associated peer
238 // NOTE: If client is made allowed to exist while peer doesn't,
239 // this has to be set to 0 when there is no peer.
240 // Also, the client must be moved to some other container.
242 // The serialization version to use with the client
243 u8 serialization_version;
245 u16 net_proto_version;
246 // Version is stored in here after INIT before INIT2
247 u8 pending_serialization_version;
249 bool definitions_sent;
252 m_time_from_building(9999),
253 m_excess_gotblocks(0)
256 serialization_version = SER_FMT_VER_INVALID;
257 net_proto_version = 0;
258 pending_serialization_version = SER_FMT_VER_INVALID;
259 definitions_sent = false;
260 m_nearest_unsent_d = 0;
261 m_nearest_unsent_reset_timer = 0.0;
262 m_nothing_to_send_counter = 0;
263 m_nothing_to_send_pause_timer = 0;
270 Finds block that should be sent next to the client.
271 Environment should be locked when this is called.
272 dtime is used for resetting send radius at slow interval
274 void GetNextBlocks(Server *server, float dtime,
275 std::vector<PrioritySortedBlockTransfer> &dest);
277 void GotBlock(v3s16 p);
279 void SentBlock(v3s16 p);
281 void SetBlockNotSent(v3s16 p);
282 void SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks);
286 return m_blocks_sending.size();
289 // Increments timeouts and removes timed-out blocks from list
290 // NOTE: This doesn't fix the server-not-sending-block bug
291 // because it is related to emerging, not sending.
292 //void RunSendingTimeouts(float dtime, float timeout);
294 void PrintInfo(std::ostream &o)
296 o<<"RemoteClient "<<peer_id<<": "
297 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
298 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
299 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
300 <<", m_excess_gotblocks="<<m_excess_gotblocks
302 m_excess_gotblocks = 0;
305 // Time from last placing or removing blocks
306 float m_time_from_building;
308 /*JMutex m_dig_mutex;
309 float m_dig_time_remaining;
312 v3s16 m_dig_position;*/
315 List of active objects that the client knows of.
318 std::set<u16> m_known_objects;
322 Blocks that have been sent to client.
323 - These don't have to be sent again.
324 - A block is cleared from here when client says it has
325 deleted it from it's memory
327 Key is position, value is dummy.
328 No MapBlock* is stored here because the blocks can get deleted.
330 std::set<v3s16> m_blocks_sent;
331 s16 m_nearest_unsent_d;
333 float m_nearest_unsent_reset_timer;
336 Blocks that are currently on the line.
337 This is used for throttling the sending of blocks.
338 - The size of this list is limited to some value
339 Block is added when it is sent with BLOCKDATA.
340 Block is removed when GOTBLOCKS is received.
341 Value is time from sending. (not used at the moment)
343 std::map<v3s16, float> m_blocks_sending;
346 Count of excess GotBlocks().
347 There is an excess amount because the client sometimes
348 gets a block so late that the server sends it again,
349 and the client then sends two GOTBLOCKs.
350 This is resetted by PrintInfo()
352 u32 m_excess_gotblocks;
354 // CPU usage optimization
355 u32 m_nothing_to_send_counter;
356 float m_nothing_to_send_pause_timer;
359 class Server : public con::PeerHandler, public MapEventReceiver,
360 public InventoryManager, public IGameDef,
361 public IBackgroundBlockEmerger
365 NOTE: Every public method should be thread-safe
369 const std::string &path_world,
370 const std::string &path_config,
371 const SubgameSpec &gamespec,
372 bool simple_singleplayer_mode
375 void start(unsigned short port);
377 // This is mainly a way to pass the time to the server.
378 // Actual processing is done in an another thread.
379 void step(float dtime);
380 // This is run by ServerThread and does the actual processing
383 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
385 std::list<PlayerInfo> getPlayerInfo();
387 // Environment must be locked when called
388 void setTimeOfDay(u32 time)
390 m_env->setTimeOfDay(time);
391 m_time_of_day_send_timer = 0;
394 bool getShutdownRequested()
396 return m_shutdown_requested;
400 Shall be called with the environment locked.
401 This is accessed by the map, which is inside the environment,
402 so it shouldn't be a problem.
404 void onMapEditEvent(MapEditEvent *event);
407 Shall be called with the environment and the connection locked.
409 Inventory* getInventory(const InventoryLocation &loc);
410 void setInventoryModified(const InventoryLocation &loc);
412 // Connection must be locked when called
413 std::wstring getStatusString();
415 void requestShutdown(void)
417 m_shutdown_requested = true;
420 // Returns -1 if failed, sound handle on success
422 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
423 void stopSound(s32 handle);
426 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
427 bool checkPriv(const std::string &name, const std::string &priv);
428 void reportPrivsModified(const std::string &name=""); // ""=all
429 void reportInventoryFormspecModified(const std::string &name);
431 // Saves g_settings to configpath given at initialization
434 void setIpBanned(const std::string &ip, const std::string &name)
436 m_banmanager.add(ip, name);
440 void unsetIpBanned(const std::string &ip_or_name)
442 m_banmanager.remove(ip_or_name);
446 std::string getBanDescription(const std::string &ip_or_name)
448 return m_banmanager.getBanDescription(ip_or_name);
451 Address getPeerAddress(u16 peer_id)
453 return m_con.GetPeerAddress(peer_id);
456 // Envlock and conlock should be locked when calling this
457 void notifyPlayer(const char *name, const std::wstring msg);
458 void notifyPlayers(const std::wstring msg);
459 void spawnParticle(const char *playername,
460 v3f pos, v3f velocity, v3f acceleration,
461 float expirationtime, float size,
462 bool collisiondetection, std::string texture);
464 void spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
465 float expirationtime, float size,
466 bool collisiondetection, std::string texture);
468 u32 addParticleSpawner(const char *playername,
469 u16 amount, float spawntime,
470 v3f minpos, v3f maxpos,
471 v3f minvel, v3f maxvel,
472 v3f minacc, v3f maxacc,
473 float minexptime, float maxexptime,
474 float minsize, float maxsize,
475 bool collisiondetection, std::string texture);
477 u32 addParticleSpawnerAll(u16 amount, float spawntime,
478 v3f minpos, v3f maxpos,
479 v3f minvel, v3f maxvel,
480 v3f minacc, v3f maxacc,
481 float minexptime, float maxexptime,
482 float minsize, float maxsize,
483 bool collisiondetection, std::string texture);
485 void deleteParticleSpawner(const char *playername, u32 id);
486 void deleteParticleSpawnerAll(u32 id);
488 void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
490 // Creates or resets inventory
491 Inventory* createDetachedInventory(const std::string &name);
493 // Envlock and conlock should be locked when using Lua
494 lua_State *getLua(){ return m_lua; }
496 // Envlock should be locked when using the rollback manager
497 IRollbackManager *getRollbackManager(){ return m_rollback; }
499 //TODO: determine what (if anything) should be locked to access EmergeManager
500 EmergeManager *getEmergeManager(){ return m_emerge; }
502 // actions: time-reversed list
503 // Return value: success/failure
504 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
505 std::list<std::string> *log);
507 // IGameDef interface
509 virtual IItemDefManager* getItemDefManager();
510 virtual INodeDefManager* getNodeDefManager();
511 virtual ICraftDefManager* getCraftDefManager();
512 virtual ITextureSource* getTextureSource();
513 virtual IShaderSource* getShaderSource();
514 virtual u16 allocateUnknownNodeId(const std::string &name);
515 virtual ISoundManager* getSoundManager();
516 virtual MtEventManager* getEventManager();
517 virtual IRollbackReportSink* getRollbackReportSink();
519 IWritableItemDefManager* getWritableItemDefManager();
520 IWritableNodeDefManager* getWritableNodeDefManager();
521 IWritableCraftDefManager* getWritableCraftDefManager();
523 const ModSpec* getModSpec(const std::string &modname);
524 void getModNames(std::list<std::string> &modlist);
525 std::string getBuiltinLuaPath();
527 std::string getWorldPath(){ return m_path_world; }
529 bool isSingleplayer(){ return m_simple_singleplayer_mode; }
531 void setAsyncFatalError(const std::string &error)
533 m_async_fatal_error.set(error);
536 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
539 // con::PeerHandler implementation.
540 // These queue stuff to be processed by handlePeerChanges().
541 // As of now, these create and remove clients and players.
542 void peerAdded(con::Peer *peer);
543 void deletingPeer(con::Peer *peer, bool timeout);
549 static void SendMovement(con::Connection &con, u16 peer_id);
550 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
551 static void SendAccessDenied(con::Connection &con, u16 peer_id,
552 const std::wstring &reason);
553 static void SendDeathscreen(con::Connection &con, u16 peer_id,
554 bool set_camera_point_target, v3f camera_point_target);
555 static void SendItemDef(con::Connection &con, u16 peer_id,
556 IItemDefManager *itemdef, u16 protocol_version);
557 static void SendNodeDef(con::Connection &con, u16 peer_id,
558 INodeDefManager *nodedef, u16 protocol_version);
561 Non-static send methods.
562 Conlock should be always used.
563 Envlock usage is documented badly but it's easy to figure out
564 which ones access the environment.
567 // Envlock and conlock should be locked when calling these
568 void SendInventory(u16 peer_id);
569 void SendChatMessage(u16 peer_id, const std::wstring &message);
570 void BroadcastChatMessage(const std::wstring &message);
571 void SendPlayerHP(u16 peer_id);
572 void SendMovePlayer(u16 peer_id);
573 void SendPlayerPrivileges(u16 peer_id);
574 void SendPlayerInventoryFormspec(u16 peer_id);
575 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
577 Send a node removal/addition event to all clients except ignore_id.
578 Additionally, if far_players!=NULL, players further away than
579 far_d_nodes are ignored and their peer_ids are added to far_players
581 // Envlock and conlock should be locked when calling these
582 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
583 std::list<u16> *far_players=NULL, float far_d_nodes=100);
584 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
585 std::list<u16> *far_players=NULL, float far_d_nodes=100);
586 void setBlockNotSent(v3s16 p);
588 // Environment and Connection must be locked when called
589 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
591 // Sends blocks to clients (locks env and con on its own)
592 void SendBlocks(float dtime);
594 void fillMediaCache();
595 void sendMediaAnnouncement(u16 peer_id);
596 void sendRequestedMedia(u16 peer_id,
597 const std::list<MediaRequest> &tosend);
599 void sendDetachedInventory(const std::string &name, u16 peer_id);
600 void sendDetachedInventoryToAll(const std::string &name);
601 void sendDetachedInventories(u16 peer_id);
603 // Adds a ParticleSpawner on peer with peer_id
604 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
605 v3f minpos, v3f maxpos,
606 v3f minvel, v3f maxvel,
607 v3f minacc, v3f maxacc,
608 float minexptime, float maxexptime,
609 float minsize, float maxsize,
610 bool collisiondetection, std::string texture, u32 id);
612 // Adds a ParticleSpawner on all peers
613 void SendAddParticleSpawnerAll(u16 amount, float spawntime,
614 v3f minpos, v3f maxpos,
615 v3f minvel, v3f maxvel,
616 v3f minacc, v3f maxacc,
617 float minexptime, float maxexptime,
618 float minsize, float maxsize,
619 bool collisiondetection, std::string texture, u32 id);
621 // Deletes ParticleSpawner on a single client
622 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
624 // Deletes ParticleSpawner on all clients
625 void SendDeleteParticleSpawnerAll(u32 id);
627 // Spawns particle on single client
628 void SendSpawnParticle(u16 peer_id,
629 v3f pos, v3f velocity, v3f acceleration,
630 float expirationtime, float size,
631 bool collisiondetection, std::string texture);
633 // Spawns particle on all clients
634 void SendSpawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
635 float expirationtime, float size,
636 bool collisiondetection, std::string texture);
642 void DiePlayer(u16 peer_id);
643 void RespawnPlayer(u16 peer_id);
645 void UpdateCrafting(u16 peer_id);
647 // When called, connection mutex should be locked
648 RemoteClient* getClient(u16 peer_id);
650 // When called, environment mutex should be locked
651 std::string getPlayerName(u16 peer_id)
653 Player *player = m_env->getPlayer(peer_id);
655 return "[id="+itos(peer_id)+"]";
656 return player->getName();
659 // When called, environment mutex should be locked
660 PlayerSAO* getPlayerSAO(u16 peer_id)
662 Player *player = m_env->getPlayer(peer_id);
665 return player->getPlayerSAO();
669 Get a player from memory or creates one.
670 If player is already connected, return NULL
671 Does not verify/modify auth info and password.
673 Call with env and con locked.
675 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
677 // Locks environment and connection by its own
679 void handlePeerChange(PeerChange &c);
680 void handlePeerChanges();
687 std::string m_path_world;
688 // Path to user's configuration file ("" = no configuration file)
689 std::string m_path_config;
690 // Subgame specification
691 SubgameSpec m_gamespec;
692 // If true, do not allow multiple players and hide some multiplayer
694 bool m_simple_singleplayer_mode;
696 // Thread can set; step() will throw as ServerError
697 MutexedVariable<std::string> m_async_fatal_error;
700 float m_liquid_transform_timer;
701 float m_liquid_transform_every;
702 float m_print_info_timer;
703 float m_masterserver_timer;
704 float m_objectdata_timer;
705 float m_emergethread_trigger_timer;
706 float m_savemap_timer;
707 IntervalLimiter m_map_timer_and_unload_interval;
709 // NOTE: If connection and environment are both to be locked,
710 // environment shall be locked first.
713 ServerEnvironment *m_env;
717 con::Connection m_con;
719 // Connected clients (behind the con mutex)
720 std::map<u16, RemoteClient*> m_clients;
721 u16 m_clients_number; //for announcing masterserver
724 BanManager m_banmanager;
726 // Rollback manager (behind m_env_mutex)
727 IRollbackManager *m_rollback;
728 bool m_rollback_sink_enabled;
729 bool m_enable_rollback_recording; // Updated once in a while
732 EmergeManager *m_emerge;
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 std::vector<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;
769 // Timer for sending time of day over network
770 float m_time_of_day_send_timer;
771 // Uptime of server in seconds
772 MutexedVariable<double> m_uptime;
776 Queues stuff from peerAdded() and deletingPeer() to
790 Queue<PeerChange> m_peer_change_queue;
796 // Mod parent directory paths
797 std::list<std::string> m_modspaths;
799 bool m_shutdown_requested;
802 Map edit event queue. Automatically receives all map edits.
803 The constructor of this class registers us to receive them through
806 NOTE: Should these be moved to actually be members of
811 Queue of map edits from the environment for sending to the clients
812 This is behind m_env_mutex
814 Queue<MapEditEvent*> m_unsent_map_edit_queue;
816 Set to true when the server itself is modifying the map and does
817 all sending of information by itself.
818 This is behind m_env_mutex
820 bool m_ignore_map_edit_events;
822 If a non-empty area, map edit events contained within are left
823 unsent. Done at map generation time to speed up editing of the
824 generated area, as it will be sent anyway.
825 This is behind m_env_mutex
827 VoxelArea m_ignore_map_edit_events_area;
829 If set to !=0, the incoming MapEditEvents are modified to have
830 this peed id as the disabled recipient
831 This is behind m_env_mutex
833 u16 m_ignore_map_edit_events_peer_id;
835 friend class EmergeThread;
836 friend class RemoteClient;
838 std::map<std::string,MediaInfo> m_media;
843 std::map<s32, ServerPlayingSound> m_playing_sounds;
847 Detached inventories (behind m_env_mutex)
850 std::map<std::string, Inventory*> m_detached_inventories;
855 std::vector<u32> m_particlespawner_ids;
859 Runs a simple dedicated server loop.
861 Shuts down when run is set to false.
863 void dedicated_server_loop(Server &server, bool &run);