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