server.cpp 105 KB

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