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