server.cpp 98 KB

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