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"
40 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
42 class IWritableItemDefManager;
43 class IWritableNodeDefManager;
44 class IWritableCraftDefManager;
50 class IRollbackManager;
53 class ServerEnvironment;
54 struct SimpleSoundSpec;
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;
134 Used for queueing and sorting block transfers in containers
136 Lower priority number means higher priority.
138 struct PrioritySortedBlockTransfer
140 PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
142 priority = a_priority;
146 bool operator < (const PrioritySortedBlockTransfer &other) const
148 return priority < other.priority;
159 MediaRequest(const std::string &name_=""):
167 std::string sha1_digest;
169 MediaInfo(const std::string path_="",
170 const std::string sha1_digest_=""):
172 sha1_digest(sha1_digest_)
177 struct ServerSoundParams
180 std::string to_player;
188 float max_hear_distance;
197 max_hear_distance(32*BS),
201 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
204 struct ServerPlayingSound
206 ServerSoundParams params;
207 std::set<u16> clients; // peer ids
213 // peer_id=0 means this client has no associated peer
214 // NOTE: If client is made allowed to exist while peer doesn't,
215 // this has to be set to 0 when there is no peer.
216 // Also, the client must be moved to some other container.
218 // The serialization version to use with the client
219 u8 serialization_version;
221 u16 net_proto_version;
222 // Version is stored in here after INIT before INIT2
223 u8 pending_serialization_version;
225 bool definitions_sent;
230 m_time_from_building(9999),
231 m_excess_gotblocks(0)
234 serialization_version = SER_FMT_VER_INVALID;
235 net_proto_version = 0;
236 pending_serialization_version = SER_FMT_VER_INVALID;
237 definitions_sent = false;
239 m_nearest_unsent_d = 0;
240 m_nearest_unsent_reset_timer = 0.0;
241 m_nothing_to_send_counter = 0;
242 m_nothing_to_send_pause_timer = 0;
249 Finds block that should be sent next to the client.
250 Environment should be locked when this is called.
251 dtime is used for resetting send radius at slow interval
253 void GetNextBlocks(Server *server, float dtime,
254 std::vector<PrioritySortedBlockTransfer> &dest);
256 void GotBlock(v3s16 p);
258 void SentBlock(v3s16 p);
260 void SetBlockNotSent(v3s16 p);
261 void SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks);
265 return m_blocks_sending.size();
268 // Increments timeouts and removes timed-out blocks from list
269 // NOTE: This doesn't fix the server-not-sending-block bug
270 // because it is related to emerging, not sending.
271 //void RunSendingTimeouts(float dtime, float timeout);
273 void PrintInfo(std::ostream &o)
275 o<<"RemoteClient "<<peer_id<<": "
276 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
277 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
278 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
279 <<", m_excess_gotblocks="<<m_excess_gotblocks
281 m_excess_gotblocks = 0;
284 // Time from last placing or removing blocks
285 float m_time_from_building;
287 /*JMutex m_dig_mutex;
288 float m_dig_time_remaining;
291 v3s16 m_dig_position;*/
294 List of active objects that the client knows of.
297 std::set<u16> m_known_objects;
301 Blocks that have been sent to client.
302 - These don't have to be sent again.
303 - A block is cleared from here when client says it has
304 deleted it from it's memory
306 Key is position, value is dummy.
307 No MapBlock* is stored here because the blocks can get deleted.
309 std::set<v3s16> m_blocks_sent;
310 s16 m_nearest_unsent_d;
312 float m_nearest_unsent_reset_timer;
315 Blocks that are currently on the line.
316 This is used for throttling the sending of blocks.
317 - The size of this list is limited to some value
318 Block is added when it is sent with BLOCKDATA.
319 Block is removed when GOTBLOCKS is received.
320 Value is time from sending. (not used at the moment)
322 std::map<v3s16, float> m_blocks_sending;
325 Count of excess GotBlocks().
326 There is an excess amount because the client sometimes
327 gets a block so late that the server sends it again,
328 and the client then sends two GOTBLOCKs.
329 This is resetted by PrintInfo()
331 u32 m_excess_gotblocks;
333 // CPU usage optimization
334 u32 m_nothing_to_send_counter;
335 float m_nothing_to_send_pause_timer;
338 class Server : public con::PeerHandler, public MapEventReceiver,
339 public InventoryManager, public IGameDef
343 NOTE: Every public method should be thread-safe
347 const std::string &path_world,
348 const SubgameSpec &gamespec,
349 bool simple_singleplayer_mode
352 void start(unsigned short port);
354 // This is mainly a way to pass the time to the server.
355 // Actual processing is done in an another thread.
356 void step(float dtime);
357 // This is run by ServerThread and does the actual processing
360 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
362 // Environment must be locked when called
363 void setTimeOfDay(u32 time);
365 bool getShutdownRequested()
367 return m_shutdown_requested;
371 Shall be called with the environment locked.
372 This is accessed by the map, which is inside the environment,
373 so it shouldn't be a problem.
375 void onMapEditEvent(MapEditEvent *event);
378 Shall be called with the environment and the connection locked.
380 Inventory* getInventory(const InventoryLocation &loc);
381 void setInventoryModified(const InventoryLocation &loc);
383 // Connection must be locked when called
384 std::wstring getStatusString();
386 void requestShutdown(void)
388 m_shutdown_requested = true;
391 // Returns -1 if failed, sound handle on success
393 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
394 void stopSound(s32 handle);
397 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
398 bool checkPriv(const std::string &name, const std::string &priv);
399 void reportPrivsModified(const std::string &name=""); // ""=all
400 void reportInventoryFormspecModified(const std::string &name);
402 void setIpBanned(const std::string &ip, const std::string &name);
403 void unsetIpBanned(const std::string &ip_or_name);
404 std::string getBanDescription(const std::string &ip_or_name);
406 Address getPeerAddress(u16 peer_id)
408 return m_con.GetPeerAddress(peer_id);
411 // Envlock and conlock should be locked when calling this
412 void notifyPlayer(const char *name, const std::wstring msg, const bool prepend);
413 void notifyPlayers(const std::wstring msg);
414 void spawnParticle(const char *playername,
415 v3f pos, v3f velocity, v3f acceleration,
416 float expirationtime, float size,
417 bool collisiondetection, std::string texture);
419 void spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
420 float expirationtime, float size,
421 bool collisiondetection, std::string texture);
423 u32 addParticleSpawner(const char *playername,
424 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 u32 addParticleSpawnerAll(u16 amount, float spawntime,
433 v3f minpos, v3f maxpos,
434 v3f minvel, v3f maxvel,
435 v3f minacc, v3f maxacc,
436 float minexptime, float maxexptime,
437 float minsize, float maxsize,
438 bool collisiondetection, std::string texture);
440 void deleteParticleSpawner(const char *playername, u32 id);
441 void deleteParticleSpawnerAll(u32 id);
443 // Creates or resets inventory
444 Inventory* createDetachedInventory(const std::string &name);
446 // Envlock and conlock should be locked when using scriptapi
447 GameScripting *getScriptIface(){ return m_script; }
449 // Envlock should be locked when using the rollback manager
450 IRollbackManager *getRollbackManager(){ return m_rollback; }
452 //TODO: determine what (if anything) should be locked to access EmergeManager
453 EmergeManager *getEmergeManager(){ return m_emerge; }
455 // actions: time-reversed list
456 // Return value: success/failure
457 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
458 std::list<std::string> *log);
460 // IGameDef interface
462 virtual IItemDefManager* getItemDefManager();
463 virtual INodeDefManager* getNodeDefManager();
464 virtual ICraftDefManager* getCraftDefManager();
465 virtual ITextureSource* getTextureSource();
466 virtual IShaderSource* getShaderSource();
467 virtual u16 allocateUnknownNodeId(const std::string &name);
468 virtual ISoundManager* getSoundManager();
469 virtual MtEventManager* getEventManager();
470 virtual IRollbackReportSink* getRollbackReportSink();
472 IWritableItemDefManager* getWritableItemDefManager();
473 IWritableNodeDefManager* getWritableNodeDefManager();
474 IWritableCraftDefManager* getWritableCraftDefManager();
476 const ModSpec* getModSpec(const std::string &modname);
477 void getModNames(std::list<std::string> &modlist);
478 std::string getBuiltinLuaPath();
480 std::string getWorldPath(){ return m_path_world; }
482 bool isSingleplayer(){ return m_simple_singleplayer_mode; }
484 void setAsyncFatalError(const std::string &error)
486 m_async_fatal_error.set(error);
489 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
491 u32 hudAdd(Player *player, HudElement *element);
492 bool hudRemove(Player *player, u32 id);
493 bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
494 bool hudSetFlags(Player *player, u32 flags, u32 mask);
495 bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
496 void hudSetHotbarImage(Player *player, std::string name);
497 void hudSetHotbarSelectedImage(Player *player, std::string name);
501 // con::PeerHandler implementation.
502 // These queue stuff to be processed by handlePeerChanges().
503 // As of now, these create and remove clients and players.
504 void peerAdded(con::Peer *peer);
505 void deletingPeer(con::Peer *peer, bool timeout);
511 static void SendMovement(con::Connection &con, u16 peer_id);
512 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
513 static void SendBreath(con::Connection &con, u16 peer_id, u16 breath);
514 static void SendAccessDenied(con::Connection &con, u16 peer_id,
515 const std::wstring &reason);
516 static void SendDeathscreen(con::Connection &con, u16 peer_id,
517 bool set_camera_point_target, v3f camera_point_target);
518 static void SendItemDef(con::Connection &con, u16 peer_id,
519 IItemDefManager *itemdef, u16 protocol_version);
520 static void SendNodeDef(con::Connection &con, u16 peer_id,
521 INodeDefManager *nodedef, u16 protocol_version);
524 Non-static send methods.
525 Conlock should be always used.
526 Envlock usage is documented badly but it's easy to figure out
527 which ones access the environment.
530 // Envlock and conlock should be locked when calling these
531 void SendInventory(u16 peer_id);
532 void SendChatMessage(u16 peer_id, const std::wstring &message);
533 void BroadcastChatMessage(const std::wstring &message);
534 void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
535 void SendPlayerHP(u16 peer_id);
536 void SendPlayerBreath(u16 peer_id);
537 void SendMovePlayer(u16 peer_id);
538 void SendPlayerPrivileges(u16 peer_id);
539 void SendPlayerInventoryFormspec(u16 peer_id);
540 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
541 void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
542 void SendHUDRemove(u16 peer_id, u32 id);
543 void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
544 void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
545 void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
548 Send a node removal/addition event to all clients except ignore_id.
549 Additionally, if far_players!=NULL, players further away than
550 far_d_nodes are ignored and their peer_ids are added to far_players
552 // Envlock and conlock should be locked when calling these
553 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
554 std::list<u16> *far_players=NULL, float far_d_nodes=100);
555 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
556 std::list<u16> *far_players=NULL, float far_d_nodes=100);
557 void setBlockNotSent(v3s16 p);
559 // Environment and Connection must be locked when called
560 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
562 // Sends blocks to clients (locks env and con on its own)
563 void SendBlocks(float dtime);
565 void fillMediaCache();
566 void sendMediaAnnouncement(u16 peer_id);
567 void sendRequestedMedia(u16 peer_id,
568 const std::list<MediaRequest> &tosend);
570 void sendDetachedInventory(const std::string &name, u16 peer_id);
571 void sendDetachedInventoryToAll(const std::string &name);
572 void sendDetachedInventories(u16 peer_id);
574 // Adds a ParticleSpawner on peer with peer_id
575 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
576 v3f minpos, v3f maxpos,
577 v3f minvel, v3f maxvel,
578 v3f minacc, v3f maxacc,
579 float minexptime, float maxexptime,
580 float minsize, float maxsize,
581 bool collisiondetection, std::string texture, u32 id);
583 // Adds a ParticleSpawner on all peers
584 void SendAddParticleSpawnerAll(u16 amount, float spawntime,
585 v3f minpos, v3f maxpos,
586 v3f minvel, v3f maxvel,
587 v3f minacc, v3f maxacc,
588 float minexptime, float maxexptime,
589 float minsize, float maxsize,
590 bool collisiondetection, std::string texture, u32 id);
592 // Deletes ParticleSpawner on a single client
593 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
595 // Deletes ParticleSpawner on all clients
596 void SendDeleteParticleSpawnerAll(u32 id);
598 // Spawns particle on single client
599 void SendSpawnParticle(u16 peer_id,
600 v3f pos, v3f velocity, v3f acceleration,
601 float expirationtime, float size,
602 bool collisiondetection, std::string texture);
604 // Spawns particle on all clients
605 void SendSpawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
606 float expirationtime, float size,
607 bool collisiondetection, std::string texture);
613 void DiePlayer(u16 peer_id);
614 void RespawnPlayer(u16 peer_id);
615 void DenyAccess(u16 peer_id, const std::wstring &reason);
617 enum ClientDeletionReason {
622 void DeleteClient(u16 peer_id, ClientDeletionReason reason);
624 void UpdateCrafting(u16 peer_id);
626 // When called, connection mutex should be locked
627 RemoteClient* getClient(u16 peer_id);
628 RemoteClient* getClientNoEx(u16 peer_id);
630 // When called, environment mutex should be locked
631 std::string getPlayerName(u16 peer_id);
632 PlayerSAO* getPlayerSAO(u16 peer_id);
635 Get a player from memory or creates one.
636 If player is already connected, return NULL
637 Does not verify/modify auth info and password.
639 Call with env and con locked.
641 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
643 // Locks environment and connection by its own
645 void handlePeerChange(PeerChange &c);
646 void handlePeerChanges();
653 std::string m_path_world;
654 // Subgame specification
655 SubgameSpec m_gamespec;
656 // If true, do not allow multiple players and hide some multiplayer
658 bool m_simple_singleplayer_mode;
660 // Thread can set; step() will throw as ServerError
661 MutexedVariable<std::string> m_async_fatal_error;
664 float m_liquid_transform_timer;
665 float m_liquid_transform_every;
666 float m_print_info_timer;
667 float m_masterserver_timer;
668 float m_objectdata_timer;
669 float m_emergethread_trigger_timer;
670 float m_savemap_timer;
671 IntervalLimiter m_map_timer_and_unload_interval;
673 // NOTE: If connection and environment are both to be locked,
674 // environment shall be locked first.
677 ServerEnvironment *m_env;
681 con::Connection m_con;
683 // Connected clients (behind the con mutex)
684 std::map<u16, RemoteClient*> m_clients;
685 u16 m_clients_number; //for announcing masterserver
688 BanManager *m_banmanager;
690 // Rollback manager (behind m_env_mutex)
691 IRollbackManager *m_rollback;
692 bool m_rollback_sink_enabled;
693 bool m_enable_rollback_recording; // Updated once in a while
696 EmergeManager *m_emerge;
699 // Envlock and conlock should be locked when using Lua
700 GameScripting *m_script;
702 // Item definition manager
703 IWritableItemDefManager *m_itemdef;
705 // Node definition manager
706 IWritableNodeDefManager *m_nodedef;
708 // Craft definition manager
709 IWritableCraftDefManager *m_craftdef;
712 EventManager *m_event;
715 std::vector<ModSpec> m_mods;
721 // A buffer for time steps
722 // step() increments and AsyncRunStep() run by m_thread reads it.
724 JMutex m_step_dtime_mutex;
726 // The server mainly operates in this thread
727 ServerThread *m_thread;
733 // Timer for sending time of day over network
734 float m_time_of_day_send_timer;
735 // Uptime of server in seconds
736 MutexedVariable<double> m_uptime;
740 Queues stuff from peerAdded() and deletingPeer() to
754 Queue<PeerChange> m_peer_change_queue;
760 // Mod parent directory paths
761 std::list<std::string> m_modspaths;
763 bool m_shutdown_requested;
766 Map edit event queue. Automatically receives all map edits.
767 The constructor of this class registers us to receive them through
770 NOTE: Should these be moved to actually be members of
775 Queue of map edits from the environment for sending to the clients
776 This is behind m_env_mutex
778 Queue<MapEditEvent*> m_unsent_map_edit_queue;
780 Set to true when the server itself is modifying the map and does
781 all sending of information by itself.
782 This is behind m_env_mutex
784 bool m_ignore_map_edit_events;
786 If a non-empty area, map edit events contained within are left
787 unsent. Done at map generation time to speed up editing of the
788 generated area, as it will be sent anyway.
789 This is behind m_env_mutex
791 VoxelArea m_ignore_map_edit_events_area;
793 If set to !=0, the incoming MapEditEvents are modified to have
794 this peed id as the disabled recipient
795 This is behind m_env_mutex
797 u16 m_ignore_map_edit_events_peer_id;
799 friend class EmergeThread;
800 friend class RemoteClient;
802 std::map<std::string,MediaInfo> m_media;
807 std::map<s32, ServerPlayingSound> m_playing_sounds;
811 Detached inventories (behind m_env_mutex)
814 std::map<std::string, Inventory*> m_detached_inventories;
819 std::vector<u32> m_particlespawner_ids;
823 Runs a simple dedicated server loop.
825 Shuts down when run is set to false.
827 void dedicated_server_loop(Server &server, bool &run);