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"
28 #include "serialization.h" // For SER_FMT_VER_INVALID
30 #include "inventorymanager.h"
32 #include "rollback_interface.h" // Needed for rollbackRevertActions()
33 #include "util/numeric.h"
34 #include "util/thread.h"
35 #include "environment.h"
41 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
43 class IWritableItemDefManager;
44 class IWritableNodeDefManager;
45 class IWritableCraftDefManager;
51 class IRollbackManager;
54 class ServerEnvironment;
55 struct SimpleSoundSpec;
58 class ServerError : public std::exception
61 ServerError(const std::string &s)
63 m_s = "ServerError: ";
66 virtual ~ServerError() throw()
68 virtual const char * what() const throw()
78 v3f findSpawnPos(ServerMap &map);
81 class MapEditEventIgnorer
84 MapEditEventIgnorer(bool *flag):
93 ~MapEditEventIgnorer()
106 class MapEditEventAreaIgnorer
109 MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
110 m_ignorevariable(ignorevariable)
112 if(m_ignorevariable->getVolume() == 0)
113 *m_ignorevariable = a;
115 m_ignorevariable = NULL;
118 ~MapEditEventAreaIgnorer()
122 assert(m_ignorevariable->getVolume() != 0);
123 *m_ignorevariable = VoxelArea();
128 VoxelArea *m_ignorevariable;
135 Used for queueing and sorting block transfers in containers
137 Lower priority number means higher priority.
139 struct PrioritySortedBlockTransfer
141 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
143 priority = a_priority;
147 bool operator < (const PrioritySortedBlockTransfer &other) const
149 return priority < other.priority;
159 std::string sha1_digest;
161 MediaInfo(const std::string path_="",
162 const std::string sha1_digest_=""):
164 sha1_digest(sha1_digest_)
169 struct ServerSoundParams
172 std::string to_player;
180 float max_hear_distance;
189 max_hear_distance(32*BS),
193 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
196 struct ServerPlayingSound
198 ServerSoundParams params;
199 std::set<u16> clients; // peer ids
205 // peer_id=0 means this client has no associated peer
206 // NOTE: If client is made allowed to exist while peer doesn't,
207 // this has to be set to 0 when there is no peer.
208 // Also, the client must be moved to some other container.
210 // The serialization version to use with the client
211 u8 serialization_version;
213 u16 net_proto_version;
214 // Version is stored in here after INIT before INIT2
215 u8 pending_serialization_version;
217 bool definitions_sent;
222 m_time_from_building(9999),
223 m_excess_gotblocks(0)
226 serialization_version = SER_FMT_VER_INVALID;
227 net_proto_version = 0;
228 pending_serialization_version = SER_FMT_VER_INVALID;
229 definitions_sent = false;
231 m_nearest_unsent_d = 0;
232 m_nearest_unsent_reset_timer = 0.0;
233 m_nothing_to_send_counter = 0;
234 m_nothing_to_send_pause_timer = 0;
241 Finds block that should be sent next to the client.
242 Environment should be locked when this is called.
243 dtime is used for resetting send radius at slow interval
245 void GetNextBlocks(Server *server, float dtime,
246 std::vector<PrioritySortedBlockTransfer> &dest);
248 void GotBlock(v3s16 p);
250 void SentBlock(v3s16 p);
252 void SetBlockNotSent(v3s16 p);
253 void SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks);
257 return m_blocks_sending.size();
260 // Increments timeouts and removes timed-out blocks from list
261 // NOTE: This doesn't fix the server-not-sending-block bug
262 // because it is related to emerging, not sending.
263 //void RunSendingTimeouts(float dtime, float timeout);
265 void PrintInfo(std::ostream &o)
267 o<<"RemoteClient "<<peer_id<<": "
268 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
269 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
270 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
271 <<", m_excess_gotblocks="<<m_excess_gotblocks
273 m_excess_gotblocks = 0;
276 // Time from last placing or removing blocks
277 float m_time_from_building;
279 /*JMutex m_dig_mutex;
280 float m_dig_time_remaining;
283 v3s16 m_dig_position;*/
286 List of active objects that the client knows of.
289 std::set<u16> m_known_objects;
293 Blocks that have been sent to client.
294 - These don't have to be sent again.
295 - A block is cleared from here when client says it has
296 deleted it from it's memory
298 Key is position, value is dummy.
299 No MapBlock* is stored here because the blocks can get deleted.
301 std::set<v3s16> m_blocks_sent;
302 s16 m_nearest_unsent_d;
304 float m_nearest_unsent_reset_timer;
307 Blocks that are currently on the line.
308 This is used for throttling the sending of blocks.
309 - The size of this list is limited to some value
310 Block is added when it is sent with BLOCKDATA.
311 Block is removed when GOTBLOCKS is received.
312 Value is time from sending. (not used at the moment)
314 std::map<v3s16, float> m_blocks_sending;
317 Count of excess GotBlocks().
318 There is an excess amount because the client sometimes
319 gets a block so late that the server sends it again,
320 and the client then sends two GOTBLOCKs.
321 This is resetted by PrintInfo()
323 u32 m_excess_gotblocks;
325 // CPU usage optimization
326 u32 m_nothing_to_send_counter;
327 float m_nothing_to_send_pause_timer;
330 class Server : public con::PeerHandler, public MapEventReceiver,
331 public InventoryManager, public IGameDef
335 NOTE: Every public method should be thread-safe
339 const std::string &path_world,
340 const SubgameSpec &gamespec,
341 bool simple_singleplayer_mode
344 void start(unsigned short port);
346 // This is mainly a way to pass the time to the server.
347 // Actual processing is done in an another thread.
348 void step(float dtime);
349 // This is run by ServerThread and does the actual processing
352 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
354 // Environment must be locked when called
355 void setTimeOfDay(u32 time);
357 bool getShutdownRequested()
359 return m_shutdown_requested;
363 Shall be called with the environment locked.
364 This is accessed by the map, which is inside the environment,
365 so it shouldn't be a problem.
367 void onMapEditEvent(MapEditEvent *event);
370 Shall be called with the environment and the connection locked.
372 Inventory* getInventory(const InventoryLocation &loc);
373 void setInventoryModified(const InventoryLocation &loc);
375 // Connection must be locked when called
376 std::wstring getStatusString();
378 void requestShutdown(void)
380 m_shutdown_requested = true;
383 // Returns -1 if failed, sound handle on success
385 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
386 void stopSound(s32 handle);
389 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
390 bool checkPriv(const std::string &name, const std::string &priv);
391 void reportPrivsModified(const std::string &name=""); // ""=all
392 void reportInventoryFormspecModified(const std::string &name);
394 void setIpBanned(const std::string &ip, const std::string &name);
395 void unsetIpBanned(const std::string &ip_or_name);
396 std::string getBanDescription(const std::string &ip_or_name);
398 Address getPeerAddress(u16 peer_id)
400 return m_con.GetPeerAddress(peer_id);
403 // Envlock and conlock should be locked when calling this
404 void notifyPlayer(const char *name, const std::wstring msg, const bool prepend);
405 void notifyPlayers(const std::wstring msg);
406 void spawnParticle(const char *playername,
407 v3f pos, v3f velocity, v3f acceleration,
408 float expirationtime, float size,
409 bool collisiondetection, std::string texture);
411 void spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
412 float expirationtime, float size,
413 bool collisiondetection, std::string texture);
415 u32 addParticleSpawner(const char *playername,
416 u16 amount, float spawntime,
417 v3f minpos, v3f maxpos,
418 v3f minvel, v3f maxvel,
419 v3f minacc, v3f maxacc,
420 float minexptime, float maxexptime,
421 float minsize, float maxsize,
422 bool collisiondetection, std::string texture);
424 u32 addParticleSpawnerAll(u16 amount, float spawntime,
425 v3f minpos, v3f maxpos,
426 v3f minvel, v3f maxvel,
427 v3f minacc, v3f maxacc,
428 float minexptime, float maxexptime,
429 float minsize, float maxsize,
430 bool collisiondetection, std::string texture);
432 void deleteParticleSpawner(const char *playername, u32 id);
433 void deleteParticleSpawnerAll(u32 id);
435 // Creates or resets inventory
436 Inventory* createDetachedInventory(const std::string &name);
438 // Envlock and conlock should be locked when using scriptapi
439 GameScripting *getScriptIface(){ return m_script; }
441 // Envlock should be locked when using the rollback manager
442 IRollbackManager *getRollbackManager(){ return m_rollback; }
444 //TODO: determine what (if anything) should be locked to access EmergeManager
445 EmergeManager *getEmergeManager(){ return m_emerge; }
447 // actions: time-reversed list
448 // Return value: success/failure
449 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
450 std::list<std::string> *log);
452 // IGameDef interface
454 virtual IItemDefManager* getItemDefManager();
455 virtual INodeDefManager* getNodeDefManager();
456 virtual ICraftDefManager* getCraftDefManager();
457 virtual ITextureSource* getTextureSource();
458 virtual IShaderSource* getShaderSource();
459 virtual u16 allocateUnknownNodeId(const std::string &name);
460 virtual ISoundManager* getSoundManager();
461 virtual MtEventManager* getEventManager();
462 virtual IRollbackReportSink* getRollbackReportSink();
464 IWritableItemDefManager* getWritableItemDefManager();
465 IWritableNodeDefManager* getWritableNodeDefManager();
466 IWritableCraftDefManager* getWritableCraftDefManager();
468 const ModSpec* getModSpec(const std::string &modname);
469 void getModNames(std::list<std::string> &modlist);
470 std::string getBuiltinLuaPath();
472 std::string getWorldPath(){ return m_path_world; }
474 bool isSingleplayer(){ return m_simple_singleplayer_mode; }
476 void setAsyncFatalError(const std::string &error)
478 m_async_fatal_error.set(error);
481 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
482 Map & getMap() { return m_env->getMap(); }
483 ServerEnvironment & getEnv() { return *m_env; }
485 u32 hudAdd(Player *player, HudElement *element);
486 bool hudRemove(Player *player, u32 id);
487 bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
488 bool hudSetFlags(Player *player, u32 flags, u32 mask);
489 bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
490 void hudSetHotbarImage(Player *player, std::string name);
491 void hudSetHotbarSelectedImage(Player *player, std::string name);
495 // con::PeerHandler implementation.
496 // These queue stuff to be processed by handlePeerChanges().
497 // As of now, these create and remove clients and players.
498 void peerAdded(con::Peer *peer);
499 void deletingPeer(con::Peer *peer, bool timeout);
505 static void SendMovement(con::Connection &con, u16 peer_id);
506 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
507 static void SendBreath(con::Connection &con, u16 peer_id, u16 breath);
508 static void SendAccessDenied(con::Connection &con, u16 peer_id,
509 const std::wstring &reason);
510 static void SendDeathscreen(con::Connection &con, u16 peer_id,
511 bool set_camera_point_target, v3f camera_point_target);
512 static void SendItemDef(con::Connection &con, u16 peer_id,
513 IItemDefManager *itemdef, u16 protocol_version);
514 static void SendNodeDef(con::Connection &con, u16 peer_id,
515 INodeDefManager *nodedef, u16 protocol_version);
518 Non-static send methods.
519 Conlock should be always used.
520 Envlock usage is documented badly but it's easy to figure out
521 which ones access the environment.
524 // Envlock and conlock should be locked when calling these
525 void SendInventory(u16 peer_id);
526 void SendChatMessage(u16 peer_id, const std::wstring &message);
527 void BroadcastChatMessage(const std::wstring &message);
528 void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
529 void SendPlayerHP(u16 peer_id);
530 void SendPlayerBreath(u16 peer_id);
531 void SendMovePlayer(u16 peer_id);
532 void SendPlayerPrivileges(u16 peer_id);
533 void SendPlayerInventoryFormspec(u16 peer_id);
534 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
535 void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
536 void SendHUDRemove(u16 peer_id, u32 id);
537 void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
538 void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
539 void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
542 Send a node removal/addition event to all clients except ignore_id.
543 Additionally, if far_players!=NULL, players further away than
544 far_d_nodes are ignored and their peer_ids are added to far_players
546 // Envlock and conlock should be locked when calling these
547 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
548 std::list<u16> *far_players=NULL, float far_d_nodes=100);
549 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
550 std::list<u16> *far_players=NULL, float far_d_nodes=100,
551 bool remove_metadata=true);
552 void setBlockNotSent(v3s16 p);
554 // Environment and Connection must be locked when called
555 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
557 // Sends blocks to clients (locks env and con on its own)
558 void SendBlocks(float dtime);
560 void fillMediaCache();
561 void sendMediaAnnouncement(u16 peer_id);
562 void sendRequestedMedia(u16 peer_id,
563 const std::list<std::string> &tosend);
565 void sendDetachedInventory(const std::string &name, u16 peer_id);
566 void sendDetachedInventoryToAll(const std::string &name);
567 void sendDetachedInventories(u16 peer_id);
569 // Adds a ParticleSpawner on peer with peer_id
570 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
571 v3f minpos, v3f maxpos,
572 v3f minvel, v3f maxvel,
573 v3f minacc, v3f maxacc,
574 float minexptime, float maxexptime,
575 float minsize, float maxsize,
576 bool collisiondetection, std::string texture, u32 id);
578 // Adds a ParticleSpawner on all peers
579 void SendAddParticleSpawnerAll(u16 amount, float spawntime,
580 v3f minpos, v3f maxpos,
581 v3f minvel, v3f maxvel,
582 v3f minacc, v3f maxacc,
583 float minexptime, float maxexptime,
584 float minsize, float maxsize,
585 bool collisiondetection, std::string texture, u32 id);
587 // Deletes ParticleSpawner on a single client
588 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
590 // Deletes ParticleSpawner on all clients
591 void SendDeleteParticleSpawnerAll(u32 id);
593 // Spawns particle on single client
594 void SendSpawnParticle(u16 peer_id,
595 v3f pos, v3f velocity, v3f acceleration,
596 float expirationtime, float size,
597 bool collisiondetection, std::string texture);
599 // Spawns particle on all clients
600 void SendSpawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
601 float expirationtime, float size,
602 bool collisiondetection, std::string texture);
608 void DiePlayer(u16 peer_id);
609 void RespawnPlayer(u16 peer_id);
610 void DenyAccess(u16 peer_id, const std::wstring &reason);
612 enum ClientDeletionReason {
617 void DeleteClient(u16 peer_id, ClientDeletionReason reason);
619 void UpdateCrafting(u16 peer_id);
621 // When called, connection mutex should be locked
622 RemoteClient* getClient(u16 peer_id);
623 RemoteClient* getClientNoEx(u16 peer_id);
625 // When called, environment mutex should be locked
626 std::string getPlayerName(u16 peer_id);
627 PlayerSAO* getPlayerSAO(u16 peer_id);
630 Get a player from memory or creates one.
631 If player is already connected, return NULL
632 Does not verify/modify auth info and password.
634 Call with env and con locked.
636 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
638 // Locks environment and connection by its own
640 void handlePeerChange(PeerChange &c);
641 void handlePeerChanges();
648 std::string m_path_world;
649 // Subgame specification
650 SubgameSpec m_gamespec;
651 // If true, do not allow multiple players and hide some multiplayer
653 bool m_simple_singleplayer_mode;
655 // Thread can set; step() will throw as ServerError
656 MutexedVariable<std::string> m_async_fatal_error;
659 float m_liquid_transform_timer;
660 float m_liquid_transform_every;
661 float m_print_info_timer;
662 float m_masterserver_timer;
663 float m_objectdata_timer;
664 float m_emergethread_trigger_timer;
665 float m_savemap_timer;
666 IntervalLimiter m_map_timer_and_unload_interval;
668 // NOTE: If connection and environment are both to be locked,
669 // environment shall be locked first.
672 ServerEnvironment *m_env;
676 con::Connection m_con;
678 // Connected clients (behind the con mutex)
679 std::map<u16, RemoteClient*> m_clients;
680 std::vector<std::string> m_clients_names; //for announcing masterserver
683 BanManager *m_banmanager;
685 // Rollback manager (behind m_env_mutex)
686 IRollbackManager *m_rollback;
687 bool m_rollback_sink_enabled;
688 bool m_enable_rollback_recording; // Updated once in a while
691 EmergeManager *m_emerge;
694 // Envlock and conlock should be locked when using Lua
695 GameScripting *m_script;
697 // Item definition manager
698 IWritableItemDefManager *m_itemdef;
700 // Node definition manager
701 IWritableNodeDefManager *m_nodedef;
703 // Craft definition manager
704 IWritableCraftDefManager *m_craftdef;
707 EventManager *m_event;
710 std::vector<ModSpec> m_mods;
716 // A buffer for time steps
717 // step() increments and AsyncRunStep() run by m_thread reads it.
719 JMutex m_step_dtime_mutex;
721 // The server mainly operates in this thread
722 ServerThread *m_thread;
728 // Timer for sending time of day over network
729 float m_time_of_day_send_timer;
730 // Uptime of server in seconds
731 MutexedVariable<double> m_uptime;
735 Queues stuff from peerAdded() and deletingPeer() to
749 Queue<PeerChange> m_peer_change_queue;
755 // Mod parent directory paths
756 std::list<std::string> m_modspaths;
758 bool m_shutdown_requested;
761 Map edit event queue. Automatically receives all map edits.
762 The constructor of this class registers us to receive them through
765 NOTE: Should these be moved to actually be members of
770 Queue of map edits from the environment for sending to the clients
771 This is behind m_env_mutex
773 Queue<MapEditEvent*> m_unsent_map_edit_queue;
775 Set to true when the server itself is modifying the map and does
776 all sending of information by itself.
777 This is behind m_env_mutex
779 bool m_ignore_map_edit_events;
781 If a non-empty area, map edit events contained within are left
782 unsent. Done at map generation time to speed up editing of the
783 generated area, as it will be sent anyway.
784 This is behind m_env_mutex
786 VoxelArea m_ignore_map_edit_events_area;
788 If set to !=0, the incoming MapEditEvents are modified to have
789 this peed id as the disabled recipient
790 This is behind m_env_mutex
792 u16 m_ignore_map_edit_events_peer_id;
794 friend class EmergeThread;
795 friend class RemoteClient;
797 std::map<std::string,MediaInfo> m_media;
802 std::map<s32, ServerPlayingSound> m_playing_sounds;
806 Detached inventories (behind m_env_mutex)
809 std::map<std::string, Inventory*> m_detached_inventories;
814 std::vector<u32> m_particlespawner_ids;
818 Runs a simple dedicated server loop.
820 Shuts down when run is set to false.
822 void dedicated_server_loop(Server &server, bool &run);