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"
33 #include "serialization.h" // For SER_FMT_VER_INVALID
35 #include "inventorymanager.h"
38 #include "util/thread.h"
39 #include "util/string.h"
40 #include "rollback_interface.h" // Needed for rollbackRevertActions()
41 #include <list> // Needed for rollbackRevertActions()
44 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
46 class IWritableItemDefManager;
47 class IWritableNodeDefManager;
48 class IWritableCraftDefManager;
51 class IRollbackManager;
53 //struct HudElement; ?????????
57 class ServerError : public std::exception
60 ServerError(const std::string &s)
62 m_s = "ServerError: ";
65 virtual ~ServerError() throw()
67 virtual const char * what() const throw()
77 v3f findSpawnPos(ServerMap &map);
80 class MapEditEventIgnorer
83 MapEditEventIgnorer(bool *flag):
92 ~MapEditEventIgnorer()
105 class MapEditEventAreaIgnorer
108 MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
109 m_ignorevariable(ignorevariable)
111 if(m_ignorevariable->getVolume() == 0)
112 *m_ignorevariable = a;
114 m_ignorevariable = NULL;
117 ~MapEditEventAreaIgnorer()
121 assert(m_ignorevariable->getVolume() != 0);
122 *m_ignorevariable = VoxelArea();
127 VoxelArea *m_ignorevariable;
132 class ServerThread : public SimpleThread
138 ServerThread(Server *server):
150 char name[PLAYERNAME_SIZE];
156 void PrintLine(std::ostream *s);
160 Used for queueing and sorting block transfers in containers
162 Lower priority number means higher priority.
164 struct PrioritySortedBlockTransfer
166 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
168 priority = a_priority;
172 bool operator < (const PrioritySortedBlockTransfer &other) const
174 return priority < other.priority;
185 MediaRequest(const std::string &name_=""):
193 std::string sha1_digest;
195 MediaInfo(const std::string path_="",
196 const std::string sha1_digest_=""):
198 sha1_digest(sha1_digest_)
203 struct ServerSoundParams
206 std::string to_player;
214 float max_hear_distance;
223 max_hear_distance(32*BS),
227 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
230 struct ServerPlayingSound
232 ServerSoundParams params;
233 std::set<u16> clients; // peer ids
239 // peer_id=0 means this client has no associated peer
240 // NOTE: If client is made allowed to exist while peer doesn't,
241 // this has to be set to 0 when there is no peer.
242 // Also, the client must be moved to some other container.
244 // The serialization version to use with the client
245 u8 serialization_version;
247 u16 net_proto_version;
248 // Version is stored in here after INIT before INIT2
249 u8 pending_serialization_version;
251 bool definitions_sent;
256 m_time_from_building(9999),
257 m_excess_gotblocks(0)
260 serialization_version = SER_FMT_VER_INVALID;
261 net_proto_version = 0;
262 pending_serialization_version = SER_FMT_VER_INVALID;
263 definitions_sent = false;
265 m_nearest_unsent_d = 0;
266 m_nearest_unsent_reset_timer = 0.0;
267 m_nothing_to_send_counter = 0;
268 m_nothing_to_send_pause_timer = 0;
275 Finds block that should be sent next to the client.
276 Environment should be locked when this is called.
277 dtime is used for resetting send radius at slow interval
279 void GetNextBlocks(Server *server, float dtime,
280 std::vector<PrioritySortedBlockTransfer> &dest);
282 void GotBlock(v3s16 p);
284 void SentBlock(v3s16 p);
286 void SetBlockNotSent(v3s16 p);
287 void SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks);
291 return m_blocks_sending.size();
294 // Increments timeouts and removes timed-out blocks from list
295 // NOTE: This doesn't fix the server-not-sending-block bug
296 // because it is related to emerging, not sending.
297 //void RunSendingTimeouts(float dtime, float timeout);
299 void PrintInfo(std::ostream &o)
301 o<<"RemoteClient "<<peer_id<<": "
302 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
303 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
304 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
305 <<", m_excess_gotblocks="<<m_excess_gotblocks
307 m_excess_gotblocks = 0;
310 // Time from last placing or removing blocks
311 float m_time_from_building;
313 /*JMutex m_dig_mutex;
314 float m_dig_time_remaining;
317 v3s16 m_dig_position;*/
320 List of active objects that the client knows of.
323 std::set<u16> m_known_objects;
327 Blocks that have been sent to client.
328 - These don't have to be sent again.
329 - A block is cleared from here when client says it has
330 deleted it from it's memory
332 Key is position, value is dummy.
333 No MapBlock* is stored here because the blocks can get deleted.
335 std::set<v3s16> m_blocks_sent;
336 s16 m_nearest_unsent_d;
338 float m_nearest_unsent_reset_timer;
341 Blocks that are currently on the line.
342 This is used for throttling the sending of blocks.
343 - The size of this list is limited to some value
344 Block is added when it is sent with BLOCKDATA.
345 Block is removed when GOTBLOCKS is received.
346 Value is time from sending. (not used at the moment)
348 std::map<v3s16, float> m_blocks_sending;
351 Count of excess GotBlocks().
352 There is an excess amount because the client sometimes
353 gets a block so late that the server sends it again,
354 and the client then sends two GOTBLOCKs.
355 This is resetted by PrintInfo()
357 u32 m_excess_gotblocks;
359 // CPU usage optimization
360 u32 m_nothing_to_send_counter;
361 float m_nothing_to_send_pause_timer;
364 class Server : public con::PeerHandler, public MapEventReceiver,
365 public InventoryManager, public IGameDef,
366 public IBackgroundBlockEmerger
370 NOTE: Every public method should be thread-safe
374 const std::string &path_world,
375 const std::string &path_config,
376 const SubgameSpec &gamespec,
377 bool simple_singleplayer_mode
380 void start(unsigned short port);
382 // This is mainly a way to pass the time to the server.
383 // Actual processing is done in an another thread.
384 void step(float dtime);
385 // This is run by ServerThread and does the actual processing
388 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
390 //std::list<PlayerInfo> getPlayerInfo();
392 // Environment must be locked when called
393 void setTimeOfDay(u32 time)
395 m_env->setTimeOfDay(time);
396 m_time_of_day_send_timer = 0;
399 bool getShutdownRequested()
401 return m_shutdown_requested;
405 Shall be called with the environment locked.
406 This is accessed by the map, which is inside the environment,
407 so it shouldn't be a problem.
409 void onMapEditEvent(MapEditEvent *event);
412 Shall be called with the environment and the connection locked.
414 Inventory* getInventory(const InventoryLocation &loc);
415 void setInventoryModified(const InventoryLocation &loc);
417 // Connection must be locked when called
418 std::wstring getStatusString();
420 void requestShutdown(void)
422 m_shutdown_requested = true;
425 // Returns -1 if failed, sound handle on success
427 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
428 void stopSound(s32 handle);
431 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
432 bool checkPriv(const std::string &name, const std::string &priv);
433 void reportPrivsModified(const std::string &name=""); // ""=all
434 void reportInventoryFormspecModified(const std::string &name);
436 // Saves g_settings to configpath given at initialization
439 void setIpBanned(const std::string &ip, const std::string &name)
441 m_banmanager.add(ip, name);
445 void unsetIpBanned(const std::string &ip_or_name)
447 m_banmanager.remove(ip_or_name);
451 std::string getBanDescription(const std::string &ip_or_name)
453 return m_banmanager.getBanDescription(ip_or_name);
456 Address getPeerAddress(u16 peer_id)
458 return m_con.GetPeerAddress(peer_id);
461 // Envlock and conlock should be locked when calling this
462 void notifyPlayer(const char *name, const std::wstring msg, const bool prepend);
463 void notifyPlayers(const std::wstring msg);
464 void spawnParticle(const char *playername,
465 v3f pos, v3f velocity, v3f acceleration,
466 float expirationtime, float size,
467 bool collisiondetection, std::string texture);
469 void spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
470 float expirationtime, float size,
471 bool collisiondetection, std::string texture);
473 u32 addParticleSpawner(const char *playername,
474 u16 amount, float spawntime,
475 v3f minpos, v3f maxpos,
476 v3f minvel, v3f maxvel,
477 v3f minacc, v3f maxacc,
478 float minexptime, float maxexptime,
479 float minsize, float maxsize,
480 bool collisiondetection, std::string texture);
482 u32 addParticleSpawnerAll(u16 amount, float spawntime,
483 v3f minpos, v3f maxpos,
484 v3f minvel, v3f maxvel,
485 v3f minacc, v3f maxacc,
486 float minexptime, float maxexptime,
487 float minsize, float maxsize,
488 bool collisiondetection, std::string texture);
490 void deleteParticleSpawner(const char *playername, u32 id);
491 void deleteParticleSpawnerAll(u32 id);
493 void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
495 // Creates or resets inventory
496 Inventory* createDetachedInventory(const std::string &name);
498 // Envlock and conlock should be locked when using scriptapi
499 ScriptApi *getScriptIface(){ return m_script; }
501 // Envlock should be locked when using the rollback manager
502 IRollbackManager *getRollbackManager(){ return m_rollback; }
504 //TODO: determine what (if anything) should be locked to access EmergeManager
505 EmergeManager *getEmergeManager(){ return m_emerge; }
507 // actions: time-reversed list
508 // Return value: success/failure
509 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
510 std::list<std::string> *log);
512 // IGameDef interface
514 virtual IItemDefManager* getItemDefManager();
515 virtual INodeDefManager* getNodeDefManager();
516 virtual ICraftDefManager* getCraftDefManager();
517 virtual ITextureSource* getTextureSource();
518 virtual IShaderSource* getShaderSource();
519 virtual u16 allocateUnknownNodeId(const std::string &name);
520 virtual ISoundManager* getSoundManager();
521 virtual MtEventManager* getEventManager();
522 virtual IRollbackReportSink* getRollbackReportSink();
524 IWritableItemDefManager* getWritableItemDefManager();
525 IWritableNodeDefManager* getWritableNodeDefManager();
526 IWritableCraftDefManager* getWritableCraftDefManager();
528 const ModSpec* getModSpec(const std::string &modname);
529 void getModNames(std::list<std::string> &modlist);
530 std::string getBuiltinLuaPath();
532 std::string getWorldPath(){ return m_path_world; }
534 bool isSingleplayer(){ return m_simple_singleplayer_mode; }
536 void setAsyncFatalError(const std::string &error)
538 m_async_fatal_error.set(error);
541 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
543 u32 hudAdd(Player *player, HudElement *element);
544 bool hudRemove(Player *player, u32 id);
545 bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
546 bool hudSetFlags(Player *player, u32 flags, u32 mask);
547 bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
551 // con::PeerHandler implementation.
552 // These queue stuff to be processed by handlePeerChanges().
553 // As of now, these create and remove clients and players.
554 void peerAdded(con::Peer *peer);
555 void deletingPeer(con::Peer *peer, bool timeout);
561 static void SendMovement(con::Connection &con, u16 peer_id);
562 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
563 static void SendBreath(con::Connection &con, u16 peer_id, u16 breath);
564 static void SendAccessDenied(con::Connection &con, u16 peer_id,
565 const std::wstring &reason);
566 static void SendDeathscreen(con::Connection &con, u16 peer_id,
567 bool set_camera_point_target, v3f camera_point_target);
568 static void SendItemDef(con::Connection &con, u16 peer_id,
569 IItemDefManager *itemdef, u16 protocol_version);
570 static void SendNodeDef(con::Connection &con, u16 peer_id,
571 INodeDefManager *nodedef, u16 protocol_version);
574 Non-static send methods.
575 Conlock should be always used.
576 Envlock usage is documented badly but it's easy to figure out
577 which ones access the environment.
580 // Envlock and conlock should be locked when calling these
581 void SendInventory(u16 peer_id);
582 void SendChatMessage(u16 peer_id, const std::wstring &message);
583 void BroadcastChatMessage(const std::wstring &message);
584 void SendPlayerHP(u16 peer_id);
585 void SendPlayerBreath(u16 peer_id);
586 void SendMovePlayer(u16 peer_id);
587 void SendPlayerPrivileges(u16 peer_id);
588 void SendPlayerInventoryFormspec(u16 peer_id);
589 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
590 void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
591 void SendHUDRemove(u16 peer_id, u32 id);
592 void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
593 void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
594 void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
597 Send a node removal/addition event to all clients except ignore_id.
598 Additionally, if far_players!=NULL, players further away than
599 far_d_nodes are ignored and their peer_ids are added to far_players
601 // Envlock and conlock should be locked when calling these
602 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
603 std::list<u16> *far_players=NULL, float far_d_nodes=100);
604 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
605 std::list<u16> *far_players=NULL, float far_d_nodes=100);
606 void setBlockNotSent(v3s16 p);
608 // Environment and Connection must be locked when called
609 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
611 // Sends blocks to clients (locks env and con on its own)
612 void SendBlocks(float dtime);
614 void fillMediaCache();
615 void sendMediaAnnouncement(u16 peer_id);
616 void sendRequestedMedia(u16 peer_id,
617 const std::list<MediaRequest> &tosend);
619 void sendDetachedInventory(const std::string &name, u16 peer_id);
620 void sendDetachedInventoryToAll(const std::string &name);
621 void sendDetachedInventories(u16 peer_id);
623 // Adds a ParticleSpawner on peer with peer_id
624 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
625 v3f minpos, v3f maxpos,
626 v3f minvel, v3f maxvel,
627 v3f minacc, v3f maxacc,
628 float minexptime, float maxexptime,
629 float minsize, float maxsize,
630 bool collisiondetection, std::string texture, u32 id);
632 // Adds a ParticleSpawner on all peers
633 void SendAddParticleSpawnerAll(u16 amount, float spawntime,
634 v3f minpos, v3f maxpos,
635 v3f minvel, v3f maxvel,
636 v3f minacc, v3f maxacc,
637 float minexptime, float maxexptime,
638 float minsize, float maxsize,
639 bool collisiondetection, std::string texture, u32 id);
641 // Deletes ParticleSpawner on a single client
642 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
644 // Deletes ParticleSpawner on all clients
645 void SendDeleteParticleSpawnerAll(u32 id);
647 // Spawns particle on single client
648 void SendSpawnParticle(u16 peer_id,
649 v3f pos, v3f velocity, v3f acceleration,
650 float expirationtime, float size,
651 bool collisiondetection, std::string texture);
653 // Spawns particle on all clients
654 void SendSpawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
655 float expirationtime, float size,
656 bool collisiondetection, std::string texture);
662 void DiePlayer(u16 peer_id);
663 void RespawnPlayer(u16 peer_id);
664 void DenyAccess(u16 peer_id, const std::wstring &reason);
666 enum ClientDeletionReason {
671 void DeleteClient(u16 peer_id, ClientDeletionReason reason);
673 void UpdateCrafting(u16 peer_id);
675 // When called, connection mutex should be locked
676 RemoteClient* getClient(u16 peer_id);
677 RemoteClient* getClientNoEx(u16 peer_id);
679 // When called, environment mutex should be locked
680 std::string getPlayerName(u16 peer_id)
682 Player *player = m_env->getPlayer(peer_id);
684 return "[id="+itos(peer_id)+"]";
685 return player->getName();
688 // When called, environment mutex should be locked
689 PlayerSAO* getPlayerSAO(u16 peer_id)
691 Player *player = m_env->getPlayer(peer_id);
694 return player->getPlayerSAO();
698 Get a player from memory or creates one.
699 If player is already connected, return NULL
700 Does not verify/modify auth info and password.
702 Call with env and con locked.
704 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
706 // Locks environment and connection by its own
708 void handlePeerChange(PeerChange &c);
709 void handlePeerChanges();
716 std::string m_path_world;
717 // Path to user's configuration file ("" = no configuration file)
718 std::string m_path_config;
719 // Subgame specification
720 SubgameSpec m_gamespec;
721 // If true, do not allow multiple players and hide some multiplayer
723 bool m_simple_singleplayer_mode;
725 // Thread can set; step() will throw as ServerError
726 MutexedVariable<std::string> m_async_fatal_error;
729 float m_liquid_transform_timer;
730 float m_liquid_transform_every;
731 float m_print_info_timer;
732 float m_masterserver_timer;
733 float m_objectdata_timer;
734 float m_emergethread_trigger_timer;
735 float m_savemap_timer;
736 IntervalLimiter m_map_timer_and_unload_interval;
738 // NOTE: If connection and environment are both to be locked,
739 // environment shall be locked first.
742 ServerEnvironment *m_env;
746 con::Connection m_con;
748 // Connected clients (behind the con mutex)
749 std::map<u16, RemoteClient*> m_clients;
750 u16 m_clients_number; //for announcing masterserver
753 BanManager m_banmanager;
755 // Rollback manager (behind m_env_mutex)
756 IRollbackManager *m_rollback;
757 bool m_rollback_sink_enabled;
758 bool m_enable_rollback_recording; // Updated once in a while
761 EmergeManager *m_emerge;
764 // Envlock and conlock should be locked when using Lua
767 // Item definition manager
768 IWritableItemDefManager *m_itemdef;
770 // Node definition manager
771 IWritableNodeDefManager *m_nodedef;
773 // Craft definition manager
774 IWritableCraftDefManager *m_craftdef;
777 EventManager *m_event;
780 std::vector<ModSpec> m_mods;
786 // A buffer for time steps
787 // step() increments and AsyncRunStep() run by m_thread reads it.
789 JMutex m_step_dtime_mutex;
791 // The server mainly operates in this thread
792 ServerThread m_thread;
798 // Timer for sending time of day over network
799 float m_time_of_day_send_timer;
800 // Uptime of server in seconds
801 MutexedVariable<double> m_uptime;
805 Queues stuff from peerAdded() and deletingPeer() to
819 Queue<PeerChange> m_peer_change_queue;
825 // Mod parent directory paths
826 std::list<std::string> m_modspaths;
828 bool m_shutdown_requested;
831 Map edit event queue. Automatically receives all map edits.
832 The constructor of this class registers us to receive them through
835 NOTE: Should these be moved to actually be members of
840 Queue of map edits from the environment for sending to the clients
841 This is behind m_env_mutex
843 Queue<MapEditEvent*> m_unsent_map_edit_queue;
845 Set to true when the server itself is modifying the map and does
846 all sending of information by itself.
847 This is behind m_env_mutex
849 bool m_ignore_map_edit_events;
851 If a non-empty area, map edit events contained within are left
852 unsent. Done at map generation time to speed up editing of the
853 generated area, as it will be sent anyway.
854 This is behind m_env_mutex
856 VoxelArea m_ignore_map_edit_events_area;
858 If set to !=0, the incoming MapEditEvents are modified to have
859 this peed id as the disabled recipient
860 This is behind m_env_mutex
862 u16 m_ignore_map_edit_events_peer_id;
864 friend class EmergeThread;
865 friend class RemoteClient;
867 std::map<std::string,MediaInfo> m_media;
872 std::map<s32, ServerPlayingSound> m_playing_sounds;
876 Detached inventories (behind m_env_mutex)
879 std::map<std::string, Inventory*> m_detached_inventories;
884 std::vector<u32> m_particlespawner_ids;
888 Runs a simple dedicated server loop.
890 Shuts down when run is set to false.
892 void dedicated_server_loop(Server &server, bool &run);