server.cpp 95 KB

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