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(); }
492 ServerEnvironment & getEnv() { return *m_env; }
494 u32 hudAdd(Player *player, HudElement *element);
495 bool hudRemove(Player *player, u32 id);
496 bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
497 bool hudSetFlags(Player *player, u32 flags, u32 mask);
498 bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
499 void hudSetHotbarImage(Player *player, std::string name);
500 void hudSetHotbarSelectedImage(Player *player, std::string name);
504 // con::PeerHandler implementation.
505 // These queue stuff to be processed by handlePeerChanges().
506 // As of now, these create and remove clients and players.
507 void peerAdded(con::Peer *peer);
508 void deletingPeer(con::Peer *peer, bool timeout);
514 static void SendMovement(con::Connection &con, u16 peer_id);
515 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
516 static void SendBreath(con::Connection &con, u16 peer_id, u16 breath);
517 static void SendAccessDenied(con::Connection &con, u16 peer_id,
518 const std::wstring &reason);
519 static void SendDeathscreen(con::Connection &con, u16 peer_id,
520 bool set_camera_point_target, v3f camera_point_target);
521 static void SendItemDef(con::Connection &con, u16 peer_id,
522 IItemDefManager *itemdef, u16 protocol_version);
523 static void SendNodeDef(con::Connection &con, u16 peer_id,
524 INodeDefManager *nodedef, u16 protocol_version);
527 Non-static send methods.
528 Conlock should be always used.
529 Envlock usage is documented badly but it's easy to figure out
530 which ones access the environment.
533 // Envlock and conlock should be locked when calling these
534 void SendInventory(u16 peer_id);
535 void SendChatMessage(u16 peer_id, const std::wstring &message);
536 void BroadcastChatMessage(const std::wstring &message);
537 void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
538 void SendPlayerHP(u16 peer_id);
539 void SendPlayerBreath(u16 peer_id);
540 void SendMovePlayer(u16 peer_id);
541 void SendPlayerPrivileges(u16 peer_id);
542 void SendPlayerInventoryFormspec(u16 peer_id);
543 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
544 void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
545 void SendHUDRemove(u16 peer_id, u32 id);
546 void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
547 void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
548 void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
551 Send a node removal/addition event to all clients except ignore_id.
552 Additionally, if far_players!=NULL, players further away than
553 far_d_nodes are ignored and their peer_ids are added to far_players
555 // Envlock and conlock should be locked when calling these
556 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
557 std::list<u16> *far_players=NULL, float far_d_nodes=100);
558 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
559 std::list<u16> *far_players=NULL, float far_d_nodes=100);
560 void setBlockNotSent(v3s16 p);
562 // Environment and Connection must be locked when called
563 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
565 // Sends blocks to clients (locks env and con on its own)
566 void SendBlocks(float dtime);
568 void fillMediaCache();
569 void sendMediaAnnouncement(u16 peer_id);
570 void sendRequestedMedia(u16 peer_id,
571 const std::list<MediaRequest> &tosend);
573 void sendDetachedInventory(const std::string &name, u16 peer_id);
574 void sendDetachedInventoryToAll(const std::string &name);
575 void sendDetachedInventories(u16 peer_id);
577 // Adds a ParticleSpawner on peer with peer_id
578 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
579 v3f minpos, v3f maxpos,
580 v3f minvel, v3f maxvel,
581 v3f minacc, v3f maxacc,
582 float minexptime, float maxexptime,
583 float minsize, float maxsize,
584 bool collisiondetection, std::string texture, u32 id);
586 // Adds a ParticleSpawner on all peers
587 void SendAddParticleSpawnerAll(u16 amount, float spawntime,
588 v3f minpos, v3f maxpos,
589 v3f minvel, v3f maxvel,
590 v3f minacc, v3f maxacc,
591 float minexptime, float maxexptime,
592 float minsize, float maxsize,
593 bool collisiondetection, std::string texture, u32 id);
595 // Deletes ParticleSpawner on a single client
596 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
598 // Deletes ParticleSpawner on all clients
599 void SendDeleteParticleSpawnerAll(u32 id);
601 // Spawns particle on single client
602 void SendSpawnParticle(u16 peer_id,
603 v3f pos, v3f velocity, v3f acceleration,
604 float expirationtime, float size,
605 bool collisiondetection, std::string texture);
607 // Spawns particle on all clients
608 void SendSpawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
609 float expirationtime, float size,
610 bool collisiondetection, std::string texture);
616 void DiePlayer(u16 peer_id);
617 void RespawnPlayer(u16 peer_id);
618 void DenyAccess(u16 peer_id, const std::wstring &reason);
620 enum ClientDeletionReason {
625 void DeleteClient(u16 peer_id, ClientDeletionReason reason);
627 void UpdateCrafting(u16 peer_id);
629 // When called, connection mutex should be locked
630 RemoteClient* getClient(u16 peer_id);
631 RemoteClient* getClientNoEx(u16 peer_id);
633 // When called, environment mutex should be locked
634 std::string getPlayerName(u16 peer_id);
635 PlayerSAO* getPlayerSAO(u16 peer_id);
638 Get a player from memory or creates one.
639 If player is already connected, return NULL
640 Does not verify/modify auth info and password.
642 Call with env and con locked.
644 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
646 // Locks environment and connection by its own
648 void handlePeerChange(PeerChange &c);
649 void handlePeerChanges();
656 std::string m_path_world;
657 // Subgame specification
658 SubgameSpec m_gamespec;
659 // If true, do not allow multiple players and hide some multiplayer
661 bool m_simple_singleplayer_mode;
663 // Thread can set; step() will throw as ServerError
664 MutexedVariable<std::string> m_async_fatal_error;
667 float m_liquid_transform_timer;
668 float m_liquid_transform_every;
669 float m_print_info_timer;
670 float m_masterserver_timer;
671 float m_objectdata_timer;
672 float m_emergethread_trigger_timer;
673 float m_savemap_timer;
674 IntervalLimiter m_map_timer_and_unload_interval;
676 // NOTE: If connection and environment are both to be locked,
677 // environment shall be locked first.
680 ServerEnvironment *m_env;
684 con::Connection m_con;
686 // Connected clients (behind the con mutex)
687 std::map<u16, RemoteClient*> m_clients;
688 std::vector<std::string> m_clients_names; //for announcing masterserver
691 BanManager *m_banmanager;
693 // Rollback manager (behind m_env_mutex)
694 IRollbackManager *m_rollback;
695 bool m_rollback_sink_enabled;
696 bool m_enable_rollback_recording; // Updated once in a while
699 EmergeManager *m_emerge;
702 // Envlock and conlock should be locked when using Lua
703 GameScripting *m_script;
705 // Item definition manager
706 IWritableItemDefManager *m_itemdef;
708 // Node definition manager
709 IWritableNodeDefManager *m_nodedef;
711 // Craft definition manager
712 IWritableCraftDefManager *m_craftdef;
715 EventManager *m_event;
718 std::vector<ModSpec> m_mods;
724 // A buffer for time steps
725 // step() increments and AsyncRunStep() run by m_thread reads it.
727 JMutex m_step_dtime_mutex;
729 // The server mainly operates in this thread
730 ServerThread *m_thread;
736 // Timer for sending time of day over network
737 float m_time_of_day_send_timer;
738 // Uptime of server in seconds
739 MutexedVariable<double> m_uptime;
743 Queues stuff from peerAdded() and deletingPeer() to
757 Queue<PeerChange> m_peer_change_queue;
763 // Mod parent directory paths
764 std::list<std::string> m_modspaths;
766 bool m_shutdown_requested;
769 Map edit event queue. Automatically receives all map edits.
770 The constructor of this class registers us to receive them through
773 NOTE: Should these be moved to actually be members of
778 Queue of map edits from the environment for sending to the clients
779 This is behind m_env_mutex
781 Queue<MapEditEvent*> m_unsent_map_edit_queue;
783 Set to true when the server itself is modifying the map and does
784 all sending of information by itself.
785 This is behind m_env_mutex
787 bool m_ignore_map_edit_events;
789 If a non-empty area, map edit events contained within are left
790 unsent. Done at map generation time to speed up editing of the
791 generated area, as it will be sent anyway.
792 This is behind m_env_mutex
794 VoxelArea m_ignore_map_edit_events_area;
796 If set to !=0, the incoming MapEditEvents are modified to have
797 this peed id as the disabled recipient
798 This is behind m_env_mutex
800 u16 m_ignore_map_edit_events_peer_id;
802 friend class EmergeThread;
803 friend class RemoteClient;
805 std::map<std::string,MediaInfo> m_media;
810 std::map<s32, ServerPlayingSound> m_playing_sounds;
814 Detached inventories (behind m_env_mutex)
817 std::map<std::string, Inventory*> m_detached_inventories;
822 std::vector<u32> m_particlespawner_ids;
826 Runs a simple dedicated server loop.
828 Shuts down when run is set to false.
830 void dedicated_server_loop(Server &server, bool &run);