server.cpp 95 KB

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