server.cpp 103 KB

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