server.cpp 109 KB

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