server.cpp 116 KB

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