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
180 void start(unsigned short port);
182 // This is mainly a way to pass the time to the server.
183 // Actual processing is done in an another thread.
184 void step(float dtime);
185 // This is run by ServerThread and does the actual processing
186 void AsyncRunStep(bool initial_step=false);
188 void ProcessData(u8 *data, u32 datasize, u16 peer_id);
190 // Environment must be locked when called
191 void setTimeOfDay(u32 time);
194 Shall be called with the environment locked.
195 This is accessed by the map, which is inside the environment,
196 so it shouldn't be a problem.
198 void onMapEditEvent(MapEditEvent *event);
201 Shall be called with the environment and the connection locked.
203 Inventory* getInventory(const InventoryLocation &loc);
204 void setInventoryModified(const InventoryLocation &loc);
206 // Connection must be locked when called
207 std::wstring getStatusString();
209 // read shutdown state
210 inline bool getShutdownRequested()
211 { return m_shutdown_requested; }
213 // request server to shutdown
214 inline void requestShutdown(void)
215 { m_shutdown_requested = true; }
217 // Returns -1 if failed, sound handle on success
219 s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams ¶ms);
220 void stopSound(s32 handle);
223 std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
224 bool checkPriv(const std::string &name, const std::string &priv);
225 void reportPrivsModified(const std::string &name=""); // ""=all
226 void reportInventoryFormspecModified(const std::string &name);
228 void setIpBanned(const std::string &ip, const std::string &name);
229 void unsetIpBanned(const std::string &ip_or_name);
230 std::string getBanDescription(const std::string &ip_or_name);
232 void notifyPlayer(const char *name, const std::wstring msg, const bool prepend);
233 void notifyPlayers(const std::wstring msg);
234 void spawnParticle(const char *playername,
235 v3f pos, v3f velocity, v3f acceleration,
236 float expirationtime, float size,
237 bool collisiondetection, bool vertical, std::string texture);
239 void spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
240 float expirationtime, float size,
241 bool collisiondetection, bool vertical, std::string texture);
243 u32 addParticleSpawner(const char *playername,
244 u16 amount, float spawntime,
245 v3f minpos, v3f maxpos,
246 v3f minvel, v3f maxvel,
247 v3f minacc, v3f maxacc,
248 float minexptime, float maxexptime,
249 float minsize, float maxsize,
250 bool collisiondetection, bool vertical, std::string texture);
252 u32 addParticleSpawnerAll(u16 amount, float spawntime,
253 v3f minpos, v3f maxpos,
254 v3f minvel, v3f maxvel,
255 v3f minacc, v3f maxacc,
256 float minexptime, float maxexptime,
257 float minsize, float maxsize,
258 bool collisiondetection, bool vertical, std::string texture);
260 void deleteParticleSpawner(const char *playername, u32 id);
261 void deleteParticleSpawnerAll(u32 id);
263 // Creates or resets inventory
264 Inventory* createDetachedInventory(const std::string &name);
266 // Envlock and conlock should be locked when using scriptapi
267 GameScripting *getScriptIface(){ return m_script; }
269 // Envlock should be locked when using the rollback manager
270 IRollbackManager *getRollbackManager(){ return m_rollback; }
272 //TODO: determine what (if anything) should be locked to access EmergeManager
273 EmergeManager *getEmergeManager(){ return m_emerge; }
275 // actions: time-reversed list
276 // Return value: success/failure
277 bool rollbackRevertActions(const std::list<RollbackAction> &actions,
278 std::list<std::string> *log);
280 // IGameDef interface
282 virtual IItemDefManager* getItemDefManager();
283 virtual INodeDefManager* getNodeDefManager();
284 virtual ICraftDefManager* getCraftDefManager();
285 virtual ITextureSource* getTextureSource();
286 virtual IShaderSource* getShaderSource();
287 virtual u16 allocateUnknownNodeId(const std::string &name);
288 virtual ISoundManager* getSoundManager();
289 virtual MtEventManager* getEventManager();
290 virtual IRollbackReportSink* getRollbackReportSink();
292 IWritableItemDefManager* getWritableItemDefManager();
293 IWritableNodeDefManager* getWritableNodeDefManager();
294 IWritableCraftDefManager* getWritableCraftDefManager();
296 const ModSpec* getModSpec(const std::string &modname);
297 void getModNames(std::list<std::string> &modlist);
298 std::string getBuiltinLuaPath();
299 inline std::string getWorldPath()
300 { return m_path_world; }
302 inline bool isSingleplayer()
303 { return m_simple_singleplayer_mode; }
305 inline void setAsyncFatalError(const std::string &error)
306 { m_async_fatal_error.set(error); }
308 bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
309 Map & getMap() { return m_env->getMap(); }
310 ServerEnvironment & getEnv() { return *m_env; }
312 u32 hudAdd(Player *player, HudElement *element);
313 bool hudRemove(Player *player, u32 id);
314 bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
315 bool hudSetFlags(Player *player, u32 flags, u32 mask);
316 bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
317 void hudSetHotbarImage(Player *player, std::string name);
318 void hudSetHotbarSelectedImage(Player *player, std::string name);
320 inline Address getPeerAddress(u16 peer_id)
321 { return m_con.GetPeerAddress(peer_id); }
323 /* con::PeerHandler implementation. */
324 void peerAdded(con::Peer *peer);
325 void deletingPeer(con::Peer *peer, bool timeout);
329 friend class EmergeThread;
330 friend class RemoteClient;
332 void SendMovement(u16 peer_id);
333 void SendHP(u16 peer_id, u8 hp);
334 void SendBreath(u16 peer_id, u16 breath);
335 void SendAccessDenied(u16 peer_id,const std::wstring &reason);
336 void SendDeathscreen(u16 peer_id,bool set_camera_point_target, v3f camera_point_target);
337 void SendItemDef(u16 peer_id,IItemDefManager *itemdef, u16 protocol_version);
338 void SendNodeDef(u16 peer_id,INodeDefManager *nodedef, u16 protocol_version);
340 /* mark blocks not sent for all clients */
341 void SetBlocksNotSent(std::map<v3s16, MapBlock *>& block);
343 // Envlock and conlock should be locked when calling these
344 void SendInventory(u16 peer_id);
345 void SendChatMessage(u16 peer_id, const std::wstring &message);
346 void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
347 void SendPlayerHP(u16 peer_id);
348 void SendPlayerBreath(u16 peer_id);
349 void SendMovePlayer(u16 peer_id);
350 void SendPlayerPrivileges(u16 peer_id);
351 void SendPlayerInventoryFormspec(u16 peer_id);
352 void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
353 void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
354 void SendHUDRemove(u16 peer_id, u32 id);
355 void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
356 void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
357 void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
360 Send a node removal/addition event to all clients except ignore_id.
361 Additionally, if far_players!=NULL, players further away than
362 far_d_nodes are ignored and their peer_ids are added to far_players
364 // Envlock and conlock should be locked when calling these
365 void sendRemoveNode(v3s16 p, u16 ignore_id=0,
366 std::list<u16> *far_players=NULL, float far_d_nodes=100);
367 void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
368 std::list<u16> *far_players=NULL, float far_d_nodes=100,
369 bool remove_metadata=true);
370 void setBlockNotSent(v3s16 p);
372 // Environment and Connection must be locked when called
373 void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
375 // Sends blocks to clients (locks env and con on its own)
376 void SendBlocks(float dtime);
378 void fillMediaCache();
379 void sendMediaAnnouncement(u16 peer_id);
380 void sendRequestedMedia(u16 peer_id,
381 const std::list<std::string> &tosend);
383 void sendDetachedInventory(const std::string &name, u16 peer_id);
384 void sendDetachedInventories(u16 peer_id);
386 // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all)
387 void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
388 v3f minpos, v3f maxpos,
389 v3f minvel, v3f maxvel,
390 v3f minacc, v3f maxacc,
391 float minexptime, float maxexptime,
392 float minsize, float maxsize,
393 bool collisiondetection, bool vertical, std::string texture, u32 id);
395 void SendDeleteParticleSpawner(u16 peer_id, u32 id);
397 // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all)
398 void SendSpawnParticle(u16 peer_id,
399 v3f pos, v3f velocity, v3f acceleration,
400 float expirationtime, float size,
401 bool collisiondetection, bool vertical, std::string texture);
407 void DiePlayer(u16 peer_id);
408 void RespawnPlayer(u16 peer_id);
409 void DenyAccess(u16 peer_id, const std::wstring &reason);
410 void DeleteClient(u16 peer_id, ClientDeletionReason reason);
411 void UpdateCrafting(u16 peer_id);
413 // When called, connection mutex should be locked
414 RemoteClient* getClient(u16 peer_id,ClientState state_min=Active);
415 RemoteClient* getClientNoEx(u16 peer_id,ClientState state_min=Active);
417 // When called, environment mutex should be locked
418 std::string getPlayerName(u16 peer_id);
419 PlayerSAO* getPlayerSAO(u16 peer_id);
422 Get a player from memory or creates one.
423 If player is already connected, return NULL
424 Does not verify/modify auth info and password.
426 Call with env and con locked.
428 PlayerSAO *emergePlayer(const char *name, u16 peer_id);
430 void handlePeerChanges();
437 std::string m_path_world;
438 // Subgame specification
439 SubgameSpec m_gamespec;
440 // If true, do not allow multiple players and hide some multiplayer
442 bool m_simple_singleplayer_mode;
444 // Thread can set; step() will throw as ServerError
445 MutexedVariable<std::string> m_async_fatal_error;
448 float m_liquid_transform_timer;
449 float m_liquid_transform_every;
450 float m_print_info_timer;
451 float m_masterserver_timer;
452 float m_objectdata_timer;
453 float m_emergethread_trigger_timer;
454 float m_savemap_timer;
455 IntervalLimiter m_map_timer_and_unload_interval;
458 ServerEnvironment *m_env;
462 con::Connection m_con;
465 BanManager *m_banmanager;
467 // Rollback manager (behind m_env_mutex)
468 IRollbackManager *m_rollback;
469 bool m_rollback_sink_enabled;
470 bool m_enable_rollback_recording; // Updated once in a while
473 EmergeManager *m_emerge;
476 // Envlock and conlock should be locked when using Lua
477 GameScripting *m_script;
479 // Item definition manager
480 IWritableItemDefManager *m_itemdef;
482 // Node definition manager
483 IWritableNodeDefManager *m_nodedef;
485 // Craft definition manager
486 IWritableCraftDefManager *m_craftdef;
489 EventManager *m_event;
492 std::vector<ModSpec> m_mods;
498 // A buffer for time steps
499 // step() increments and AsyncRunStep() run by m_thread reads it.
501 JMutex m_step_dtime_mutex;
503 // current server step lag counter
506 // The server mainly operates in this thread
507 ServerThread *m_thread;
513 // Timer for sending time of day over network
514 float m_time_of_day_send_timer;
515 // Uptime of server in seconds
516 MutexedVariable<double> m_uptime;
521 ClientInterface m_clients;
525 Queues stuff from peerAdded() and deletingPeer() to
528 Queue<con::PeerChange> m_peer_change_queue;
534 // Mod parent directory paths
535 std::list<std::string> m_modspaths;
537 bool m_shutdown_requested;
540 Map edit event queue. Automatically receives all map edits.
541 The constructor of this class registers us to receive them through
544 NOTE: Should these be moved to actually be members of
549 Queue of map edits from the environment for sending to the clients
550 This is behind m_env_mutex
552 Queue<MapEditEvent*> m_unsent_map_edit_queue;
554 Set to true when the server itself is modifying the map and does
555 all sending of information by itself.
556 This is behind m_env_mutex
558 bool m_ignore_map_edit_events;
560 If a non-empty area, map edit events contained within are left
561 unsent. Done at map generation time to speed up editing of the
562 generated area, as it will be sent anyway.
563 This is behind m_env_mutex
565 VoxelArea m_ignore_map_edit_events_area;
567 If set to !=0, the incoming MapEditEvents are modified to have
568 this peed id as the disabled recipient
569 This is behind m_env_mutex
571 u16 m_ignore_map_edit_events_peer_id;
573 // media files known to server
574 std::map<std::string,MediaInfo> m_media;
579 std::map<s32, ServerPlayingSound> m_playing_sounds;
583 Detached inventories (behind m_env_mutex)
586 std::map<std::string, Inventory*> m_detached_inventories;
591 std::vector<u32> m_particlespawner_ids;
595 Runs a simple dedicated server loop.
597 Shuts down when run is set to false.
599 void dedicated_server_loop(Server &server, bool &run);