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);
499 // con::PeerHandler implementation.
500 // These queue stuff to be processed by handlePeerChanges().
501 // As of now, these create and remove clients and players.
502 void peerAdded(con::Peer *peer);
503 void deletingPeer(con::Peer *peer, bool timeout);
509 static void SendMovement(con::Connection &con, u16 peer_id);
510 static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
511 static void SendBreath(con::Connection &con, u16 peer_id, u16 breath);
512 static void SendAccessDenied(con::Connection &con, u16 peer_id,
513 const std::wstring &reason);
514 static void SendDeathscreen(con::Connection &con, u16 peer_id,
515 bool set_camera_point_target, v3f camera_point_target);
516 static void SendItemDef(con::Connection &con, u16 peer_id,
517 IItemDefManager *itemdef, u16 protocol_version);
518 static void SendNodeDef(con::Connection &con, u16 peer_id,
519 INodeDefManager *nodedef, u16 protocol_version);
522 Non-static send methods.
523 Conlock should be always used.
524 Envlock usage is documented badly but it's easy to figure out
525 which ones access the environment.
528 // Envlock and conlock should be locked when calling these
529 void SendInventory(u16 peer_id);
530 void SendChatMessage(u16 peer_id, const std::wstring &message);
531 void BroadcastChatMessage(const std::wstring &message);
532 void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
533 void SendPlayerHP(u16 peer_id);
534 void SendPlayerBreath(u16 peer_id);
535 void SendMovePlayer(u16 peer_id);
536 void SendPlayerPrivileges(u16 peer_id);
537 void SendPlayerInventoryFormspec(u16 peer_id);
538 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
539 void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
540 void SendHUDRemove(u16 peer_id, u32 id);
541 void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
542 void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
543 void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
546 Send a node removal/addition event to all clients except ignore_id.
547 Additionally, if far_players!=NULL, players further away than
548 far_d_nodes are ignored and their peer_ids are added to far_players
550 // Envlock and conlock should be locked when calling these
551 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
552 std::list<u16> *far_players=NULL, float far_d_nodes=100);
553 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
554 std::list<u16> *far_players=NULL, float far_d_nodes=100);
555 void setBlockNotSent(v3s16 p);
557 // Environment and Connection must be locked when called
558 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
560 // Sends blocks to clients (locks env and con on its own)
561 void SendBlocks(float dtime);
563 void fillMediaCache();
564 void sendMediaAnnouncement(u16 peer_id);
565 void sendRequestedMedia(u16 peer_id,
566 const std::list<MediaRequest> &tosend);
568 void sendDetachedInventory(const std::string &name, u16 peer_id);
569 void sendDetachedInventoryToAll(const std::string &name);
570 void sendDetachedInventories(u16 peer_id);
572 // Adds a ParticleSpawner on peer with peer_id
573 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
574 v3f minpos, v3f maxpos,
575 v3f minvel, v3f maxvel,
576 v3f minacc, v3f maxacc,
577 float minexptime, float maxexptime,
578 float minsize, float maxsize,
579 bool collisiondetection, std::string texture, u32 id);
581 // Adds a ParticleSpawner on all peers
582 void SendAddParticleSpawnerAll(u16 amount, float spawntime,
583 v3f minpos, v3f maxpos,
584 v3f minvel, v3f maxvel,
585 v3f minacc, v3f maxacc,
586 float minexptime, float maxexptime,
587 float minsize, float maxsize,
588 bool collisiondetection, std::string texture, u32 id);
590 // Deletes ParticleSpawner on a single client
591 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
593 // Deletes ParticleSpawner on all clients
594 void SendDeleteParticleSpawnerAll(u32 id);
596 // Spawns particle on single client
597 void SendSpawnParticle(u16 peer_id,
598 v3f pos, v3f velocity, v3f acceleration,
599 float expirationtime, float size,
600 bool collisiondetection, std::string texture);
602 // Spawns particle on all clients
603 void SendSpawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
604 float expirationtime, float size,
605 bool collisiondetection, std::string texture);
611 void DiePlayer(u16 peer_id);
612 void RespawnPlayer(u16 peer_id);
613 void DenyAccess(u16 peer_id, const std::wstring &reason);
615 enum ClientDeletionReason {
620 void DeleteClient(u16 peer_id, ClientDeletionReason reason);
622 void UpdateCrafting(u16 peer_id);
624 // When called, connection mutex should be locked
625 RemoteClient* getClient(u16 peer_id);
626 RemoteClient* getClientNoEx(u16 peer_id);
628 // When called, environment mutex should be locked
629 std::string getPlayerName(u16 peer_id);
630 PlayerSAO* getPlayerSAO(u16 peer_id);
633 Get a player from memory or creates one.
634 If player is already connected, return NULL
635 Does not verify/modify auth info and password.
637 Call with env and con locked.
639 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
641 // Locks environment and connection by its own
643 void handlePeerChange(PeerChange &c);
644 void handlePeerChanges();
651 std::string m_path_world;
652 // Subgame specification
653 SubgameSpec m_gamespec;
654 // If true, do not allow multiple players and hide some multiplayer
656 bool m_simple_singleplayer_mode;
658 // Thread can set; step() will throw as ServerError
659 MutexedVariable<std::string> m_async_fatal_error;
662 float m_liquid_transform_timer;
663 float m_liquid_transform_every;
664 float m_print_info_timer;
665 float m_masterserver_timer;
666 float m_objectdata_timer;
667 float m_emergethread_trigger_timer;
668 float m_savemap_timer;
669 IntervalLimiter m_map_timer_and_unload_interval;
671 // NOTE: If connection and environment are both to be locked,
672 // environment shall be locked first.
675 ServerEnvironment *m_env;
679 con::Connection m_con;
681 // Connected clients (behind the con mutex)
682 std::map<u16, RemoteClient*> m_clients;
683 u16 m_clients_number; //for announcing masterserver
686 BanManager *m_banmanager;
688 // Rollback manager (behind m_env_mutex)
689 IRollbackManager *m_rollback;
690 bool m_rollback_sink_enabled;
691 bool m_enable_rollback_recording; // Updated once in a while
694 EmergeManager *m_emerge;
697 // Envlock and conlock should be locked when using Lua
698 GameScripting *m_script;
700 // Item definition manager
701 IWritableItemDefManager *m_itemdef;
703 // Node definition manager
704 IWritableNodeDefManager *m_nodedef;
706 // Craft definition manager
707 IWritableCraftDefManager *m_craftdef;
710 EventManager *m_event;
713 std::vector<ModSpec> m_mods;
719 // A buffer for time steps
720 // step() increments and AsyncRunStep() run by m_thread reads it.
722 JMutex m_step_dtime_mutex;
724 // The server mainly operates in this thread
725 ServerThread *m_thread;
731 // Timer for sending time of day over network
732 float m_time_of_day_send_timer;
733 // Uptime of server in seconds
734 MutexedVariable<double> m_uptime;
738 Queues stuff from peerAdded() and deletingPeer() to
752 Queue<PeerChange> m_peer_change_queue;
758 // Mod parent directory paths
759 std::list<std::string> m_modspaths;
761 bool m_shutdown_requested;
764 Map edit event queue. Automatically receives all map edits.
765 The constructor of this class registers us to receive them through
768 NOTE: Should these be moved to actually be members of
773 Queue of map edits from the environment for sending to the clients
774 This is behind m_env_mutex
776 Queue<MapEditEvent*> m_unsent_map_edit_queue;
778 Set to true when the server itself is modifying the map and does
779 all sending of information by itself.
780 This is behind m_env_mutex
782 bool m_ignore_map_edit_events;
784 If a non-empty area, map edit events contained within are left
785 unsent. Done at map generation time to speed up editing of the
786 generated area, as it will be sent anyway.
787 This is behind m_env_mutex
789 VoxelArea m_ignore_map_edit_events_area;
791 If set to !=0, the incoming MapEditEvents are modified to have
792 this peed id as the disabled recipient
793 This is behind m_env_mutex
795 u16 m_ignore_map_edit_events_peer_id;
797 friend class EmergeThread;
798 friend class RemoteClient;
800 std::map<std::string,MediaInfo> m_media;
805 std::map<s32, ServerPlayingSound> m_playing_sounds;
809 Detached inventories (behind m_env_mutex)
812 std::map<std::string, Inventory*> m_detached_inventories;
817 std::vector<u32> m_particlespawner_ids;
821 Runs a simple dedicated server loop.
823 Shuts down when run is set to false.
825 void dedicated_server_loop(Server &server, bool &run);