9cbefa6440295bc87c0d19747cc98637ba892b9c
[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 "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 struct LuaState;
38 typedef struct lua_State lua_State;
39 class IWritableItemDefManager;
40 class IWritableNodeDefManager;
41 class IWritableCraftDefManager;
42 class EventManager;
43 class PlayerSAO;
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 MediaRequest
256 {
257         std::string name;
258
259         MediaRequest(const std::string &name_=""):
260                 name(name_)
261         {}
262 };
263
264 struct MediaInfo
265 {
266         std::string path;
267         std::string sha1_digest;
268
269         MediaInfo(const std::string path_="",
270                         const std::string sha1_digest_=""):
271                 path(path_),
272                 sha1_digest(sha1_digest_)
273         {
274         }
275 };
276
277 struct ServerSoundParams
278 {
279         float gain;
280         std::string to_player;
281         enum Type{
282                 SSP_LOCAL=0,
283                 SSP_POSITIONAL=1,
284                 SSP_OBJECT=2
285         } type;
286         v3f pos;
287         u16 object;
288         float max_hear_distance;
289         bool loop;
290
291         ServerSoundParams():
292                 gain(1.0),
293                 to_player(""),
294                 type(SSP_LOCAL),
295                 pos(0,0,0),
296                 object(0),
297                 max_hear_distance(32*BS),
298                 loop(false)
299         {}
300         
301         v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
302 };
303
304 struct ServerPlayingSound
305 {
306         ServerSoundParams params;
307         std::set<u16> clients; // peer ids
308 };
309
310 class RemoteClient
311 {
312 public:
313         // peer_id=0 means this client has no associated peer
314         // NOTE: If client is made allowed to exist while peer doesn't,
315         //       this has to be set to 0 when there is no peer.
316         //       Also, the client must be moved to some other container.
317         u16 peer_id;
318         // The serialization version to use with the client
319         u8 serialization_version;
320         //
321         u16 net_proto_version;
322         // Version is stored in here after INIT before INIT2
323         u8 pending_serialization_version;
324
325         bool definitions_sent;
326
327         RemoteClient():
328                 m_time_from_building(9999),
329                 m_excess_gotblocks(0)
330         {
331                 peer_id = 0;
332                 serialization_version = SER_FMT_VER_INVALID;
333                 net_proto_version = 0;
334                 pending_serialization_version = SER_FMT_VER_INVALID;
335                 definitions_sent = false;
336                 m_nearest_unsent_d = 0;
337                 m_nearest_unsent_reset_timer = 0.0;
338                 m_nothing_to_send_counter = 0;
339                 m_nothing_to_send_pause_timer = 0;
340         }
341         ~RemoteClient()
342         {
343         }
344         
345         /*
346                 Finds block that should be sent next to the client.
347                 Environment should be locked when this is called.
348                 dtime is used for resetting send radius at slow interval
349         */
350         void GetNextBlocks(Server *server, float dtime,
351                         core::array<PrioritySortedBlockTransfer> &dest);
352
353         void GotBlock(v3s16 p);
354
355         void SentBlock(v3s16 p);
356
357         void SetBlockNotSent(v3s16 p);
358         void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
359
360         s32 SendingCount()
361         {
362                 return m_blocks_sending.size();
363         }
364         
365         // Increments timeouts and removes timed-out blocks from list
366         // NOTE: This doesn't fix the server-not-sending-block bug
367         //       because it is related to emerging, not sending.
368         //void RunSendingTimeouts(float dtime, float timeout);
369
370         void PrintInfo(std::ostream &o)
371         {
372                 o<<"RemoteClient "<<peer_id<<": "
373                                 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
374                                 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
375                                 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
376                                 <<", m_excess_gotblocks="<<m_excess_gotblocks
377                                 <<std::endl;
378                 m_excess_gotblocks = 0;
379         }
380
381         // Time from last placing or removing blocks
382         float m_time_from_building;
383         
384         /*JMutex m_dig_mutex;
385         float m_dig_time_remaining;
386         // -1 = not digging
387         s16 m_dig_tool_item;
388         v3s16 m_dig_position;*/
389         
390         /*
391                 List of active objects that the client knows of.
392                 Value is dummy.
393         */
394         core::map<u16, bool> m_known_objects;
395
396 private:
397         /*
398                 Blocks that have been sent to client.
399                 - These don't have to be sent again.
400                 - A block is cleared from here when client says it has
401                   deleted it from it's memory
402                 
403                 Key is position, value is dummy.
404                 No MapBlock* is stored here because the blocks can get deleted.
405         */
406         core::map<v3s16, bool> m_blocks_sent;
407         s16 m_nearest_unsent_d;
408         v3s16 m_last_center;
409         float m_nearest_unsent_reset_timer;
410         
411         /*
412                 Blocks that are currently on the line.
413                 This is used for throttling the sending of blocks.
414                 - The size of this list is limited to some value
415                 Block is added when it is sent with BLOCKDATA.
416                 Block is removed when GOTBLOCKS is received.
417                 Value is time from sending. (not used at the moment)
418         */
419         core::map<v3s16, float> m_blocks_sending;
420
421         /*
422                 Count of excess GotBlocks().
423                 There is an excess amount because the client sometimes
424                 gets a block so late that the server sends it again,
425                 and the client then sends two GOTBLOCKs.
426                 This is resetted by PrintInfo()
427         */
428         u32 m_excess_gotblocks;
429         
430         // CPU usage optimization
431         u32 m_nothing_to_send_counter;
432         float m_nothing_to_send_pause_timer;
433 };
434
435 class Server : public con::PeerHandler, public MapEventReceiver,
436                 public InventoryManager, public IGameDef,
437                 public IBackgroundBlockEmerger
438 {
439 public:
440         /*
441                 NOTE: Every public method should be thread-safe
442         */
443         
444         Server(
445                 const std::string &path_world,
446                 const std::string &path_config,
447                 const SubgameSpec &gamespec,
448                 bool simple_singleplayer_mode
449         );
450         ~Server();
451         void start(unsigned short port);
452         void stop();
453         // This is mainly a way to pass the time to the server.
454         // Actual processing is done in an another thread.
455         void step(float dtime);
456         // This is run by ServerThread and does the actual processing
457         void AsyncRunStep();
458         void Receive();
459         void ProcessData(u8 *data, u32 datasize, u16 peer_id);
460
461         core::list<PlayerInfo> getPlayerInfo();
462
463         // Environment must be locked when called
464         void setTimeOfDay(u32 time)
465         {
466                 m_env->setTimeOfDay(time);
467                 m_time_of_day_send_timer = 0;
468         }
469
470         bool getShutdownRequested()
471         {
472                 return m_shutdown_requested;
473         }
474         
475         /*
476                 Shall be called with the environment locked.
477                 This is accessed by the map, which is inside the environment,
478                 so it shouldn't be a problem.
479         */
480         void onMapEditEvent(MapEditEvent *event);
481
482         /*
483                 Shall be called with the environment and the connection locked.
484         */
485         Inventory* getInventory(const InventoryLocation &loc);
486         std::string getInventoryOwner(const InventoryLocation &loc);
487         void setInventoryModified(const InventoryLocation &loc);
488
489         // Connection must be locked when called
490         std::wstring getStatusString();
491
492         void requestShutdown(void)
493         {
494                 m_shutdown_requested = true;
495         }
496
497         // Returns -1 if failed, sound handle on success
498         // Envlock + conlock
499         s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams &params);
500         void stopSound(s32 handle);
501         
502         // Envlock + conlock
503         std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
504         bool checkPriv(const std::string &name, const std::string &priv);
505         void reportPrivsModified(const std::string &name=""); // ""=all
506
507         // Saves g_settings to configpath given at initialization
508         void saveConfig();
509
510         void setIpBanned(const std::string &ip, const std::string &name)
511         {
512                 m_banmanager.add(ip, name);
513                 return;
514         }
515
516         void unsetIpBanned(const std::string &ip_or_name)
517         {
518                 m_banmanager.remove(ip_or_name);
519                 return;
520         }
521
522         std::string getBanDescription(const std::string &ip_or_name)
523         {
524                 return m_banmanager.getBanDescription(ip_or_name);
525         }
526
527         Address getPeerAddress(u16 peer_id)
528         {
529                 return m_con.GetPeerAddress(peer_id);
530         }
531         
532         // Envlock and conlock should be locked when calling this
533         void notifyPlayer(const char *name, const std::wstring msg);
534         void notifyPlayers(const std::wstring msg);
535
536         void queueBlockEmerge(v3s16 blockpos, bool allow_generate);
537         
538         // Envlock and conlock should be locked when using Lua
539         lua_State *getLua(){ return m_lua; }
540         
541         // IGameDef interface
542         // Under envlock
543         virtual IItemDefManager* getItemDefManager();
544         virtual INodeDefManager* getNodeDefManager();
545         virtual ICraftDefManager* getCraftDefManager();
546         virtual ITextureSource* getTextureSource();
547         virtual u16 allocateUnknownNodeId(const std::string &name);
548         virtual ISoundManager* getSoundManager();
549         virtual MtEventManager* getEventManager();
550         
551         IWritableItemDefManager* getWritableItemDefManager();
552         IWritableNodeDefManager* getWritableNodeDefManager();
553         IWritableCraftDefManager* getWritableCraftDefManager();
554
555         const ModSpec* getModSpec(const std::string &modname);
556         std::string getBuiltinLuaPath();
557         
558         std::string getWorldPath(){ return m_path_world; }
559
560         bool isSingleplayer(){ return m_simple_singleplayer_mode; }
561
562         void setAsyncFatalError(const std::string &error)
563         {
564                 m_async_fatal_error.set(error);
565         }
566
567 private:
568
569         // con::PeerHandler implementation.
570         // These queue stuff to be processed by handlePeerChanges().
571         // As of now, these create and remove clients and players.
572         void peerAdded(con::Peer *peer);
573         void deletingPeer(con::Peer *peer, bool timeout);
574         
575         /*
576                 Static send methods
577         */
578         
579         static void SendHP(con::Connection &con, u16 peer_id, u8 hp);
580         static void SendAccessDenied(con::Connection &con, u16 peer_id,
581                         const std::wstring &reason);
582         static void SendDeathscreen(con::Connection &con, u16 peer_id,
583                         bool set_camera_point_target, v3f camera_point_target);
584         static void SendItemDef(con::Connection &con, u16 peer_id,
585                         IItemDefManager *itemdef);
586         static void SendNodeDef(con::Connection &con, u16 peer_id,
587                         INodeDefManager *nodedef);
588         
589         /*
590                 Non-static send methods.
591                 Conlock should be always used.
592                 Envlock usage is documented badly but it's easy to figure out
593                 which ones access the environment.
594         */
595
596         // Envlock and conlock should be locked when calling these
597         void SendInventory(u16 peer_id);
598         void SendChatMessage(u16 peer_id, const std::wstring &message);
599         void BroadcastChatMessage(const std::wstring &message);
600         void SendPlayerHP(u16 peer_id);
601         void SendMovePlayer(u16 peer_id);
602         void SendPlayerPrivileges(u16 peer_id);
603         /*
604                 Send a node removal/addition event to all clients except ignore_id.
605                 Additionally, if far_players!=NULL, players further away than
606                 far_d_nodes are ignored and their peer_ids are added to far_players
607         */
608         // Envlock and conlock should be locked when calling these
609         void sendRemoveNode(v3s16 p, u16 ignore_id=0,
610                         core::list<u16> *far_players=NULL, float far_d_nodes=100);
611         void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
612                         core::list<u16> *far_players=NULL, float far_d_nodes=100);
613         void setBlockNotSent(v3s16 p);
614         
615         // Environment and Connection must be locked when called
616         void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
617         
618         // Sends blocks to clients (locks env and con on its own)
619         void SendBlocks(float dtime);
620         
621         void fillMediaCache();
622         void sendMediaAnnouncement(u16 peer_id);
623         void sendRequestedMedia(u16 peer_id,
624                         const core::list<MediaRequest> &tosend);
625
626         /*
627                 Something random
628         */
629         
630         void DiePlayer(u16 peer_id);
631         void RespawnPlayer(u16 peer_id);
632         
633         void UpdateCrafting(u16 peer_id);
634         
635         // When called, connection mutex should be locked
636         RemoteClient* getClient(u16 peer_id);
637         
638         // When called, environment mutex should be locked
639         std::string getPlayerName(u16 peer_id)
640         {
641                 Player *player = m_env->getPlayer(peer_id);
642                 if(player == NULL)
643                         return "[id="+itos(peer_id)+"]";
644                 return player->getName();
645         }
646
647         // When called, environment mutex should be locked
648         PlayerSAO* getPlayerSAO(u16 peer_id)
649         {
650                 Player *player = m_env->getPlayer(peer_id);
651                 if(player == NULL)
652                         return NULL;
653                 return player->getPlayerSAO();
654         }
655
656         /*
657                 Get a player from memory or creates one.
658                 If player is already connected, return NULL
659                 Does not verify/modify auth info and password.
660
661                 Call with env and con locked.
662         */
663         PlayerSAO *emergePlayer(const char *name, u16 peer_id);
664         
665         // Locks environment and connection by its own
666         struct PeerChange;
667         void handlePeerChange(PeerChange &c);
668         void handlePeerChanges();
669
670         /*
671                 Variables
672         */
673         
674         // World directory
675         std::string m_path_world;
676         // Path to user's configuration file ("" = no configuration file)
677         std::string m_path_config;
678         // Subgame specification
679         SubgameSpec m_gamespec;
680         // If true, do not allow multiple players and hide some multiplayer
681         // functionality
682         bool m_simple_singleplayer_mode;
683
684         // Thread can set; step() will throw as ServerError
685         MutexedVariable<std::string> m_async_fatal_error;
686         
687         // Some timers
688         float m_liquid_transform_timer;
689         float m_print_info_timer;
690         float m_objectdata_timer;
691         float m_emergethread_trigger_timer;
692         float m_savemap_timer;
693         IntervalLimiter m_map_timer_and_unload_interval;
694         
695         // NOTE: If connection and environment are both to be locked,
696         // environment shall be locked first.
697
698         // Environment
699         ServerEnvironment *m_env;
700         JMutex m_env_mutex;
701         
702         // Connection
703         con::Connection m_con;
704         JMutex m_con_mutex;
705         // Connected clients (behind the con mutex)
706         core::map<u16, RemoteClient*> m_clients;
707
708         // Bann checking
709         BanManager m_banmanager;
710
711         // Scripting
712         // Envlock and conlock should be locked when using Lua
713         lua_State *m_lua;
714
715         // Item definition manager
716         IWritableItemDefManager *m_itemdef;
717         
718         // Node definition manager
719         IWritableNodeDefManager *m_nodedef;
720         
721         // Craft definition manager
722         IWritableCraftDefManager *m_craftdef;
723         
724         // Event manager
725         EventManager *m_event;
726         
727         // Mods
728         core::list<ModSpec> m_mods;
729         
730         /*
731                 Threads
732         */
733         
734         // A buffer for time steps
735         // step() increments and AsyncRunStep() run by m_thread reads it.
736         float m_step_dtime;
737         JMutex m_step_dtime_mutex;
738
739         // The server mainly operates in this thread
740         ServerThread m_thread;
741         // This thread fetches and generates map
742         EmergeThread m_emergethread;
743         // Queue of block coordinates to be processed by the emerge thread
744         BlockEmergeQueue m_emerge_queue;
745         
746         /*
747                 Time related stuff
748         */
749
750         // Timer for sending time of day over network
751         float m_time_of_day_send_timer;
752         // Uptime of server in seconds
753         MutexedVariable<double> m_uptime;
754         
755         /*
756                 Peer change queue.
757                 Queues stuff from peerAdded() and deletingPeer() to
758                 handlePeerChanges()
759         */
760         enum PeerChangeType
761         {
762                 PEER_ADDED,
763                 PEER_REMOVED
764         };
765         struct PeerChange
766         {
767                 PeerChangeType type;
768                 u16 peer_id;
769                 bool timeout;
770         };
771         Queue<PeerChange> m_peer_change_queue;
772
773         /*
774                 Random stuff
775         */
776         
777         // Mod parent directory paths
778         core::list<std::string> m_modspaths;
779
780         bool m_shutdown_requested;
781
782         /*
783                 Map edit event queue. Automatically receives all map edits.
784                 The constructor of this class registers us to receive them through
785                 onMapEditEvent
786
787                 NOTE: Should these be moved to actually be members of
788                 ServerEnvironment?
789         */
790
791         /*
792                 Queue of map edits from the environment for sending to the clients
793                 This is behind m_env_mutex
794         */
795         Queue<MapEditEvent*> m_unsent_map_edit_queue;
796         /*
797                 Set to true when the server itself is modifying the map and does
798                 all sending of information by itself.
799                 This is behind m_env_mutex
800         */
801         bool m_ignore_map_edit_events;
802         /*
803                 If a non-empty area, map edit events contained within are left
804                 unsent. Done at map generation time to speed up editing of the
805                 generated area, as it will be sent anyway.
806                 This is behind m_env_mutex
807         */
808         VoxelArea m_ignore_map_edit_events_area;
809         /*
810                 If set to !=0, the incoming MapEditEvents are modified to have
811                 this peed id as the disabled recipient
812                 This is behind m_env_mutex
813         */
814         u16 m_ignore_map_edit_events_peer_id;
815
816         friend class EmergeThread;
817         friend class RemoteClient;
818
819         std::map<std::string,MediaInfo> m_media;
820
821         /*
822                 Sounds
823         */
824         std::map<s32, ServerPlayingSound> m_playing_sounds;
825         s32 m_next_sound_id;
826 };
827
828 /*
829         Runs a simple dedicated server loop.
830
831         Shuts down when run is set to false.
832 */
833 void dedicated_server_loop(Server &server, bool &run);
834
835 #endif
836