]> git.lizzy.rs Git - dragonfireclient.git/blob - src/server.h
Send real port to server list
[dragonfireclient.git] / src / server.h
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #ifndef SERVER_HEADER
21 #define SERVER_HEADER
22
23 #include "connection.h"
24 #include "irr_v3d.h"
25 #include "map.h"
26 #include "hud.h"
27 #include "gamedef.h"
28 #include "serialization.h" // For SER_FMT_VER_INVALID
29 #include "mods.h"
30 #include "inventorymanager.h"
31 #include "subgame.h"
32 #include "util/numeric.h"
33 #include "util/thread.h"
34 #include "environment.h"
35 #include "clientiface.h"
36 #include <string>
37 #include <list>
38 #include <map>
39 #include <vector>
40
41 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
42
43 class IWritableItemDefManager;
44 class IWritableNodeDefManager;
45 class IWritableCraftDefManager;
46 class BanManager;
47 class EventManager;
48 class Inventory;
49 class Player;
50 class PlayerSAO;
51 class IRollbackManager;
52 struct RollbackAction;
53 class EmergeManager;
54 class GameScripting;
55 class ServerEnvironment;
56 struct SimpleSoundSpec;
57 class ServerThread;
58
59 enum ClientDeletionReason {
60         CDR_LEAVE,
61         CDR_TIMEOUT,
62         CDR_DENY
63 };
64
65 /*
66         Some random functions
67 */
68 v3f findSpawnPos(ServerMap &map);
69
70 class MapEditEventIgnorer
71 {
72 public:
73         MapEditEventIgnorer(bool *flag):
74                 m_flag(flag)
75         {
76                 if(*m_flag == false)
77                         *m_flag = true;
78                 else
79                         m_flag = NULL;
80         }
81
82         ~MapEditEventIgnorer()
83         {
84                 if(m_flag)
85                 {
86                         assert(*m_flag);
87                         *m_flag = false;
88                 }
89         }
90
91 private:
92         bool *m_flag;
93 };
94
95 class MapEditEventAreaIgnorer
96 {
97 public:
98         MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
99                 m_ignorevariable(ignorevariable)
100         {
101                 if(m_ignorevariable->getVolume() == 0)
102                         *m_ignorevariable = a;
103                 else
104                         m_ignorevariable = NULL;
105         }
106
107         ~MapEditEventAreaIgnorer()
108         {
109                 if(m_ignorevariable)
110                 {
111                         assert(m_ignorevariable->getVolume() != 0);
112                         *m_ignorevariable = VoxelArea();
113                 }
114         }
115
116 private:
117         VoxelArea *m_ignorevariable;
118 };
119
120 struct MediaInfo
121 {
122         std::string path;
123         std::string sha1_digest;
124
125         MediaInfo(const std::string &path_="",
126                   const std::string &sha1_digest_=""):
127                 path(path_),
128                 sha1_digest(sha1_digest_)
129         {
130         }
131 };
132
133 struct ServerSoundParams
134 {
135         float gain;
136         std::string to_player;
137         enum Type{
138                 SSP_LOCAL=0,
139                 SSP_POSITIONAL=1,
140                 SSP_OBJECT=2
141         } type;
142         v3f pos;
143         u16 object;
144         float max_hear_distance;
145         bool loop;
146
147         ServerSoundParams():
148                 gain(1.0),
149                 to_player(""),
150                 type(SSP_LOCAL),
151                 pos(0,0,0),
152                 object(0),
153                 max_hear_distance(32*BS),
154                 loop(false)
155         {}
156
157         v3f getPos(ServerEnvironment *env, bool *pos_exists) const;
158 };
159
160 struct ServerPlayingSound
161 {
162         ServerSoundParams params;
163         std::set<u16> clients; // peer ids
164 };
165
166 class Server : public con::PeerHandler, public MapEventReceiver,
167                 public InventoryManager, public IGameDef
168 {
169 public:
170         /*
171                 NOTE: Every public method should be thread-safe
172         */
173
174         Server(
175                 const std::string &path_world,
176                 const SubgameSpec &gamespec,
177                 bool simple_singleplayer_mode,
178                 bool ipv6
179         );
180         ~Server();
181         void start(Address bind_addr);
182         void stop();
183         // This is mainly a way to pass the time to the server.
184         // Actual processing is done in an another thread.
185         void step(float dtime);
186         // This is run by ServerThread and does the actual processing
187         void AsyncRunStep(bool initial_step=false);
188         void Receive();
189         PlayerSAO* StageTwoClientInit(u16 peer_id);
190         void ProcessData(u8 *data, u32 datasize, u16 peer_id);
191
192         // Environment must be locked when called
193         void setTimeOfDay(u32 time);
194
195         /*
196                 Shall be called with the environment locked.
197                 This is accessed by the map, which is inside the environment,
198                 so it shouldn't be a problem.
199         */
200         void onMapEditEvent(MapEditEvent *event);
201
202         /*
203                 Shall be called with the environment and the connection locked.
204         */
205         Inventory* getInventory(const InventoryLocation &loc);
206         void setInventoryModified(const InventoryLocation &loc);
207
208         // Connection must be locked when called
209         std::wstring getStatusString();
210
211         // read shutdown state
212         inline bool getShutdownRequested()
213                         { return m_shutdown_requested; }
214
215         // request server to shutdown
216         inline void requestShutdown(void)
217                         { m_shutdown_requested = true; }
218
219         // Returns -1 if failed, sound handle on success
220         // Envlock
221         s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams &params);
222         void stopSound(s32 handle);
223
224         // Envlock
225         std::set<std::string> getPlayerEffectivePrivs(const std::string &name);
226         bool checkPriv(const std::string &name, const std::string &priv);
227         void reportPrivsModified(const std::string &name=""); // ""=all
228         void reportInventoryFormspecModified(const std::string &name);
229
230         void setIpBanned(const std::string &ip, const std::string &name);
231         void unsetIpBanned(const std::string &ip_or_name);
232         std::string getBanDescription(const std::string &ip_or_name);
233
234         void notifyPlayer(const char *name, const std::wstring &msg);
235         void notifyPlayers(const std::wstring &msg);
236         void spawnParticle(const char *playername,
237                 v3f pos, v3f velocity, v3f acceleration,
238                 float expirationtime, float size,
239                 bool collisiondetection, bool vertical, std::string texture);
240
241         void spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
242                 float expirationtime, float size,
243                 bool collisiondetection, bool vertical, std::string texture);
244
245         u32 addParticleSpawner(const char *playername,
246                 u16 amount, float spawntime,
247                 v3f minpos, v3f maxpos,
248                 v3f minvel, v3f maxvel,
249                 v3f minacc, v3f maxacc,
250                 float minexptime, float maxexptime,
251                 float minsize, float maxsize,
252                 bool collisiondetection, bool vertical, std::string texture);
253
254         u32 addParticleSpawnerAll(u16 amount, float spawntime,
255                 v3f minpos, v3f maxpos,
256                 v3f minvel, v3f maxvel,
257                 v3f minacc, v3f maxacc,
258                 float minexptime, float maxexptime,
259                 float minsize, float maxsize,
260                 bool collisiondetection, bool vertical, std::string texture);
261
262         void deleteParticleSpawner(const char *playername, u32 id);
263         void deleteParticleSpawnerAll(u32 id);
264
265         // Creates or resets inventory
266         Inventory* createDetachedInventory(const std::string &name);
267
268         // Envlock and conlock should be locked when using scriptapi
269         GameScripting *getScriptIface(){ return m_script; }
270
271         //TODO: determine what (if anything) should be locked to access EmergeManager
272         EmergeManager *getEmergeManager(){ return m_emerge; }
273
274         // actions: time-reversed list
275         // Return value: success/failure
276         bool rollbackRevertActions(const std::list<RollbackAction> &actions,
277                         std::list<std::string> *log);
278
279         // IGameDef interface
280         // Under envlock
281         virtual IItemDefManager* getItemDefManager();
282         virtual INodeDefManager* getNodeDefManager();
283         virtual ICraftDefManager* getCraftDefManager();
284         virtual ITextureSource* getTextureSource();
285         virtual IShaderSource* getShaderSource();
286         virtual u16 allocateUnknownNodeId(const std::string &name);
287         virtual ISoundManager* getSoundManager();
288         virtual MtEventManager* getEventManager();
289         virtual scene::ISceneManager* getSceneManager();
290         virtual IRollbackManager *getRollbackManager() { return m_rollback; }
291
292
293         IWritableItemDefManager* getWritableItemDefManager();
294         IWritableNodeDefManager* getWritableNodeDefManager();
295         IWritableCraftDefManager* getWritableCraftDefManager();
296
297         const ModSpec* getModSpec(const std::string &modname);
298         void getModNames(std::list<std::string> &modlist);
299         std::string getBuiltinLuaPath();
300         inline std::string getWorldPath()
301                         { return m_path_world; }
302
303         inline bool isSingleplayer()
304                         { return m_simple_singleplayer_mode; }
305
306         inline void setAsyncFatalError(const std::string &error)
307                         { m_async_fatal_error.set(error); }
308
309         bool showFormspec(const char *name, const std::string &formspec, const std::string &formname);
310         Map & getMap() { return m_env->getMap(); }
311         ServerEnvironment & getEnv() { return *m_env; }
312         
313         u32 hudAdd(Player *player, HudElement *element);
314         bool hudRemove(Player *player, u32 id);
315         bool hudChange(Player *player, u32 id, HudElementStat stat, void *value);
316         bool hudSetFlags(Player *player, u32 flags, u32 mask);
317         bool hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount);
318         void hudSetHotbarImage(Player *player, std::string name);
319         void hudSetHotbarSelectedImage(Player *player, std::string name);
320
321         inline Address getPeerAddress(u16 peer_id)
322                         { return m_con.GetPeerAddress(peer_id); }
323                         
324         bool setLocalPlayerAnimations(Player *player, v2s32 animation_frames[4], f32 frame_speed);
325         bool setPlayerEyeOffset(Player *player, v3f first, v3f third);
326
327         bool setSky(Player *player, const video::SColor &bgcolor,
328                         const std::string &type, const std::vector<std::string> &params);
329         
330         bool overrideDayNightRatio(Player *player, bool do_override,
331                         float brightness);
332
333         /* con::PeerHandler implementation. */
334         void peerAdded(con::Peer *peer);
335         void deletingPeer(con::Peer *peer, bool timeout);
336
337         void DenyAccess(u16 peer_id, const std::wstring &reason);
338         bool getClientConInfo(u16 peer_id, con::rtt_stat_type type,float* retval);
339         bool getClientInfo(u16 peer_id,ClientState* state, u32* uptime,
340                         u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch,
341                         std::string* vers_string);
342
343         // Bind address
344         Address m_bind_addr;
345
346 private:
347
348         friend class EmergeThread;
349         friend class RemoteClient;
350
351         void SendMovement(u16 peer_id);
352         void SendHP(u16 peer_id, u8 hp);
353         void SendBreath(u16 peer_id, u16 breath);
354         void SendAccessDenied(u16 peer_id,const std::wstring &reason);
355         void SendDeathscreen(u16 peer_id,bool set_camera_point_target, v3f camera_point_target);
356         void SendItemDef(u16 peer_id,IItemDefManager *itemdef, u16 protocol_version);
357         void SendNodeDef(u16 peer_id,INodeDefManager *nodedef, u16 protocol_version);
358
359         /* mark blocks not sent for all clients */
360         void SetBlocksNotSent(std::map<v3s16, MapBlock *>& block);
361
362         // Envlock and conlock should be locked when calling these
363         void SendInventory(u16 peer_id);
364         void SendChatMessage(u16 peer_id, const std::wstring &message);
365         void SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed);
366         void SendPlayerHP(u16 peer_id);
367         void SendPlayerBreath(u16 peer_id);
368         void SendMovePlayer(u16 peer_id);
369         void SendLocalPlayerAnimations(u16 peer_id, v2s32 animation_frames[4], f32 animation_speed);
370         void SendEyeOffset(u16 peer_id, v3f first, v3f third);
371         void SendPlayerPrivileges(u16 peer_id);
372         void SendPlayerInventoryFormspec(u16 peer_id);
373         void SendShowFormspecMessage(u16 peer_id, const std::string &formspec, const std::string &formname);
374         void SendHUDAdd(u16 peer_id, u32 id, HudElement *form);
375         void SendHUDRemove(u16 peer_id, u32 id);
376         void SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value);
377         void SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask);
378         void SendHUDSetParam(u16 peer_id, u16 param, const std::string &value);
379         void SendSetSky(u16 peer_id, const video::SColor &bgcolor,
380                         const std::string &type, const std::vector<std::string> &params);
381         void SendOverrideDayNightRatio(u16 peer_id, bool do_override, float ratio);
382         
383         /*
384                 Send a node removal/addition event to all clients except ignore_id.
385                 Additionally, if far_players!=NULL, players further away than
386                 far_d_nodes are ignored and their peer_ids are added to far_players
387         */
388         // Envlock and conlock should be locked when calling these
389         void sendRemoveNode(v3s16 p, u16 ignore_id=0,
390                         std::list<u16> *far_players=NULL, float far_d_nodes=100);
391         void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
392                         std::list<u16> *far_players=NULL, float far_d_nodes=100,
393                         bool remove_metadata=true);
394         void setBlockNotSent(v3s16 p);
395
396         // Environment and Connection must be locked when called
397         void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version);
398
399         // Sends blocks to clients (locks env and con on its own)
400         void SendBlocks(float dtime);
401
402         void fillMediaCache();
403         void sendMediaAnnouncement(u16 peer_id);
404         void sendRequestedMedia(u16 peer_id,
405                         const std::list<std::string> &tosend);
406
407         void sendDetachedInventory(const std::string &name, u16 peer_id);
408         void sendDetachedInventories(u16 peer_id);
409
410         // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all)
411         void SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime,
412                 v3f minpos, v3f maxpos,
413                 v3f minvel, v3f maxvel,
414                 v3f minacc, v3f maxacc,
415                 float minexptime, float maxexptime,
416                 float minsize, float maxsize,
417                 bool collisiondetection, bool vertical, std::string texture, u32 id);
418
419         void SendDeleteParticleSpawner(u16 peer_id, u32 id);
420
421         // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all)
422         void SendSpawnParticle(u16 peer_id,
423                 v3f pos, v3f velocity, v3f acceleration,
424                 float expirationtime, float size,
425                 bool collisiondetection, bool vertical, std::string texture);
426
427         /*
428                 Something random
429         */
430
431         void DiePlayer(u16 peer_id);
432         void RespawnPlayer(u16 peer_id);
433         void DeleteClient(u16 peer_id, ClientDeletionReason reason);
434         void UpdateCrafting(u16 peer_id);
435
436         // When called, connection mutex should be locked
437         RemoteClient* getClient(u16 peer_id,ClientState state_min=CS_Active);
438         RemoteClient* getClientNoEx(u16 peer_id,ClientState state_min=CS_Active);
439
440         // When called, environment mutex should be locked
441         std::string getPlayerName(u16 peer_id);
442         PlayerSAO* getPlayerSAO(u16 peer_id);
443
444         /*
445                 Get a player from memory or creates one.
446                 If player is already connected, return NULL
447                 Does not verify/modify auth info and password.
448
449                 Call with env and con locked.
450         */
451         PlayerSAO *emergePlayer(const char *name, u16 peer_id);
452
453         void handlePeerChanges();
454
455         /*
456                 Variables
457         */
458
459         // World directory
460         std::string m_path_world;
461         // Subgame specification
462         SubgameSpec m_gamespec;
463         // If true, do not allow multiple players and hide some multiplayer
464         // functionality
465         bool m_simple_singleplayer_mode;
466
467         // Thread can set; step() will throw as ServerError
468         MutexedVariable<std::string> m_async_fatal_error;
469
470         // Some timers
471         float m_liquid_transform_timer;
472         float m_liquid_transform_every;
473         float m_print_info_timer;
474         float m_masterserver_timer;
475         float m_objectdata_timer;
476         float m_emergethread_trigger_timer;
477         float m_savemap_timer;
478         IntervalLimiter m_map_timer_and_unload_interval;
479
480         // Environment
481         ServerEnvironment *m_env;
482         JMutex m_env_mutex;
483
484         // server connection
485         con::Connection m_con;
486
487         // Ban checking
488         BanManager *m_banmanager;
489
490         // Rollback manager (behind m_env_mutex)
491         IRollbackManager *m_rollback;
492         bool m_enable_rollback_recording; // Updated once in a while
493
494         // Emerge manager
495         EmergeManager *m_emerge;
496
497         // Scripting
498         // Envlock and conlock should be locked when using Lua
499         GameScripting *m_script;
500
501         // Item definition manager
502         IWritableItemDefManager *m_itemdef;
503
504         // Node definition manager
505         IWritableNodeDefManager *m_nodedef;
506
507         // Craft definition manager
508         IWritableCraftDefManager *m_craftdef;
509
510         // Event manager
511         EventManager *m_event;
512
513         // Mods
514         std::vector<ModSpec> m_mods;
515
516         /*
517                 Threads
518         */
519
520         // A buffer for time steps
521         // step() increments and AsyncRunStep() run by m_thread reads it.
522         float m_step_dtime;
523         JMutex m_step_dtime_mutex;
524
525         // current server step lag counter
526         float m_lag;
527
528         // The server mainly operates in this thread
529         ServerThread *m_thread;
530
531         /*
532                 Time related stuff
533         */
534
535         // Timer for sending time of day over network
536         float m_time_of_day_send_timer;
537         // Uptime of server in seconds
538         MutexedVariable<double> m_uptime;
539
540         /*
541          Client interface
542          */
543         ClientInterface m_clients;
544
545         /*
546                 Peer change queue.
547                 Queues stuff from peerAdded() and deletingPeer() to
548                 handlePeerChanges()
549         */
550         Queue<con::PeerChange> m_peer_change_queue;
551
552         /*
553                 Random stuff
554         */
555
556         // Mod parent directory paths
557         std::list<std::string> m_modspaths;
558
559         bool m_shutdown_requested;
560
561         /*
562                 Map edit event queue. Automatically receives all map edits.
563                 The constructor of this class registers us to receive them through
564                 onMapEditEvent
565
566                 NOTE: Should these be moved to actually be members of
567                 ServerEnvironment?
568         */
569
570         /*
571                 Queue of map edits from the environment for sending to the clients
572                 This is behind m_env_mutex
573         */
574         Queue<MapEditEvent*> m_unsent_map_edit_queue;
575         /*
576                 Set to true when the server itself is modifying the map and does
577                 all sending of information by itself.
578                 This is behind m_env_mutex
579         */
580         bool m_ignore_map_edit_events;
581         /*
582                 If a non-empty area, map edit events contained within are left
583                 unsent. Done at map generation time to speed up editing of the
584                 generated area, as it will be sent anyway.
585                 This is behind m_env_mutex
586         */
587         VoxelArea m_ignore_map_edit_events_area;
588         /*
589                 If set to !=0, the incoming MapEditEvents are modified to have
590                 this peed id as the disabled recipient
591                 This is behind m_env_mutex
592         */
593         u16 m_ignore_map_edit_events_peer_id;
594
595         // media files known to server
596         std::map<std::string,MediaInfo> m_media;
597
598         /*
599                 Sounds
600         */
601         std::map<s32, ServerPlayingSound> m_playing_sounds;
602         s32 m_next_sound_id;
603
604         /*
605                 Detached inventories (behind m_env_mutex)
606         */
607         // key = name
608         std::map<std::string, Inventory*> m_detached_inventories;
609
610         /*
611                 Particles
612         */
613         std::vector<u32> m_particlespawner_ids;
614 };
615
616 /*
617         Runs a simple dedicated server loop.
618
619         Shuts down when run is set to false.
620 */
621 void dedicated_server_loop(Server &server, bool &run);
622
623 #endif
624