server.cpp 102 KB

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