server.cpp 94 KB

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