c0928e5743d579a8f4a06203a4718e52b9badf85
[oweals/minetest.git] / src / server.h
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #ifndef SERVER_HEADER
21 #define SERVER_HEADER
22
23 #include "connection.h"
24 #include "irr_v3d.h"
25 #include "map.h"
26 #include "hud.h"
27 #include "gamedef.h"
28 #include "serialization.h" // For SER_FMT_VER_INVALID
29 #include "mods.h"
30 #include "inventorymanager.h"
31 #include "subgame.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"
37 #include <string>
38 #include <list>
39 #include <map>
40 #include <vector>
41
42 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
43
44 class IWritableItemDefManager;
45 class IWritableNodeDefManager;
46 class IWritableCraftDefManager;
47 class BanManager;
48 class EventManager;
49 class Inventory;
50 class Player;
51 class PlayerSAO;
52 class IRollbackManager;
53 class EmergeManager;
54 class GameScripting;
55 class ServerEnvironment;
56 struct SimpleSoundSpec;
57 class ServerThread;
58
59 enum ClientDeletionReason {
60         CDR_LEAVE,
61         CDR_TIMEOUT,
62         CDR_DENY
63 };
64
65 /*
66         Some random functions
67 */
68 v3f findSpawnPos(ServerMap &map);
69
70 class MapEditEventIgnorer
71 {
72 public:
73         MapEditEventIgnorer(bool *flag):
74                 m_flag(flag)
75         {
76                 if(*m_flag == false)
77                         *m_flag = true;
78                 else
79                         m_flag = NULL;
80         }
81
82         ~MapEditEventIgnorer()
83         {
84                 if(m_flag)
85                 {
86                         assert(*m_flag);
87                         *m_flag = false;
88                 }
89         }
90
91 private:
92         bool *m_flag;
93 };
94
95 class MapEditEventAreaIgnorer
96 {
97 public:
98         MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
99                 m_ignorevariable(ignorevariable)
100         {
101                 if(m_ignorevariable->getVolume() == 0)
102                         *m_ignorevariable = a;
103                 else
104                         m_ignorevariable = NULL;
105         }
106
107         ~MapEditEventAreaIgnorer()
108         {
109                 if(m_ignorevariable)
110                 {
111                         assert(m_ignorevariable->getVolume() != 0);
112                         *m_ignorevariable = VoxelArea();
113                 }
114         }
115
116 private:
117         VoxelArea *m_ignorevariable;
118 };
119
120 struct MediaInfo
121 {
122         std::string path;
123         std::string sha1_digest;
124
125         MediaInfo(const std::string &path_="",
126                   const std::string &sha1_digest_=""):
127                 path(path_),
128                 sha1_digest(sha1_digest_)
129         {
130         }
131 };
132
133 struct ServerSoundParams
134 {
135         float gain;
136         std::string to_player;
137         enum Type{
138                 SSP_LOCAL=0,
139                 SSP_POSITIONAL=1,
140                 SSP_OBJECT=2
141         } type;
142         v3f pos;
143         u16 object;
144         float max_hear_distance;
145         bool loop;
146
147         ServerSoundParams():
148                 gain(1.0),
149                 to_player(""),
150                 type(SSP_LOCAL),
151                 pos(0,0,0),
152                 object(0),
153                 max_hear_distance(32*BS),
154                 loop(false)
155         {}
156
157         v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
158 };
159
160 struct ServerPlayingSound
161 {
162         ServerSoundParams params;
163         std::set<u16> clients; // peer ids
164 };
165
166 class Server : public con::PeerHandler, public MapEventReceiver,
167                 public InventoryManager, public IGameDef
168 {
169 public:
170         /*
171                 NOTE: Every public method should be thread-safe
172         */
173
174         Server(
175                 const std::string &path_world,
176                 const SubgameSpec &gamespec,
177                 bool simple_singleplayer_mode
178         );
179         ~Server();
180         void start(Address bind_addr);
181         void stop();
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);
187         void Receive();
188         PlayerSAO* StageTwoClientInit(u16 peer_id);
189         void ProcessData(u8 *data, u32 datasize, u16 peer_id);
190
191         // Environment must be locked when called
192         void setTimeOfDay(u32 time);
193
194         /*
195                 Shall be called with the environment locked.
196                 This is accessed by the map, which is inside the environment,
197                 so it shouldn't be a problem.
198         */
199         void onMapEditEvent(MapEditEvent *event);
200
201         /*
202                 Shall be called with the environment and the connection locked.
203         */
204         Inventory* getInventory(const InventoryLocation &loc);
205         void setInventoryModified(const InventoryLocation &loc);
206
207         // Connection must be locked when called
208         std::wstring getStatusString();
209
210         // read shutdown state
211         inline bool getShutdownRequested()
212                         { return m_shutdown_requested; }
213
214         // request server to shutdown
215         inline void requestShutdown(void)
216                         { m_shutdown_requested = true; }
217
218         // Returns -1 if failed, sound handle on success
219         // Envlock
220         s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams &params);
221         void stopSound(s32 handle);
222
223         // Envlock
224         std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
225         bool checkPriv(const std::string &name, const std::string &priv);
226         void reportPrivsModified(const std::string &name=""); // ""=all
227         void reportInventoryFormspecModified(const std::string &name);
228
229         void setIpBanned(const std::string &ip, const std::string &name);
230         void unsetIpBanned(const std::string &ip_or_name);
231         std::string getBanDescription(const std::string &ip_or_name);
232
233         void notifyPlayer(const char *name, const std::wstring &msg);
234         void notifyPlayers(const std::wstring &msg);
235         void spawnParticle(const char *playername,
236                 v3f pos, v3f velocity, v3f acceleration,
237                 float expirationtime, float size,
238                 bool collisiondetection, bool vertical, std::string texture);
239
240         void spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
241                 float expirationtime, float size,
242                 bool collisiondetection, bool vertical, std::string texture);
243
244         u32 addParticleSpawner(const char *playername,
245                 u16 amount, float spawntime,
246                 v3f minpos, v3f maxpos,
247                 v3f minvel, v3f maxvel,
248                 v3f minacc, v3f maxacc,
249                 float minexptime, float maxexptime,
250                 float minsize, float maxsize,
251                 bool collisiondetection, bool vertical, std::string texture);
252
253         u32 addParticleSpawnerAll(u16 amount, float spawntime,
254                 v3f minpos, v3f maxpos,
255                 v3f minvel, v3f maxvel,
256                 v3f minacc, v3f maxacc,
257                 float minexptime, float maxexptime,
258                 float minsize, float maxsize,
259                 bool collisiondetection, bool vertical, std::string texture);
260
261         void deleteParticleSpawner(const char *playername, u32 id);
262         void deleteParticleSpawnerAll(u32 id);
263
264         // Creates or resets inventory
265         Inventory* createDetachedInventory(const std::string &name);
266
267         // Envlock and conlock should be locked when using scriptapi
268         GameScripting *getScriptIface(){ return m_script; }
269
270         // Envlock should be locked when using the rollback manager
271         IRollbackManager *getRollbackManager(){ return m_rollback; }
272
273         //TODO: determine what (if anything) should be locked to access EmergeManager
274         EmergeManager *getEmergeManager(){ return m_emerge; }
275
276         // actions: time-reversed list
277         // Return value: success/failure
278         bool rollbackRevertActions(const std::list<RollbackAction> &actions,
279                         std::list<std::string> *log);
280
281         // IGameDef interface
282         // Under envlock
283         virtual IItemDefManager* getItemDefManager();
284         virtual INodeDefManager* getNodeDefManager();
285         virtual ICraftDefManager* getCraftDefManager();
286         virtual ITextureSource* getTextureSource();
287         virtual IShaderSource* getShaderSource();
288         virtual u16 allocateUnknownNodeId(const std::string &name);
289         virtual ISoundManager* getSoundManager();
290         virtual MtEventManager* getEventManager();
291         virtual IRollbackReportSink* getRollbackReportSink();
292
293         IWritableItemDefManager* getWritableItemDefManager();
294         IWritableNodeDefManager* getWritableNodeDefManager();
295         IWritableCraftDefManager* getWritableCraftDefManager();
296
297         const ModSpec* getModSpec(const std::string &modname);
298         void getModNames(std::list<std::string> &modlist);
299         std::string getBuiltinLuaPath();
300         inline std::string getWorldPath()
301                         { return m_path_world; }
302
303         inline bool isSingleplayer()
304                         { return m_simple_singleplayer_mode; }
305
306         inline void setAsyncFatalError(const std::string &error)
307                         { m_async_fatal_error.set(error); }
308
309         bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
310         Map & getMap() { return m_env->getMap(); }
311         ServerEnvironment & getEnv() { return *m_env; }
312         
313         u32 hudAdd(Player *player, HudElement *element);
314         bool hudRemove(Player *player, u32 id);
315         bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
316         bool hudSetFlags(Player *player, u32 flags, u32 mask);
317         bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
318         void hudSetHotbarImage(Player *player, std::string name);
319         void hudSetHotbarSelectedImage(Player *player, std::string name);
320
321         inline Address getPeerAddress(u16 peer_id)
322                         { return m_con.GetPeerAddress(peer_id); }
323                         
324         bool setSky(Player *player, const video::SColor &bgcolor,
325                         const std::string &type, const std::vector<std::string> &params);
326         
327         bool overrideDayNightRatio(Player *player, bool do_override,
328                         float brightness);
329
330         /* con::PeerHandler implementation. */
331         void peerAdded(con::Peer *peer);
332         void deletingPeer(con::Peer *peer, bool timeout);
333
334         void DenyAccess(u16 peer_id, const std::wstring &reason);
335         bool getClientConInfo(u16 peer_id, con::rtt_stat_type type,float* retval);
336         bool getClientInfo(u16 peer_id,ClientState* state, u32* uptime,
337                         u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch,
338                         std::string* vers_string);
339
340 private:
341
342         friend class EmergeThread;
343         friend class RemoteClient;
344
345         void SendMovement(u16 peer_id);
346         void SendHP(u16 peer_id, u8 hp);
347         void SendBreath(u16 peer_id, u16 breath);
348         void SendAccessDenied(u16 peer_id,const std::wstring &reason);
349         void SendDeathscreen(u16 peer_id,bool set_camera_point_target, v3f camera_point_target);
350         void SendItemDef(u16 peer_id,IItemDefManager *itemdef, u16 protocol_version);
351         void SendNodeDef(u16 peer_id,INodeDefManager *nodedef, u16 protocol_version);
352
353         /* mark blocks not sent for all clients */
354         void SetBlocksNotSent(std::map<v3s16, MapBlock *>& block);
355
356         // Envlock and conlock should be locked when calling these
357         void SendInventory(u16 peer_id);
358         void SendChatMessage(u16 peer_id, const std::wstring &message);
359         void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
360         void SendPlayerHP(u16 peer_id);
361         void SendPlayerBreath(u16 peer_id);
362         void SendMovePlayer(u16 peer_id);
363         void SendPlayerPrivileges(u16 peer_id);
364         void SendPlayerInventoryFormspec(u16 peer_id);
365         void SendShowFormspecMessage(u16 peer_id, const std::string &formspec, const std::string &formname);
366         void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
367         void SendHUDRemove(u16 peer_id, u32 id);
368         void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
369         void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
370         void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
371         void SendSetSky(u16 peer_id, const video::SColor &bgcolor,
372                         const std::string &type, const std::vector<std::string> &params);
373         void SendOverrideDayNightRatio(u16 peer_id, bool do_override, float ratio);
374         
375         /*
376                 Send a node removal/addition event to all clients except ignore_id.
377                 Additionally, if far_players!=NULL, players further away than
378                 far_d_nodes are ignored and their peer_ids are added to far_players
379         */
380         // Envlock and conlock should be locked when calling these
381         void sendRemoveNode(v3s16 p, u16 ignore_id=0,
382                         std::list<u16> *far_players=NULL, float far_d_nodes=100);
383         void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
384                         std::list<u16> *far_players=NULL, float far_d_nodes=100,
385                         bool remove_metadata=true);
386         void setBlockNotSent(v3s16 p);
387
388         // Environment and Connection must be locked when called
389         void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
390
391         // Sends blocks to clients (locks env and con on its own)
392         void SendBlocks(float dtime);
393
394         void fillMediaCache();
395         void sendMediaAnnouncement(u16 peer_id);
396         void sendRequestedMedia(u16 peer_id,
397                         const std::list<std::string> &tosend);
398
399         void sendDetachedInventory(const std::string &name, u16 peer_id);
400         void sendDetachedInventories(u16 peer_id);
401
402         // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all)
403         void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
404                 v3f minpos, v3f maxpos,
405                 v3f minvel, v3f maxvel,
406                 v3f minacc, v3f maxacc,
407                 float minexptime, float maxexptime,
408                 float minsize, float maxsize,
409                 bool collisiondetection, bool vertical, std::string texture, u32 id);
410
411         void SendDeleteParticleSpawner(u16 peer_id, u32 id);
412
413         // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all)
414         void SendSpawnParticle(u16 peer_id,
415                 v3f pos, v3f velocity, v3f acceleration,
416                 float expirationtime, float size,
417                 bool collisiondetection, bool vertical, std::string texture);
418
419         /*
420                 Something random
421         */
422
423         void DiePlayer(u16 peer_id);
424         void RespawnPlayer(u16 peer_id);
425         void DeleteClient(u16 peer_id, ClientDeletionReason reason);
426         void UpdateCrafting(u16 peer_id);
427
428         // When called, connection mutex should be locked
429         RemoteClient* getClient(u16 peer_id,ClientState state_min=Active);
430         RemoteClient* getClientNoEx(u16 peer_id,ClientState state_min=Active);
431
432         // When called, environment mutex should be locked
433         std::string getPlayerName(u16 peer_id);
434         PlayerSAO* getPlayerSAO(u16 peer_id);
435
436         /*
437                 Get a player from memory or creates one.
438                 If player is already connected, return NULL
439                 Does not verify/modify auth info and password.
440
441                 Call with env and con locked.
442         */
443         PlayerSAO *emergePlayer(const char *name, u16 peer_id);
444
445         void handlePeerChanges();
446
447         /*
448                 Variables
449         */
450
451         // World directory
452         std::string m_path_world;
453         // Subgame specification
454         SubgameSpec m_gamespec;
455         // If true, do not allow multiple players and hide some multiplayer
456         // functionality
457         bool m_simple_singleplayer_mode;
458
459         // Thread can set; step() will throw as ServerError
460         MutexedVariable<std::string> m_async_fatal_error;
461
462         // Some timers
463         float m_liquid_transform_timer;
464         float m_liquid_transform_every;
465         float m_print_info_timer;
466         float m_masterserver_timer;
467         float m_objectdata_timer;
468         float m_emergethread_trigger_timer;
469         float m_savemap_timer;
470         IntervalLimiter m_map_timer_and_unload_interval;
471
472         // Environment
473         ServerEnvironment *m_env;
474         JMutex m_env_mutex;
475
476         // server connection
477         con::Connection m_con;
478
479         // Ban checking
480         BanManager *m_banmanager;
481
482         // Rollback manager (behind m_env_mutex)
483         IRollbackManager *m_rollback;
484         bool m_rollback_sink_enabled;
485         bool m_enable_rollback_recording; // Updated once in a while
486
487         // Emerge manager
488         EmergeManager *m_emerge;
489
490         // Scripting
491         // Envlock and conlock should be locked when using Lua
492         GameScripting *m_script;
493
494         // Item definition manager
495         IWritableItemDefManager *m_itemdef;
496
497         // Node definition manager
498         IWritableNodeDefManager *m_nodedef;
499
500         // Craft definition manager
501         IWritableCraftDefManager *m_craftdef;
502
503         // Event manager
504         EventManager *m_event;
505
506         // Mods
507         std::vector<ModSpec> m_mods;
508
509         /*
510                 Threads
511         */
512
513         // A buffer for time steps
514         // step() increments and AsyncRunStep() run by m_thread reads it.
515         float m_step_dtime;
516         JMutex m_step_dtime_mutex;
517
518         // current server step lag counter
519         float m_lag;
520
521         // The server mainly operates in this thread
522         ServerThread *m_thread;
523
524         /*
525                 Time related stuff
526         */
527
528         // Timer for sending time of day over network
529         float m_time_of_day_send_timer;
530         // Uptime of server in seconds
531         MutexedVariable<double> m_uptime;
532
533         /*
534          Client interface
535          */
536         ClientInterface m_clients;
537
538         /*
539                 Peer change queue.
540                 Queues stuff from peerAdded() and deletingPeer() to
541                 handlePeerChanges()
542         */
543         Queue<con::PeerChange> m_peer_change_queue;
544
545         /*
546                 Random stuff
547         */
548
549         // Mod parent directory paths
550         std::list<std::string> m_modspaths;
551
552         bool m_shutdown_requested;
553
554         /*
555                 Map edit event queue. Automatically receives all map edits.
556                 The constructor of this class registers us to receive them through
557                 onMapEditEvent
558
559                 NOTE: Should these be moved to actually be members of
560                 ServerEnvironment?
561         */
562
563         /*
564                 Queue of map edits from the environment for sending to the clients
565                 This is behind m_env_mutex
566         */
567         Queue<MapEditEvent*> m_unsent_map_edit_queue;
568         /*
569                 Set to true when the server itself is modifying the map and does
570                 all sending of information by itself.
571                 This is behind m_env_mutex
572         */
573         bool m_ignore_map_edit_events;
574         /*
575                 If a non-empty area, map edit events contained within are left
576                 unsent. Done at map generation time to speed up editing of the
577                 generated area, as it will be sent anyway.
578                 This is behind m_env_mutex
579         */
580         VoxelArea m_ignore_map_edit_events_area;
581         /*
582                 If set to !=0, the incoming MapEditEvents are modified to have
583                 this peed id as the disabled recipient
584                 This is behind m_env_mutex
585         */
586         u16 m_ignore_map_edit_events_peer_id;
587
588         // media files known to server
589         std::map<std::string,MediaInfo> m_media;
590
591         /*
592                 Sounds
593         */
594         std::map<s32, ServerPlayingSound> m_playing_sounds;
595         s32 m_next_sound_id;
596
597         /*
598                 Detached inventories (behind m_env_mutex)
599         */
600         // key = name
601         std::map<std::string, Inventory*> m_detached_inventories;
602
603         /*
604                 Particles
605         */
606         std::vector<u32> m_particlespawner_ids;
607 };
608
609 /*
610         Runs a simple dedicated server loop.
611
612         Shuts down when run is set to false.
613 */
614 void dedicated_server_loop(Server &server, bool &run);
615
616 #endif
617