server.cpp 109 KB

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