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