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"
36 #include "clientiface.h"
42 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
44 class IWritableItemDefManager;
45 class IWritableNodeDefManager;
46 class IWritableCraftDefManager;
52 class IRollbackManager;
55 class ServerEnvironment;
56 struct SimpleSoundSpec;
59 enum ClientDeletionReason {
68 v3f findSpawnPos(ServerMap &map);
70 class MapEditEventIgnorer
73 MapEditEventIgnorer(bool *flag):
82 ~MapEditEventIgnorer()
95 class MapEditEventAreaIgnorer
98 MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
99 m_ignorevariable(ignorevariable)
101 if(m_ignorevariable->getVolume() == 0)
102 *m_ignorevariable = a;
104 m_ignorevariable = NULL;
107 ~MapEditEventAreaIgnorer()
111 assert(m_ignorevariable->getVolume() != 0);
112 *m_ignorevariable = VoxelArea();
117 VoxelArea *m_ignorevariable;
123 std::string sha1_digest;
125 MediaInfo(const std::string &path_="",
126 const std::string &sha1_digest_=""):
128 sha1_digest(sha1_digest_)
133 struct ServerSoundParams
136 std::string to_player;
144 float max_hear_distance;
153 max_hear_distance(32*BS),
157 v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
160 struct ServerPlayingSound
162 ServerSoundParams params;
163 std::set<u16> clients; // peer ids
166 class Server : public con::PeerHandler, public MapEventReceiver,
167 public InventoryManager, public IGameDef
171 NOTE: Every public method should be thread-safe
175 const std::string &path_world,
176 const SubgameSpec &gamespec,
177 bool simple_singleplayer_mode,
181 void start(Address bind_addr);
183 // This is mainly a way to pass the time to the server.
184 // Actual processing is done in an another thread.
185 void step(float dtime);
186 // This is run by ServerThread and does the actual processing
187 void AsyncRunStep(bool initial_step=false);
189 PlayerSAO* StageTwoClientInit(u16 peer_id);
190 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
192 // Environment must be locked when called
193 void setTimeOfDay(u32 time);
196 Shall be called with the environment locked.
197 This is accessed by the map, which is inside the environment,
198 so it shouldn't be a problem.
200 void onMapEditEvent(MapEditEvent *event);
203 Shall be called with the environment and the connection locked.
205 Inventory* getInventory(const InventoryLocation &loc);
206 void setInventoryModified(const InventoryLocation &loc);
208 // Connection must be locked when called
209 std::wstring getStatusString();
211 // read shutdown state
212 inline bool getShutdownRequested()
213 { return m_shutdown_requested; }
215 // request server to shutdown
216 inline void requestShutdown(void)
217 { m_shutdown_requested = true; }
219 // Returns -1 if failed, sound handle on success
221 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
222 void stopSound(s32 handle);
225 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
226 bool checkPriv(const std::string &name, const std::string &priv);
227 void reportPrivsModified(const std::string &name=""); // ""=all
228 void reportInventoryFormspecModified(const std::string &name);
230 void setIpBanned(const std::string &ip, const std::string &name);
231 void unsetIpBanned(const std::string &ip_or_name);
232 std::string getBanDescription(const std::string &ip_or_name);
234 void notifyPlayer(const char *name, const std::wstring &msg);
235 void notifyPlayers(const std::wstring &msg);
236 void spawnParticle(const char *playername,
237 v3f pos, v3f velocity, v3f acceleration,
238 float expirationtime, float size,
239 bool collisiondetection, bool vertical, std::string texture);
241 void spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
242 float expirationtime, float size,
243 bool collisiondetection, bool vertical, std::string texture);
245 u32 addParticleSpawner(const char *playername,
246 u16 amount, float spawntime,
247 v3f minpos, v3f maxpos,
248 v3f minvel, v3f maxvel,
249 v3f minacc, v3f maxacc,
250 float minexptime, float maxexptime,
251 float minsize, float maxsize,
252 bool collisiondetection, bool vertical, std::string texture);
254 u32 addParticleSpawnerAll(u16 amount, float spawntime,
255 v3f minpos, v3f maxpos,
256 v3f minvel, v3f maxvel,
257 v3f minacc, v3f maxacc,
258 float minexptime, float maxexptime,
259 float minsize, float maxsize,
260 bool collisiondetection, bool vertical, std::string texture);
262 void deleteParticleSpawner(const char *playername, u32 id);
263 void deleteParticleSpawnerAll(u32 id);
265 // Creates or resets inventory
266 Inventory* createDetachedInventory(const std::string &name);
268 // Envlock and conlock should be locked when using scriptapi
269 GameScripting *getScriptIface(){ return m_script; }
271 // Envlock should be locked when using the rollback manager
272 IRollbackManager *getRollbackManager(){ return m_rollback; }
274 //TODO: determine what (if anything) should be locked to access EmergeManager
275 EmergeManager *getEmergeManager(){ return m_emerge; }
277 // actions: time-reversed list
278 // Return value: success/failure
279 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
280 std::list<std::string> *log);
282 // IGameDef interface
284 virtual IItemDefManager* getItemDefManager();
285 virtual INodeDefManager* getNodeDefManager();
286 virtual ICraftDefManager* getCraftDefManager();
287 virtual ITextureSource* getTextureSource();
288 virtual IShaderSource* getShaderSource();
289 virtual u16 allocateUnknownNodeId(const std::string &name);
290 virtual ISoundManager* getSoundManager();
291 virtual MtEventManager* getEventManager();
292 virtual IRollbackReportSink* getRollbackReportSink();
294 IWritableItemDefManager* getWritableItemDefManager();
295 IWritableNodeDefManager* getWritableNodeDefManager();
296 IWritableCraftDefManager* getWritableCraftDefManager();
298 const ModSpec* getModSpec(const std::string &modname);
299 void getModNames(std::list<std::string> &modlist);
300 std::string getBuiltinLuaPath();
301 inline std::string getWorldPath()
302 { return m_path_world; }
304 inline bool isSingleplayer()
305 { return m_simple_singleplayer_mode; }
307 inline void setAsyncFatalError(const std::string &error)
308 { m_async_fatal_error.set(error); }
310 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
311 Map & getMap() { return m_env->getMap(); }
312 ServerEnvironment & getEnv() { return *m_env; }
314 u32 hudAdd(Player *player, HudElement *element);
315 bool hudRemove(Player *player, u32 id);
316 bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
317 bool hudSetFlags(Player *player, u32 flags, u32 mask);
318 bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
319 void hudSetHotbarImage(Player *player, std::string name);
320 void hudSetHotbarSelectedImage(Player *player, std::string name);
322 inline Address getPeerAddress(u16 peer_id)
323 { return m_con.GetPeerAddress(peer_id); }
325 bool setLocalPlayerAnimations(Player *player, v2s32 animation_frames[4], f32 frame_speed);
326 bool setPlayerEyeOffset(Player *player, v3f first, v3f third);
328 bool setSky(Player *player, const video::SColor &bgcolor,
329 const std::string &type, const std::vector<std::string> ¶ms);
331 bool overrideDayNightRatio(Player *player, bool do_override,
334 /* con::PeerHandler implementation. */
335 void peerAdded(con::Peer *peer);
336 void deletingPeer(con::Peer *peer, bool timeout);
338 void DenyAccess(u16 peer_id, const std::wstring &reason);
339 bool getClientConInfo(u16 peer_id, con::rtt_stat_type type,float* retval);
340 bool getClientInfo(u16 peer_id,ClientState* state, u32* uptime,
341 u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch,
342 std::string* vers_string);
346 friend class EmergeThread;
347 friend class RemoteClient;
349 void SendMovement(u16 peer_id);
350 void SendHP(u16 peer_id, u8 hp);
351 void SendBreath(u16 peer_id, u16 breath);
352 void SendAccessDenied(u16 peer_id,const std::wstring &reason);
353 void SendDeathscreen(u16 peer_id,bool set_camera_point_target, v3f camera_point_target);
354 void SendItemDef(u16 peer_id,IItemDefManager *itemdef, u16 protocol_version);
355 void SendNodeDef(u16 peer_id,INodeDefManager *nodedef, u16 protocol_version);
357 /* mark blocks not sent for all clients */
358 void SetBlocksNotSent(std::map<v3s16, MapBlock *>& block);
360 // Envlock and conlock should be locked when calling these
361 void SendInventory(u16 peer_id);
362 void SendChatMessage(u16 peer_id, const std::wstring &message);
363 void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
364 void SendPlayerHP(u16 peer_id);
365 void SendPlayerBreath(u16 peer_id);
366 void SendMovePlayer(u16 peer_id);
367 void SendLocalPlayerAnimations(u16 peer_id, v2s32 animation_frames[4], f32 animation_speed);
368 void SendEyeOffset(u16 peer_id, v3f first, v3f third);
369 void SendPlayerPrivileges(u16 peer_id);
370 void SendPlayerInventoryFormspec(u16 peer_id);
371 void SendShowFormspecMessage(u16 peer_id, const std::string &formspec, const std::string &formname);
372 void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
373 void SendHUDRemove(u16 peer_id, u32 id);
374 void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
375 void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
376 void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
377 void SendSetSky(u16 peer_id, const video::SColor &bgcolor,
378 const std::string &type, const std::vector<std::string> ¶ms);
379 void SendOverrideDayNightRatio(u16 peer_id, bool do_override, float ratio);
382 Send a node removal/addition event to all clients except ignore_id.
383 Additionally, if far_players!=NULL, players further away than
384 far_d_nodes are ignored and their peer_ids are added to far_players
386 // Envlock and conlock should be locked when calling these
387 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
388 std::list<u16> *far_players=NULL, float far_d_nodes=100);
389 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
390 std::list<u16> *far_players=NULL, float far_d_nodes=100,
391 bool remove_metadata=true);
392 void setBlockNotSent(v3s16 p);
394 // Environment and Connection must be locked when called
395 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
397 // Sends blocks to clients (locks env and con on its own)
398 void SendBlocks(float dtime);
400 void fillMediaCache();
401 void sendMediaAnnouncement(u16 peer_id);
402 void sendRequestedMedia(u16 peer_id,
403 const std::list<std::string> &tosend);
405 void sendDetachedInventory(const std::string &name, u16 peer_id);
406 void sendDetachedInventories(u16 peer_id);
408 // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all)
409 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
410 v3f minpos, v3f maxpos,
411 v3f minvel, v3f maxvel,
412 v3f minacc, v3f maxacc,
413 float minexptime, float maxexptime,
414 float minsize, float maxsize,
415 bool collisiondetection, bool vertical, std::string texture, u32 id);
417 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
419 // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all)
420 void SendSpawnParticle(u16 peer_id,
421 v3f pos, v3f velocity, v3f acceleration,
422 float expirationtime, float size,
423 bool collisiondetection, bool vertical, std::string texture);
429 void DiePlayer(u16 peer_id);
430 void RespawnPlayer(u16 peer_id);
431 void DeleteClient(u16 peer_id, ClientDeletionReason reason);
432 void UpdateCrafting(u16 peer_id);
434 // When called, connection mutex should be locked
435 RemoteClient* getClient(u16 peer_id,ClientState state_min=CS_Active);
436 RemoteClient* getClientNoEx(u16 peer_id,ClientState state_min=CS_Active);
438 // When called, environment mutex should be locked
439 std::string getPlayerName(u16 peer_id);
440 PlayerSAO* getPlayerSAO(u16 peer_id);
443 Get a player from memory or creates one.
444 If player is already connected, return NULL
445 Does not verify/modify auth info and password.
447 Call with env and con locked.
449 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
451 void handlePeerChanges();
458 std::string m_path_world;
459 // Subgame specification
460 SubgameSpec m_gamespec;
461 // If true, do not allow multiple players and hide some multiplayer
463 bool m_simple_singleplayer_mode;
465 // Thread can set; step() will throw as ServerError
466 MutexedVariable<std::string> m_async_fatal_error;
469 float m_liquid_transform_timer;
470 float m_liquid_transform_every;
471 float m_print_info_timer;
472 float m_masterserver_timer;
473 float m_objectdata_timer;
474 float m_emergethread_trigger_timer;
475 float m_savemap_timer;
476 IntervalLimiter m_map_timer_and_unload_interval;
479 ServerEnvironment *m_env;
483 con::Connection m_con;
486 BanManager *m_banmanager;
488 // Rollback manager (behind m_env_mutex)
489 IRollbackManager *m_rollback;
490 bool m_rollback_sink_enabled;
491 bool m_enable_rollback_recording; // Updated once in a while
494 EmergeManager *m_emerge;
497 // Envlock and conlock should be locked when using Lua
498 GameScripting *m_script;
500 // Item definition manager
501 IWritableItemDefManager *m_itemdef;
503 // Node definition manager
504 IWritableNodeDefManager *m_nodedef;
506 // Craft definition manager
507 IWritableCraftDefManager *m_craftdef;
510 EventManager *m_event;
513 std::vector<ModSpec> m_mods;
519 // A buffer for time steps
520 // step() increments and AsyncRunStep() run by m_thread reads it.
522 JMutex m_step_dtime_mutex;
524 // current server step lag counter
527 // The server mainly operates in this thread
528 ServerThread *m_thread;
534 // Timer for sending time of day over network
535 float m_time_of_day_send_timer;
536 // Uptime of server in seconds
537 MutexedVariable<double> m_uptime;
542 ClientInterface m_clients;
546 Queues stuff from peerAdded() and deletingPeer() to
549 Queue<con::PeerChange> m_peer_change_queue;
555 // Mod parent directory paths
556 std::list<std::string> m_modspaths;
558 bool m_shutdown_requested;
561 Map edit event queue. Automatically receives all map edits.
562 The constructor of this class registers us to receive them through
565 NOTE: Should these be moved to actually be members of
570 Queue of map edits from the environment for sending to the clients
571 This is behind m_env_mutex
573 Queue<MapEditEvent*> m_unsent_map_edit_queue;
575 Set to true when the server itself is modifying the map and does
576 all sending of information by itself.
577 This is behind m_env_mutex
579 bool m_ignore_map_edit_events;
581 If a non-empty area, map edit events contained within are left
582 unsent. Done at map generation time to speed up editing of the
583 generated area, as it will be sent anyway.
584 This is behind m_env_mutex
586 VoxelArea m_ignore_map_edit_events_area;
588 If set to !=0, the incoming MapEditEvents are modified to have
589 this peed id as the disabled recipient
590 This is behind m_env_mutex
592 u16 m_ignore_map_edit_events_peer_id;
594 // media files known to server
595 std::map<std::string,MediaInfo> m_media;
600 std::map<s32, ServerPlayingSound> m_playing_sounds;
604 Detached inventories (behind m_env_mutex)
607 std::map<std::string, Inventory*> m_detached_inventories;
612 std::vector<u32> m_particlespawner_ids;
616 Runs a simple dedicated server loop.
618 Shuts down when run is set to false.
620 void dedicated_server_loop(Server &server, bool &run);