server.cpp 109 KB

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