server.cpp 108 KB

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