]> git.lizzy.rs Git - minetest.git/blob - src/server.h
Merge remote branch 'origin/master'
[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 "environment.h"
25 #include "irrlichttypes_bloated.h"
26 #include <string>
27 #include "porting.h"
28 #include "map.h"
29 #include "inventory.h"
30 #include "ban.h"
31 #include "gamedef.h"
32 #include "serialization.h" // For SER_FMT_VER_INVALID
33 #include "mods.h"
34 #include "inventorymanager.h"
35 #include "subgame.h"
36 #include "sound.h"
37 #include "util/thread.h"
38 #include "util/string.h"
39 #include "rollback_interface.h" // Needed for rollbackRevertActions()
40 #include <list> // Needed for rollbackRevertActions()
41
42 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
43
44 struct LuaState;
45 typedef struct lua_State lua_State;
46 class IWritableItemDefManager;
47 class IWritableNodeDefManager;
48 class IWritableCraftDefManager;
49 class EventManager;
50 class PlayerSAO;
51 class IRollbackManager;
52 class EmergeManager;
53
54 class ServerError : public std::exception
55 {
56 public:
57         ServerError(const std::string &s)
58         {
59                 m_s = "ServerError: ";
60                 m_s += s;
61         }
62         virtual ~ServerError() throw()
63         {}
64         virtual const char * what() const throw()
65         {
66                 return m_s.c_str();
67         }
68         std::string m_s;
69 };
70
71 /*
72         Some random functions
73 */
74 v3f findSpawnPos(ServerMap &map);
75
76
77 class MapEditEventIgnorer
78 {
79 public:
80         MapEditEventIgnorer(bool *flag):
81                 m_flag(flag)
82         {
83                 if(*m_flag == false)
84                         *m_flag = true;
85                 else
86                         m_flag = NULL;
87         }
88
89         ~MapEditEventIgnorer()
90         {
91                 if(m_flag)
92                 {
93                         assert(*m_flag);
94                         *m_flag = false;
95                 }
96         }
97
98 private:
99         bool *m_flag;
100 };
101
102 class MapEditEventAreaIgnorer
103 {
104 public:
105         MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
106                 m_ignorevariable(ignorevariable)
107         {
108                 if(m_ignorevariable->getVolume() == 0)
109                         *m_ignorevariable = a;
110                 else
111                         m_ignorevariable = NULL;
112         }
113
114         ~MapEditEventAreaIgnorer()
115         {
116                 if(m_ignorevariable)
117                 {
118                         assert(m_ignorevariable->getVolume() != 0);
119                         *m_ignorevariable = VoxelArea();
120                 }
121         }
122
123 private:
124         VoxelArea *m_ignorevariable;
125 };
126
127 class Server;
128
129 class ServerThread : public SimpleThread
130 {
131         Server *m_server;
132
133 public:
134
135         ServerThread(Server *server):
136                 SimpleThread(),
137                 m_server(server)
138         {
139         }
140
141         void * Thread();
142 };
143
144 struct PlayerInfo
145 {
146         u16 id;
147         char name[PLAYERNAME_SIZE];
148         v3f position;
149         Address address;
150         float avg_rtt;
151
152         PlayerInfo();
153         void PrintLine(std::ostream *s);
154 };
155
156 /*
157         Used for queueing and sorting block transfers in containers
158
159         Lower priority number means higher priority.
160 */
161 struct PrioritySortedBlockTransfer
162 {
163         PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
164         {
165                 priority = a_priority;
166                 pos = a_pos;
167                 peer_id = a_peer_id;
168         }
169         bool operator < (PrioritySortedBlockTransfer &other)
170         {
171                 return priority < other.priority;
172         }
173         float priority;
174         v3s16 pos;
175         u16 peer_id;
176 };
177
178 struct MediaRequest
179 {
180         std::string name;
181
182         MediaRequest(const std::string &name_=""):
183                 name(name_)
184         {}
185 };
186
187 struct MediaInfo
188 {
189         std::string path;
190         std::string sha1_digest;
191
192         MediaInfo(const std::string path_="",
193                         const std::string sha1_digest_=""):
194                 path(path_),
195                 sha1_digest(sha1_digest_)
196         {
197         }
198 };
199
200 struct ServerSoundParams
201 {
202         float gain;
203         std::string to_player;
204         enum Type{
205                 SSP_LOCAL=0,
206                 SSP_POSITIONAL=1,
207                 SSP_OBJECT=2
208         } type;
209         v3f pos;
210         u16 object;
211         float max_hear_distance;
212         bool loop;
213
214         ServerSoundParams():
215                 gain(1.0),
216                 to_player(""),
217                 type(SSP_LOCAL),
218                 pos(0,0,0),
219                 object(0),
220                 max_hear_distance(32*BS),
221                 loop(false)
222         {}
223
224         v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
225 };
226
227 struct ServerPlayingSound
228 {
229         ServerSoundParams params;
230         std::set<u16> clients; // peer ids
231 };
232
233 class RemoteClient
234 {
235 public:
236         // peer_id=0 means this client has no associated peer
237         // NOTE: If client is made allowed to exist while peer doesn't,
238         //       this has to be set to 0 when there is no peer.
239         //       Also, the client must be moved to some other container.
240         u16 peer_id;
241         // The serialization version to use with the client
242         u8 serialization_version;
243         //
244         u16 net_proto_version;
245         // Version is stored in here after INIT before INIT2
246         u8 pending_serialization_version;
247
248         bool definitions_sent;
249
250         RemoteClient():
251                 m_time_from_building(9999),
252                 m_excess_gotblocks(0)
253         {
254                 peer_id = 0;
255                 serialization_version = SER_FMT_VER_INVALID;
256                 net_proto_version = 0;
257                 pending_serialization_version = SER_FMT_VER_INVALID;
258                 definitions_sent = false;
259                 m_nearest_unsent_d = 0;
260                 m_nearest_unsent_reset_timer = 0.0;
261                 m_nothing_to_send_counter = 0;
262                 m_nothing_to_send_pause_timer = 0;
263         }
264         ~RemoteClient()
265         {
266         }
267
268         /*
269                 Finds block that should be sent next to the client.
270                 Environment should be locked when this is called.
271                 dtime is used for resetting send radius at slow interval
272         */
273         void GetNextBlocks(Server *server, float dtime,
274                         core::array<PrioritySortedBlockTransfer> &dest);
275
276         void GotBlock(v3s16 p);
277
278         void SentBlock(v3s16 p);
279
280         void SetBlockNotSent(v3s16 p);
281         void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
282
283         s32 SendingCount()
284         {
285                 return m_blocks_sending.size();
286         }
287
288         // Increments timeouts and removes timed-out blocks from list
289         // NOTE: This doesn't fix the server-not-sending-block bug
290         //       because it is related to emerging, not sending.
291         //void RunSendingTimeouts(float dtime, float timeout);
292
293         void PrintInfo(std::ostream &o)
294         {
295                 o<<"RemoteClient "<<peer_id<<": "
296                                 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
297                                 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
298                                 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
299                                 <<", m_excess_gotblocks="<<m_excess_gotblocks
300                                 <<std::endl;
301                 m_excess_gotblocks = 0;
302         }
303
304         // Time from last placing or removing blocks
305         float m_time_from_building;
306
307         /*JMutex m_dig_mutex;
308         float m_dig_time_remaining;
309         // -1 = not digging
310         s16 m_dig_tool_item;
311         v3s16 m_dig_position;*/
312
313         /*
314                 List of active objects that the client knows of.
315                 Value is dummy.
316         */
317         core::map<u16, bool> m_known_objects;
318
319 private:
320         /*
321                 Blocks that have been sent to client.
322                 - These don't have to be sent again.
323                 - A block is cleared from here when client says it has
324                   deleted it from it's memory
325
326                 Key is position, value is dummy.
327                 No MapBlock* is stored here because the blocks can get deleted.
328         */
329         core::map<v3s16, bool> m_blocks_sent;
330         s16 m_nearest_unsent_d;
331         v3s16 m_last_center;
332         float m_nearest_unsent_reset_timer;
333
334         /*
335                 Blocks that are currently on the line.
336                 This is used for throttling the sending of blocks.
337                 - The size of this list is limited to some value
338                 Block is added when it is sent with BLOCKDATA.
339                 Block is removed when GOTBLOCKS is received.
340                 Value is time from sending. (not used at the moment)
341         */
342         core::map<v3s16, float> m_blocks_sending;
343
344         /*
345                 Count of excess GotBlocks().
346                 There is an excess amount because the client sometimes
347                 gets a block so late that the server sends it again,
348                 and the client then sends two GOTBLOCKs.
349                 This is resetted by PrintInfo()
350         */
351         u32 m_excess_gotblocks;
352
353         // CPU usage optimization
354         u32 m_nothing_to_send_counter;
355         float m_nothing_to_send_pause_timer;
356 };
357
358 class Server : public con::PeerHandler, public MapEventReceiver,
359                 public InventoryManager, public IGameDef,
360                 public IBackgroundBlockEmerger
361 {
362 public:
363         /*
364                 NOTE: Every public method should be thread-safe
365         */
366
367         Server(
368                 const std::string &path_world,
369                 const std::string &path_config,
370                 const SubgameSpec &gamespec,
371                 bool simple_singleplayer_mode
372         );
373         ~Server();
374         void start(unsigned short port);
375         void stop();
376         // This is mainly a way to pass the time to the server.
377         // Actual processing is done in an another thread.
378         void step(float dtime);
379         // This is run by ServerThread and does the actual processing
380         void AsyncRunStep();
381         void Receive();
382         void ProcessData(u8 *data, u32 datasize, u16 peer_id);
383
384         core::list<PlayerInfo> getPlayerInfo();
385
386         // Environment must be locked when called
387         void setTimeOfDay(u32 time)
388         {
389                 m_env->setTimeOfDay(time);
390                 m_time_of_day_send_timer = 0;
391         }
392
393         bool getShutdownRequested()
394         {
395                 return m_shutdown_requested;
396         }
397
398         /*
399                 Shall be called with the environment locked.
400                 This is accessed by the map, which is inside the environment,
401                 so it shouldn't be a problem.
402         */
403         void onMapEditEvent(MapEditEvent *event);
404
405         /*
406                 Shall be called with the environment and the connection locked.
407         */
408         Inventory* getInventory(const InventoryLocation &loc);
409         void setInventoryModified(const InventoryLocation &loc);
410
411         // Connection must be locked when called
412         std::wstring getStatusString();
413
414         void requestShutdown(void)
415         {
416                 m_shutdown_requested = true;
417         }
418
419         // Returns -1 if failed, sound handle on success
420         // Envlock + conlock
421         s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams &params);
422         void stopSound(s32 handle);
423
424         // Envlock + conlock
425         std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
426         bool checkPriv(const std::string &name, const std::string &priv);
427         void reportPrivsModified(const std::string &name=""); // ""=all
428         void reportInventoryFormspecModified(const std::string &name);
429
430         // Saves g_settings to configpath given at initialization
431         void saveConfig();
432
433         void setIpBanned(const std::string &ip, const std::string &name)
434         {
435                 m_banmanager.add(ip, name);
436                 return;
437         }
438
439         void unsetIpBanned(const std::string &ip_or_name)
440         {
441                 m_banmanager.remove(ip_or_name);
442                 return;
443         }
444
445         std::string getBanDescription(const std::string &ip_or_name)
446         {
447                 return m_banmanager.getBanDescription(ip_or_name);
448         }
449
450         Address getPeerAddress(u16 peer_id)
451         {
452                 return m_con.GetPeerAddress(peer_id);
453         }
454
455         // Envlock and conlock should be locked when calling this
456         void notifyPlayer(const char *name, const std::wstring msg);
457         void notifyPlayers(const std::wstring msg);
458
459         void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
460
461         // Creates or resets inventory
462         Inventory* createDetachedInventory(const std::string &name);
463
464         // Envlock and conlock should be locked when using Lua
465         lua_State *getLua(){ return m_lua; }
466
467         // Envlock should be locked when using the rollback manager
468         IRollbackManager *getRollbackManager(){ return m_rollback; }
469
470         //TODO:  determine what should be locked when accessing the emerge manager
471         EmergeManager *getEmergeManager(){ return m_emerge; }
472
473         BiomeDefManager *getBiomeDef(){ return m_biomedef; }
474
475         // actions: time-reversed list
476         // Return value: success/failure
477         bool rollbackRevertActions(const std::list<RollbackAction> &actions,
478                         std::list<std::string> *log);
479
480         // IGameDef interface
481         // Under envlock
482         virtual IItemDefManager* getItemDefManager();
483         virtual INodeDefManager* getNodeDefManager();
484         virtual ICraftDefManager* getCraftDefManager();
485         virtual ITextureSource* getTextureSource();
486         virtual IShaderSource* getShaderSource();
487         virtual u16 allocateUnknownNodeId(const std::string &name);
488         virtual ISoundManager* getSoundManager();
489         virtual MtEventManager* getEventManager();
490         virtual IRollbackReportSink* getRollbackReportSink();
491
492         IWritableItemDefManager* getWritableItemDefManager();
493         IWritableNodeDefManager* getWritableNodeDefManager();
494         IWritableCraftDefManager* getWritableCraftDefManager();
495
496         const ModSpec* getModSpec(const std::string &modname);
497         void getModNames(core::list<std::string> &modlist);
498         std::string getBuiltinLuaPath();
499
500         std::string getWorldPath(){ return m_path_world; }
501
502         bool isSingleplayer(){ return m_simple_singleplayer_mode; }
503
504         void setAsyncFatalError(const std::string &error)
505         {
506                 m_async_fatal_error.set(error);
507         }
508
509         bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
510 private:
511
512         // con::PeerHandler implementation.
513         // These queue stuff to be processed by handlePeerChanges().
514         // As of now, these create and remove clients and players.
515         void peerAdded(con::Peer *peer);
516         void deletingPeer(con::Peer *peer, bool timeout);
517
518         /*
519                 Static send methods
520         */
521
522         static void SendMovement(con::Connection &con, u16 peer_id);
523         static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
524         static void SendAccessDenied(con::Connection &con, u16 peer_id,
525                         const std::wstring &reason);
526         static void SendDeathscreen(con::Connection &con, u16 peer_id,
527                         bool set_camera_point_target, v3f camera_point_target);
528         static void SendItemDef(con::Connection &con, u16 peer_id,
529                         IItemDefManager *itemdef);
530         static void SendNodeDef(con::Connection &con, u16 peer_id,
531                         INodeDefManager *nodedef, u16 protocol_version);
532
533         /*
534                 Non-static send methods.
535                 Conlock should be always used.
536                 Envlock usage is documented badly but it's easy to figure out
537                 which ones access the environment.
538         */
539
540         // Envlock and conlock should be locked when calling these
541         void SendInventory(u16 peer_id);
542         void SendChatMessage(u16 peer_id, const std::wstring &message);
543         void BroadcastChatMessage(const std::wstring &message);
544         void SendPlayerHP(u16 peer_id);
545         void SendMovePlayer(u16 peer_id);
546         void SendPlayerPrivileges(u16 peer_id);
547         void SendPlayerInventoryFormspec(u16 peer_id);
548         void SendShowFormspecMessage(u16 peer_id, const std::string formspec, const std::string formname);
549         /*
550                 Send a node removal/addition event to all clients except ignore_id.
551                 Additionally, if far_players!=NULL, players further away than
552                 far_d_nodes are ignored and their peer_ids are added to far_players
553         */
554         // Envlock and conlock should be locked when calling these
555         void sendRemoveNode(v3s16 p, u16 ignore_id=0,
556                         core::list<u16> *far_players=NULL, float far_d_nodes=100);
557         void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
558                         core::list<u16> *far_players=NULL, float far_d_nodes=100);
559         void setBlockNotSent(v3s16 p);
560
561         // Environment and Connection must be locked when called
562         void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
563
564         // Sends blocks to clients (locks env and con on its own)
565         void SendBlocks(float dtime);
566
567         void fillMediaCache();
568         void sendMediaAnnouncement(u16 peer_id);
569         void sendRequestedMedia(u16 peer_id,
570                         const core::list<MediaRequest> &tosend);
571
572         void sendDetachedInventory(const std::string &name, u16 peer_id);
573         void sendDetachedInventoryToAll(const std::string &name);
574         void sendDetachedInventories(u16 peer_id);
575
576         /*
577                 Something random
578         */
579
580         void DiePlayer(u16 peer_id);
581         void RespawnPlayer(u16 peer_id);
582
583         void UpdateCrafting(u16 peer_id);
584
585         // When called, connection mutex should be locked
586         RemoteClient* getClient(u16 peer_id);
587
588         // When called, environment mutex should be locked
589         std::string getPlayerName(u16 peer_id)
590         {
591                 Player *player = m_env->getPlayer(peer_id);
592                 if(player == NULL)
593                         return "[id="+itos(peer_id)+"]";
594                 return player->getName();
595         }
596
597         // When called, environment mutex should be locked
598         PlayerSAO* getPlayerSAO(u16 peer_id)
599         {
600                 Player *player = m_env->getPlayer(peer_id);
601                 if(player == NULL)
602                         return NULL;
603                 return player->getPlayerSAO();
604         }
605
606         /*
607                 Get a player from memory or creates one.
608                 If player is already connected, return NULL
609                 Does not verify/modify auth info and password.
610
611                 Call with env and con locked.
612         */
613         PlayerSAO *emergePlayer(const char *name, u16 peer_id);
614
615         // Locks environment and connection by its own
616         struct PeerChange;
617         void handlePeerChange(PeerChange &c);
618         void handlePeerChanges();
619
620         /*
621                 Variables
622         */
623
624         // World directory
625         std::string m_path_world;
626         // Path to user's configuration file ("" = no configuration file)
627         std::string m_path_config;
628         // Subgame specification
629         SubgameSpec m_gamespec;
630         // If true, do not allow multiple players and hide some multiplayer
631         // functionality
632         bool m_simple_singleplayer_mode;
633
634         // Thread can set; step() will throw as ServerError
635         MutexedVariable<std::string> m_async_fatal_error;
636
637         // Some timers
638         float m_liquid_transform_timer;
639         float m_liquid_transform_every;
640         float m_print_info_timer;
641         float m_masterserver_timer;
642         float m_objectdata_timer;
643         float m_emergethread_trigger_timer;
644         float m_savemap_timer;
645         IntervalLimiter m_map_timer_and_unload_interval;
646
647         // NOTE: If connection and environment are both to be locked,
648         // environment shall be locked first.
649
650         // Environment
651         ServerEnvironment *m_env;
652         JMutex m_env_mutex;
653
654         // Connection
655         con::Connection m_con;
656         JMutex m_con_mutex;
657         // Connected clients (behind the con mutex)
658         core::map<u16, RemoteClient*> m_clients;
659         u16 m_clients_number; //for announcing masterserver
660
661         // Bann checking
662         BanManager m_banmanager;
663
664         // Rollback manager (behind m_env_mutex)
665         IRollbackManager *m_rollback;
666         bool m_rollback_sink_enabled;
667         bool m_enable_rollback_recording; // Updated once in a while
668
669         // Emerge manager
670         EmergeManager *m_emerge;
671
672         // Biome Definition Manager
673         BiomeDefManager *m_biomedef;
674
675         // Scripting
676         // Envlock and conlock should be locked when using Lua
677         lua_State *m_lua;
678
679         // Item definition manager
680         IWritableItemDefManager *m_itemdef;
681
682         // Node definition manager
683         IWritableNodeDefManager *m_nodedef;
684
685         // Craft definition manager
686         IWritableCraftDefManager *m_craftdef;
687
688         // Event manager
689         EventManager *m_event;
690
691         // Mods
692         std::vector<ModSpec> m_mods;
693
694         /*
695                 Threads
696         */
697
698         // A buffer for time steps
699         // step() increments and AsyncRunStep() run by m_thread reads it.
700         float m_step_dtime;
701         JMutex m_step_dtime_mutex;
702
703         // The server mainly operates in this thread
704         ServerThread m_thread;
705
706         /*
707                 Time related stuff
708         */
709
710         // Timer for sending time of day over network
711         float m_time_of_day_send_timer;
712         // Uptime of server in seconds
713         MutexedVariable<double> m_uptime;
714
715         /*
716                 Peer change queue.
717                 Queues stuff from peerAdded() and deletingPeer() to
718                 handlePeerChanges()
719         */
720         enum PeerChangeType
721         {
722                 PEER_ADDED,
723                 PEER_REMOVED
724         };
725         struct PeerChange
726         {
727                 PeerChangeType type;
728                 u16 peer_id;
729                 bool timeout;
730         };
731         Queue<PeerChange> m_peer_change_queue;
732
733         /*
734                 Random stuff
735         */
736
737         // Mod parent directory paths
738         core::list<std::string> m_modspaths;
739
740         bool m_shutdown_requested;
741
742         /*
743                 Map edit event queue. Automatically receives all map edits.
744                 The constructor of this class registers us to receive them through
745                 onMapEditEvent
746
747                 NOTE: Should these be moved to actually be members of
748                 ServerEnvironment?
749         */
750
751         /*
752                 Queue of map edits from the environment for sending to the clients
753                 This is behind m_env_mutex
754         */
755         Queue<MapEditEvent*> m_unsent_map_edit_queue;
756         /*
757                 Set to true when the server itself is modifying the map and does
758                 all sending of information by itself.
759                 This is behind m_env_mutex
760         */
761         bool m_ignore_map_edit_events;
762         /*
763                 If a non-empty area, map edit events contained within are left
764                 unsent. Done at map generation time to speed up editing of the
765                 generated area, as it will be sent anyway.
766                 This is behind m_env_mutex
767         */
768         VoxelArea m_ignore_map_edit_events_area;
769         /*
770                 If set to !=0, the incoming MapEditEvents are modified to have
771                 this peed id as the disabled recipient
772                 This is behind m_env_mutex
773         */
774         u16 m_ignore_map_edit_events_peer_id;
775
776         friend class EmergeThread;
777         friend class RemoteClient;
778
779         std::map<std::string,MediaInfo> m_media;
780
781         /*
782                 Sounds
783         */
784         std::map<s32, ServerPlayingSound> m_playing_sounds;
785         s32 m_next_sound_id;
786
787         /*
788                 Detached inventories (behind m_env_mutex)
789         */
790         // key = name
791         std::map<std::string, Inventory*> m_detached_inventories;
792 };
793
794 /*
795         Runs a simple dedicated server loop.
796
797         Shuts down when run is set to false.
798 */
799 void dedicated_server_loop(Server &server, bool &run);
800
801 #endif
802