server.cpp 102 KB

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