server.cpp 93 KB

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