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;
160 MediaRequest(const std::string &name_=""):
168 std::string sha1_digest;
170 MediaInfo(const std::string path_="",
171 const std::string sha1_digest_=""):
173 sha1_digest(sha1_digest_)
178 struct ServerSoundParams
181 std::string to_player;
189 float max_hear_distance;
198 max_hear_distance(32*BS),
202 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
205 struct ServerPlayingSound
207 ServerSoundParams params;
208 std::set<u16> clients; // peer ids
214 // peer_id=0 means this client has no associated peer
215 // NOTE: If client is made allowed to exist while peer doesn't,
216 // this has to be set to 0 when there is no peer.
217 // Also, the client must be moved to some other container.
219 // The serialization version to use with the client
220 u8 serialization_version;
222 u16 net_proto_version;
223 // Version is stored in here after INIT before INIT2
224 u8 pending_serialization_version;
226 bool definitions_sent;
231 m_time_from_building(9999),
232 m_excess_gotblocks(0)
235 serialization_version = SER_FMT_VER_INVALID;
236 net_proto_version = 0;
237 pending_serialization_version = SER_FMT_VER_INVALID;
238 definitions_sent = false;
240 m_nearest_unsent_d = 0;
241 m_nearest_unsent_reset_timer = 0.0;
242 m_nothing_to_send_counter = 0;
243 m_nothing_to_send_pause_timer = 0;
250 Finds block that should be sent next to the client.
251 Environment should be locked when this is called.
252 dtime is used for resetting send radius at slow interval
254 void GetNextBlocks(Server *server, float dtime,
255 std::vector<PrioritySortedBlockTransfer> &dest);
257 void GotBlock(v3s16 p);
259 void SentBlock(v3s16 p);
261 void SetBlockNotSent(v3s16 p);
262 void SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks);
266 return m_blocks_sending.size();
269 // Increments timeouts and removes timed-out blocks from list
270 // NOTE: This doesn't fix the server-not-sending-block bug
271 // because it is related to emerging, not sending.
272 //void RunSendingTimeouts(float dtime, float timeout);
274 void PrintInfo(std::ostream &o)
276 o<<"RemoteClient "<<peer_id<<": "
277 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
278 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
279 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
280 <<", m_excess_gotblocks="<<m_excess_gotblocks
282 m_excess_gotblocks = 0;
285 // Time from last placing or removing blocks
286 float m_time_from_building;
288 /*JMutex m_dig_mutex;
289 float m_dig_time_remaining;
292 v3s16 m_dig_position;*/
295 List of active objects that the client knows of.
298 std::set<u16> m_known_objects;
302 Blocks that have been sent to client.
303 - These don't have to be sent again.
304 - A block is cleared from here when client says it has
305 deleted it from it's memory
307 Key is position, value is dummy.
308 No MapBlock* is stored here because the blocks can get deleted.
310 std::set<v3s16> m_blocks_sent;
311 s16 m_nearest_unsent_d;
313 float m_nearest_unsent_reset_timer;
316 Blocks that are currently on the line.
317 This is used for throttling the sending of blocks.
318 - The size of this list is limited to some value
319 Block is added when it is sent with BLOCKDATA.
320 Block is removed when GOTBLOCKS is received.
321 Value is time from sending. (not used at the moment)
323 std::map<v3s16, float> m_blocks_sending;
326 Count of excess GotBlocks().
327 There is an excess amount because the client sometimes
328 gets a block so late that the server sends it again,
329 and the client then sends two GOTBLOCKs.
330 This is resetted by PrintInfo()
332 u32 m_excess_gotblocks;
334 // CPU usage optimization
335 u32 m_nothing_to_send_counter;
336 float m_nothing_to_send_pause_timer;
339 class Server : public con::PeerHandler, public MapEventReceiver,
340 public InventoryManager, public IGameDef
344 NOTE: Every public method should be thread-safe
348 const std::string &path_world,
349 const SubgameSpec &gamespec,
350 bool simple_singleplayer_mode
353 void start(unsigned short port);
355 // This is mainly a way to pass the time to the server.
356 // Actual processing is done in an another thread.
357 void step(float dtime);
358 // This is run by ServerThread and does the actual processing
361 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
363 // Environment must be locked when called
364 void setTimeOfDay(u32 time);
366 bool getShutdownRequested()
368 return m_shutdown_requested;
372 Shall be called with the environment locked.
373 This is accessed by the map, which is inside the environment,
374 so it shouldn't be a problem.
376 void onMapEditEvent(MapEditEvent *event);
379 Shall be called with the environment and the connection locked.
381 Inventory* getInventory(const InventoryLocation &loc);
382 void setInventoryModified(const InventoryLocation &loc);
384 // Connection must be locked when called
385 std::wstring getStatusString();
387 void requestShutdown(void)
389 m_shutdown_requested = true;
392 // Returns -1 if failed, sound handle on success
394 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
395 void stopSound(s32 handle);
398 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
399 bool checkPriv(const std::string &name, const std::string &priv);
400 void reportPrivsModified(const std::string &name=""); // ""=all
401 void reportInventoryFormspecModified(const std::string &name);
403 void setIpBanned(const std::string &ip, const std::string &name);
404 void unsetIpBanned(const std::string &ip_or_name);
405 std::string getBanDescription(const std::string &ip_or_name);
407 Address getPeerAddress(u16 peer_id)
409 return m_con.GetPeerAddress(peer_id);
412 // Envlock and conlock should be locked when calling this
413 void notifyPlayer(const char *name, const std::wstring msg, const bool prepend);
414 void notifyPlayers(const std::wstring msg);
415 void spawnParticle(const char *playername,
416 v3f pos, v3f velocity, v3f acceleration,
417 float expirationtime, float size,
418 bool collisiondetection, std::string texture);
420 void spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
421 float expirationtime, float size,
422 bool collisiondetection, std::string texture);
424 u32 addParticleSpawner(const char *playername,
425 u16 amount, float spawntime,
426 v3f minpos, v3f maxpos,
427 v3f minvel, v3f maxvel,
428 v3f minacc, v3f maxacc,
429 float minexptime, float maxexptime,
430 float minsize, float maxsize,
431 bool collisiondetection, std::string texture);
433 u32 addParticleSpawnerAll(u16 amount, float spawntime,
434 v3f minpos, v3f maxpos,
435 v3f minvel, v3f maxvel,
436 v3f minacc, v3f maxacc,
437 float minexptime, float maxexptime,
438 float minsize, float maxsize,
439 bool collisiondetection, std::string texture);
441 void deleteParticleSpawner(const char *playername, u32 id);
442 void deleteParticleSpawnerAll(u32 id);
444 // Creates or resets inventory
445 Inventory* createDetachedInventory(const std::string &name);
447 // Envlock and conlock should be locked when using scriptapi
448 GameScripting *getScriptIface(){ return m_script; }
450 // Envlock should be locked when using the rollback manager
451 IRollbackManager *getRollbackManager(){ return m_rollback; }
453 //TODO: determine what (if anything) should be locked to access EmergeManager
454 EmergeManager *getEmergeManager(){ return m_emerge; }
456 // actions: time-reversed list
457 // Return value: success/failure
458 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
459 std::list<std::string> *log);
461 // IGameDef interface
463 virtual IItemDefManager* getItemDefManager();
464 virtual INodeDefManager* getNodeDefManager();
465 virtual ICraftDefManager* getCraftDefManager();
466 virtual ITextureSource* getTextureSource();
467 virtual IShaderSource* getShaderSource();
468 virtual u16 allocateUnknownNodeId(const std::string &name);
469 virtual ISoundManager* getSoundManager();
470 virtual MtEventManager* getEventManager();
471 virtual IRollbackReportSink* getRollbackReportSink();
473 IWritableItemDefManager* getWritableItemDefManager();
474 IWritableNodeDefManager* getWritableNodeDefManager();
475 IWritableCraftDefManager* getWritableCraftDefManager();
477 const ModSpec* getModSpec(const std::string &modname);
478 void getModNames(std::list<std::string> &modlist);
479 std::string getBuiltinLuaPath();
481 std::string getWorldPath(){ return m_path_world; }
483 bool isSingleplayer(){ return m_simple_singleplayer_mode; }
485 void setAsyncFatalError(const std::string &error)
487 m_async_fatal_error.set(error);
490 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
491 Map & getMap() { return m_env->getMap(); }
493 u32 hudAdd(Player *player, HudElement *element);
494 bool hudRemove(Player *player, u32 id);
495 bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
496 bool hudSetFlags(Player *player, u32 flags, u32 mask);
497 bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
498 void hudSetHotbarImage(Player *player, std::string name);
499 void hudSetHotbarSelectedImage(Player *player, std::string name);
503 // con::PeerHandler implementation.
504 // These queue stuff to be processed by handlePeerChanges().
505 // As of now, these create and remove clients and players.
506 void peerAdded(con::Peer *peer);
507 void deletingPeer(con::Peer *peer, bool timeout);
513 static void SendMovement(con::Connection &con, u16 peer_id);
514 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
515 static void SendBreath(con::Connection &con, u16 peer_id, u16 breath);
516 static void SendAccessDenied(con::Connection &con, u16 peer_id,
517 const std::wstring &reason);
518 static void SendDeathscreen(con::Connection &con, u16 peer_id,
519 bool set_camera_point_target, v3f camera_point_target);
520 static void SendItemDef(con::Connection &con, u16 peer_id,
521 IItemDefManager *itemdef, u16 protocol_version);
522 static void SendNodeDef(con::Connection &con, u16 peer_id,
523 INodeDefManager *nodedef, u16 protocol_version);
526 Non-static send methods.
527 Conlock should be always used.
528 Envlock usage is documented badly but it's easy to figure out
529 which ones access the environment.
532 // Envlock and conlock should be locked when calling these
533 void SendInventory(u16 peer_id);
534 void SendChatMessage(u16 peer_id, const std::wstring &message);
535 void BroadcastChatMessage(const std::wstring &message);
536 void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
537 void SendPlayerHP(u16 peer_id);
538 void SendPlayerBreath(u16 peer_id);
539 void SendMovePlayer(u16 peer_id);
540 void SendPlayerPrivileges(u16 peer_id);
541 void SendPlayerInventoryFormspec(u16 peer_id);
542 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
543 void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
544 void SendHUDRemove(u16 peer_id, u32 id);
545 void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
546 void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
547 void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
550 Send a node removal/addition event to all clients except ignore_id.
551 Additionally, if far_players!=NULL, players further away than
552 far_d_nodes are ignored and their peer_ids are added to far_players
554 // Envlock and conlock should be locked when calling these
555 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
556 std::list<u16> *far_players=NULL, float far_d_nodes=100);
557 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
558 std::list<u16> *far_players=NULL, float far_d_nodes=100);
559 void setBlockNotSent(v3s16 p);
561 // Environment and Connection must be locked when called
562 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
564 // Sends blocks to clients (locks env and con on its own)
565 void SendBlocks(float dtime);
567 void fillMediaCache();
568 void sendMediaAnnouncement(u16 peer_id);
569 void sendRequestedMedia(u16 peer_id,
570 const std::list<MediaRequest> &tosend);
572 void sendDetachedInventory(const std::string &name, u16 peer_id);
573 void sendDetachedInventoryToAll(const std::string &name);
574 void sendDetachedInventories(u16 peer_id);
576 // Adds a ParticleSpawner on peer with peer_id
577 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
578 v3f minpos, v3f maxpos,
579 v3f minvel, v3f maxvel,
580 v3f minacc, v3f maxacc,
581 float minexptime, float maxexptime,
582 float minsize, float maxsize,
583 bool collisiondetection, std::string texture, u32 id);
585 // Adds a ParticleSpawner on all peers
586 void SendAddParticleSpawnerAll(u16 amount, float spawntime,
587 v3f minpos, v3f maxpos,
588 v3f minvel, v3f maxvel,
589 v3f minacc, v3f maxacc,
590 float minexptime, float maxexptime,
591 float minsize, float maxsize,
592 bool collisiondetection, std::string texture, u32 id);
594 // Deletes ParticleSpawner on a single client
595 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
597 // Deletes ParticleSpawner on all clients
598 void SendDeleteParticleSpawnerAll(u32 id);
600 // Spawns particle on single client
601 void SendSpawnParticle(u16 peer_id,
602 v3f pos, v3f velocity, v3f acceleration,
603 float expirationtime, float size,
604 bool collisiondetection, std::string texture);
606 // Spawns particle on all clients
607 void SendSpawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
608 float expirationtime, float size,
609 bool collisiondetection, std::string texture);
615 void DiePlayer(u16 peer_id);
616 void RespawnPlayer(u16 peer_id);
617 void DenyAccess(u16 peer_id, const std::wstring &reason);
619 enum ClientDeletionReason {
624 void DeleteClient(u16 peer_id, ClientDeletionReason reason);
626 void UpdateCrafting(u16 peer_id);
628 // When called, connection mutex should be locked
629 RemoteClient* getClient(u16 peer_id);
630 RemoteClient* getClientNoEx(u16 peer_id);
632 // When called, environment mutex should be locked
633 std::string getPlayerName(u16 peer_id);
634 PlayerSAO* getPlayerSAO(u16 peer_id);
637 Get a player from memory or creates one.
638 If player is already connected, return NULL
639 Does not verify/modify auth info and password.
641 Call with env and con locked.
643 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
645 // Locks environment and connection by its own
647 void handlePeerChange(PeerChange &c);
648 void handlePeerChanges();
655 std::string m_path_world;
656 // Subgame specification
657 SubgameSpec m_gamespec;
658 // If true, do not allow multiple players and hide some multiplayer
660 bool m_simple_singleplayer_mode;
662 // Thread can set; step() will throw as ServerError
663 MutexedVariable<std::string> m_async_fatal_error;
666 float m_liquid_transform_timer;
667 float m_liquid_transform_every;
668 float m_print_info_timer;
669 float m_masterserver_timer;
670 float m_objectdata_timer;
671 float m_emergethread_trigger_timer;
672 float m_savemap_timer;
673 IntervalLimiter m_map_timer_and_unload_interval;
675 // NOTE: If connection and environment are both to be locked,
676 // environment shall be locked first.
679 ServerEnvironment *m_env;
683 con::Connection m_con;
685 // Connected clients (behind the con mutex)
686 std::map<u16, RemoteClient*> m_clients;
687 u16 m_clients_number; //for announcing masterserver
690 BanManager *m_banmanager;
692 // Rollback manager (behind m_env_mutex)
693 IRollbackManager *m_rollback;
694 bool m_rollback_sink_enabled;
695 bool m_enable_rollback_recording; // Updated once in a while
698 EmergeManager *m_emerge;
701 // Envlock and conlock should be locked when using Lua
702 GameScripting *m_script;
704 // Item definition manager
705 IWritableItemDefManager *m_itemdef;
707 // Node definition manager
708 IWritableNodeDefManager *m_nodedef;
710 // Craft definition manager
711 IWritableCraftDefManager *m_craftdef;
714 EventManager *m_event;
717 std::vector<ModSpec> m_mods;
723 // A buffer for time steps
724 // step() increments and AsyncRunStep() run by m_thread reads it.
726 JMutex m_step_dtime_mutex;
728 // The server mainly operates in this thread
729 ServerThread *m_thread;
735 // Timer for sending time of day over network
736 float m_time_of_day_send_timer;
737 // Uptime of server in seconds
738 MutexedVariable<double> m_uptime;
742 Queues stuff from peerAdded() and deletingPeer() to
756 Queue<PeerChange> m_peer_change_queue;
762 // Mod parent directory paths
763 std::list<std::string> m_modspaths;
765 bool m_shutdown_requested;
768 Map edit event queue. Automatically receives all map edits.
769 The constructor of this class registers us to receive them through
772 NOTE: Should these be moved to actually be members of
777 Queue of map edits from the environment for sending to the clients
778 This is behind m_env_mutex
780 Queue<MapEditEvent*> m_unsent_map_edit_queue;
782 Set to true when the server itself is modifying the map and does
783 all sending of information by itself.
784 This is behind m_env_mutex
786 bool m_ignore_map_edit_events;
788 If a non-empty area, map edit events contained within are left
789 unsent. Done at map generation time to speed up editing of the
790 generated area, as it will be sent anyway.
791 This is behind m_env_mutex
793 VoxelArea m_ignore_map_edit_events_area;
795 If set to !=0, the incoming MapEditEvents are modified to have
796 this peed id as the disabled recipient
797 This is behind m_env_mutex
799 u16 m_ignore_map_edit_events_peer_id;
801 friend class EmergeThread;
802 friend class RemoteClient;
804 std::map<std::string,MediaInfo> m_media;
809 std::map<s32, ServerPlayingSound> m_playing_sounds;
813 Detached inventories (behind m_env_mutex)
816 std::map<std::string, Inventory*> m_detached_inventories;
821 std::vector<u32> m_particlespawner_ids;
825 Runs a simple dedicated server loop.
827 Shuts down when run is set to false.
829 void dedicated_server_loop(Server &server, bool &run);