server.cpp 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583
  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. #include "server.h"
  17. #include <iostream>
  18. #include <queue>
  19. #include <algorithm>
  20. #include "network/connection.h"
  21. #include "network/networkprotocol.h"
  22. #include "network/serveropcodes.h"
  23. #include "ban.h"
  24. #include "environment.h"
  25. #include "map.h"
  26. #include "threading/mutex_auto_lock.h"
  27. #include "constants.h"
  28. #include "voxel.h"
  29. #include "config.h"
  30. #include "version.h"
  31. #include "filesys.h"
  32. #include "mapblock.h"
  33. #include "serverobject.h"
  34. #include "genericobject.h"
  35. #include "settings.h"
  36. #include "profiler.h"
  37. #include "log.h"
  38. #include "scripting_server.h"
  39. #include "nodedef.h"
  40. #include "itemdef.h"
  41. #include "craftdef.h"
  42. #include "emerge.h"
  43. #include "mapgen/mapgen.h"
  44. #include "mapgen/mg_biome.h"
  45. #include "content_mapnode.h"
  46. #include "content_nodemeta.h"
  47. #include "content_sao.h"
  48. #include "mods.h"
  49. #include "event_manager.h"
  50. #include "modchannels.h"
  51. #include "serverlist.h"
  52. #include "util/string.h"
  53. #include "rollback.h"
  54. #include "util/serialize.h"
  55. #include "util/thread.h"
  56. #include "defaultsettings.h"
  57. #include "server/mods.h"
  58. #include "util/base64.h"
  59. #include "util/sha1.h"
  60. #include "util/hex.h"
  61. #include "database/database.h"
  62. #include "chatmessage.h"
  63. #include "chat_interface.h"
  64. #include "remoteplayer.h"
  65. class ClientNotFoundException : public BaseException
  66. {
  67. public:
  68. ClientNotFoundException(const char *s):
  69. BaseException(s)
  70. {}
  71. };
  72. class ServerThread : public Thread
  73. {
  74. public:
  75. ServerThread(Server *server):
  76. Thread("Server"),
  77. m_server(server)
  78. {}
  79. void *run();
  80. private:
  81. Server *m_server;
  82. };
  83. void *ServerThread::run()
  84. {
  85. BEGIN_DEBUG_EXCEPTION_HANDLER
  86. m_server->AsyncRunStep(true);
  87. while (!stopRequested()) {
  88. try {
  89. m_server->AsyncRunStep();
  90. m_server->Receive();
  91. } catch (con::NoIncomingDataException &e) {
  92. } catch (con::PeerNotFoundException &e) {
  93. infostream<<"Server: PeerNotFoundException"<<std::endl;
  94. } catch (ClientNotFoundException &e) {
  95. } catch (con::ConnectionBindFailed &e) {
  96. m_server->setAsyncFatalError(e.what());
  97. } catch (LuaError &e) {
  98. m_server->setAsyncFatalError(
  99. "ServerThread::run Lua: " + std::string(e.what()));
  100. }
  101. }
  102. END_DEBUG_EXCEPTION_HANDLER
  103. return nullptr;
  104. }
  105. v3f ServerSoundParams::getPos(ServerEnvironment *env, bool *pos_exists) const
  106. {
  107. if(pos_exists) *pos_exists = false;
  108. switch(type){
  109. case SSP_LOCAL:
  110. return v3f(0,0,0);
  111. case SSP_POSITIONAL:
  112. if(pos_exists) *pos_exists = true;
  113. return pos;
  114. case SSP_OBJECT: {
  115. if(object == 0)
  116. return v3f(0,0,0);
  117. ServerActiveObject *sao = env->getActiveObject(object);
  118. if(!sao)
  119. return v3f(0,0,0);
  120. if(pos_exists) *pos_exists = true;
  121. return sao->getBasePosition(); }
  122. }
  123. return v3f(0,0,0);
  124. }
  125. /*
  126. Server
  127. */
  128. Server::Server(
  129. const std::string &path_world,
  130. const SubgameSpec &gamespec,
  131. bool simple_singleplayer_mode,
  132. Address bind_addr,
  133. bool dedicated,
  134. ChatInterface *iface
  135. ):
  136. m_bind_addr(bind_addr),
  137. m_path_world(path_world),
  138. m_gamespec(gamespec),
  139. m_simple_singleplayer_mode(simple_singleplayer_mode),
  140. m_dedicated(dedicated),
  141. m_async_fatal_error(""),
  142. m_con(std::make_shared<con::Connection>(PROTOCOL_ID,
  143. 512,
  144. CONNECTION_TIMEOUT,
  145. m_bind_addr.isIPv6(),
  146. this)),
  147. m_itemdef(createItemDefManager()),
  148. m_nodedef(createNodeDefManager()),
  149. m_craftdef(createCraftDefManager()),
  150. m_event(new EventManager()),
  151. m_uptime(0),
  152. m_clients(m_con),
  153. m_admin_chat(iface),
  154. m_modchannel_mgr(new ModChannelMgr())
  155. {
  156. m_lag = g_settings->getFloat("dedicated_server_step");
  157. if (path_world.empty())
  158. throw ServerError("Supplied empty world path");
  159. if(!gamespec.isValid())
  160. throw ServerError("Supplied invalid gamespec");
  161. infostream<<"Server created for gameid \""<<m_gamespec.id<<"\"";
  162. if(m_simple_singleplayer_mode)
  163. infostream<<" in simple singleplayer mode"<<std::endl;
  164. else
  165. infostream<<std::endl;
  166. infostream<<"- world: "<<m_path_world<<std::endl;
  167. infostream<<"- game: "<<m_gamespec.path<<std::endl;
  168. // Create world if it doesn't exist
  169. if(!loadGameConfAndInitWorld(m_path_world, m_gamespec))
  170. throw ServerError("Failed to initialize world");
  171. // Create server thread
  172. m_thread = new ServerThread(this);
  173. // Create emerge manager
  174. m_emerge = new EmergeManager(this);
  175. // Create ban manager
  176. std::string ban_path = m_path_world + DIR_DELIM "ipban.txt";
  177. m_banmanager = new BanManager(ban_path);
  178. m_modmgr = std::unique_ptr<ServerModManager>(new ServerModManager(
  179. m_path_world));
  180. std::vector<ModSpec> unsatisfied_mods = m_modmgr->getUnsatisfiedMods();
  181. // complain about mods with unsatisfied dependencies
  182. if (!m_modmgr->isConsistent()) {
  183. m_modmgr->printUnsatisfiedModsError();
  184. }
  185. //lock environment
  186. MutexAutoLock envlock(m_env_mutex);
  187. // Create the Map (loads map_meta.txt, overriding configured mapgen params)
  188. ServerMap *servermap = new ServerMap(path_world, this, m_emerge);
  189. // Initialize scripting
  190. infostream<<"Server: Initializing Lua"<<std::endl;
  191. m_script = new ServerScripting(this);
  192. m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
  193. m_modmgr->loadMods(m_script);
  194. // Read Textures and calculate sha1 sums
  195. fillMediaCache();
  196. // Apply item aliases in the node definition manager
  197. m_nodedef->updateAliases(m_itemdef);
  198. // Apply texture overrides from texturepack/override.txt
  199. std::vector<std::string> paths;
  200. fs::GetRecursiveDirs(paths, g_settings->get("texture_path"));
  201. fs::GetRecursiveDirs(paths, m_gamespec.path + DIR_DELIM + "textures");
  202. for (const std::string &path : paths)
  203. m_nodedef->applyTextureOverrides(path + DIR_DELIM + "override.txt");
  204. m_nodedef->setNodeRegistrationStatus(true);
  205. // Perform pending node name resolutions
  206. m_nodedef->runNodeResolveCallbacks();
  207. // unmap node names for connected nodeboxes
  208. m_nodedef->mapNodeboxConnections();
  209. // init the recipe hashes to speed up crafting
  210. m_craftdef->initHashes(this);
  211. // Initialize Environment
  212. m_env = new ServerEnvironment(servermap, m_script, this, m_path_world);
  213. m_clients.setEnv(m_env);
  214. if (!servermap->settings_mgr.makeMapgenParams())
  215. FATAL_ERROR("Couldn't create any mapgen type");
  216. // Initialize mapgens
  217. m_emerge->initMapgens(servermap->getMapgenParams());
  218. if (g_settings->getBool("enable_rollback_recording")) {
  219. // Create rollback manager
  220. m_rollback = new RollbackManager(m_path_world, this);
  221. }
  222. // Give environment reference to scripting api
  223. m_script->initializeEnvironment(m_env);
  224. // Register us to receive map edit events
  225. servermap->addEventReceiver(this);
  226. m_env->loadMeta();
  227. m_liquid_transform_every = g_settings->getFloat("liquid_update");
  228. m_max_chatmessage_length = g_settings->getU16("chat_message_max_size");
  229. m_csm_flavour_limits = g_settings->getU64("csm_flavour_limits");
  230. m_csm_noderange_limit = g_settings->getU32("csm_flavour_noderange_limit");
  231. }
  232. Server::~Server()
  233. {
  234. infostream << "Server destructing" << std::endl;
  235. // Send shutdown message
  236. SendChatMessage(PEER_ID_INEXISTENT, ChatMessage(CHATMESSAGE_TYPE_ANNOUNCE,
  237. L"*** Server shutting down"));
  238. {
  239. MutexAutoLock envlock(m_env_mutex);
  240. infostream << "Server: Saving players" << std::endl;
  241. m_env->saveLoadedPlayers();
  242. infostream << "Server: Kicking players" << std::endl;
  243. std::string kick_msg;
  244. bool reconnect = false;
  245. if (getShutdownRequested()) {
  246. reconnect = m_shutdown_ask_reconnect;
  247. kick_msg = m_shutdown_msg;
  248. }
  249. if (kick_msg.empty()) {
  250. kick_msg = g_settings->get("kick_msg_shutdown");
  251. }
  252. m_env->kickAllPlayers(SERVER_ACCESSDENIED_SHUTDOWN,
  253. kick_msg, reconnect);
  254. }
  255. // Do this before stopping the server in case mapgen callbacks need to access
  256. // server-controlled resources (like ModStorages). Also do them before
  257. // shutdown callbacks since they may modify state that is finalized in a
  258. // callback.
  259. m_emerge->stopThreads();
  260. {
  261. MutexAutoLock envlock(m_env_mutex);
  262. // Execute script shutdown hooks
  263. infostream << "Executing shutdown hooks" << std::endl;
  264. m_script->on_shutdown();
  265. infostream << "Server: Saving environment metadata" << std::endl;
  266. m_env->saveMeta();
  267. }
  268. // Stop threads
  269. stop();
  270. delete m_thread;
  271. // Delete things in the reverse order of creation
  272. delete m_emerge;
  273. delete m_env;
  274. delete m_rollback;
  275. delete m_banmanager;
  276. delete m_event;
  277. delete m_itemdef;
  278. delete m_nodedef;
  279. delete m_craftdef;
  280. // Deinitialize scripting
  281. infostream << "Server: Deinitializing scripting" << std::endl;
  282. delete m_script;
  283. // Delete detached inventories
  284. for (auto &detached_inventory : m_detached_inventories) {
  285. delete detached_inventory.second;
  286. }
  287. }
  288. void Server::start()
  289. {
  290. infostream << "Starting server on " << m_bind_addr.serializeString()
  291. << "..." << std::endl;
  292. // Stop thread if already running
  293. m_thread->stop();
  294. // Initialize connection
  295. m_con->SetTimeoutMs(30);
  296. m_con->Serve(m_bind_addr);
  297. // Start thread
  298. m_thread->start();
  299. // ASCII art for the win!
  300. rawstream
  301. << " .__ __ __ " << std::endl
  302. << " _____ |__| ____ _____/ |_ ____ _______/ |_ " << std::endl
  303. << " / \\| |/ \\_/ __ \\ __\\/ __ \\ / ___/\\ __\\" << std::endl
  304. << "| Y Y \\ | | \\ ___/| | \\ ___/ \\___ \\ | | " << std::endl
  305. << "|__|_| /__|___| /\\___ >__| \\___ >____ > |__| " << std::endl
  306. << " \\/ \\/ \\/ \\/ \\/ " << std::endl;
  307. actionstream << "World at [" << m_path_world << "]" << std::endl;
  308. actionstream << "Server for gameid=\"" << m_gamespec.id
  309. << "\" listening on " << m_bind_addr.serializeString() << ":"
  310. << m_bind_addr.getPort() << "." << std::endl;
  311. }
  312. void Server::stop()
  313. {
  314. infostream<<"Server: Stopping and waiting threads"<<std::endl;
  315. // Stop threads (set run=false first so both start stopping)
  316. m_thread->stop();
  317. //m_emergethread.setRun(false);
  318. m_thread->wait();
  319. //m_emergethread.stop();
  320. infostream<<"Server: Threads stopped"<<std::endl;
  321. }
  322. void Server::step(float dtime)
  323. {
  324. // Limit a bit
  325. if (dtime > 2.0)
  326. dtime = 2.0;
  327. {
  328. MutexAutoLock lock(m_step_dtime_mutex);
  329. m_step_dtime += dtime;
  330. }
  331. // Throw if fatal error occurred in thread
  332. std::string async_err = m_async_fatal_error.get();
  333. if (!async_err.empty()) {
  334. if (!m_simple_singleplayer_mode) {
  335. m_env->kickAllPlayers(SERVER_ACCESSDENIED_CRASH,
  336. g_settings->get("kick_msg_crash"),
  337. g_settings->getBool("ask_reconnect_on_crash"));
  338. }
  339. throw ServerError("AsyncErr: " + async_err);
  340. }
  341. }
  342. void Server::AsyncRunStep(bool initial_step)
  343. {
  344. g_profiler->add("Server::AsyncRunStep (num)", 1);
  345. float dtime;
  346. {
  347. MutexAutoLock lock1(m_step_dtime_mutex);
  348. dtime = m_step_dtime;
  349. }
  350. {
  351. // Send blocks to clients
  352. SendBlocks(dtime);
  353. }
  354. if((dtime < 0.001) && !initial_step)
  355. return;
  356. g_profiler->add("Server::AsyncRunStep with dtime (num)", 1);
  357. //infostream<<"Server steps "<<dtime<<std::endl;
  358. //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
  359. {
  360. MutexAutoLock lock1(m_step_dtime_mutex);
  361. m_step_dtime -= dtime;
  362. }
  363. /*
  364. Update uptime
  365. */
  366. {
  367. m_uptime.set(m_uptime.get() + dtime);
  368. }
  369. handlePeerChanges();
  370. /*
  371. Update time of day and overall game time
  372. */
  373. m_env->setTimeOfDaySpeed(g_settings->getFloat("time_speed"));
  374. /*
  375. Send to clients at constant intervals
  376. */
  377. m_time_of_day_send_timer -= dtime;
  378. if(m_time_of_day_send_timer < 0.0) {
  379. m_time_of_day_send_timer = g_settings->getFloat("time_send_interval");
  380. u16 time = m_env->getTimeOfDay();
  381. float time_speed = g_settings->getFloat("time_speed");
  382. SendTimeOfDay(PEER_ID_INEXISTENT, time, time_speed);
  383. }
  384. {
  385. MutexAutoLock lock(m_env_mutex);
  386. // Figure out and report maximum lag to environment
  387. float max_lag = m_env->getMaxLagEstimate();
  388. max_lag *= 0.9998; // Decrease slowly (about half per 5 minutes)
  389. if(dtime > max_lag){
  390. if(dtime > 0.1 && dtime > max_lag * 2.0)
  391. infostream<<"Server: Maximum lag peaked to "<<dtime
  392. <<" s"<<std::endl;
  393. max_lag = dtime;
  394. }
  395. m_env->reportMaxLagEstimate(max_lag);
  396. // Step environment
  397. ScopeProfiler sp(g_profiler, "SEnv step");
  398. ScopeProfiler sp2(g_profiler, "SEnv step avg", SPT_AVG);
  399. m_env->step(dtime);
  400. }
  401. static const float map_timer_and_unload_dtime = 2.92;
  402. if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
  403. {
  404. MutexAutoLock lock(m_env_mutex);
  405. // Run Map's timers and unload unused data
  406. ScopeProfiler sp(g_profiler, "Server: map timer and unload");
  407. m_env->getMap().timerUpdate(map_timer_and_unload_dtime,
  408. g_settings->getFloat("server_unload_unused_data_timeout"),
  409. U32_MAX);
  410. }
  411. /*
  412. Listen to the admin chat, if available
  413. */
  414. if (m_admin_chat) {
  415. if (!m_admin_chat->command_queue.empty()) {
  416. MutexAutoLock lock(m_env_mutex);
  417. while (!m_admin_chat->command_queue.empty()) {
  418. ChatEvent *evt = m_admin_chat->command_queue.pop_frontNoEx();
  419. handleChatInterfaceEvent(evt);
  420. delete evt;
  421. }
  422. }
  423. m_admin_chat->outgoing_queue.push_back(
  424. new ChatEventTimeInfo(m_env->getGameTime(), m_env->getTimeOfDay()));
  425. }
  426. /*
  427. Do background stuff
  428. */
  429. /* Transform liquids */
  430. m_liquid_transform_timer += dtime;
  431. if(m_liquid_transform_timer >= m_liquid_transform_every)
  432. {
  433. m_liquid_transform_timer -= m_liquid_transform_every;
  434. MutexAutoLock lock(m_env_mutex);
  435. ScopeProfiler sp(g_profiler, "Server: liquid transform");
  436. std::map<v3s16, MapBlock*> modified_blocks;
  437. m_env->getMap().transformLiquids(modified_blocks, m_env);
  438. /*
  439. Set the modified blocks unsent for all the clients
  440. */
  441. if (!modified_blocks.empty()) {
  442. SetBlocksNotSent(modified_blocks);
  443. }
  444. }
  445. m_clients.step(dtime);
  446. m_lag += (m_lag > dtime ? -1 : 1) * dtime/100;
  447. #if USE_CURL
  448. // send masterserver announce
  449. {
  450. float &counter = m_masterserver_timer;
  451. if (!isSingleplayer() && (!counter || counter >= 300.0) &&
  452. g_settings->getBool("server_announce")) {
  453. ServerList::sendAnnounce(counter ? ServerList::AA_UPDATE :
  454. ServerList::AA_START,
  455. m_bind_addr.getPort(),
  456. m_clients.getPlayerNames(),
  457. m_uptime.get(),
  458. m_env->getGameTime(),
  459. m_lag,
  460. m_gamespec.id,
  461. Mapgen::getMapgenName(m_emerge->mgparams->mgtype),
  462. m_modmgr->getMods(),
  463. m_dedicated);
  464. counter = 0.01;
  465. }
  466. counter += dtime;
  467. }
  468. #endif
  469. /*
  470. Check added and deleted active objects
  471. */
  472. {
  473. //infostream<<"Server: Checking added and deleted active objects"<<std::endl;
  474. MutexAutoLock envlock(m_env_mutex);
  475. m_clients.lock();
  476. const RemoteClientMap &clients = m_clients.getClientList();
  477. ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
  478. // Radius inside which objects are active
  479. static thread_local const s16 radius =
  480. g_settings->getS16("active_object_send_range_blocks") * MAP_BLOCKSIZE;
  481. // Radius inside which players are active
  482. static thread_local const bool is_transfer_limited =
  483. g_settings->exists("unlimited_player_transfer_distance") &&
  484. !g_settings->getBool("unlimited_player_transfer_distance");
  485. static thread_local const s16 player_transfer_dist =
  486. g_settings->getS16("player_transfer_distance") * MAP_BLOCKSIZE;
  487. s16 player_radius = player_transfer_dist;
  488. if (player_radius == 0 && is_transfer_limited)
  489. player_radius = radius;
  490. for (const auto &client_it : clients) {
  491. RemoteClient *client = client_it.second;
  492. // If definitions and textures have not been sent, don't
  493. // send objects either
  494. if (client->getState() < CS_DefinitionsSent)
  495. continue;
  496. RemotePlayer *player = m_env->getPlayer(client->peer_id);
  497. if (!player) {
  498. // This can happen if the client timeouts somehow
  499. continue;
  500. }
  501. PlayerSAO *playersao = player->getPlayerSAO();
  502. if (!playersao)
  503. continue;
  504. s16 my_radius = MYMIN(radius, playersao->getWantedRange() * MAP_BLOCKSIZE);
  505. if (my_radius <= 0) my_radius = radius;
  506. //infostream << "Server: Active Radius " << my_radius << std::endl;
  507. std::queue<u16> removed_objects;
  508. std::queue<u16> added_objects;
  509. m_env->getRemovedActiveObjects(playersao, my_radius, player_radius,
  510. client->m_known_objects, removed_objects);
  511. m_env->getAddedActiveObjects(playersao, my_radius, player_radius,
  512. client->m_known_objects, added_objects);
  513. // Ignore if nothing happened
  514. if (removed_objects.empty() && added_objects.empty()) {
  515. continue;
  516. }
  517. std::string data_buffer;
  518. char buf[4];
  519. // Handle removed objects
  520. writeU16((u8*)buf, removed_objects.size());
  521. data_buffer.append(buf, 2);
  522. while (!removed_objects.empty()) {
  523. // Get object
  524. u16 id = removed_objects.front();
  525. ServerActiveObject* obj = m_env->getActiveObject(id);
  526. // Add to data buffer for sending
  527. writeU16((u8*)buf, id);
  528. data_buffer.append(buf, 2);
  529. // Remove from known objects
  530. client->m_known_objects.erase(id);
  531. if(obj && obj->m_known_by_count > 0)
  532. obj->m_known_by_count--;
  533. removed_objects.pop();
  534. }
  535. // Handle added objects
  536. writeU16((u8*)buf, added_objects.size());
  537. data_buffer.append(buf, 2);
  538. while (!added_objects.empty()) {
  539. // Get object
  540. u16 id = added_objects.front();
  541. ServerActiveObject* obj = m_env->getActiveObject(id);
  542. // Get object type
  543. u8 type = ACTIVEOBJECT_TYPE_INVALID;
  544. if (!obj)
  545. warningstream << FUNCTION_NAME << ": NULL object" << std::endl;
  546. else
  547. type = obj->getSendType();
  548. // Add to data buffer for sending
  549. writeU16((u8*)buf, id);
  550. data_buffer.append(buf, 2);
  551. writeU8((u8*)buf, type);
  552. data_buffer.append(buf, 1);
  553. if(obj)
  554. data_buffer.append(serializeLongString(
  555. obj->getClientInitializationData(client->net_proto_version)));
  556. else
  557. data_buffer.append(serializeLongString(""));
  558. // Add to known objects
  559. client->m_known_objects.insert(id);
  560. if(obj)
  561. obj->m_known_by_count++;
  562. added_objects.pop();
  563. }
  564. u32 pktSize = SendActiveObjectRemoveAdd(client->peer_id, data_buffer);
  565. verbosestream << "Server: Sent object remove/add: "
  566. << removed_objects.size() << " removed, "
  567. << added_objects.size() << " added, "
  568. << "packet size is " << pktSize << std::endl;
  569. }
  570. m_clients.unlock();
  571. m_mod_storage_save_timer -= dtime;
  572. if (m_mod_storage_save_timer <= 0.0f) {
  573. infostream << "Saving registered mod storages." << std::endl;
  574. m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
  575. for (std::unordered_map<std::string, ModMetadata *>::const_iterator
  576. it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
  577. if (it->second->isModified()) {
  578. it->second->save(getModStoragePath());
  579. }
  580. }
  581. }
  582. }
  583. /*
  584. Send object messages
  585. */
  586. {
  587. MutexAutoLock envlock(m_env_mutex);
  588. ScopeProfiler sp(g_profiler, "Server: sending object messages");
  589. // Key = object id
  590. // Value = data sent by object
  591. std::unordered_map<u16, std::vector<ActiveObjectMessage>*> buffered_messages;
  592. // Get active object messages from environment
  593. for(;;) {
  594. ActiveObjectMessage aom = m_env->getActiveObjectMessage();
  595. if (aom.id == 0)
  596. break;
  597. std::vector<ActiveObjectMessage>* message_list = nullptr;
  598. std::unordered_map<u16, std::vector<ActiveObjectMessage>* >::iterator n;
  599. n = buffered_messages.find(aom.id);
  600. if (n == buffered_messages.end()) {
  601. message_list = new std::vector<ActiveObjectMessage>;
  602. buffered_messages[aom.id] = message_list;
  603. }
  604. else {
  605. message_list = n->second;
  606. }
  607. message_list->push_back(aom);
  608. }
  609. m_clients.lock();
  610. const RemoteClientMap &clients = m_clients.getClientList();
  611. // Route data to every client
  612. for (const auto &client_it : clients) {
  613. RemoteClient *client = client_it.second;
  614. std::string reliable_data;
  615. std::string unreliable_data;
  616. // Go through all objects in message buffer
  617. for (const auto &buffered_message : buffered_messages) {
  618. // If object is not known by client, skip it
  619. u16 id = buffered_message.first;
  620. if (client->m_known_objects.find(id) == client->m_known_objects.end())
  621. continue;
  622. // Get message list of object
  623. std::vector<ActiveObjectMessage>* list = buffered_message.second;
  624. // Go through every message
  625. for (const ActiveObjectMessage &aom : *list) {
  626. // Compose the full new data with header
  627. std::string new_data;
  628. // Add object id
  629. char buf[2];
  630. writeU16((u8*)&buf[0], aom.id);
  631. new_data.append(buf, 2);
  632. // Add data
  633. new_data += serializeString(aom.datastring);
  634. // Add data to buffer
  635. if (aom.reliable)
  636. reliable_data += new_data;
  637. else
  638. unreliable_data += new_data;
  639. }
  640. }
  641. /*
  642. reliable_data and unreliable_data are now ready.
  643. Send them.
  644. */
  645. if (!reliable_data.empty()) {
  646. SendActiveObjectMessages(client->peer_id, reliable_data);
  647. }
  648. if (!unreliable_data.empty()) {
  649. SendActiveObjectMessages(client->peer_id, unreliable_data, false);
  650. }
  651. }
  652. m_clients.unlock();
  653. // Clear buffered_messages
  654. for (auto &buffered_message : buffered_messages) {
  655. delete buffered_message.second;
  656. }
  657. }
  658. /*
  659. Send queued-for-sending map edit events.
  660. */
  661. {
  662. // We will be accessing the environment
  663. MutexAutoLock lock(m_env_mutex);
  664. // Don't send too many at a time
  665. //u32 count = 0;
  666. // Single change sending is disabled if queue size is not small
  667. bool disable_single_change_sending = false;
  668. if(m_unsent_map_edit_queue.size() >= 4)
  669. disable_single_change_sending = true;
  670. int event_count = m_unsent_map_edit_queue.size();
  671. // We'll log the amount of each
  672. Profiler prof;
  673. while (!m_unsent_map_edit_queue.empty()) {
  674. MapEditEvent* event = m_unsent_map_edit_queue.front();
  675. m_unsent_map_edit_queue.pop();
  676. // Players far away from the change are stored here.
  677. // Instead of sending the changes, MapBlocks are set not sent
  678. // for them.
  679. std::vector<u16> far_players;
  680. switch (event->type) {
  681. case MEET_ADDNODE:
  682. case MEET_SWAPNODE:
  683. prof.add("MEET_ADDNODE", 1);
  684. sendAddNode(event->p, event->n, event->already_known_by_peer,
  685. &far_players, disable_single_change_sending ? 5 : 30,
  686. event->type == MEET_ADDNODE);
  687. break;
  688. case MEET_REMOVENODE:
  689. prof.add("MEET_REMOVENODE", 1);
  690. sendRemoveNode(event->p, event->already_known_by_peer,
  691. &far_players, disable_single_change_sending ? 5 : 30);
  692. break;
  693. case MEET_BLOCK_NODE_METADATA_CHANGED:
  694. infostream << "Server: MEET_BLOCK_NODE_METADATA_CHANGED" << std::endl;
  695. prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1);
  696. m_clients.markBlockposAsNotSent(event->p);
  697. break;
  698. case MEET_OTHER:
  699. infostream << "Server: MEET_OTHER" << std::endl;
  700. prof.add("MEET_OTHER", 1);
  701. for (const v3s16 &modified_block : event->modified_blocks) {
  702. m_clients.markBlockposAsNotSent(modified_block);
  703. }
  704. break;
  705. default:
  706. prof.add("unknown", 1);
  707. warningstream << "Server: Unknown MapEditEvent "
  708. << ((u32)event->type) << std::endl;
  709. break;
  710. }
  711. /*
  712. Set blocks not sent to far players
  713. */
  714. if (!far_players.empty()) {
  715. // Convert list format to that wanted by SetBlocksNotSent
  716. std::map<v3s16, MapBlock*> modified_blocks2;
  717. for (const v3s16 &modified_block : event->modified_blocks) {
  718. modified_blocks2[modified_block] =
  719. m_env->getMap().getBlockNoCreateNoEx(modified_block);
  720. }
  721. // Set blocks not sent
  722. for (const u16 far_player : far_players) {
  723. if (RemoteClient *client = getClient(far_player))
  724. client->SetBlocksNotSent(modified_blocks2);
  725. }
  726. }
  727. delete event;
  728. }
  729. if (event_count >= 5) {
  730. infostream << "Server: MapEditEvents:" << std::endl;
  731. prof.print(infostream);
  732. } else if (event_count != 0) {
  733. verbosestream << "Server: MapEditEvents:" << std::endl;
  734. prof.print(verbosestream);
  735. }
  736. }
  737. /*
  738. Trigger emergethread (it somehow gets to a non-triggered but
  739. bysy state sometimes)
  740. */
  741. {
  742. float &counter = m_emergethread_trigger_timer;
  743. counter += dtime;
  744. if (counter >= 2.0) {
  745. counter = 0.0;
  746. m_emerge->startThreads();
  747. }
  748. }
  749. // Save map, players and auth stuff
  750. {
  751. float &counter = m_savemap_timer;
  752. counter += dtime;
  753. static thread_local const float save_interval =
  754. g_settings->getFloat("server_map_save_interval");
  755. if (counter >= save_interval) {
  756. counter = 0.0;
  757. MutexAutoLock lock(m_env_mutex);
  758. ScopeProfiler sp(g_profiler, "Server: saving stuff");
  759. // Save ban file
  760. if (m_banmanager->isModified()) {
  761. m_banmanager->save();
  762. }
  763. // Save changed parts of map
  764. m_env->getMap().save(MOD_STATE_WRITE_NEEDED);
  765. // Save players
  766. m_env->saveLoadedPlayers();
  767. // Save environment metadata
  768. m_env->saveMeta();
  769. }
  770. }
  771. // Timed shutdown
  772. static const float shutdown_msg_times[] =
  773. {
  774. 1, 2, 3, 4, 5, 10, 15, 20, 25, 30, 45, 60, 120, 180, 300, 600, 1200, 1800, 3600
  775. };
  776. if (m_shutdown_timer > 0.0f) {
  777. // Automated messages
  778. if (m_shutdown_timer < shutdown_msg_times[ARRLEN(shutdown_msg_times) - 1]) {
  779. for (u16 i = 0; i < ARRLEN(shutdown_msg_times) - 1; i++) {
  780. // If shutdown timer matches an automessage, shot it
  781. if (m_shutdown_timer > shutdown_msg_times[i] &&
  782. m_shutdown_timer - dtime < shutdown_msg_times[i]) {
  783. std::wstringstream ws;
  784. ws << L"*** Server shutting down in "
  785. << duration_to_string(myround(m_shutdown_timer - dtime)).c_str()
  786. << ".";
  787. infostream << wide_to_utf8(ws.str()).c_str() << std::endl;
  788. SendChatMessage(PEER_ID_INEXISTENT, ws.str());
  789. break;
  790. }
  791. }
  792. }
  793. m_shutdown_timer -= dtime;
  794. if (m_shutdown_timer < 0.0f) {
  795. m_shutdown_timer = 0.0f;
  796. m_shutdown_requested = true;
  797. }
  798. }
  799. }
  800. void Server::Receive()
  801. {
  802. session_t peer_id;
  803. try {
  804. NetworkPacket pkt;
  805. m_con->Receive(&pkt);
  806. peer_id = pkt.getPeerId();
  807. ProcessData(&pkt);
  808. } catch (const con::InvalidIncomingDataException &e) {
  809. infostream << "Server::Receive(): InvalidIncomingDataException: what()="
  810. << e.what() << std::endl;
  811. } catch (const SerializationError &e) {
  812. infostream << "Server::Receive(): SerializationError: what()="
  813. << e.what() << std::endl;
  814. } catch (const ClientStateError &e) {
  815. errorstream << "ProcessData: peer=" << peer_id << e.what() << std::endl;
  816. DenyAccess_Legacy(peer_id, L"Your client sent something server didn't expect."
  817. L"Try reconnecting or updating your client");
  818. } catch (const con::PeerNotFoundException &e) {
  819. // Do nothing
  820. }
  821. }
  822. PlayerSAO* Server::StageTwoClientInit(session_t peer_id)
  823. {
  824. std::string playername;
  825. PlayerSAO *playersao = NULL;
  826. m_clients.lock();
  827. try {
  828. RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_InitDone);
  829. if (client) {
  830. playername = client->getName();
  831. playersao = emergePlayer(playername.c_str(), peer_id, client->net_proto_version);
  832. }
  833. } catch (std::exception &e) {
  834. m_clients.unlock();
  835. throw;
  836. }
  837. m_clients.unlock();
  838. RemotePlayer *player = m_env->getPlayer(playername.c_str());
  839. // If failed, cancel
  840. if (!playersao || !player) {
  841. if (player && player->getPeerId() != PEER_ID_INEXISTENT) {
  842. actionstream << "Server: Failed to emerge player \"" << playername
  843. << "\" (player allocated to an another client)" << std::endl;
  844. DenyAccess_Legacy(peer_id, L"Another client is connected with this "
  845. L"name. If your client closed unexpectedly, try again in "
  846. L"a minute.");
  847. } else {
  848. errorstream << "Server: " << playername << ": Failed to emerge player"
  849. << std::endl;
  850. DenyAccess_Legacy(peer_id, L"Could not allocate player.");
  851. }
  852. return NULL;
  853. }
  854. /*
  855. Send complete position information
  856. */
  857. SendMovePlayer(peer_id);
  858. // Send privileges
  859. SendPlayerPrivileges(peer_id);
  860. // Send inventory formspec
  861. SendPlayerInventoryFormspec(peer_id);
  862. // Send inventory
  863. SendInventory(playersao);
  864. // Send HP or death screen
  865. if (playersao->isDead())
  866. SendDeathscreen(peer_id, false, v3f(0,0,0));
  867. else
  868. SendPlayerHPOrDie(playersao);
  869. // Send Breath
  870. SendPlayerBreath(playersao);
  871. // Note things in chat if not in simple singleplayer mode
  872. if (!m_simple_singleplayer_mode && g_settings->getBool("show_statusline_on_connect")) {
  873. // Send information about server to player in chat
  874. SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM, getStatusString()));
  875. }
  876. Address addr = getPeerAddress(player->getPeerId());
  877. std::string ip_str = addr.serializeString();
  878. actionstream<<player->getName() <<" [" << ip_str << "] joins game. " << std::endl;
  879. /*
  880. Print out action
  881. */
  882. {
  883. const std::vector<std::string> &names = m_clients.getPlayerNames();
  884. actionstream << player->getName() << " joins game. List of players: ";
  885. for (const std::string &name : names) {
  886. actionstream << name << " ";
  887. }
  888. actionstream << player->getName() <<std::endl;
  889. }
  890. return playersao;
  891. }
  892. inline void Server::handleCommand(NetworkPacket* pkt)
  893. {
  894. const ToServerCommandHandler& opHandle = toServerCommandTable[pkt->getCommand()];
  895. (this->*opHandle.handler)(pkt);
  896. }
  897. void Server::ProcessData(NetworkPacket *pkt)
  898. {
  899. // Environment is locked first.
  900. MutexAutoLock envlock(m_env_mutex);
  901. ScopeProfiler sp(g_profiler, "Server::ProcessData");
  902. u32 peer_id = pkt->getPeerId();
  903. try {
  904. Address address = getPeerAddress(peer_id);
  905. std::string addr_s = address.serializeString();
  906. if(m_banmanager->isIpBanned(addr_s)) {
  907. std::string ban_name = m_banmanager->getBanName(addr_s);
  908. infostream << "Server: A banned client tried to connect from "
  909. << addr_s << "; banned name was "
  910. << ban_name << std::endl;
  911. // This actually doesn't seem to transfer to the client
  912. DenyAccess_Legacy(peer_id, L"Your ip is banned. Banned name was "
  913. + utf8_to_wide(ban_name));
  914. return;
  915. }
  916. }
  917. catch(con::PeerNotFoundException &e) {
  918. /*
  919. * no peer for this packet found
  920. * most common reason is peer timeout, e.g. peer didn't
  921. * respond for some time, your server was overloaded or
  922. * things like that.
  923. */
  924. infostream << "Server::ProcessData(): Canceling: peer "
  925. << peer_id << " not found" << std::endl;
  926. return;
  927. }
  928. try {
  929. ToServerCommand command = (ToServerCommand) pkt->getCommand();
  930. // Command must be handled into ToServerCommandHandler
  931. if (command >= TOSERVER_NUM_MSG_TYPES) {
  932. infostream << "Server: Ignoring unknown command "
  933. << command << std::endl;
  934. return;
  935. }
  936. if (toServerCommandTable[command].state == TOSERVER_STATE_NOT_CONNECTED) {
  937. handleCommand(pkt);
  938. return;
  939. }
  940. u8 peer_ser_ver = getClient(peer_id, CS_InitDone)->serialization_version;
  941. if(peer_ser_ver == SER_FMT_VER_INVALID) {
  942. errorstream << "Server::ProcessData(): Cancelling: Peer"
  943. " serialization format invalid or not initialized."
  944. " Skipping incoming command=" << command << std::endl;
  945. return;
  946. }
  947. /* Handle commands related to client startup */
  948. if (toServerCommandTable[command].state == TOSERVER_STATE_STARTUP) {
  949. handleCommand(pkt);
  950. return;
  951. }
  952. if (m_clients.getClientState(peer_id) < CS_Active) {
  953. if (command == TOSERVER_PLAYERPOS) return;
  954. errorstream << "Got packet command: " << command << " for peer id "
  955. << peer_id << " but client isn't active yet. Dropping packet "
  956. << std::endl;
  957. return;
  958. }
  959. handleCommand(pkt);
  960. } catch (SendFailedException &e) {
  961. errorstream << "Server::ProcessData(): SendFailedException: "
  962. << "what=" << e.what()
  963. << std::endl;
  964. } catch (PacketError &e) {
  965. actionstream << "Server::ProcessData(): PacketError: "
  966. << "what=" << e.what()
  967. << std::endl;
  968. }
  969. }
  970. void Server::setTimeOfDay(u32 time)
  971. {
  972. m_env->setTimeOfDay(time);
  973. m_time_of_day_send_timer = 0;
  974. }
  975. void Server::onMapEditEvent(MapEditEvent *event)
  976. {
  977. if(m_ignore_map_edit_events)
  978. return;
  979. if(m_ignore_map_edit_events_area.contains(event->getArea()))
  980. return;
  981. MapEditEvent *e = event->clone();
  982. m_unsent_map_edit_queue.push(e);
  983. }
  984. Inventory* Server::getInventory(const InventoryLocation &loc)
  985. {
  986. switch (loc.type) {
  987. case InventoryLocation::UNDEFINED:
  988. case InventoryLocation::CURRENT_PLAYER:
  989. break;
  990. case InventoryLocation::PLAYER:
  991. {
  992. RemotePlayer *player = m_env->getPlayer(loc.name.c_str());
  993. if(!player)
  994. return NULL;
  995. PlayerSAO *playersao = player->getPlayerSAO();
  996. if(!playersao)
  997. return NULL;
  998. return playersao->getInventory();
  999. }
  1000. break;
  1001. case InventoryLocation::NODEMETA:
  1002. {
  1003. NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p);
  1004. if(!meta)
  1005. return NULL;
  1006. return meta->getInventory();
  1007. }
  1008. break;
  1009. case InventoryLocation::DETACHED:
  1010. {
  1011. if(m_detached_inventories.count(loc.name) == 0)
  1012. return NULL;
  1013. return m_detached_inventories[loc.name];
  1014. }
  1015. break;
  1016. default:
  1017. sanity_check(false); // abort
  1018. break;
  1019. }
  1020. return NULL;
  1021. }
  1022. void Server::setInventoryModified(const InventoryLocation &loc, bool playerSend)
  1023. {
  1024. switch(loc.type){
  1025. case InventoryLocation::UNDEFINED:
  1026. break;
  1027. case InventoryLocation::PLAYER:
  1028. {
  1029. if (!playerSend)
  1030. return;
  1031. RemotePlayer *player = m_env->getPlayer(loc.name.c_str());
  1032. if (!player)
  1033. return;
  1034. PlayerSAO *playersao = player->getPlayerSAO();
  1035. if(!playersao)
  1036. return;
  1037. SendInventory(playersao);
  1038. }
  1039. break;
  1040. case InventoryLocation::NODEMETA:
  1041. {
  1042. v3s16 blockpos = getNodeBlockPos(loc.p);
  1043. MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
  1044. if (block)
  1045. block->raiseModified(MOD_STATE_WRITE_NEEDED);
  1046. m_clients.markBlockposAsNotSent(blockpos);
  1047. }
  1048. break;
  1049. case InventoryLocation::DETACHED:
  1050. {
  1051. sendDetachedInventory(loc.name,PEER_ID_INEXISTENT);
  1052. }
  1053. break;
  1054. default:
  1055. sanity_check(false); // abort
  1056. break;
  1057. }
  1058. }
  1059. void Server::SetBlocksNotSent(std::map<v3s16, MapBlock *>& block)
  1060. {
  1061. std::vector<session_t> clients = m_clients.getClientIDs();
  1062. m_clients.lock();
  1063. // Set the modified blocks unsent for all the clients
  1064. for (const session_t client_id : clients) {
  1065. if (RemoteClient *client = m_clients.lockedGetClientNoEx(client_id))
  1066. client->SetBlocksNotSent(block);
  1067. }
  1068. m_clients.unlock();
  1069. }
  1070. void Server::peerAdded(con::Peer *peer)
  1071. {
  1072. verbosestream<<"Server::peerAdded(): peer->id="
  1073. <<peer->id<<std::endl;
  1074. m_peer_change_queue.push(con::PeerChange(con::PEER_ADDED, peer->id, false));
  1075. }
  1076. void Server::deletingPeer(con::Peer *peer, bool timeout)
  1077. {
  1078. verbosestream<<"Server::deletingPeer(): peer->id="
  1079. <<peer->id<<", timeout="<<timeout<<std::endl;
  1080. m_clients.event(peer->id, CSE_Disconnect);
  1081. m_peer_change_queue.push(con::PeerChange(con::PEER_REMOVED, peer->id, timeout));
  1082. }
  1083. bool Server::getClientConInfo(session_t peer_id, con::rtt_stat_type type, float* retval)
  1084. {
  1085. *retval = m_con->getPeerStat(peer_id,type);
  1086. return *retval != -1;
  1087. }
  1088. bool Server::getClientInfo(
  1089. session_t peer_id,
  1090. ClientState* state,
  1091. u32* uptime,
  1092. u8* ser_vers,
  1093. u16* prot_vers,
  1094. u8* major,
  1095. u8* minor,
  1096. u8* patch,
  1097. std::string* vers_string
  1098. )
  1099. {
  1100. *state = m_clients.getClientState(peer_id);
  1101. m_clients.lock();
  1102. RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_Invalid);
  1103. if (!client) {
  1104. m_clients.unlock();
  1105. return false;
  1106. }
  1107. *uptime = client->uptime();
  1108. *ser_vers = client->serialization_version;
  1109. *prot_vers = client->net_proto_version;
  1110. *major = client->getMajor();
  1111. *minor = client->getMinor();
  1112. *patch = client->getPatch();
  1113. *vers_string = client->getPatch();
  1114. m_clients.unlock();
  1115. return true;
  1116. }
  1117. void Server::handlePeerChanges()
  1118. {
  1119. while(!m_peer_change_queue.empty())
  1120. {
  1121. con::PeerChange c = m_peer_change_queue.front();
  1122. m_peer_change_queue.pop();
  1123. verbosestream<<"Server: Handling peer change: "
  1124. <<"id="<<c.peer_id<<", timeout="<<c.timeout
  1125. <<std::endl;
  1126. switch(c.type)
  1127. {
  1128. case con::PEER_ADDED:
  1129. m_clients.CreateClient(c.peer_id);
  1130. break;
  1131. case con::PEER_REMOVED:
  1132. DeleteClient(c.peer_id, c.timeout?CDR_TIMEOUT:CDR_LEAVE);
  1133. break;
  1134. default:
  1135. FATAL_ERROR("Invalid peer change event received!");
  1136. break;
  1137. }
  1138. }
  1139. }
  1140. void Server::printToConsoleOnly(const std::string &text)
  1141. {
  1142. if (m_admin_chat) {
  1143. m_admin_chat->outgoing_queue.push_back(
  1144. new ChatEventChat("", utf8_to_wide(text)));
  1145. } else {
  1146. std::cout << text << std::endl;
  1147. }
  1148. }
  1149. void Server::Send(NetworkPacket *pkt)
  1150. {
  1151. Send(pkt->getPeerId(), pkt);
  1152. }
  1153. void Server::Send(session_t peer_id, NetworkPacket *pkt)
  1154. {
  1155. m_clients.send(peer_id,
  1156. clientCommandFactoryTable[pkt->getCommand()].channel,
  1157. pkt,
  1158. clientCommandFactoryTable[pkt->getCommand()].reliable);
  1159. }
  1160. void Server::SendMovement(session_t peer_id)
  1161. {
  1162. std::ostringstream os(std::ios_base::binary);
  1163. NetworkPacket pkt(TOCLIENT_MOVEMENT, 12 * sizeof(float), peer_id);
  1164. pkt << g_settings->getFloat("movement_acceleration_default");
  1165. pkt << g_settings->getFloat("movement_acceleration_air");
  1166. pkt << g_settings->getFloat("movement_acceleration_fast");
  1167. pkt << g_settings->getFloat("movement_speed_walk");
  1168. pkt << g_settings->getFloat("movement_speed_crouch");
  1169. pkt << g_settings->getFloat("movement_speed_fast");
  1170. pkt << g_settings->getFloat("movement_speed_climb");
  1171. pkt << g_settings->getFloat("movement_speed_jump");
  1172. pkt << g_settings->getFloat("movement_liquid_fluidity");
  1173. pkt << g_settings->getFloat("movement_liquid_fluidity_smooth");
  1174. pkt << g_settings->getFloat("movement_liquid_sink");
  1175. pkt << g_settings->getFloat("movement_gravity");
  1176. Send(&pkt);
  1177. }
  1178. void Server::SendPlayerHPOrDie(PlayerSAO *playersao)
  1179. {
  1180. if (!g_settings->getBool("enable_damage"))
  1181. return;
  1182. session_t peer_id = playersao->getPeerID();
  1183. bool is_alive = playersao->getHP() > 0;
  1184. if (is_alive)
  1185. SendPlayerHP(peer_id);
  1186. else
  1187. DiePlayer(peer_id);
  1188. }
  1189. void Server::SendHP(session_t peer_id, u16 hp)
  1190. {
  1191. NetworkPacket pkt(TOCLIENT_HP, 1, peer_id);
  1192. pkt << hp;
  1193. Send(&pkt);
  1194. }
  1195. void Server::SendBreath(session_t peer_id, u16 breath)
  1196. {
  1197. NetworkPacket pkt(TOCLIENT_BREATH, 2, peer_id);
  1198. pkt << (u16) breath;
  1199. Send(&pkt);
  1200. }
  1201. void Server::SendAccessDenied(session_t peer_id, AccessDeniedCode reason,
  1202. const std::string &custom_reason, bool reconnect)
  1203. {
  1204. assert(reason < SERVER_ACCESSDENIED_MAX);
  1205. NetworkPacket pkt(TOCLIENT_ACCESS_DENIED, 1, peer_id);
  1206. pkt << (u8)reason;
  1207. if (reason == SERVER_ACCESSDENIED_CUSTOM_STRING)
  1208. pkt << custom_reason;
  1209. else if (reason == SERVER_ACCESSDENIED_SHUTDOWN ||
  1210. reason == SERVER_ACCESSDENIED_CRASH)
  1211. pkt << custom_reason << (u8)reconnect;
  1212. Send(&pkt);
  1213. }
  1214. void Server::SendAccessDenied_Legacy(session_t peer_id,const std::wstring &reason)
  1215. {
  1216. NetworkPacket pkt(TOCLIENT_ACCESS_DENIED_LEGACY, 0, peer_id);
  1217. pkt << reason;
  1218. Send(&pkt);
  1219. }
  1220. void Server::SendDeathscreen(session_t peer_id, bool set_camera_point_target,
  1221. v3f camera_point_target)
  1222. {
  1223. NetworkPacket pkt(TOCLIENT_DEATHSCREEN, 1 + sizeof(v3f), peer_id);
  1224. pkt << set_camera_point_target << camera_point_target;
  1225. Send(&pkt);
  1226. }
  1227. void Server::SendItemDef(session_t peer_id,
  1228. IItemDefManager *itemdef, u16 protocol_version)
  1229. {
  1230. NetworkPacket pkt(TOCLIENT_ITEMDEF, 0, peer_id);
  1231. /*
  1232. u16 command
  1233. u32 length of the next item
  1234. zlib-compressed serialized ItemDefManager
  1235. */
  1236. std::ostringstream tmp_os(std::ios::binary);
  1237. itemdef->serialize(tmp_os, protocol_version);
  1238. std::ostringstream tmp_os2(std::ios::binary);
  1239. compressZlib(tmp_os.str(), tmp_os2);
  1240. pkt.putLongString(tmp_os2.str());
  1241. // Make data buffer
  1242. verbosestream << "Server: Sending item definitions to id(" << peer_id
  1243. << "): size=" << pkt.getSize() << std::endl;
  1244. Send(&pkt);
  1245. }
  1246. void Server::SendNodeDef(session_t peer_id,
  1247. const NodeDefManager *nodedef, u16 protocol_version)
  1248. {
  1249. NetworkPacket pkt(TOCLIENT_NODEDEF, 0, peer_id);
  1250. /*
  1251. u16 command
  1252. u32 length of the next item
  1253. zlib-compressed serialized NodeDefManager
  1254. */
  1255. std::ostringstream tmp_os(std::ios::binary);
  1256. nodedef->serialize(tmp_os, protocol_version);
  1257. std::ostringstream tmp_os2(std::ios::binary);
  1258. compressZlib(tmp_os.str(), tmp_os2);
  1259. pkt.putLongString(tmp_os2.str());
  1260. // Make data buffer
  1261. verbosestream << "Server: Sending node definitions to id(" << peer_id
  1262. << "): size=" << pkt.getSize() << std::endl;
  1263. Send(&pkt);
  1264. }
  1265. /*
  1266. Non-static send methods
  1267. */
  1268. void Server::SendInventory(PlayerSAO* playerSAO)
  1269. {
  1270. UpdateCrafting(playerSAO->getPlayer());
  1271. /*
  1272. Serialize it
  1273. */
  1274. NetworkPacket pkt(TOCLIENT_INVENTORY, 0, playerSAO->getPeerID());
  1275. std::ostringstream os;
  1276. playerSAO->getInventory()->serialize(os);
  1277. std::string s = os.str();
  1278. pkt.putRawString(s.c_str(), s.size());
  1279. Send(&pkt);
  1280. }
  1281. void Server::SendChatMessage(session_t peer_id, const ChatMessage &message)
  1282. {
  1283. NetworkPacket pkt(TOCLIENT_CHAT_MESSAGE, 0, peer_id);
  1284. u8 version = 1;
  1285. u8 type = message.type;
  1286. pkt << version << type << std::wstring(L"") << message.message << message.timestamp;
  1287. if (peer_id != PEER_ID_INEXISTENT) {
  1288. RemotePlayer *player = m_env->getPlayer(peer_id);
  1289. if (!player)
  1290. return;
  1291. Send(&pkt);
  1292. } else {
  1293. m_clients.sendToAll(&pkt);
  1294. }
  1295. }
  1296. void Server::SendShowFormspecMessage(session_t peer_id, const std::string &formspec,
  1297. const std::string &formname)
  1298. {
  1299. NetworkPacket pkt(TOCLIENT_SHOW_FORMSPEC, 0 , peer_id);
  1300. if (formspec.empty()){
  1301. //the client should close the formspec
  1302. m_formspec_state_data.erase(peer_id);
  1303. pkt.putLongString("");
  1304. } else {
  1305. m_formspec_state_data[peer_id] = formname;
  1306. pkt.putLongString(FORMSPEC_VERSION_STRING + formspec);
  1307. }
  1308. pkt << formname;
  1309. Send(&pkt);
  1310. }
  1311. // Spawns a particle on peer with peer_id
  1312. void Server::SendSpawnParticle(session_t peer_id, u16 protocol_version,
  1313. v3f pos, v3f velocity, v3f acceleration,
  1314. float expirationtime, float size, bool collisiondetection,
  1315. bool collision_removal,
  1316. bool vertical, const std::string &texture,
  1317. const struct TileAnimationParams &animation, u8 glow)
  1318. {
  1319. static thread_local const float radius =
  1320. g_settings->getS16("max_block_send_distance") * MAP_BLOCKSIZE * BS;
  1321. if (peer_id == PEER_ID_INEXISTENT) {
  1322. std::vector<session_t> clients = m_clients.getClientIDs();
  1323. for (const session_t client_id : clients) {
  1324. RemotePlayer *player = m_env->getPlayer(client_id);
  1325. if (!player)
  1326. continue;
  1327. PlayerSAO *sao = player->getPlayerSAO();
  1328. if (!sao)
  1329. continue;
  1330. // Do not send to distant clients
  1331. if (sao->getBasePosition().getDistanceFrom(pos * BS) > radius)
  1332. continue;
  1333. SendSpawnParticle(client_id, player->protocol_version,
  1334. pos, velocity, acceleration,
  1335. expirationtime, size, collisiondetection,
  1336. collision_removal, vertical, texture, animation, glow);
  1337. }
  1338. return;
  1339. }
  1340. NetworkPacket pkt(TOCLIENT_SPAWN_PARTICLE, 0, peer_id);
  1341. pkt << pos << velocity << acceleration << expirationtime
  1342. << size << collisiondetection;
  1343. pkt.putLongString(texture);
  1344. pkt << vertical;
  1345. pkt << collision_removal;
  1346. // This is horrible but required (why are there two ways to serialize pkts?)
  1347. std::ostringstream os(std::ios_base::binary);
  1348. animation.serialize(os, protocol_version);
  1349. pkt.putRawString(os.str());
  1350. pkt << glow;
  1351. Send(&pkt);
  1352. }
  1353. // Adds a ParticleSpawner on peer with peer_id
  1354. void Server::SendAddParticleSpawner(session_t peer_id, u16 protocol_version,
  1355. u16 amount, float spawntime, v3f minpos, v3f maxpos,
  1356. v3f minvel, v3f maxvel, v3f minacc, v3f maxacc, float minexptime, float maxexptime,
  1357. float minsize, float maxsize, bool collisiondetection, bool collision_removal,
  1358. u16 attached_id, bool vertical, const std::string &texture, u32 id,
  1359. const struct TileAnimationParams &animation, u8 glow)
  1360. {
  1361. if (peer_id == PEER_ID_INEXISTENT) {
  1362. // This sucks and should be replaced:
  1363. std::vector<session_t> clients = m_clients.getClientIDs();
  1364. for (const session_t client_id : clients) {
  1365. RemotePlayer *player = m_env->getPlayer(client_id);
  1366. if (!player)
  1367. continue;
  1368. SendAddParticleSpawner(client_id, player->protocol_version,
  1369. amount, spawntime, minpos, maxpos,
  1370. minvel, maxvel, minacc, maxacc, minexptime, maxexptime,
  1371. minsize, maxsize, collisiondetection, collision_removal,
  1372. attached_id, vertical, texture, id, animation, glow);
  1373. }
  1374. return;
  1375. }
  1376. NetworkPacket pkt(TOCLIENT_ADD_PARTICLESPAWNER, 0, peer_id);
  1377. pkt << amount << spawntime << minpos << maxpos << minvel << maxvel
  1378. << minacc << maxacc << minexptime << maxexptime << minsize
  1379. << maxsize << collisiondetection;
  1380. pkt.putLongString(texture);
  1381. pkt << id << vertical;
  1382. pkt << collision_removal;
  1383. pkt << attached_id;
  1384. // This is horrible but required
  1385. std::ostringstream os(std::ios_base::binary);
  1386. animation.serialize(os, protocol_version);
  1387. pkt.putRawString(os.str());
  1388. pkt << glow;
  1389. Send(&pkt);
  1390. }
  1391. void Server::SendDeleteParticleSpawner(session_t peer_id, u32 id)
  1392. {
  1393. NetworkPacket pkt(TOCLIENT_DELETE_PARTICLESPAWNER, 4, peer_id);
  1394. // Ugly error in this packet
  1395. pkt << id;
  1396. if (peer_id != PEER_ID_INEXISTENT)
  1397. Send(&pkt);
  1398. else
  1399. m_clients.sendToAll(&pkt);
  1400. }
  1401. void Server::SendHUDAdd(session_t peer_id, u32 id, HudElement *form)
  1402. {
  1403. NetworkPacket pkt(TOCLIENT_HUDADD, 0 , peer_id);
  1404. pkt << id << (u8) form->type << form->pos << form->name << form->scale
  1405. << form->text << form->number << form->item << form->dir
  1406. << form->align << form->offset << form->world_pos << form->size;
  1407. Send(&pkt);
  1408. }
  1409. void Server::SendHUDRemove(session_t peer_id, u32 id)
  1410. {
  1411. NetworkPacket pkt(TOCLIENT_HUDRM, 4, peer_id);
  1412. pkt << id;
  1413. Send(&pkt);
  1414. }
  1415. void Server::SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value)
  1416. {
  1417. NetworkPacket pkt(TOCLIENT_HUDCHANGE, 0, peer_id);
  1418. pkt << id << (u8) stat;
  1419. switch (stat) {
  1420. case HUD_STAT_POS:
  1421. case HUD_STAT_SCALE:
  1422. case HUD_STAT_ALIGN:
  1423. case HUD_STAT_OFFSET:
  1424. pkt << *(v2f *) value;
  1425. break;
  1426. case HUD_STAT_NAME:
  1427. case HUD_STAT_TEXT:
  1428. pkt << *(std::string *) value;
  1429. break;
  1430. case HUD_STAT_WORLD_POS:
  1431. pkt << *(v3f *) value;
  1432. break;
  1433. case HUD_STAT_SIZE:
  1434. pkt << *(v2s32 *) value;
  1435. break;
  1436. case HUD_STAT_NUMBER:
  1437. case HUD_STAT_ITEM:
  1438. case HUD_STAT_DIR:
  1439. default:
  1440. pkt << *(u32 *) value;
  1441. break;
  1442. }
  1443. Send(&pkt);
  1444. }
  1445. void Server::SendHUDSetFlags(session_t peer_id, u32 flags, u32 mask)
  1446. {
  1447. NetworkPacket pkt(TOCLIENT_HUD_SET_FLAGS, 4 + 4, peer_id);
  1448. flags &= ~(HUD_FLAG_HEALTHBAR_VISIBLE | HUD_FLAG_BREATHBAR_VISIBLE);
  1449. pkt << flags << mask;
  1450. Send(&pkt);
  1451. }
  1452. void Server::SendHUDSetParam(session_t peer_id, u16 param, const std::string &value)
  1453. {
  1454. NetworkPacket pkt(TOCLIENT_HUD_SET_PARAM, 0, peer_id);
  1455. pkt << param << value;
  1456. Send(&pkt);
  1457. }
  1458. void Server::SendSetSky(session_t peer_id, const video::SColor &bgcolor,
  1459. const std::string &type, const std::vector<std::string> &params,
  1460. bool &clouds)
  1461. {
  1462. NetworkPacket pkt(TOCLIENT_SET_SKY, 0, peer_id);
  1463. pkt << bgcolor << type << (u16) params.size();
  1464. for (const std::string &param : params)
  1465. pkt << param;
  1466. pkt << clouds;
  1467. Send(&pkt);
  1468. }
  1469. void Server::SendCloudParams(session_t peer_id, const CloudParams &params)
  1470. {
  1471. NetworkPacket pkt(TOCLIENT_CLOUD_PARAMS, 0, peer_id);
  1472. pkt << params.density << params.color_bright << params.color_ambient
  1473. << params.height << params.thickness << params.speed;
  1474. Send(&pkt);
  1475. }
  1476. void Server::SendOverrideDayNightRatio(session_t peer_id, bool do_override,
  1477. float ratio)
  1478. {
  1479. NetworkPacket pkt(TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO,
  1480. 1 + 2, peer_id);
  1481. pkt << do_override << (u16) (ratio * 65535);
  1482. Send(&pkt);
  1483. }
  1484. void Server::SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed)
  1485. {
  1486. NetworkPacket pkt(TOCLIENT_TIME_OF_DAY, 0, peer_id);
  1487. pkt << time << time_speed;
  1488. if (peer_id == PEER_ID_INEXISTENT) {
  1489. m_clients.sendToAll(&pkt);
  1490. }
  1491. else {
  1492. Send(&pkt);
  1493. }
  1494. }
  1495. void Server::SendPlayerHP(session_t peer_id)
  1496. {
  1497. PlayerSAO *playersao = getPlayerSAO(peer_id);
  1498. // In some rare case if the player is disconnected
  1499. // while Lua call l_punch, for example, this can be NULL
  1500. if (!playersao)
  1501. return;
  1502. SendHP(peer_id, playersao->getHP());
  1503. m_script->player_event(playersao,"health_changed");
  1504. // Send to other clients
  1505. std::string str = gob_cmd_punched(playersao->readDamage(), playersao->getHP());
  1506. ActiveObjectMessage aom(playersao->getId(), true, str);
  1507. playersao->m_messages_out.push(aom);
  1508. }
  1509. void Server::SendPlayerBreath(PlayerSAO *sao)
  1510. {
  1511. assert(sao);
  1512. m_script->player_event(sao, "breath_changed");
  1513. SendBreath(sao->getPeerID(), sao->getBreath());
  1514. }
  1515. void Server::SendMovePlayer(session_t peer_id)
  1516. {
  1517. RemotePlayer *player = m_env->getPlayer(peer_id);
  1518. assert(player);
  1519. PlayerSAO *sao = player->getPlayerSAO();
  1520. assert(sao);
  1521. NetworkPacket pkt(TOCLIENT_MOVE_PLAYER, sizeof(v3f) + sizeof(f32) * 2, peer_id);
  1522. pkt << sao->getBasePosition() << sao->getPitch() << sao->getYaw();
  1523. {
  1524. v3f pos = sao->getBasePosition();
  1525. verbosestream << "Server: Sending TOCLIENT_MOVE_PLAYER"
  1526. << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")"
  1527. << " pitch=" << sao->getPitch()
  1528. << " yaw=" << sao->getYaw()
  1529. << std::endl;
  1530. }
  1531. Send(&pkt);
  1532. }
  1533. void Server::SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4],
  1534. f32 animation_speed)
  1535. {
  1536. NetworkPacket pkt(TOCLIENT_LOCAL_PLAYER_ANIMATIONS, 0,
  1537. peer_id);
  1538. pkt << animation_frames[0] << animation_frames[1] << animation_frames[2]
  1539. << animation_frames[3] << animation_speed;
  1540. Send(&pkt);
  1541. }
  1542. void Server::SendEyeOffset(session_t peer_id, v3f first, v3f third)
  1543. {
  1544. NetworkPacket pkt(TOCLIENT_EYE_OFFSET, 0, peer_id);
  1545. pkt << first << third;
  1546. Send(&pkt);
  1547. }
  1548. void Server::SendPlayerPrivileges(session_t peer_id)
  1549. {
  1550. RemotePlayer *player = m_env->getPlayer(peer_id);
  1551. assert(player);
  1552. if(player->getPeerId() == PEER_ID_INEXISTENT)
  1553. return;
  1554. std::set<std::string> privs;
  1555. m_script->getAuth(player->getName(), NULL, &privs);
  1556. NetworkPacket pkt(TOCLIENT_PRIVILEGES, 0, peer_id);
  1557. pkt << (u16) privs.size();
  1558. for (const std::string &priv : privs) {
  1559. pkt << priv;
  1560. }
  1561. Send(&pkt);
  1562. }
  1563. void Server::SendPlayerInventoryFormspec(session_t peer_id)
  1564. {
  1565. RemotePlayer *player = m_env->getPlayer(peer_id);
  1566. assert(player);
  1567. if(player->getPeerId() == PEER_ID_INEXISTENT)
  1568. return;
  1569. NetworkPacket pkt(TOCLIENT_INVENTORY_FORMSPEC, 0, peer_id);
  1570. pkt.putLongString(FORMSPEC_VERSION_STRING + player->inventory_formspec);
  1571. Send(&pkt);
  1572. }
  1573. u32 Server::SendActiveObjectRemoveAdd(session_t peer_id, const std::string &datas)
  1574. {
  1575. NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD, datas.size(), peer_id);
  1576. pkt.putRawString(datas.c_str(), datas.size());
  1577. Send(&pkt);
  1578. return pkt.getSize();
  1579. }
  1580. void Server::SendActiveObjectMessages(session_t peer_id, const std::string &datas,
  1581. bool reliable)
  1582. {
  1583. NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_MESSAGES,
  1584. datas.size(), peer_id);
  1585. pkt.putRawString(datas.c_str(), datas.size());
  1586. m_clients.send(pkt.getPeerId(),
  1587. reliable ? clientCommandFactoryTable[pkt.getCommand()].channel : 1,
  1588. &pkt, reliable);
  1589. }
  1590. void Server::SendCSMFlavourLimits(session_t peer_id)
  1591. {
  1592. NetworkPacket pkt(TOCLIENT_CSM_FLAVOUR_LIMITS,
  1593. sizeof(m_csm_flavour_limits) + sizeof(m_csm_noderange_limit), peer_id);
  1594. pkt << m_csm_flavour_limits << m_csm_noderange_limit;
  1595. Send(&pkt);
  1596. }
  1597. s32 Server::playSound(const SimpleSoundSpec &spec,
  1598. const ServerSoundParams &params)
  1599. {
  1600. // Find out initial position of sound
  1601. bool pos_exists = false;
  1602. v3f pos = params.getPos(m_env, &pos_exists);
  1603. // If position is not found while it should be, cancel sound
  1604. if(pos_exists != (params.type != ServerSoundParams::SSP_LOCAL))
  1605. return -1;
  1606. // Filter destination clients
  1607. std::vector<session_t> dst_clients;
  1608. if(!params.to_player.empty()) {
  1609. RemotePlayer *player = m_env->getPlayer(params.to_player.c_str());
  1610. if(!player){
  1611. infostream<<"Server::playSound: Player \""<<params.to_player
  1612. <<"\" not found"<<std::endl;
  1613. return -1;
  1614. }
  1615. if (player->getPeerId() == PEER_ID_INEXISTENT) {
  1616. infostream<<"Server::playSound: Player \""<<params.to_player
  1617. <<"\" not connected"<<std::endl;
  1618. return -1;
  1619. }
  1620. dst_clients.push_back(player->getPeerId());
  1621. } else {
  1622. std::vector<session_t> clients = m_clients.getClientIDs();
  1623. for (const session_t client_id : clients) {
  1624. RemotePlayer *player = m_env->getPlayer(client_id);
  1625. if (!player)
  1626. continue;
  1627. PlayerSAO *sao = player->getPlayerSAO();
  1628. if (!sao)
  1629. continue;
  1630. if (pos_exists) {
  1631. if(sao->getBasePosition().getDistanceFrom(pos) >
  1632. params.max_hear_distance)
  1633. continue;
  1634. }
  1635. dst_clients.push_back(client_id);
  1636. }
  1637. }
  1638. if(dst_clients.empty())
  1639. return -1;
  1640. // Create the sound
  1641. s32 id = m_next_sound_id++;
  1642. // The sound will exist as a reference in m_playing_sounds
  1643. m_playing_sounds[id] = ServerPlayingSound();
  1644. ServerPlayingSound &psound = m_playing_sounds[id];
  1645. psound.params = params;
  1646. psound.spec = spec;
  1647. float gain = params.gain * spec.gain;
  1648. NetworkPacket pkt(TOCLIENT_PLAY_SOUND, 0);
  1649. pkt << id << spec.name << gain
  1650. << (u8) params.type << pos << params.object
  1651. << params.loop << params.fade << params.pitch;
  1652. // Backwards compability
  1653. bool play_sound = gain > 0;
  1654. for (const u16 dst_client : dst_clients) {
  1655. if (play_sound || m_clients.getProtocolVersion(dst_client) >= 32) {
  1656. psound.clients.insert(dst_client);
  1657. m_clients.send(dst_client, 0, &pkt, true);
  1658. }
  1659. }
  1660. return id;
  1661. }
  1662. void Server::stopSound(s32 handle)
  1663. {
  1664. // Get sound reference
  1665. std::unordered_map<s32, ServerPlayingSound>::iterator i =
  1666. m_playing_sounds.find(handle);
  1667. if (i == m_playing_sounds.end())
  1668. return;
  1669. ServerPlayingSound &psound = i->second;
  1670. NetworkPacket pkt(TOCLIENT_STOP_SOUND, 4);
  1671. pkt << handle;
  1672. for (std::unordered_set<session_t>::const_iterator si = psound.clients.begin();
  1673. si != psound.clients.end(); ++si) {
  1674. // Send as reliable
  1675. m_clients.send(*si, 0, &pkt, true);
  1676. }
  1677. // Remove sound reference
  1678. m_playing_sounds.erase(i);
  1679. }
  1680. void Server::fadeSound(s32 handle, float step, float gain)
  1681. {
  1682. // Get sound reference
  1683. std::unordered_map<s32, ServerPlayingSound>::iterator i =
  1684. m_playing_sounds.find(handle);
  1685. if (i == m_playing_sounds.end())
  1686. return;
  1687. ServerPlayingSound &psound = i->second;
  1688. psound.params.gain = gain;
  1689. NetworkPacket pkt(TOCLIENT_FADE_SOUND, 4);
  1690. pkt << handle << step << gain;
  1691. // Backwards compability
  1692. bool play_sound = gain > 0;
  1693. ServerPlayingSound compat_psound = psound;
  1694. compat_psound.clients.clear();
  1695. NetworkPacket compat_pkt(TOCLIENT_STOP_SOUND, 4);
  1696. compat_pkt << handle;
  1697. for (std::unordered_set<u16>::iterator it = psound.clients.begin();
  1698. it != psound.clients.end();) {
  1699. if (m_clients.getProtocolVersion(*it) >= 32) {
  1700. // Send as reliable
  1701. m_clients.send(*it, 0, &pkt, true);
  1702. ++it;
  1703. } else {
  1704. compat_psound.clients.insert(*it);
  1705. // Stop old sound
  1706. m_clients.send(*it, 0, &compat_pkt, true);
  1707. psound.clients.erase(it++);
  1708. }
  1709. }
  1710. // Remove sound reference
  1711. if (!play_sound || psound.clients.empty())
  1712. m_playing_sounds.erase(i);
  1713. if (play_sound && !compat_psound.clients.empty()) {
  1714. // Play new sound volume on older clients
  1715. playSound(compat_psound.spec, compat_psound.params);
  1716. }
  1717. }
  1718. void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
  1719. std::vector<u16> *far_players, float far_d_nodes)
  1720. {
  1721. float maxd = far_d_nodes*BS;
  1722. v3f p_f = intToFloat(p, BS);
  1723. NetworkPacket pkt(TOCLIENT_REMOVENODE, 6);
  1724. pkt << p;
  1725. std::vector<session_t> clients = m_clients.getClientIDs();
  1726. for (session_t client_id : clients) {
  1727. if (far_players) {
  1728. // Get player
  1729. if (RemotePlayer *player = m_env->getPlayer(client_id)) {
  1730. PlayerSAO *sao = player->getPlayerSAO();
  1731. if (!sao)
  1732. continue;
  1733. // If player is far away, only set modified blocks not sent
  1734. v3f player_pos = sao->getBasePosition();
  1735. if (player_pos.getDistanceFrom(p_f) > maxd) {
  1736. far_players->push_back(client_id);
  1737. continue;
  1738. }
  1739. }
  1740. }
  1741. // Send as reliable
  1742. m_clients.send(client_id, 0, &pkt, true);
  1743. }
  1744. }
  1745. void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
  1746. std::vector<u16> *far_players, float far_d_nodes,
  1747. bool remove_metadata)
  1748. {
  1749. float maxd = far_d_nodes*BS;
  1750. v3f p_f = intToFloat(p, BS);
  1751. std::vector<session_t> clients = m_clients.getClientIDs();
  1752. for (const session_t client_id : clients) {
  1753. if (far_players) {
  1754. // Get player
  1755. if (RemotePlayer *player = m_env->getPlayer(client_id)) {
  1756. PlayerSAO *sao = player->getPlayerSAO();
  1757. if (!sao)
  1758. continue;
  1759. // If player is far away, only set modified blocks not sent
  1760. v3f player_pos = sao->getBasePosition();
  1761. if(player_pos.getDistanceFrom(p_f) > maxd) {
  1762. far_players->push_back(client_id);
  1763. continue;
  1764. }
  1765. }
  1766. }
  1767. NetworkPacket pkt(TOCLIENT_ADDNODE, 6 + 2 + 1 + 1 + 1);
  1768. m_clients.lock();
  1769. RemoteClient* client = m_clients.lockedGetClientNoEx(client_id);
  1770. if (client) {
  1771. pkt << p << n.param0 << n.param1 << n.param2
  1772. << (u8) (remove_metadata ? 0 : 1);
  1773. }
  1774. m_clients.unlock();
  1775. // Send as reliable
  1776. if (pkt.getSize() > 0)
  1777. m_clients.send(client_id, 0, &pkt, true);
  1778. }
  1779. }
  1780. void Server::SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver,
  1781. u16 net_proto_version)
  1782. {
  1783. /*
  1784. Create a packet with the block in the right format
  1785. */
  1786. std::ostringstream os(std::ios_base::binary);
  1787. block->serialize(os, ver, false);
  1788. block->serializeNetworkSpecific(os);
  1789. std::string s = os.str();
  1790. NetworkPacket pkt(TOCLIENT_BLOCKDATA, 2 + 2 + 2 + 2 + s.size(), peer_id);
  1791. pkt << block->getPos();
  1792. pkt.putRawString(s.c_str(), s.size());
  1793. Send(&pkt);
  1794. }
  1795. void Server::SendBlocks(float dtime)
  1796. {
  1797. MutexAutoLock envlock(m_env_mutex);
  1798. //TODO check if one big lock could be faster then multiple small ones
  1799. ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
  1800. std::vector<PrioritySortedBlockTransfer> queue;
  1801. u32 total_sending = 0;
  1802. {
  1803. ScopeProfiler sp2(g_profiler, "Server: selecting blocks for sending");
  1804. std::vector<session_t> clients = m_clients.getClientIDs();
  1805. m_clients.lock();
  1806. for (const session_t client_id : clients) {
  1807. RemoteClient *client = m_clients.lockedGetClientNoEx(client_id, CS_Active);
  1808. if (!client)
  1809. continue;
  1810. total_sending += client->getSendingCount();
  1811. client->GetNextBlocks(m_env,m_emerge, dtime, queue);
  1812. }
  1813. m_clients.unlock();
  1814. }
  1815. // Sort.
  1816. // Lowest priority number comes first.
  1817. // Lowest is most important.
  1818. std::sort(queue.begin(), queue.end());
  1819. m_clients.lock();
  1820. // Maximal total count calculation
  1821. // The per-client block sends is halved with the maximal online users
  1822. u32 max_blocks_to_send = (m_env->getPlayerCount() + g_settings->getU32("max_users")) *
  1823. g_settings->getU32("max_simultaneous_block_sends_per_client") / 4 + 1;
  1824. for (const PrioritySortedBlockTransfer &block_to_send : queue) {
  1825. if (total_sending >= max_blocks_to_send)
  1826. break;
  1827. MapBlock *block = nullptr;
  1828. try {
  1829. block = m_env->getMap().getBlockNoCreate(block_to_send.pos);
  1830. } catch (const InvalidPositionException &e) {
  1831. continue;
  1832. }
  1833. RemoteClient *client = m_clients.lockedGetClientNoEx(block_to_send.peer_id,
  1834. CS_Active);
  1835. if (!client)
  1836. continue;
  1837. SendBlockNoLock(block_to_send.peer_id, block, client->serialization_version,
  1838. client->net_proto_version);
  1839. client->SentBlock(block_to_send.pos);
  1840. total_sending++;
  1841. }
  1842. m_clients.unlock();
  1843. }
  1844. void Server::fillMediaCache()
  1845. {
  1846. infostream<<"Server: Calculating media file checksums"<<std::endl;
  1847. // Collect all media file paths
  1848. std::vector<std::string> paths;
  1849. m_modmgr->getModsMediaPaths(paths);
  1850. fs::GetRecursiveDirs(paths, m_gamespec.path + DIR_DELIM + "textures");
  1851. fs::GetRecursiveDirs(paths, porting::path_user + DIR_DELIM + "textures" + DIR_DELIM + "server");
  1852. // Collect media file information from paths into cache
  1853. for (const std::string &mediapath : paths) {
  1854. std::vector<fs::DirListNode> dirlist = fs::GetDirListing(mediapath);
  1855. for (const fs::DirListNode &dln : dirlist) {
  1856. if (dln.dir) // Ignode dirs
  1857. continue;
  1858. std::string filename = dln.name;
  1859. // If name contains illegal characters, ignore the file
  1860. if (!string_allowed(filename, TEXTURENAME_ALLOWED_CHARS)) {
  1861. infostream<<"Server: ignoring illegal file name: \""
  1862. << filename << "\"" << std::endl;
  1863. continue;
  1864. }
  1865. // If name is not in a supported format, ignore it
  1866. const char *supported_ext[] = {
  1867. ".png", ".jpg", ".bmp", ".tga",
  1868. ".pcx", ".ppm", ".psd", ".wal", ".rgb",
  1869. ".ogg",
  1870. ".x", ".b3d", ".md2", ".obj",
  1871. // Custom translation file format
  1872. ".tr",
  1873. NULL
  1874. };
  1875. if (removeStringEnd(filename, supported_ext).empty()){
  1876. infostream << "Server: ignoring unsupported file extension: \""
  1877. << filename << "\"" << std::endl;
  1878. continue;
  1879. }
  1880. // Ok, attempt to load the file and add to cache
  1881. std::string filepath;
  1882. filepath.append(mediapath).append(DIR_DELIM).append(filename);
  1883. // Read data
  1884. std::ifstream fis(filepath.c_str(), std::ios_base::binary);
  1885. if (!fis.good()) {
  1886. errorstream << "Server::fillMediaCache(): Could not open \""
  1887. << filename << "\" for reading" << std::endl;
  1888. continue;
  1889. }
  1890. std::ostringstream tmp_os(std::ios_base::binary);
  1891. bool bad = false;
  1892. for(;;) {
  1893. char buf[1024];
  1894. fis.read(buf, 1024);
  1895. std::streamsize len = fis.gcount();
  1896. tmp_os.write(buf, len);
  1897. if (fis.eof())
  1898. break;
  1899. if (!fis.good()) {
  1900. bad = true;
  1901. break;
  1902. }
  1903. }
  1904. if(bad) {
  1905. errorstream<<"Server::fillMediaCache(): Failed to read \""
  1906. << filename << "\"" << std::endl;
  1907. continue;
  1908. }
  1909. if(tmp_os.str().length() == 0) {
  1910. errorstream << "Server::fillMediaCache(): Empty file \""
  1911. << filepath << "\"" << std::endl;
  1912. continue;
  1913. }
  1914. SHA1 sha1;
  1915. sha1.addBytes(tmp_os.str().c_str(), tmp_os.str().length());
  1916. unsigned char *digest = sha1.getDigest();
  1917. std::string sha1_base64 = base64_encode(digest, 20);
  1918. std::string sha1_hex = hex_encode((char*)digest, 20);
  1919. free(digest);
  1920. // Put in list
  1921. m_media[filename] = MediaInfo(filepath, sha1_base64);
  1922. verbosestream << "Server: " << sha1_hex << " is " << filename
  1923. << std::endl;
  1924. }
  1925. }
  1926. }
  1927. void Server::sendMediaAnnouncement(session_t peer_id, const std::string &lang_code)
  1928. {
  1929. verbosestream << "Server: Announcing files to id(" << peer_id << ")"
  1930. << std::endl;
  1931. // Make packet
  1932. NetworkPacket pkt(TOCLIENT_ANNOUNCE_MEDIA, 0, peer_id);
  1933. u16 media_sent = 0;
  1934. std::string lang_suffix;
  1935. lang_suffix.append(".").append(lang_code).append(".tr");
  1936. for (const auto &i : m_media) {
  1937. if (str_ends_with(i.first, ".tr") && !str_ends_with(i.first, lang_suffix))
  1938. continue;
  1939. media_sent++;
  1940. }
  1941. pkt << media_sent;
  1942. for (const auto &i : m_media) {
  1943. if (str_ends_with(i.first, ".tr") && !str_ends_with(i.first, lang_suffix))
  1944. continue;
  1945. pkt << i.first << i.second.sha1_digest;
  1946. }
  1947. pkt << g_settings->get("remote_media");
  1948. Send(&pkt);
  1949. }
  1950. struct SendableMedia
  1951. {
  1952. std::string name;
  1953. std::string path;
  1954. std::string data;
  1955. SendableMedia(const std::string &name_="", const std::string &path_="",
  1956. const std::string &data_=""):
  1957. name(name_),
  1958. path(path_),
  1959. data(data_)
  1960. {}
  1961. };
  1962. void Server::sendRequestedMedia(session_t peer_id,
  1963. const std::vector<std::string> &tosend)
  1964. {
  1965. verbosestream<<"Server::sendRequestedMedia(): "
  1966. <<"Sending files to client"<<std::endl;
  1967. /* Read files */
  1968. // Put 5kB in one bunch (this is not accurate)
  1969. u32 bytes_per_bunch = 5000;
  1970. std::vector< std::vector<SendableMedia> > file_bunches;
  1971. file_bunches.emplace_back();
  1972. u32 file_size_bunch_total = 0;
  1973. for (const std::string &name : tosend) {
  1974. if (m_media.find(name) == m_media.end()) {
  1975. errorstream<<"Server::sendRequestedMedia(): Client asked for "
  1976. <<"unknown file \""<<(name)<<"\""<<std::endl;
  1977. continue;
  1978. }
  1979. //TODO get path + name
  1980. std::string tpath = m_media[name].path;
  1981. // Read data
  1982. std::ifstream fis(tpath.c_str(), std::ios_base::binary);
  1983. if(!fis.good()){
  1984. errorstream<<"Server::sendRequestedMedia(): Could not open \""
  1985. <<tpath<<"\" for reading"<<std::endl;
  1986. continue;
  1987. }
  1988. std::ostringstream tmp_os(std::ios_base::binary);
  1989. bool bad = false;
  1990. for(;;) {
  1991. char buf[1024];
  1992. fis.read(buf, 1024);
  1993. std::streamsize len = fis.gcount();
  1994. tmp_os.write(buf, len);
  1995. file_size_bunch_total += len;
  1996. if(fis.eof())
  1997. break;
  1998. if(!fis.good()) {
  1999. bad = true;
  2000. break;
  2001. }
  2002. }
  2003. if (bad) {
  2004. errorstream<<"Server::sendRequestedMedia(): Failed to read \""
  2005. <<name<<"\""<<std::endl;
  2006. continue;
  2007. }
  2008. /*infostream<<"Server::sendRequestedMedia(): Loaded \""
  2009. <<tname<<"\""<<std::endl;*/
  2010. // Put in list
  2011. file_bunches[file_bunches.size()-1].emplace_back(name, tpath, tmp_os.str());
  2012. // Start next bunch if got enough data
  2013. if(file_size_bunch_total >= bytes_per_bunch) {
  2014. file_bunches.emplace_back();
  2015. file_size_bunch_total = 0;
  2016. }
  2017. }
  2018. /* Create and send packets */
  2019. u16 num_bunches = file_bunches.size();
  2020. for (u16 i = 0; i < num_bunches; i++) {
  2021. /*
  2022. u16 command
  2023. u16 total number of texture bunches
  2024. u16 index of this bunch
  2025. u32 number of files in this bunch
  2026. for each file {
  2027. u16 length of name
  2028. string name
  2029. u32 length of data
  2030. data
  2031. }
  2032. */
  2033. NetworkPacket pkt(TOCLIENT_MEDIA, 4 + 0, peer_id);
  2034. pkt << num_bunches << i << (u32) file_bunches[i].size();
  2035. for (const SendableMedia &j : file_bunches[i]) {
  2036. pkt << j.name;
  2037. pkt.putLongString(j.data);
  2038. }
  2039. verbosestream << "Server::sendRequestedMedia(): bunch "
  2040. << i << "/" << num_bunches
  2041. << " files=" << file_bunches[i].size()
  2042. << " size=" << pkt.getSize() << std::endl;
  2043. Send(&pkt);
  2044. }
  2045. }
  2046. void Server::sendDetachedInventory(const std::string &name, session_t peer_id)
  2047. {
  2048. if(m_detached_inventories.count(name) == 0) {
  2049. errorstream<<FUNCTION_NAME<<": \""<<name<<"\" not found"<<std::endl;
  2050. return;
  2051. }
  2052. Inventory *inv = m_detached_inventories[name];
  2053. std::ostringstream os(std::ios_base::binary);
  2054. os << serializeString(name);
  2055. inv->serialize(os);
  2056. // Make data buffer
  2057. std::string s = os.str();
  2058. NetworkPacket pkt(TOCLIENT_DETACHED_INVENTORY, 0, peer_id);
  2059. pkt.putRawString(s.c_str(), s.size());
  2060. const std::string &check = m_detached_inventories_player[name];
  2061. if (peer_id == PEER_ID_INEXISTENT) {
  2062. if (check.empty())
  2063. return m_clients.sendToAll(&pkt);
  2064. RemotePlayer *p = m_env->getPlayer(check.c_str());
  2065. if (p)
  2066. m_clients.send(p->getPeerId(), 0, &pkt, true);
  2067. } else {
  2068. if (check.empty() || getPlayerName(peer_id) == check)
  2069. Send(&pkt);
  2070. }
  2071. }
  2072. void Server::sendDetachedInventories(session_t peer_id)
  2073. {
  2074. for (const auto &detached_inventory : m_detached_inventories) {
  2075. const std::string &name = detached_inventory.first;
  2076. //Inventory *inv = i->second;
  2077. sendDetachedInventory(name, peer_id);
  2078. }
  2079. }
  2080. /*
  2081. Something random
  2082. */
  2083. void Server::DiePlayer(session_t peer_id)
  2084. {
  2085. PlayerSAO *playersao = getPlayerSAO(peer_id);
  2086. // In some rare cases this can be NULL -- if the player is disconnected
  2087. // when a Lua function modifies l_punch, for example
  2088. if (!playersao)
  2089. return;
  2090. infostream << "Server::DiePlayer(): Player "
  2091. << playersao->getPlayer()->getName()
  2092. << " dies" << std::endl;
  2093. playersao->setHP(0);
  2094. // Trigger scripted stuff
  2095. m_script->on_dieplayer(playersao);
  2096. SendPlayerHP(peer_id);
  2097. SendDeathscreen(peer_id, false, v3f(0,0,0));
  2098. }
  2099. void Server::RespawnPlayer(session_t peer_id)
  2100. {
  2101. PlayerSAO *playersao = getPlayerSAO(peer_id);
  2102. assert(playersao);
  2103. infostream << "Server::RespawnPlayer(): Player "
  2104. << playersao->getPlayer()->getName()
  2105. << " respawns" << std::endl;
  2106. playersao->setHP(playersao->accessObjectProperties()->hp_max);
  2107. playersao->setBreath(playersao->accessObjectProperties()->breath_max);
  2108. bool repositioned = m_script->on_respawnplayer(playersao);
  2109. if (!repositioned) {
  2110. // setPos will send the new position to client
  2111. playersao->setPos(findSpawnPos());
  2112. }
  2113. SendPlayerHP(peer_id);
  2114. }
  2115. void Server::DenySudoAccess(session_t peer_id)
  2116. {
  2117. NetworkPacket pkt(TOCLIENT_DENY_SUDO_MODE, 0, peer_id);
  2118. Send(&pkt);
  2119. }
  2120. void Server::DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, AccessDeniedCode reason,
  2121. const std::string &str_reason, bool reconnect)
  2122. {
  2123. SendAccessDenied(peer_id, reason, str_reason, reconnect);
  2124. m_clients.event(peer_id, CSE_SetDenied);
  2125. DisconnectPeer(peer_id);
  2126. }
  2127. void Server::DenyAccess(session_t peer_id, AccessDeniedCode reason,
  2128. const std::string &custom_reason)
  2129. {
  2130. SendAccessDenied(peer_id, reason, custom_reason);
  2131. m_clients.event(peer_id, CSE_SetDenied);
  2132. DisconnectPeer(peer_id);
  2133. }
  2134. // 13/03/15: remove this function when protocol version 25 will become
  2135. // the minimum version for MT users, maybe in 1 year
  2136. void Server::DenyAccess_Legacy(session_t peer_id, const std::wstring &reason)
  2137. {
  2138. SendAccessDenied_Legacy(peer_id, reason);
  2139. m_clients.event(peer_id, CSE_SetDenied);
  2140. DisconnectPeer(peer_id);
  2141. }
  2142. void Server::DisconnectPeer(session_t peer_id)
  2143. {
  2144. m_modchannel_mgr->leaveAllChannels(peer_id);
  2145. m_con->DisconnectPeer(peer_id);
  2146. }
  2147. void Server::acceptAuth(session_t peer_id, bool forSudoMode)
  2148. {
  2149. if (!forSudoMode) {
  2150. RemoteClient* client = getClient(peer_id, CS_Invalid);
  2151. NetworkPacket resp_pkt(TOCLIENT_AUTH_ACCEPT, 1 + 6 + 8 + 4, peer_id);
  2152. // Right now, the auth mechs don't change between login and sudo mode.
  2153. u32 sudo_auth_mechs = client->allowed_auth_mechs;
  2154. client->allowed_sudo_mechs = sudo_auth_mechs;
  2155. resp_pkt << v3f(0,0,0) << (u64) m_env->getServerMap().getSeed()
  2156. << g_settings->getFloat("dedicated_server_step")
  2157. << sudo_auth_mechs;
  2158. Send(&resp_pkt);
  2159. m_clients.event(peer_id, CSE_AuthAccept);
  2160. } else {
  2161. NetworkPacket resp_pkt(TOCLIENT_ACCEPT_SUDO_MODE, 1 + 6 + 8 + 4, peer_id);
  2162. // We only support SRP right now
  2163. u32 sudo_auth_mechs = AUTH_MECHANISM_FIRST_SRP;
  2164. resp_pkt << sudo_auth_mechs;
  2165. Send(&resp_pkt);
  2166. m_clients.event(peer_id, CSE_SudoSuccess);
  2167. }
  2168. }
  2169. void Server::DeleteClient(session_t peer_id, ClientDeletionReason reason)
  2170. {
  2171. std::wstring message;
  2172. {
  2173. /*
  2174. Clear references to playing sounds
  2175. */
  2176. for (std::unordered_map<s32, ServerPlayingSound>::iterator
  2177. i = m_playing_sounds.begin(); i != m_playing_sounds.end();) {
  2178. ServerPlayingSound &psound = i->second;
  2179. psound.clients.erase(peer_id);
  2180. if (psound.clients.empty())
  2181. m_playing_sounds.erase(i++);
  2182. else
  2183. ++i;
  2184. }
  2185. // clear formspec info so the next client can't abuse the current state
  2186. m_formspec_state_data.erase(peer_id);
  2187. RemotePlayer *player = m_env->getPlayer(peer_id);
  2188. /* Run scripts and remove from environment */
  2189. if (player) {
  2190. PlayerSAO *playersao = player->getPlayerSAO();
  2191. assert(playersao);
  2192. // inform connected clients
  2193. NetworkPacket notice(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
  2194. // (u16) 1 + std::string represents a vector serialization representation
  2195. notice << (u8) PLAYER_LIST_REMOVE << (u16) 1 << std::string(playersao->getPlayer()->getName());
  2196. m_clients.sendToAll(&notice);
  2197. // run scripts
  2198. m_script->on_leaveplayer(playersao, reason == CDR_TIMEOUT);
  2199. playersao->disconnected();
  2200. }
  2201. /*
  2202. Print out action
  2203. */
  2204. {
  2205. if (player && reason != CDR_DENY) {
  2206. std::ostringstream os(std::ios_base::binary);
  2207. std::vector<session_t> clients = m_clients.getClientIDs();
  2208. for (const session_t client_id : clients) {
  2209. // Get player
  2210. RemotePlayer *player = m_env->getPlayer(client_id);
  2211. if (!player)
  2212. continue;
  2213. // Get name of player
  2214. os << player->getName() << " ";
  2215. }
  2216. std::string name = player->getName();
  2217. actionstream << name << " "
  2218. << (reason == CDR_TIMEOUT ? "times out." : "leaves game.")
  2219. << " List of players: " << os.str() << std::endl;
  2220. if (m_admin_chat)
  2221. m_admin_chat->outgoing_queue.push_back(
  2222. new ChatEventNick(CET_NICK_REMOVE, name));
  2223. }
  2224. }
  2225. {
  2226. MutexAutoLock env_lock(m_env_mutex);
  2227. m_clients.DeleteClient(peer_id);
  2228. }
  2229. }
  2230. // Send leave chat message to all remaining clients
  2231. if (!message.empty()) {
  2232. SendChatMessage(PEER_ID_INEXISTENT,
  2233. ChatMessage(CHATMESSAGE_TYPE_ANNOUNCE, message));
  2234. }
  2235. }
  2236. void Server::UpdateCrafting(RemotePlayer *player)
  2237. {
  2238. // Get a preview for crafting
  2239. ItemStack preview;
  2240. InventoryLocation loc;
  2241. loc.setPlayer(player->getName());
  2242. std::vector<ItemStack> output_replacements;
  2243. getCraftingResult(&player->inventory, preview, output_replacements, false, this);
  2244. m_env->getScriptIface()->item_CraftPredict(preview, player->getPlayerSAO(),
  2245. (&player->inventory)->getList("craft"), loc);
  2246. // Put the new preview in
  2247. InventoryList *plist = player->inventory.getList("craftpreview");
  2248. sanity_check(plist);
  2249. sanity_check(plist->getSize() >= 1);
  2250. plist->changeItem(0, preview);
  2251. }
  2252. void Server::handleChatInterfaceEvent(ChatEvent *evt)
  2253. {
  2254. if (evt->type == CET_NICK_ADD) {
  2255. // The terminal informed us of its nick choice
  2256. m_admin_nick = ((ChatEventNick *)evt)->nick;
  2257. if (!m_script->getAuth(m_admin_nick, NULL, NULL)) {
  2258. errorstream << "You haven't set up an account." << std::endl
  2259. << "Please log in using the client as '"
  2260. << m_admin_nick << "' with a secure password." << std::endl
  2261. << "Until then, you can't execute admin tasks via the console," << std::endl
  2262. << "and everybody can claim the user account instead of you," << std::endl
  2263. << "giving them full control over this server." << std::endl;
  2264. }
  2265. } else {
  2266. assert(evt->type == CET_CHAT);
  2267. handleAdminChat((ChatEventChat *)evt);
  2268. }
  2269. }
  2270. std::wstring Server::handleChat(const std::string &name, const std::wstring &wname,
  2271. std::wstring wmessage, bool check_shout_priv, RemotePlayer *player)
  2272. {
  2273. // If something goes wrong, this player is to blame
  2274. RollbackScopeActor rollback_scope(m_rollback,
  2275. std::string("player:") + name);
  2276. if (g_settings->getBool("strip_color_codes"))
  2277. wmessage = unescape_enriched(wmessage);
  2278. if (player) {
  2279. switch (player->canSendChatMessage()) {
  2280. case RPLAYER_CHATRESULT_FLOODING: {
  2281. std::wstringstream ws;
  2282. ws << L"You cannot send more messages. You are limited to "
  2283. << g_settings->getFloat("chat_message_limit_per_10sec")
  2284. << L" messages per 10 seconds.";
  2285. return ws.str();
  2286. }
  2287. case RPLAYER_CHATRESULT_KICK:
  2288. DenyAccess_Legacy(player->getPeerId(),
  2289. L"You have been kicked due to message flooding.");
  2290. return L"";
  2291. case RPLAYER_CHATRESULT_OK:
  2292. break;
  2293. default:
  2294. FATAL_ERROR("Unhandled chat filtering result found.");
  2295. }
  2296. }
  2297. if (m_max_chatmessage_length > 0
  2298. && wmessage.length() > m_max_chatmessage_length) {
  2299. return L"Your message exceed the maximum chat message limit set on the server. "
  2300. L"It was refused. Send a shorter message";
  2301. }
  2302. // Run script hook, exit if script ate the chat message
  2303. if (m_script->on_chat_message(name, wide_to_utf8(wmessage)))
  2304. return L"";
  2305. // Line to send
  2306. std::wstring line;
  2307. // Whether to send line to the player that sent the message, or to all players
  2308. bool broadcast_line = true;
  2309. if (check_shout_priv && !checkPriv(name, "shout")) {
  2310. line += L"-!- You don't have permission to shout.";
  2311. broadcast_line = false;
  2312. } else {
  2313. line += L"<";
  2314. line += wname;
  2315. line += L"> ";
  2316. line += wmessage;
  2317. }
  2318. /*
  2319. Tell calling method to send the message to sender
  2320. */
  2321. if (!broadcast_line)
  2322. return line;
  2323. /*
  2324. Send the message to others
  2325. */
  2326. actionstream << "CHAT: " << wide_to_narrow(unescape_enriched(line)) << std::endl;
  2327. std::vector<session_t> clients = m_clients.getClientIDs();
  2328. /*
  2329. Send the message back to the inital sender
  2330. if they are using protocol version >= 29
  2331. */
  2332. session_t peer_id_to_avoid_sending =
  2333. (player ? player->getPeerId() : PEER_ID_INEXISTENT);
  2334. if (player && player->protocol_version >= 29)
  2335. peer_id_to_avoid_sending = PEER_ID_INEXISTENT;
  2336. for (u16 cid : clients) {
  2337. if (cid != peer_id_to_avoid_sending)
  2338. SendChatMessage(cid, ChatMessage(line));
  2339. }
  2340. return L"";
  2341. }
  2342. void Server::handleAdminChat(const ChatEventChat *evt)
  2343. {
  2344. std::string name = evt->nick;
  2345. std::wstring wname = utf8_to_wide(name);
  2346. std::wstring wmessage = evt->evt_msg;
  2347. std::wstring answer = handleChat(name, wname, wmessage);
  2348. // If asked to send answer to sender
  2349. if (!answer.empty()) {
  2350. m_admin_chat->outgoing_queue.push_back(new ChatEventChat("", answer));
  2351. }
  2352. }
  2353. RemoteClient *Server::getClient(session_t peer_id, ClientState state_min)
  2354. {
  2355. RemoteClient *client = getClientNoEx(peer_id,state_min);
  2356. if(!client)
  2357. throw ClientNotFoundException("Client not found");
  2358. return client;
  2359. }
  2360. RemoteClient *Server::getClientNoEx(session_t peer_id, ClientState state_min)
  2361. {
  2362. return m_clients.getClientNoEx(peer_id, state_min);
  2363. }
  2364. std::string Server::getPlayerName(session_t peer_id)
  2365. {
  2366. RemotePlayer *player = m_env->getPlayer(peer_id);
  2367. if (!player)
  2368. return "[id="+itos(peer_id)+"]";
  2369. return player->getName();
  2370. }
  2371. PlayerSAO *Server::getPlayerSAO(session_t peer_id)
  2372. {
  2373. RemotePlayer *player = m_env->getPlayer(peer_id);
  2374. if (!player)
  2375. return NULL;
  2376. return player->getPlayerSAO();
  2377. }
  2378. std::wstring Server::getStatusString()
  2379. {
  2380. std::wostringstream os(std::ios_base::binary);
  2381. os<<L"# Server: ";
  2382. // Version
  2383. os<<L"version="<<narrow_to_wide(g_version_string);
  2384. // Uptime
  2385. os<<L", uptime="<<m_uptime.get();
  2386. // Max lag estimate
  2387. os<<L", max_lag="<<m_env->getMaxLagEstimate();
  2388. // Information about clients
  2389. bool first = true;
  2390. os<<L", clients={";
  2391. std::vector<session_t> clients = m_clients.getClientIDs();
  2392. for (session_t client_id : clients) {
  2393. // Get player
  2394. RemotePlayer *player = m_env->getPlayer(client_id);
  2395. // Get name of player
  2396. std::wstring name = L"unknown";
  2397. if (player)
  2398. name = narrow_to_wide(player->getName());
  2399. // Add name to information string
  2400. if(!first)
  2401. os << L", ";
  2402. else
  2403. first = false;
  2404. os << name;
  2405. }
  2406. os << L"}";
  2407. if (!((ServerMap*)(&m_env->getMap()))->isSavingEnabled())
  2408. os<<std::endl<<L"# Server: "<<" WARNING: Map saving is disabled.";
  2409. if (!g_settings->get("motd").empty())
  2410. os<<std::endl<<L"# Server: "<<narrow_to_wide(g_settings->get("motd"));
  2411. return os.str();
  2412. }
  2413. std::set<std::string> Server::getPlayerEffectivePrivs(const std::string &name)
  2414. {
  2415. std::set<std::string> privs;
  2416. m_script->getAuth(name, NULL, &privs);
  2417. return privs;
  2418. }
  2419. bool Server::checkPriv(const std::string &name, const std::string &priv)
  2420. {
  2421. std::set<std::string> privs = getPlayerEffectivePrivs(name);
  2422. return (privs.count(priv) != 0);
  2423. }
  2424. void Server::reportPrivsModified(const std::string &name)
  2425. {
  2426. if (name.empty()) {
  2427. std::vector<session_t> clients = m_clients.getClientIDs();
  2428. for (const session_t client_id : clients) {
  2429. RemotePlayer *player = m_env->getPlayer(client_id);
  2430. reportPrivsModified(player->getName());
  2431. }
  2432. } else {
  2433. RemotePlayer *player = m_env->getPlayer(name.c_str());
  2434. if (!player)
  2435. return;
  2436. SendPlayerPrivileges(player->getPeerId());
  2437. PlayerSAO *sao = player->getPlayerSAO();
  2438. if(!sao)
  2439. return;
  2440. sao->updatePrivileges(
  2441. getPlayerEffectivePrivs(name),
  2442. isSingleplayer());
  2443. }
  2444. }
  2445. void Server::reportInventoryFormspecModified(const std::string &name)
  2446. {
  2447. RemotePlayer *player = m_env->getPlayer(name.c_str());
  2448. if (!player)
  2449. return;
  2450. SendPlayerInventoryFormspec(player->getPeerId());
  2451. }
  2452. void Server::setIpBanned(const std::string &ip, const std::string &name)
  2453. {
  2454. m_banmanager->add(ip, name);
  2455. }
  2456. void Server::unsetIpBanned(const std::string &ip_or_name)
  2457. {
  2458. m_banmanager->remove(ip_or_name);
  2459. }
  2460. std::string Server::getBanDescription(const std::string &ip_or_name)
  2461. {
  2462. return m_banmanager->getBanDescription(ip_or_name);
  2463. }
  2464. void Server::notifyPlayer(const char *name, const std::wstring &msg)
  2465. {
  2466. // m_env will be NULL if the server is initializing
  2467. if (!m_env)
  2468. return;
  2469. if (m_admin_nick == name && !m_admin_nick.empty()) {
  2470. m_admin_chat->outgoing_queue.push_back(new ChatEventChat("", msg));
  2471. }
  2472. RemotePlayer *player = m_env->getPlayer(name);
  2473. if (!player) {
  2474. return;
  2475. }
  2476. if (player->getPeerId() == PEER_ID_INEXISTENT)
  2477. return;
  2478. SendChatMessage(player->getPeerId(), ChatMessage(msg));
  2479. }
  2480. bool Server::showFormspec(const char *playername, const std::string &formspec,
  2481. const std::string &formname)
  2482. {
  2483. // m_env will be NULL if the server is initializing
  2484. if (!m_env)
  2485. return false;
  2486. RemotePlayer *player = m_env->getPlayer(playername);
  2487. if (!player)
  2488. return false;
  2489. SendShowFormspecMessage(player->getPeerId(), formspec, formname);
  2490. return true;
  2491. }
  2492. u32 Server::hudAdd(RemotePlayer *player, HudElement *form)
  2493. {
  2494. if (!player)
  2495. return -1;
  2496. u32 id = player->addHud(form);
  2497. SendHUDAdd(player->getPeerId(), id, form);
  2498. return id;
  2499. }
  2500. bool Server::hudRemove(RemotePlayer *player, u32 id) {
  2501. if (!player)
  2502. return false;
  2503. HudElement* todel = player->removeHud(id);
  2504. if (!todel)
  2505. return false;
  2506. delete todel;
  2507. SendHUDRemove(player->getPeerId(), id);
  2508. return true;
  2509. }
  2510. bool Server::hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *data)
  2511. {
  2512. if (!player)
  2513. return false;
  2514. SendHUDChange(player->getPeerId(), id, stat, data);
  2515. return true;
  2516. }
  2517. bool Server::hudSetFlags(RemotePlayer *player, u32 flags, u32 mask)
  2518. {
  2519. if (!player)
  2520. return false;
  2521. SendHUDSetFlags(player->getPeerId(), flags, mask);
  2522. player->hud_flags &= ~mask;
  2523. player->hud_flags |= flags;
  2524. PlayerSAO* playersao = player->getPlayerSAO();
  2525. if (!playersao)
  2526. return false;
  2527. m_script->player_event(playersao, "hud_changed");
  2528. return true;
  2529. }
  2530. bool Server::hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount)
  2531. {
  2532. if (!player)
  2533. return false;
  2534. if (hotbar_itemcount <= 0 || hotbar_itemcount > HUD_HOTBAR_ITEMCOUNT_MAX)
  2535. return false;
  2536. player->setHotbarItemcount(hotbar_itemcount);
  2537. std::ostringstream os(std::ios::binary);
  2538. writeS32(os, hotbar_itemcount);
  2539. SendHUDSetParam(player->getPeerId(), HUD_PARAM_HOTBAR_ITEMCOUNT, os.str());
  2540. return true;
  2541. }
  2542. void Server::hudSetHotbarImage(RemotePlayer *player, std::string name)
  2543. {
  2544. if (!player)
  2545. return;
  2546. player->setHotbarImage(name);
  2547. SendHUDSetParam(player->getPeerId(), HUD_PARAM_HOTBAR_IMAGE, name);
  2548. }
  2549. void Server::hudSetHotbarSelectedImage(RemotePlayer *player, std::string name)
  2550. {
  2551. if (!player)
  2552. return;
  2553. player->setHotbarSelectedImage(name);
  2554. SendHUDSetParam(player->getPeerId(), HUD_PARAM_HOTBAR_SELECTED_IMAGE, name);
  2555. }
  2556. Address Server::getPeerAddress(session_t peer_id)
  2557. {
  2558. return m_con->GetPeerAddress(peer_id);
  2559. }
  2560. void Server::setLocalPlayerAnimations(RemotePlayer *player,
  2561. v2s32 animation_frames[4], f32 frame_speed)
  2562. {
  2563. sanity_check(player);
  2564. player->setLocalAnimations(animation_frames, frame_speed);
  2565. SendLocalPlayerAnimations(player->getPeerId(), animation_frames, frame_speed);
  2566. }
  2567. void Server::setPlayerEyeOffset(RemotePlayer *player, const v3f &first, const v3f &third)
  2568. {
  2569. sanity_check(player);
  2570. player->eye_offset_first = first;
  2571. player->eye_offset_third = third;
  2572. SendEyeOffset(player->getPeerId(), first, third);
  2573. }
  2574. void Server::setSky(RemotePlayer *player, const video::SColor &bgcolor,
  2575. const std::string &type, const std::vector<std::string> &params,
  2576. bool &clouds)
  2577. {
  2578. sanity_check(player);
  2579. player->setSky(bgcolor, type, params, clouds);
  2580. SendSetSky(player->getPeerId(), bgcolor, type, params, clouds);
  2581. }
  2582. void Server::setClouds(RemotePlayer *player, const CloudParams &params)
  2583. {
  2584. sanity_check(player);
  2585. player->setCloudParams(params);
  2586. SendCloudParams(player->getPeerId(), params);
  2587. }
  2588. bool Server::overrideDayNightRatio(RemotePlayer *player, bool do_override,
  2589. float ratio)
  2590. {
  2591. if (!player)
  2592. return false;
  2593. player->overrideDayNightRatio(do_override, ratio);
  2594. SendOverrideDayNightRatio(player->getPeerId(), do_override, ratio);
  2595. return true;
  2596. }
  2597. void Server::notifyPlayers(const std::wstring &msg)
  2598. {
  2599. SendChatMessage(PEER_ID_INEXISTENT, ChatMessage(msg));
  2600. }
  2601. void Server::spawnParticle(const std::string &playername, v3f pos,
  2602. v3f velocity, v3f acceleration,
  2603. float expirationtime, float size, bool
  2604. collisiondetection, bool collision_removal,
  2605. bool vertical, const std::string &texture,
  2606. const struct TileAnimationParams &animation, u8 glow)
  2607. {
  2608. // m_env will be NULL if the server is initializing
  2609. if (!m_env)
  2610. return;
  2611. session_t peer_id = PEER_ID_INEXISTENT;
  2612. u16 proto_ver = 0;
  2613. if (!playername.empty()) {
  2614. RemotePlayer *player = m_env->getPlayer(playername.c_str());
  2615. if (!player)
  2616. return;
  2617. peer_id = player->getPeerId();
  2618. proto_ver = player->protocol_version;
  2619. }
  2620. SendSpawnParticle(peer_id, proto_ver, pos, velocity, acceleration,
  2621. expirationtime, size, collisiondetection,
  2622. collision_removal, vertical, texture, animation, glow);
  2623. }
  2624. u32 Server::addParticleSpawner(u16 amount, float spawntime,
  2625. v3f minpos, v3f maxpos, v3f minvel, v3f maxvel, v3f minacc, v3f maxacc,
  2626. float minexptime, float maxexptime, float minsize, float maxsize,
  2627. bool collisiondetection, bool collision_removal,
  2628. ServerActiveObject *attached, bool vertical, const std::string &texture,
  2629. const std::string &playername, const struct TileAnimationParams &animation,
  2630. u8 glow)
  2631. {
  2632. // m_env will be NULL if the server is initializing
  2633. if (!m_env)
  2634. return -1;
  2635. session_t peer_id = PEER_ID_INEXISTENT;
  2636. u16 proto_ver = 0;
  2637. if (!playername.empty()) {
  2638. RemotePlayer *player = m_env->getPlayer(playername.c_str());
  2639. if (!player)
  2640. return -1;
  2641. peer_id = player->getPeerId();
  2642. proto_ver = player->protocol_version;
  2643. }
  2644. u16 attached_id = attached ? attached->getId() : 0;
  2645. u32 id;
  2646. if (attached_id == 0)
  2647. id = m_env->addParticleSpawner(spawntime);
  2648. else
  2649. id = m_env->addParticleSpawner(spawntime, attached_id);
  2650. SendAddParticleSpawner(peer_id, proto_ver, amount, spawntime,
  2651. minpos, maxpos, minvel, maxvel, minacc, maxacc,
  2652. minexptime, maxexptime, minsize, maxsize,
  2653. collisiondetection, collision_removal, attached_id, vertical,
  2654. texture, id, animation, glow);
  2655. return id;
  2656. }
  2657. void Server::deleteParticleSpawner(const std::string &playername, u32 id)
  2658. {
  2659. // m_env will be NULL if the server is initializing
  2660. if (!m_env)
  2661. throw ServerError("Can't delete particle spawners during initialisation!");
  2662. session_t peer_id = PEER_ID_INEXISTENT;
  2663. if (!playername.empty()) {
  2664. RemotePlayer *player = m_env->getPlayer(playername.c_str());
  2665. if (!player)
  2666. return;
  2667. peer_id = player->getPeerId();
  2668. }
  2669. m_env->deleteParticleSpawner(id);
  2670. SendDeleteParticleSpawner(peer_id, id);
  2671. }
  2672. Inventory* Server::createDetachedInventory(const std::string &name, const std::string &player)
  2673. {
  2674. if(m_detached_inventories.count(name) > 0){
  2675. infostream<<"Server clearing detached inventory \""<<name<<"\""<<std::endl;
  2676. delete m_detached_inventories[name];
  2677. } else {
  2678. infostream<<"Server creating detached inventory \""<<name<<"\""<<std::endl;
  2679. }
  2680. Inventory *inv = new Inventory(m_itemdef);
  2681. sanity_check(inv);
  2682. m_detached_inventories[name] = inv;
  2683. m_detached_inventories_player[name] = player;
  2684. //TODO find a better way to do this
  2685. sendDetachedInventory(name,PEER_ID_INEXISTENT);
  2686. return inv;
  2687. }
  2688. // actions: time-reversed list
  2689. // Return value: success/failure
  2690. bool Server::rollbackRevertActions(const std::list<RollbackAction> &actions,
  2691. std::list<std::string> *log)
  2692. {
  2693. infostream<<"Server::rollbackRevertActions(len="<<actions.size()<<")"<<std::endl;
  2694. ServerMap *map = (ServerMap*)(&m_env->getMap());
  2695. // Fail if no actions to handle
  2696. if(actions.empty()){
  2697. log->push_back("Nothing to do.");
  2698. return false;
  2699. }
  2700. int num_tried = 0;
  2701. int num_failed = 0;
  2702. for (const RollbackAction &action : actions) {
  2703. num_tried++;
  2704. bool success = action.applyRevert(map, this, this);
  2705. if(!success){
  2706. num_failed++;
  2707. std::ostringstream os;
  2708. os<<"Revert of step ("<<num_tried<<") "<<action.toString()<<" failed";
  2709. infostream<<"Map::rollbackRevertActions(): "<<os.str()<<std::endl;
  2710. if (log)
  2711. log->push_back(os.str());
  2712. }else{
  2713. std::ostringstream os;
  2714. os<<"Successfully reverted step ("<<num_tried<<") "<<action.toString();
  2715. infostream<<"Map::rollbackRevertActions(): "<<os.str()<<std::endl;
  2716. if (log)
  2717. log->push_back(os.str());
  2718. }
  2719. }
  2720. infostream<<"Map::rollbackRevertActions(): "<<num_failed<<"/"<<num_tried
  2721. <<" failed"<<std::endl;
  2722. // Call it done if less than half failed
  2723. return num_failed <= num_tried/2;
  2724. }
  2725. // IGameDef interface
  2726. // Under envlock
  2727. IItemDefManager *Server::getItemDefManager()
  2728. {
  2729. return m_itemdef;
  2730. }
  2731. const NodeDefManager *Server::getNodeDefManager()
  2732. {
  2733. return m_nodedef;
  2734. }
  2735. ICraftDefManager *Server::getCraftDefManager()
  2736. {
  2737. return m_craftdef;
  2738. }
  2739. u16 Server::allocateUnknownNodeId(const std::string &name)
  2740. {
  2741. return m_nodedef->allocateDummy(name);
  2742. }
  2743. MtEventManager *Server::getEventManager()
  2744. {
  2745. return m_event;
  2746. }
  2747. IWritableItemDefManager *Server::getWritableItemDefManager()
  2748. {
  2749. return m_itemdef;
  2750. }
  2751. NodeDefManager *Server::getWritableNodeDefManager()
  2752. {
  2753. return m_nodedef;
  2754. }
  2755. IWritableCraftDefManager *Server::getWritableCraftDefManager()
  2756. {
  2757. return m_craftdef;
  2758. }
  2759. const std::vector<ModSpec> & Server::getMods() const
  2760. {
  2761. return m_modmgr->getMods();
  2762. }
  2763. const ModSpec *Server::getModSpec(const std::string &modname) const
  2764. {
  2765. return m_modmgr->getModSpec(modname);
  2766. }
  2767. void Server::getModNames(std::vector<std::string> &modlist)
  2768. {
  2769. m_modmgr->getModNames(modlist);
  2770. }
  2771. std::string Server::getBuiltinLuaPath()
  2772. {
  2773. return porting::path_share + DIR_DELIM + "builtin";
  2774. }
  2775. std::string Server::getModStoragePath() const
  2776. {
  2777. return m_path_world + DIR_DELIM + "mod_storage";
  2778. }
  2779. v3f Server::findSpawnPos()
  2780. {
  2781. ServerMap &map = m_env->getServerMap();
  2782. v3f nodeposf;
  2783. if (g_settings->getV3FNoEx("static_spawnpoint", nodeposf)) {
  2784. return nodeposf * BS;
  2785. }
  2786. bool is_good = false;
  2787. // Limit spawn range to mapgen edges (determined by 'mapgen_limit')
  2788. s32 range_max = map.getMapgenParams()->getSpawnRangeMax();
  2789. // Try to find a good place a few times
  2790. for(s32 i = 0; i < 4000 && !is_good; i++) {
  2791. s32 range = MYMIN(1 + i, range_max);
  2792. // We're going to try to throw the player to this position
  2793. v2s16 nodepos2d = v2s16(
  2794. -range + (myrand() % (range * 2)),
  2795. -range + (myrand() % (range * 2)));
  2796. // Get spawn level at point
  2797. s16 spawn_level = m_emerge->getSpawnLevelAtPoint(nodepos2d);
  2798. // Continue if MAX_MAP_GENERATION_LIMIT was returned by
  2799. // the mapgen to signify an unsuitable spawn position
  2800. if (spawn_level == MAX_MAP_GENERATION_LIMIT)
  2801. continue;
  2802. v3s16 nodepos(nodepos2d.X, spawn_level, nodepos2d.Y);
  2803. s32 air_count = 0;
  2804. for (s32 i = 0; i < 10; i++) {
  2805. v3s16 blockpos = getNodeBlockPos(nodepos);
  2806. map.emergeBlock(blockpos, true);
  2807. content_t c = map.getNodeNoEx(nodepos).getContent();
  2808. if (c == CONTENT_AIR || c == CONTENT_IGNORE) {
  2809. air_count++;
  2810. if (air_count >= 2) {
  2811. nodeposf = intToFloat(nodepos, BS);
  2812. // Don't spawn the player outside map boundaries
  2813. if (objectpos_over_limit(nodeposf))
  2814. continue;
  2815. is_good = true;
  2816. break;
  2817. }
  2818. }
  2819. nodepos.Y++;
  2820. }
  2821. }
  2822. return nodeposf;
  2823. }
  2824. void Server::requestShutdown(const std::string &msg, bool reconnect, float delay)
  2825. {
  2826. m_shutdown_timer = delay;
  2827. m_shutdown_msg = msg;
  2828. m_shutdown_ask_reconnect = reconnect;
  2829. if (delay == 0.0f) {
  2830. // No delay, shutdown immediately
  2831. m_shutdown_requested = true;
  2832. // only print to the infostream, a chat message saying
  2833. // "Server Shutting Down" is sent when the server destructs.
  2834. infostream << "*** Immediate Server shutdown requested." << std::endl;
  2835. } else if (delay < 0.0f && m_shutdown_timer > 0.0f) {
  2836. // Negative delay, cancel shutdown if requested
  2837. m_shutdown_timer = 0.0f;
  2838. m_shutdown_msg = "";
  2839. m_shutdown_ask_reconnect = false;
  2840. m_shutdown_requested = false;
  2841. std::wstringstream ws;
  2842. ws << L"*** Server shutdown canceled.";
  2843. infostream << wide_to_utf8(ws.str()).c_str() << std::endl;
  2844. SendChatMessage(PEER_ID_INEXISTENT, ws.str());
  2845. } else if (delay > 0.0f) {
  2846. // Positive delay, tell the clients when the server will shut down
  2847. std::wstringstream ws;
  2848. ws << L"*** Server shutting down in "
  2849. << duration_to_string(myround(m_shutdown_timer)).c_str()
  2850. << ".";
  2851. infostream << wide_to_utf8(ws.str()).c_str() << std::endl;
  2852. SendChatMessage(PEER_ID_INEXISTENT, ws.str());
  2853. }
  2854. }
  2855. PlayerSAO* Server::emergePlayer(const char *name, session_t peer_id, u16 proto_version)
  2856. {
  2857. /*
  2858. Try to get an existing player
  2859. */
  2860. RemotePlayer *player = m_env->getPlayer(name);
  2861. // If player is already connected, cancel
  2862. if (player && player->getPeerId() != PEER_ID_INEXISTENT) {
  2863. infostream<<"emergePlayer(): Player already connected"<<std::endl;
  2864. return NULL;
  2865. }
  2866. /*
  2867. If player with the wanted peer_id already exists, cancel.
  2868. */
  2869. if (m_env->getPlayer(peer_id)) {
  2870. infostream<<"emergePlayer(): Player with wrong name but same"
  2871. " peer_id already exists"<<std::endl;
  2872. return NULL;
  2873. }
  2874. if (!player) {
  2875. player = new RemotePlayer(name, idef());
  2876. }
  2877. bool newplayer = false;
  2878. // Load player
  2879. PlayerSAO *playersao = m_env->loadPlayer(player, &newplayer, peer_id, isSingleplayer());
  2880. // Complete init with server parts
  2881. playersao->finalize(player, getPlayerEffectivePrivs(player->getName()));
  2882. player->protocol_version = proto_version;
  2883. /* Run scripts */
  2884. if (newplayer) {
  2885. m_script->on_newplayer(playersao);
  2886. }
  2887. return playersao;
  2888. }
  2889. bool Server::registerModStorage(ModMetadata *storage)
  2890. {
  2891. if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
  2892. errorstream << "Unable to register same mod storage twice. Storage name: "
  2893. << storage->getModName() << std::endl;
  2894. return false;
  2895. }
  2896. m_mod_storages[storage->getModName()] = storage;
  2897. return true;
  2898. }
  2899. void Server::unregisterModStorage(const std::string &name)
  2900. {
  2901. std::unordered_map<std::string, ModMetadata *>::const_iterator it = m_mod_storages.find(name);
  2902. if (it != m_mod_storages.end()) {
  2903. // Save unconditionaly on unregistration
  2904. it->second->save(getModStoragePath());
  2905. m_mod_storages.erase(name);
  2906. }
  2907. }
  2908. void dedicated_server_loop(Server &server, bool &kill)
  2909. {
  2910. verbosestream<<"dedicated_server_loop()"<<std::endl;
  2911. IntervalLimiter m_profiler_interval;
  2912. static thread_local const float steplen =
  2913. g_settings->getFloat("dedicated_server_step");
  2914. static thread_local const float profiler_print_interval =
  2915. g_settings->getFloat("profiler_print_interval");
  2916. for(;;) {
  2917. // This is kind of a hack but can be done like this
  2918. // because server.step() is very light
  2919. {
  2920. ScopeProfiler sp(g_profiler, "dedicated server sleep");
  2921. sleep_ms((int)(steplen*1000.0));
  2922. }
  2923. server.step(steplen);
  2924. if (server.getShutdownRequested() || kill)
  2925. break;
  2926. /*
  2927. Profiler
  2928. */
  2929. if (profiler_print_interval != 0) {
  2930. if(m_profiler_interval.step(steplen, profiler_print_interval))
  2931. {
  2932. infostream<<"Profiler:"<<std::endl;
  2933. g_profiler->print(infostream);
  2934. g_profiler->clear();
  2935. }
  2936. }
  2937. }
  2938. infostream << "Dedicated server quitting" << std::endl;
  2939. #if USE_CURL
  2940. if (g_settings->getBool("server_announce"))
  2941. ServerList::sendAnnounce(ServerList::AA_DELETE,
  2942. server.m_bind_addr.getPort());
  2943. #endif
  2944. }
  2945. /*
  2946. * Mod channels
  2947. */
  2948. bool Server::joinModChannel(const std::string &channel)
  2949. {
  2950. return m_modchannel_mgr->joinChannel(channel, PEER_ID_SERVER) &&
  2951. m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE);
  2952. }
  2953. bool Server::leaveModChannel(const std::string &channel)
  2954. {
  2955. return m_modchannel_mgr->leaveChannel(channel, PEER_ID_SERVER);
  2956. }
  2957. bool Server::sendModChannelMessage(const std::string &channel, const std::string &message)
  2958. {
  2959. if (!m_modchannel_mgr->canWriteOnChannel(channel))
  2960. return false;
  2961. broadcastModChannelMessage(channel, message, PEER_ID_SERVER);
  2962. return true;
  2963. }
  2964. ModChannel* Server::getModChannel(const std::string &channel)
  2965. {
  2966. return m_modchannel_mgr->getModChannel(channel);
  2967. }
  2968. void Server::broadcastModChannelMessage(const std::string &channel,
  2969. const std::string &message, session_t from_peer)
  2970. {
  2971. const std::vector<u16> &peers = m_modchannel_mgr->getChannelPeers(channel);
  2972. if (peers.empty())
  2973. return;
  2974. if (message.size() > STRING_MAX_LEN) {
  2975. warningstream << "ModChannel message too long, dropping before sending "
  2976. << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: "
  2977. << channel << ")" << std::endl;
  2978. return;
  2979. }
  2980. std::string sender;
  2981. if (from_peer != PEER_ID_SERVER) {
  2982. sender = getPlayerName(from_peer);
  2983. }
  2984. NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_MSG,
  2985. 2 + channel.size() + 2 + sender.size() + 2 + message.size());
  2986. resp_pkt << channel << sender << message;
  2987. for (session_t peer_id : peers) {
  2988. // Ignore sender
  2989. if (peer_id == from_peer)
  2990. continue;
  2991. Send(peer_id, &resp_pkt);
  2992. }
  2993. if (from_peer != PEER_ID_SERVER) {
  2994. m_script->on_modchannel_message(channel, sender, message);
  2995. }
  2996. }