server.h 17 KB

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