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);
490 Map & getMap() { return m_env->getMap(); }
492 u32 hudAdd(Player *player, HudElement *element);
493 bool hudRemove(Player *player, u32 id);
494 bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
495 bool hudSetFlags(Player *player, u32 flags, u32 mask);
496 bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
497 void hudSetHotbarImage(Player *player, std::string name);
498 void hudSetHotbarSelectedImage(Player *player, std::string name);
502 // con::PeerHandler implementation.
503 // These queue stuff to be processed by handlePeerChanges().
504 // As of now, these create and remove clients and players.
505 void peerAdded(con::Peer *peer);
506 void deletingPeer(con::Peer *peer, bool timeout);
512 static void SendMovement(con::Connection &con, u16 peer_id);
513 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
514 static void SendBreath(con::Connection &con, u16 peer_id, u16 breath);
515 static void SendAccessDenied(con::Connection &con, u16 peer_id,
516 const std::wstring &reason);
517 static void SendDeathscreen(con::Connection &con, u16 peer_id,
518 bool set_camera_point_target, v3f camera_point_target);
519 static void SendItemDef(con::Connection &con, u16 peer_id,
520 IItemDefManager *itemdef, u16 protocol_version);
521 static void SendNodeDef(con::Connection &con, u16 peer_id,
522 INodeDefManager *nodedef, u16 protocol_version);
525 Non-static send methods.
526 Conlock should be always used.
527 Envlock usage is documented badly but it's easy to figure out
528 which ones access the environment.
531 // Envlock and conlock should be locked when calling these
532 void SendInventory(u16 peer_id);
533 void SendChatMessage(u16 peer_id, const std::wstring &message);
534 void BroadcastChatMessage(const std::wstring &message);
535 void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
536 void SendPlayerHP(u16 peer_id);
537 void SendPlayerBreath(u16 peer_id);
538 void SendMovePlayer(u16 peer_id);
539 void SendPlayerPrivileges(u16 peer_id);
540 void SendPlayerInventoryFormspec(u16 peer_id);
541 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
542 void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
543 void SendHUDRemove(u16 peer_id, u32 id);
544 void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
545 void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
546 void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
549 Send a node removal/addition event to all clients except ignore_id.
550 Additionally, if far_players!=NULL, players further away than
551 far_d_nodes are ignored and their peer_ids are added to far_players
553 // Envlock and conlock should be locked when calling these
554 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
555 std::list<u16> *far_players=NULL, float far_d_nodes=100);
556 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
557 std::list<u16> *far_players=NULL, float far_d_nodes=100);
558 void setBlockNotSent(v3s16 p);
560 // Environment and Connection must be locked when called
561 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
563 // Sends blocks to clients (locks env and con on its own)
564 void SendBlocks(float dtime);
566 void fillMediaCache();
567 void sendMediaAnnouncement(u16 peer_id);
568 void sendRequestedMedia(u16 peer_id,
569 const std::list<MediaRequest> &tosend);
571 void sendDetachedInventory(const std::string &name, u16 peer_id);
572 void sendDetachedInventoryToAll(const std::string &name);
573 void sendDetachedInventories(u16 peer_id);
575 // Adds a ParticleSpawner on peer with peer_id
576 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
577 v3f minpos, v3f maxpos,
578 v3f minvel, v3f maxvel,
579 v3f minacc, v3f maxacc,
580 float minexptime, float maxexptime,
581 float minsize, float maxsize,
582 bool collisiondetection, std::string texture, u32 id);
584 // Adds a ParticleSpawner on all peers
585 void SendAddParticleSpawnerAll(u16 amount, float spawntime,
586 v3f minpos, v3f maxpos,
587 v3f minvel, v3f maxvel,
588 v3f minacc, v3f maxacc,
589 float minexptime, float maxexptime,
590 float minsize, float maxsize,
591 bool collisiondetection, std::string texture, u32 id);
593 // Deletes ParticleSpawner on a single client
594 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
596 // Deletes ParticleSpawner on all clients
597 void SendDeleteParticleSpawnerAll(u32 id);
599 // Spawns particle on single client
600 void SendSpawnParticle(u16 peer_id,
601 v3f pos, v3f velocity, v3f acceleration,
602 float expirationtime, float size,
603 bool collisiondetection, std::string texture);
605 // Spawns particle on all clients
606 void SendSpawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
607 float expirationtime, float size,
608 bool collisiondetection, std::string texture);
614 void DiePlayer(u16 peer_id);
615 void RespawnPlayer(u16 peer_id);
616 void DenyAccess(u16 peer_id, const std::wstring &reason);
618 enum ClientDeletionReason {
623 void DeleteClient(u16 peer_id, ClientDeletionReason reason);
625 void UpdateCrafting(u16 peer_id);
627 // When called, connection mutex should be locked
628 RemoteClient* getClient(u16 peer_id);
629 RemoteClient* getClientNoEx(u16 peer_id);
631 // When called, environment mutex should be locked
632 std::string getPlayerName(u16 peer_id);
633 PlayerSAO* getPlayerSAO(u16 peer_id);
636 Get a player from memory or creates one.
637 If player is already connected, return NULL
638 Does not verify/modify auth info and password.
640 Call with env and con locked.
642 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
644 // Locks environment and connection by its own
646 void handlePeerChange(PeerChange &c);
647 void handlePeerChanges();
654 std::string m_path_world;
655 // Subgame specification
656 SubgameSpec m_gamespec;
657 // If true, do not allow multiple players and hide some multiplayer
659 bool m_simple_singleplayer_mode;
661 // Thread can set; step() will throw as ServerError
662 MutexedVariable<std::string> m_async_fatal_error;
665 float m_liquid_transform_timer;
666 float m_liquid_transform_every;
667 float m_print_info_timer;
668 float m_masterserver_timer;
669 float m_objectdata_timer;
670 float m_emergethread_trigger_timer;
671 float m_savemap_timer;
672 IntervalLimiter m_map_timer_and_unload_interval;
674 // NOTE: If connection and environment are both to be locked,
675 // environment shall be locked first.
678 ServerEnvironment *m_env;
682 con::Connection m_con;
684 // Connected clients (behind the con mutex)
685 std::map<u16, RemoteClient*> m_clients;
686 u16 m_clients_number; //for announcing masterserver
689 BanManager *m_banmanager;
691 // Rollback manager (behind m_env_mutex)
692 IRollbackManager *m_rollback;
693 bool m_rollback_sink_enabled;
694 bool m_enable_rollback_recording; // Updated once in a while
697 EmergeManager *m_emerge;
700 // Envlock and conlock should be locked when using Lua
701 GameScripting *m_script;
703 // Item definition manager
704 IWritableItemDefManager *m_itemdef;
706 // Node definition manager
707 IWritableNodeDefManager *m_nodedef;
709 // Craft definition manager
710 IWritableCraftDefManager *m_craftdef;
713 EventManager *m_event;
716 std::vector<ModSpec> m_mods;
722 // A buffer for time steps
723 // step() increments and AsyncRunStep() run by m_thread reads it.
725 JMutex m_step_dtime_mutex;
727 // The server mainly operates in this thread
728 ServerThread *m_thread;
734 // Timer for sending time of day over network
735 float m_time_of_day_send_timer;
736 // Uptime of server in seconds
737 MutexedVariable<double> m_uptime;
741 Queues stuff from peerAdded() and deletingPeer() to
755 Queue<PeerChange> m_peer_change_queue;
761 // Mod parent directory paths
762 std::list<std::string> m_modspaths;
764 bool m_shutdown_requested;
767 Map edit event queue. Automatically receives all map edits.
768 The constructor of this class registers us to receive them through
771 NOTE: Should these be moved to actually be members of
776 Queue of map edits from the environment for sending to the clients
777 This is behind m_env_mutex
779 Queue<MapEditEvent*> m_unsent_map_edit_queue;
781 Set to true when the server itself is modifying the map and does
782 all sending of information by itself.
783 This is behind m_env_mutex
785 bool m_ignore_map_edit_events;
787 If a non-empty area, map edit events contained within are left
788 unsent. Done at map generation time to speed up editing of the
789 generated area, as it will be sent anyway.
790 This is behind m_env_mutex
792 VoxelArea m_ignore_map_edit_events_area;
794 If set to !=0, the incoming MapEditEvents are modified to have
795 this peed id as the disabled recipient
796 This is behind m_env_mutex
798 u16 m_ignore_map_edit_events_peer_id;
800 friend class EmergeThread;
801 friend class RemoteClient;
803 std::map<std::string,MediaInfo> m_media;
808 std::map<s32, ServerPlayingSound> m_playing_sounds;
812 Detached inventories (behind m_env_mutex)
815 std::map<std::string, Inventory*> m_detached_inventories;
820 std::vector<u32> m_particlespawner_ids;
824 Runs a simple dedicated server loop.
826 Shuts down when run is set to false.
828 void dedicated_server_loop(Server &server, bool &run);