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