server.cpp 89 KB

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