clientpackethandler.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  1. /*
  2. Minetest
  3. Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
  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 "client/client.h"
  17. #include "util/base64.h"
  18. #include "client/camera.h"
  19. #include "chatmessage.h"
  20. #include "client/clientmedia.h"
  21. #include "log.h"
  22. #include "map.h"
  23. #include "mapsector.h"
  24. #include "client/minimap.h"
  25. #include "modchannels.h"
  26. #include "nodedef.h"
  27. #include "serialization.h"
  28. #include "server.h"
  29. #include "util/strfnd.h"
  30. #include "client/clientevent.h"
  31. #include "client/sound.h"
  32. #include "network/clientopcodes.h"
  33. #include "network/connection.h"
  34. #include "script/scripting_client.h"
  35. #include "util/serialize.h"
  36. #include "util/srp.h"
  37. #include "util/sha1.h"
  38. #include "tileanimation.h"
  39. #include "gettext.h"
  40. #include "skyparams.h"
  41. #include <memory>
  42. void Client::handleCommand_Deprecated(NetworkPacket* pkt)
  43. {
  44. infostream << "Got deprecated command "
  45. << toClientCommandTable[pkt->getCommand()].name << " from peer "
  46. << pkt->getPeerId() << "!" << std::endl;
  47. }
  48. void Client::handleCommand_Hello(NetworkPacket* pkt)
  49. {
  50. if (pkt->getSize() < 1)
  51. return;
  52. u8 serialization_ver;
  53. u16 proto_ver;
  54. u16 compression_mode;
  55. u32 auth_mechs;
  56. std::string username_legacy; // for case insensitivity
  57. *pkt >> serialization_ver >> compression_mode >> proto_ver
  58. >> auth_mechs >> username_legacy;
  59. // Chose an auth method we support
  60. AuthMechanism chosen_auth_mechanism = choseAuthMech(auth_mechs);
  61. infostream << "Client: TOCLIENT_HELLO received with "
  62. << "serialization_ver=" << (u32)serialization_ver
  63. << ", auth_mechs=" << auth_mechs
  64. << ", proto_ver=" << proto_ver
  65. << ", compression_mode=" << compression_mode
  66. << ". Doing auth with mech " << chosen_auth_mechanism << std::endl;
  67. if (!ser_ver_supported(serialization_ver)) {
  68. infostream << "Client: TOCLIENT_HELLO: Server sent "
  69. << "unsupported ser_fmt_ver"<< std::endl;
  70. return;
  71. }
  72. m_server_ser_ver = serialization_ver;
  73. m_proto_ver = proto_ver;
  74. //TODO verify that username_legacy matches sent username, only
  75. // differs in casing (make both uppercase and compare)
  76. // This is only neccessary though when we actually want to add casing support
  77. if (m_chosen_auth_mech != AUTH_MECHANISM_NONE) {
  78. // we received a TOCLIENT_HELLO while auth was already going on
  79. errorstream << "Client: TOCLIENT_HELLO while auth was already going on"
  80. << "(chosen_mech=" << m_chosen_auth_mech << ")." << std::endl;
  81. if (m_chosen_auth_mech == AUTH_MECHANISM_SRP ||
  82. m_chosen_auth_mech == AUTH_MECHANISM_LEGACY_PASSWORD) {
  83. srp_user_delete((SRPUser *) m_auth_data);
  84. m_auth_data = 0;
  85. }
  86. }
  87. // Authenticate using that method, or abort if there wasn't any method found
  88. if (chosen_auth_mechanism != AUTH_MECHANISM_NONE) {
  89. bool is_register = chosen_auth_mechanism == AUTH_MECHANISM_FIRST_SRP;
  90. ELoginRegister mode = is_register ? ELoginRegister::Register : ELoginRegister::Login;
  91. if (m_allow_login_or_register != ELoginRegister::Any &&
  92. m_allow_login_or_register != mode) {
  93. m_chosen_auth_mech = AUTH_MECHANISM_NONE;
  94. m_access_denied = true;
  95. if (m_allow_login_or_register == ELoginRegister::Login) {
  96. m_access_denied_reason =
  97. gettext("Name is not registered. To create an account on this server, click 'Register'");
  98. } else {
  99. m_access_denied_reason =
  100. gettext("Name is taken. Please choose another name");
  101. }
  102. m_con->Disconnect();
  103. } else {
  104. startAuth(chosen_auth_mechanism);
  105. }
  106. } else {
  107. m_chosen_auth_mech = AUTH_MECHANISM_NONE;
  108. m_access_denied = true;
  109. m_access_denied_reason = "Unknown";
  110. m_con->Disconnect();
  111. }
  112. }
  113. void Client::handleCommand_AuthAccept(NetworkPacket* pkt)
  114. {
  115. deleteAuthData();
  116. v3f playerpos;
  117. *pkt >> playerpos >> m_map_seed >> m_recommended_send_interval
  118. >> m_sudo_auth_methods;
  119. playerpos -= v3f(0, BS / 2, 0);
  120. // Set player position
  121. LocalPlayer *player = m_env.getLocalPlayer();
  122. assert(player != NULL);
  123. player->setPosition(playerpos);
  124. infostream << "Client: received map seed: " << m_map_seed << std::endl;
  125. infostream << "Client: received recommended send interval "
  126. << m_recommended_send_interval<<std::endl;
  127. // Reply to server
  128. /*~ DO NOT TRANSLATE THIS LITERALLY!
  129. This is a special string which needs to contain the translation's
  130. language code (e.g. "de" for German). */
  131. std::string lang = gettext("LANG_CODE");
  132. if (lang == "LANG_CODE")
  133. lang.clear();
  134. NetworkPacket resp_pkt(TOSERVER_INIT2, sizeof(u16) + lang.size());
  135. resp_pkt << lang;
  136. Send(&resp_pkt);
  137. m_state = LC_Init;
  138. }
  139. void Client::handleCommand_AcceptSudoMode(NetworkPacket* pkt)
  140. {
  141. deleteAuthData();
  142. m_password = m_new_password;
  143. verbosestream << "Client: Received TOCLIENT_ACCEPT_SUDO_MODE." << std::endl;
  144. // send packet to actually set the password
  145. startAuth(AUTH_MECHANISM_FIRST_SRP);
  146. // reset again
  147. m_chosen_auth_mech = AUTH_MECHANISM_NONE;
  148. }
  149. void Client::handleCommand_DenySudoMode(NetworkPacket* pkt)
  150. {
  151. ChatMessage *chatMessage = new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  152. L"Password change denied. Password NOT changed.");
  153. pushToChatQueue(chatMessage);
  154. // reset everything and be sad
  155. deleteAuthData();
  156. }
  157. void Client::handleCommand_AccessDenied(NetworkPacket* pkt)
  158. {
  159. // The server didn't like our password. Note, this needs
  160. // to be processed even if the serialisation format has
  161. // not been agreed yet, the same as TOCLIENT_INIT.
  162. m_access_denied = true;
  163. m_access_denied_reason = "Unknown";
  164. if (pkt->getCommand() != TOCLIENT_ACCESS_DENIED) {
  165. // Legacy code from 0.4.12 and older but is still used
  166. // in some places of the server code
  167. if (pkt->getSize() >= 2) {
  168. std::wstring wide_reason;
  169. *pkt >> wide_reason;
  170. m_access_denied_reason = wide_to_utf8(wide_reason);
  171. }
  172. return;
  173. }
  174. if (pkt->getSize() < 1)
  175. return;
  176. u8 denyCode;
  177. *pkt >> denyCode;
  178. if (denyCode == SERVER_ACCESSDENIED_SHUTDOWN ||
  179. denyCode == SERVER_ACCESSDENIED_CRASH) {
  180. *pkt >> m_access_denied_reason;
  181. if (m_access_denied_reason.empty())
  182. m_access_denied_reason = accessDeniedStrings[denyCode];
  183. u8 reconnect;
  184. *pkt >> reconnect;
  185. m_access_denied_reconnect = reconnect & 1;
  186. } else if (denyCode == SERVER_ACCESSDENIED_CUSTOM_STRING) {
  187. *pkt >> m_access_denied_reason;
  188. } else if (denyCode == SERVER_ACCESSDENIED_TOO_MANY_USERS) {
  189. m_access_denied_reason = accessDeniedStrings[denyCode];
  190. m_access_denied_reconnect = true;
  191. } else if (denyCode < SERVER_ACCESSDENIED_MAX) {
  192. m_access_denied_reason = accessDeniedStrings[denyCode];
  193. } else {
  194. // Allow us to add new error messages to the
  195. // protocol without raising the protocol version, if we want to.
  196. // Until then (which may be never), this is outside
  197. // of the defined protocol.
  198. *pkt >> m_access_denied_reason;
  199. if (m_access_denied_reason.empty())
  200. m_access_denied_reason = "Unknown";
  201. }
  202. }
  203. void Client::handleCommand_RemoveNode(NetworkPacket* pkt)
  204. {
  205. if (pkt->getSize() < 6)
  206. return;
  207. v3s16 p;
  208. *pkt >> p;
  209. removeNode(p);
  210. }
  211. void Client::handleCommand_AddNode(NetworkPacket* pkt)
  212. {
  213. if (pkt->getSize() < 6 + MapNode::serializedLength(m_server_ser_ver))
  214. return;
  215. v3s16 p;
  216. *pkt >> p;
  217. MapNode n;
  218. n.deSerialize(pkt->getU8Ptr(6), m_server_ser_ver);
  219. bool remove_metadata = true;
  220. u32 index = 6 + MapNode::serializedLength(m_server_ser_ver);
  221. if ((pkt->getSize() >= index + 1) && pkt->getU8(index)) {
  222. remove_metadata = false;
  223. }
  224. addNode(p, n, remove_metadata);
  225. }
  226. void Client::handleCommand_NodemetaChanged(NetworkPacket *pkt)
  227. {
  228. if (pkt->getSize() < 1)
  229. return;
  230. std::istringstream is(pkt->readLongString(), std::ios::binary);
  231. std::stringstream sstr(std::ios::binary | std::ios::in | std::ios::out);
  232. decompressZlib(is, sstr);
  233. NodeMetadataList meta_updates_list(false);
  234. meta_updates_list.deSerialize(sstr, m_itemdef, true);
  235. Map &map = m_env.getMap();
  236. for (NodeMetadataMap::const_iterator i = meta_updates_list.begin();
  237. i != meta_updates_list.end(); ++i) {
  238. v3s16 pos = i->first;
  239. if (map.isValidPosition(pos) &&
  240. map.setNodeMetadata(pos, i->second))
  241. continue; // Prevent from deleting metadata
  242. // Meta couldn't be set, unused metadata
  243. delete i->second;
  244. }
  245. }
  246. void Client::handleCommand_BlockData(NetworkPacket* pkt)
  247. {
  248. // Ignore too small packet
  249. if (pkt->getSize() < 6)
  250. return;
  251. v3s16 p;
  252. *pkt >> p;
  253. std::string datastring(pkt->getString(6), pkt->getSize() - 6);
  254. std::istringstream istr(datastring, std::ios_base::binary);
  255. MapSector *sector;
  256. MapBlock *block;
  257. v2s16 p2d(p.X, p.Z);
  258. sector = m_env.getMap().emergeSector(p2d);
  259. assert(sector->getPos() == p2d);
  260. block = sector->getBlockNoCreateNoEx(p.Y);
  261. if (block) {
  262. /*
  263. Update an existing block
  264. */
  265. block->deSerialize(istr, m_server_ser_ver, false);
  266. block->deSerializeNetworkSpecific(istr);
  267. }
  268. else {
  269. /*
  270. Create a new block
  271. */
  272. block = new MapBlock(&m_env.getMap(), p, this);
  273. block->deSerialize(istr, m_server_ser_ver, false);
  274. block->deSerializeNetworkSpecific(istr);
  275. sector->insertBlock(block);
  276. }
  277. if (m_localdb) {
  278. ServerMap::saveBlock(block, m_localdb);
  279. }
  280. /*
  281. Add it to mesh update queue and set it to be acknowledged after update.
  282. */
  283. addUpdateMeshTaskWithEdge(p, true);
  284. }
  285. void Client::handleCommand_Inventory(NetworkPacket* pkt)
  286. {
  287. if (pkt->getSize() < 1)
  288. return;
  289. std::string datastring(pkt->getString(0), pkt->getSize());
  290. std::istringstream is(datastring, std::ios_base::binary);
  291. LocalPlayer *player = m_env.getLocalPlayer();
  292. assert(player != NULL);
  293. player->inventory.deSerialize(is);
  294. m_update_wielded_item = true;
  295. delete m_inventory_from_server;
  296. m_inventory_from_server = new Inventory(player->inventory);
  297. m_inventory_from_server_age = 0.0;
  298. }
  299. void Client::handleCommand_TimeOfDay(NetworkPacket* pkt)
  300. {
  301. if (pkt->getSize() < 2)
  302. return;
  303. u16 time_of_day;
  304. *pkt >> time_of_day;
  305. time_of_day = time_of_day % 24000;
  306. float time_speed = 0;
  307. if (pkt->getSize() >= 2 + 4) {
  308. *pkt >> time_speed;
  309. }
  310. else {
  311. // Old message; try to approximate speed of time by ourselves
  312. float time_of_day_f = (float)time_of_day / 24000.0f;
  313. float tod_diff_f = 0;
  314. if (time_of_day_f < 0.2 && m_last_time_of_day_f > 0.8)
  315. tod_diff_f = time_of_day_f - m_last_time_of_day_f + 1.0f;
  316. else
  317. tod_diff_f = time_of_day_f - m_last_time_of_day_f;
  318. m_last_time_of_day_f = time_of_day_f;
  319. float time_diff = m_time_of_day_update_timer;
  320. m_time_of_day_update_timer = 0;
  321. if (m_time_of_day_set) {
  322. time_speed = (3600.0f * 24.0f) * tod_diff_f / time_diff;
  323. infostream << "Client: Measured time_of_day speed (old format): "
  324. << time_speed << " tod_diff_f=" << tod_diff_f
  325. << " time_diff=" << time_diff << std::endl;
  326. }
  327. }
  328. // Update environment
  329. m_env.setTimeOfDay(time_of_day);
  330. m_env.setTimeOfDaySpeed(time_speed);
  331. m_time_of_day_set = true;
  332. //u32 dr = m_env.getDayNightRatio();
  333. //infostream << "Client: time_of_day=" << time_of_day
  334. // << " time_speed=" << time_speed
  335. // << " dr=" << dr << std::endl;
  336. }
  337. void Client::handleCommand_ChatMessage(NetworkPacket *pkt)
  338. {
  339. /*
  340. u8 version
  341. u8 message_type
  342. u16 sendername length
  343. wstring sendername
  344. u16 length
  345. wstring message
  346. */
  347. ChatMessage *chatMessage = new ChatMessage();
  348. u8 version, message_type;
  349. *pkt >> version >> message_type;
  350. if (version != 1 || message_type >= CHATMESSAGE_TYPE_MAX) {
  351. delete chatMessage;
  352. return;
  353. }
  354. u64 timestamp;
  355. *pkt >> chatMessage->sender >> chatMessage->message >> timestamp;
  356. chatMessage->timestamp = static_cast<std::time_t>(timestamp);
  357. chatMessage->type = (ChatMessageType) message_type;
  358. // @TODO send this to CSM using ChatMessage object
  359. if (modsLoaded() && m_script->on_receiving_message(
  360. wide_to_utf8(chatMessage->message))) {
  361. // Message was consumed by CSM and should not be handled by client
  362. delete chatMessage;
  363. } else {
  364. pushToChatQueue(chatMessage);
  365. }
  366. }
  367. void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt)
  368. {
  369. /*
  370. u16 count of removed objects
  371. for all removed objects {
  372. u16 id
  373. }
  374. u16 count of added objects
  375. for all added objects {
  376. u16 id
  377. u8 type
  378. u32 initialization data length
  379. string initialization data
  380. }
  381. */
  382. try {
  383. u8 type;
  384. u16 removed_count, added_count, id;
  385. // Read removed objects
  386. *pkt >> removed_count;
  387. for (u16 i = 0; i < removed_count; i++) {
  388. *pkt >> id;
  389. m_env.removeActiveObject(id);
  390. }
  391. // Read added objects
  392. *pkt >> added_count;
  393. for (u16 i = 0; i < added_count; i++) {
  394. *pkt >> id >> type;
  395. m_env.addActiveObject(id, type, pkt->readLongString());
  396. }
  397. } catch (PacketError &e) {
  398. infostream << "handleCommand_ActiveObjectRemoveAdd: " << e.what()
  399. << ". The packet is unreliable, ignoring" << std::endl;
  400. }
  401. // m_activeobjects_received is false before the first
  402. // TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD packet is received
  403. m_activeobjects_received = true;
  404. }
  405. void Client::handleCommand_ActiveObjectMessages(NetworkPacket* pkt)
  406. {
  407. /*
  408. for all objects
  409. {
  410. u16 id
  411. u16 message length
  412. string message
  413. }
  414. */
  415. std::string datastring(pkt->getString(0), pkt->getSize());
  416. std::istringstream is(datastring, std::ios_base::binary);
  417. try {
  418. while (is.good()) {
  419. u16 id = readU16(is);
  420. if (!is.good())
  421. break;
  422. std::string message = deSerializeString16(is);
  423. // Pass on to the environment
  424. m_env.processActiveObjectMessage(id, message);
  425. }
  426. } catch (SerializationError &e) {
  427. errorstream << "Client::handleCommand_ActiveObjectMessages: "
  428. << "caught SerializationError: " << e.what() << std::endl;
  429. }
  430. }
  431. void Client::handleCommand_Movement(NetworkPacket* pkt)
  432. {
  433. LocalPlayer *player = m_env.getLocalPlayer();
  434. assert(player != NULL);
  435. float mad, maa, maf, msw, mscr, msf, mscl, msj, lf, lfs, ls, g;
  436. *pkt >> mad >> maa >> maf >> msw >> mscr >> msf >> mscl >> msj
  437. >> lf >> lfs >> ls >> g;
  438. player->movement_acceleration_default = mad * BS;
  439. player->movement_acceleration_air = maa * BS;
  440. player->movement_acceleration_fast = maf * BS;
  441. player->movement_speed_walk = msw * BS;
  442. player->movement_speed_crouch = mscr * BS;
  443. player->movement_speed_fast = msf * BS;
  444. player->movement_speed_climb = mscl * BS;
  445. player->movement_speed_jump = msj * BS;
  446. player->movement_liquid_fluidity = lf * BS;
  447. player->movement_liquid_fluidity_smooth = lfs * BS;
  448. player->movement_liquid_sink = ls * BS;
  449. player->movement_gravity = g * BS;
  450. }
  451. void Client::handleCommand_Fov(NetworkPacket *pkt)
  452. {
  453. f32 fov;
  454. bool is_multiplier = false;
  455. f32 transition_time = 0.0f;
  456. *pkt >> fov >> is_multiplier;
  457. // Wrap transition_time extraction within a
  458. // try-catch to preserve backwards compat
  459. try {
  460. *pkt >> transition_time;
  461. } catch (PacketError &e) {};
  462. LocalPlayer *player = m_env.getLocalPlayer();
  463. assert(player);
  464. player->setFov({ fov, is_multiplier, transition_time });
  465. m_camera->notifyFovChange();
  466. }
  467. void Client::handleCommand_HP(NetworkPacket *pkt)
  468. {
  469. LocalPlayer *player = m_env.getLocalPlayer();
  470. assert(player != NULL);
  471. u16 oldhp = player->hp;
  472. u16 hp;
  473. *pkt >> hp;
  474. bool damage_effect = true;
  475. try {
  476. *pkt >> damage_effect;
  477. } catch (PacketError &e) {};
  478. player->hp = hp;
  479. if (modsLoaded())
  480. m_script->on_hp_modification(hp);
  481. if (hp < oldhp) {
  482. // Add to ClientEvent queue
  483. ClientEvent *event = new ClientEvent();
  484. event->type = CE_PLAYER_DAMAGE;
  485. event->player_damage.amount = oldhp - hp;
  486. event->player_damage.effect = damage_effect;
  487. m_client_event_queue.push(event);
  488. }
  489. }
  490. void Client::handleCommand_Breath(NetworkPacket* pkt)
  491. {
  492. LocalPlayer *player = m_env.getLocalPlayer();
  493. assert(player != NULL);
  494. u16 breath;
  495. *pkt >> breath;
  496. player->setBreath(breath);
  497. }
  498. void Client::handleCommand_MovePlayer(NetworkPacket* pkt)
  499. {
  500. LocalPlayer *player = m_env.getLocalPlayer();
  501. assert(player != NULL);
  502. v3f pos;
  503. f32 pitch, yaw;
  504. *pkt >> pos >> pitch >> yaw;
  505. player->setPosition(pos);
  506. infostream << "Client got TOCLIENT_MOVE_PLAYER"
  507. << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")"
  508. << " pitch=" << pitch
  509. << " yaw=" << yaw
  510. << std::endl;
  511. /*
  512. Add to ClientEvent queue.
  513. This has to be sent to the main program because otherwise
  514. it would just force the pitch and yaw values to whatever
  515. the camera points to.
  516. */
  517. ClientEvent *event = new ClientEvent();
  518. event->type = CE_PLAYER_FORCE_MOVE;
  519. event->player_force_move.pitch = pitch;
  520. event->player_force_move.yaw = yaw;
  521. m_client_event_queue.push(event);
  522. }
  523. void Client::handleCommand_DeathScreen(NetworkPacket* pkt)
  524. {
  525. bool set_camera_point_target;
  526. v3f camera_point_target;
  527. *pkt >> set_camera_point_target;
  528. *pkt >> camera_point_target;
  529. ClientEvent *event = new ClientEvent();
  530. event->type = CE_DEATHSCREEN;
  531. event->deathscreen.set_camera_point_target = set_camera_point_target;
  532. event->deathscreen.camera_point_target_x = camera_point_target.X;
  533. event->deathscreen.camera_point_target_y = camera_point_target.Y;
  534. event->deathscreen.camera_point_target_z = camera_point_target.Z;
  535. m_client_event_queue.push(event);
  536. }
  537. void Client::handleCommand_AnnounceMedia(NetworkPacket* pkt)
  538. {
  539. u16 num_files;
  540. *pkt >> num_files;
  541. infostream << "Client: Received media announcement: packet size: "
  542. << pkt->getSize() << std::endl;
  543. if (m_media_downloader == NULL ||
  544. m_media_downloader->isStarted()) {
  545. const char *problem = m_media_downloader ?
  546. "we already saw another announcement" :
  547. "all media has been received already";
  548. errorstream << "Client: Received media announcement but "
  549. << problem << "! "
  550. << " files=" << num_files
  551. << " size=" << pkt->getSize() << std::endl;
  552. return;
  553. }
  554. // Mesh update thread must be stopped while
  555. // updating content definitions
  556. sanity_check(!m_mesh_update_thread.isRunning());
  557. for (u16 i = 0; i < num_files; i++) {
  558. std::string name, sha1_base64;
  559. *pkt >> name >> sha1_base64;
  560. std::string sha1_raw = base64_decode(sha1_base64);
  561. m_media_downloader->addFile(name, sha1_raw);
  562. }
  563. {
  564. std::string str;
  565. *pkt >> str;
  566. Strfnd sf(str);
  567. while (!sf.at_end()) {
  568. std::string baseurl = trim(sf.next(","));
  569. if (!baseurl.empty()) {
  570. m_remote_media_servers.emplace_back(baseurl);
  571. m_media_downloader->addRemoteServer(baseurl);
  572. }
  573. }
  574. }
  575. m_media_downloader->step(this);
  576. }
  577. void Client::handleCommand_Media(NetworkPacket* pkt)
  578. {
  579. /*
  580. u16 command
  581. u16 total number of file bunches
  582. u16 index of this bunch
  583. u32 number of files in this bunch
  584. for each file {
  585. u16 length of name
  586. string name
  587. u32 length of data
  588. data
  589. }
  590. */
  591. u16 num_bunches;
  592. u16 bunch_i;
  593. u32 num_files;
  594. *pkt >> num_bunches >> bunch_i >> num_files;
  595. infostream << "Client: Received files: bunch " << bunch_i << "/"
  596. << num_bunches << " files=" << num_files
  597. << " size=" << pkt->getSize() << std::endl;
  598. if (num_files == 0)
  599. return;
  600. bool init_phase = m_media_downloader && m_media_downloader->isStarted();
  601. if (init_phase) {
  602. // Mesh update thread must be stopped while
  603. // updating content definitions
  604. sanity_check(!m_mesh_update_thread.isRunning());
  605. }
  606. for (u32 i = 0; i < num_files; i++) {
  607. std::string name, data;
  608. *pkt >> name;
  609. data = pkt->readLongString();
  610. bool ok = false;
  611. if (init_phase) {
  612. ok = m_media_downloader->conventionalTransferDone(name, data, this);
  613. } else {
  614. // Check pending dynamic transfers, one of them must be it
  615. for (const auto &it : m_pending_media_downloads) {
  616. if (it.second->conventionalTransferDone(name, data, this)) {
  617. ok = true;
  618. break;
  619. }
  620. }
  621. }
  622. if (!ok) {
  623. errorstream << "Client: Received media \"" << name
  624. << "\" but no downloads pending. " << num_bunches << " bunches, "
  625. << num_files << " in this one. (init_phase=" << init_phase
  626. << ")" << std::endl;
  627. }
  628. }
  629. }
  630. void Client::handleCommand_NodeDef(NetworkPacket* pkt)
  631. {
  632. infostream << "Client: Received node definitions: packet size: "
  633. << pkt->getSize() << std::endl;
  634. // Mesh update thread must be stopped while
  635. // updating content definitions
  636. sanity_check(!m_mesh_update_thread.isRunning());
  637. // Decompress node definitions
  638. std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
  639. std::stringstream tmp_os(std::ios::binary | std::ios::in | std::ios::out);
  640. decompressZlib(tmp_is, tmp_os);
  641. // Deserialize node definitions
  642. m_nodedef->deSerialize(tmp_os, m_proto_ver);
  643. m_nodedef_received = true;
  644. }
  645. void Client::handleCommand_ItemDef(NetworkPacket* pkt)
  646. {
  647. infostream << "Client: Received item definitions: packet size: "
  648. << pkt->getSize() << std::endl;
  649. // Mesh update thread must be stopped while
  650. // updating content definitions
  651. sanity_check(!m_mesh_update_thread.isRunning());
  652. // Decompress item definitions
  653. std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
  654. std::stringstream tmp_os(std::ios::binary | std::ios::in | std::ios::out);
  655. decompressZlib(tmp_is, tmp_os);
  656. // Deserialize node definitions
  657. m_itemdef->deSerialize(tmp_os, m_proto_ver);
  658. m_itemdef_received = true;
  659. }
  660. void Client::handleCommand_PlaySound(NetworkPacket* pkt)
  661. {
  662. /*
  663. [0] u32 server_id
  664. [4] u16 name length
  665. [6] char name[len]
  666. [ 6 + len] f32 gain
  667. [10 + len] u8 type
  668. [11 + len] (f32 * 3) pos
  669. [23 + len] u16 object_id
  670. [25 + len] bool loop
  671. [26 + len] f32 fade
  672. [30 + len] f32 pitch
  673. [34 + len] bool ephemeral
  674. */
  675. s32 server_id;
  676. SimpleSoundSpec spec;
  677. SoundLocation type; // 0=local, 1=positional, 2=object
  678. v3f pos;
  679. u16 object_id;
  680. bool ephemeral = false;
  681. *pkt >> server_id >> spec.name >> spec.gain >> (u8 &)type >> pos >> object_id >> spec.loop;
  682. try {
  683. *pkt >> spec.fade;
  684. *pkt >> spec.pitch;
  685. *pkt >> ephemeral;
  686. } catch (PacketError &e) {};
  687. // Start playing
  688. int client_id = -1;
  689. switch(type) {
  690. case SoundLocation::Local:
  691. client_id = m_sound->playSound(spec);
  692. break;
  693. case SoundLocation::Position:
  694. client_id = m_sound->playSoundAt(spec, pos);
  695. break;
  696. case SoundLocation::Object:
  697. {
  698. ClientActiveObject *cao = m_env.getActiveObject(object_id);
  699. if (cao)
  700. pos = cao->getPosition();
  701. client_id = m_sound->playSoundAt(spec, pos);
  702. break;
  703. }
  704. }
  705. if (client_id != -1) {
  706. // for ephemeral sounds, server_id is not meaningful
  707. if (!ephemeral) {
  708. m_sounds_server_to_client[server_id] = client_id;
  709. m_sounds_client_to_server[client_id] = server_id;
  710. }
  711. if (object_id != 0)
  712. m_sounds_to_objects[client_id] = object_id;
  713. }
  714. }
  715. void Client::handleCommand_StopSound(NetworkPacket* pkt)
  716. {
  717. s32 server_id;
  718. *pkt >> server_id;
  719. std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.find(server_id);
  720. if (i != m_sounds_server_to_client.end()) {
  721. int client_id = i->second;
  722. m_sound->stopSound(client_id);
  723. }
  724. }
  725. void Client::handleCommand_FadeSound(NetworkPacket *pkt)
  726. {
  727. s32 sound_id;
  728. float step;
  729. float gain;
  730. *pkt >> sound_id >> step >> gain;
  731. std::unordered_map<s32, int>::const_iterator i =
  732. m_sounds_server_to_client.find(sound_id);
  733. if (i != m_sounds_server_to_client.end())
  734. m_sound->fadeSound(i->second, step, gain);
  735. }
  736. void Client::handleCommand_Privileges(NetworkPacket* pkt)
  737. {
  738. m_privileges.clear();
  739. infostream << "Client: Privileges updated: ";
  740. u16 num_privileges;
  741. *pkt >> num_privileges;
  742. for (u16 i = 0; i < num_privileges; i++) {
  743. std::string priv;
  744. *pkt >> priv;
  745. m_privileges.insert(priv);
  746. infostream << priv << " ";
  747. }
  748. infostream << std::endl;
  749. }
  750. void Client::handleCommand_InventoryFormSpec(NetworkPacket* pkt)
  751. {
  752. LocalPlayer *player = m_env.getLocalPlayer();
  753. assert(player != NULL);
  754. // Store formspec in LocalPlayer
  755. player->inventory_formspec = pkt->readLongString();
  756. }
  757. void Client::handleCommand_DetachedInventory(NetworkPacket* pkt)
  758. {
  759. std::string name;
  760. bool keep_inv = true;
  761. *pkt >> name >> keep_inv;
  762. infostream << "Client: Detached inventory update: \"" << name
  763. << "\", mode=" << (keep_inv ? "update" : "remove") << std::endl;
  764. const auto &inv_it = m_detached_inventories.find(name);
  765. if (!keep_inv) {
  766. if (inv_it != m_detached_inventories.end()) {
  767. delete inv_it->second;
  768. m_detached_inventories.erase(inv_it);
  769. }
  770. return;
  771. }
  772. Inventory *inv = nullptr;
  773. if (inv_it == m_detached_inventories.end()) {
  774. inv = new Inventory(m_itemdef);
  775. m_detached_inventories[name] = inv;
  776. } else {
  777. inv = inv_it->second;
  778. }
  779. u16 ignore;
  780. *pkt >> ignore; // this used to be the length of the following string, ignore it
  781. std::string contents(pkt->getRemainingString(), pkt->getRemainingBytes());
  782. std::istringstream is(contents, std::ios::binary);
  783. inv->deSerialize(is);
  784. }
  785. void Client::handleCommand_ShowFormSpec(NetworkPacket* pkt)
  786. {
  787. std::string formspec = pkt->readLongString();
  788. std::string formname;
  789. *pkt >> formname;
  790. ClientEvent *event = new ClientEvent();
  791. event->type = CE_SHOW_FORMSPEC;
  792. // pointer is required as event is a struct only!
  793. // adding a std:string to a struct isn't possible
  794. event->show_formspec.formspec = new std::string(formspec);
  795. event->show_formspec.formname = new std::string(formname);
  796. m_client_event_queue.push(event);
  797. }
  798. void Client::handleCommand_SpawnParticle(NetworkPacket* pkt)
  799. {
  800. std::string datastring(pkt->getString(0), pkt->getSize());
  801. std::istringstream is(datastring, std::ios_base::binary);
  802. ParticleParameters p;
  803. p.deSerialize(is, m_proto_ver);
  804. ClientEvent *event = new ClientEvent();
  805. event->type = CE_SPAWN_PARTICLE;
  806. event->spawn_particle = new ParticleParameters(p);
  807. m_client_event_queue.push(event);
  808. }
  809. void Client::handleCommand_AddParticleSpawner(NetworkPacket* pkt)
  810. {
  811. std::string datastring(pkt->getString(0), pkt->getSize());
  812. std::istringstream is(datastring, std::ios_base::binary);
  813. ParticleSpawnerParameters p;
  814. u32 server_id;
  815. u16 attached_id = 0;
  816. p.amount = readU16(is);
  817. p.time = readF32(is);
  818. // older protocols do not support tweening, and send only
  819. // static ranges, so we can't just use the normal serialization
  820. // functions for the older values.
  821. p.pos.start.legacyDeSerialize(is);
  822. p.vel.start.legacyDeSerialize(is);
  823. p.acc.start.legacyDeSerialize(is);
  824. p.exptime.start.legacyDeSerialize(is);
  825. p.size.start.legacyDeSerialize(is);
  826. p.collisiondetection = readU8(is);
  827. p.texture.string = deSerializeString32(is);
  828. server_id = readU32(is);
  829. p.vertical = readU8(is);
  830. p.collision_removal = readU8(is);
  831. attached_id = readU16(is);
  832. p.animation.deSerialize(is, m_proto_ver);
  833. p.glow = readU8(is);
  834. p.object_collision = readU8(is);
  835. bool legacy_format = true;
  836. // This is kinda awful
  837. do {
  838. u16 tmp_param0 = readU16(is);
  839. if (is.eof())
  840. break;
  841. p.node.param0 = tmp_param0;
  842. p.node.param2 = readU8(is);
  843. p.node_tile = readU8(is);
  844. // v >= 5.6.0
  845. f32 tmp_sbias = readF32(is);
  846. if (is.eof())
  847. break;
  848. // initial bias must be stored separately in the stream to preserve
  849. // backwards compatibility with older clients, which do not support
  850. // a bias field in their range "format"
  851. p.pos.start.bias = tmp_sbias;
  852. p.vel.start.bias = readF32(is);
  853. p.acc.start.bias = readF32(is);
  854. p.exptime.start.bias = readF32(is);
  855. p.size.start.bias = readF32(is);
  856. p.pos.end.deSerialize(is);
  857. p.vel.end.deSerialize(is);
  858. p.acc.end.deSerialize(is);
  859. p.exptime.end.deSerialize(is);
  860. p.size.end.deSerialize(is);
  861. // properties for legacy texture field
  862. p.texture.deSerialize(is, m_proto_ver, true);
  863. p.drag.deSerialize(is);
  864. p.jitter.deSerialize(is);
  865. p.bounce.deSerialize(is);
  866. ParticleParamTypes::deSerializeParameterValue(is, p.attractor_kind);
  867. using ParticleParamTypes::AttractorKind;
  868. if (p.attractor_kind != AttractorKind::none) {
  869. p.attract.deSerialize(is);
  870. p.attractor_origin.deSerialize(is);
  871. p.attractor_attachment = readU16(is);
  872. /* we only check the first bit, in order to allow this value
  873. * to be turned into a bit flag field later if needed */
  874. p.attractor_kill = !!(readU8(is) & 1);
  875. if (p.attractor_kind != AttractorKind::point) {
  876. p.attractor_direction.deSerialize(is);
  877. p.attractor_direction_attachment = readU16(is);
  878. }
  879. }
  880. p.radius.deSerialize(is);
  881. u16 texpoolsz = readU16(is);
  882. p.texpool.reserve(texpoolsz);
  883. for (u16 i = 0; i < texpoolsz; ++i) {
  884. ServerParticleTexture newtex;
  885. newtex.deSerialize(is, m_proto_ver);
  886. p.texpool.push_back(newtex);
  887. }
  888. legacy_format = false;
  889. } while(0);
  890. if (legacy_format) {
  891. // there's no tweening data to be had, so we need to set the
  892. // legacy params to constant values, otherwise everything old
  893. // will tween to zero
  894. p.pos.end = p.pos.start;
  895. p.vel.end = p.vel.start;
  896. p.acc.end = p.acc.start;
  897. p.exptime.end = p.exptime.start;
  898. p.size.end = p.size.start;
  899. }
  900. auto event = new ClientEvent();
  901. event->type = CE_ADD_PARTICLESPAWNER;
  902. event->add_particlespawner.p = new ParticleSpawnerParameters(p);
  903. event->add_particlespawner.attached_id = attached_id;
  904. event->add_particlespawner.id = server_id;
  905. m_client_event_queue.push(event);
  906. }
  907. void Client::handleCommand_DeleteParticleSpawner(NetworkPacket* pkt)
  908. {
  909. u32 server_id;
  910. *pkt >> server_id;
  911. ClientEvent *event = new ClientEvent();
  912. event->type = CE_DELETE_PARTICLESPAWNER;
  913. event->delete_particlespawner.id = server_id;
  914. m_client_event_queue.push(event);
  915. }
  916. void Client::handleCommand_HudAdd(NetworkPacket* pkt)
  917. {
  918. u32 server_id;
  919. u8 type;
  920. v2f pos;
  921. std::string name;
  922. v2f scale;
  923. std::string text;
  924. u32 number;
  925. u32 item;
  926. u32 dir;
  927. v2f align;
  928. v2f offset;
  929. v3f world_pos;
  930. v2s32 size;
  931. s16 z_index = 0;
  932. std::string text2;
  933. u32 style = 0;
  934. *pkt >> server_id >> type >> pos >> name >> scale >> text >> number >> item
  935. >> dir >> align >> offset;
  936. try {
  937. *pkt >> world_pos;
  938. *pkt >> size;
  939. *pkt >> z_index;
  940. *pkt >> text2;
  941. *pkt >> style;
  942. } catch(PacketError &e) {};
  943. ClientEvent *event = new ClientEvent();
  944. event->type = CE_HUDADD;
  945. event->hudadd = new ClientEventHudAdd();
  946. event->hudadd->server_id = server_id;
  947. event->hudadd->type = type;
  948. event->hudadd->pos = pos;
  949. event->hudadd->name = name;
  950. event->hudadd->scale = scale;
  951. event->hudadd->text = text;
  952. event->hudadd->number = number;
  953. event->hudadd->item = item;
  954. event->hudadd->dir = dir;
  955. event->hudadd->align = align;
  956. event->hudadd->offset = offset;
  957. event->hudadd->world_pos = world_pos;
  958. event->hudadd->size = size;
  959. event->hudadd->z_index = z_index;
  960. event->hudadd->text2 = text2;
  961. event->hudadd->style = style;
  962. m_client_event_queue.push(event);
  963. }
  964. void Client::handleCommand_HudRemove(NetworkPacket* pkt)
  965. {
  966. u32 server_id;
  967. *pkt >> server_id;
  968. ClientEvent *event = new ClientEvent();
  969. event->type = CE_HUDRM;
  970. event->hudrm.id = server_id;
  971. m_client_event_queue.push(event);
  972. }
  973. void Client::handleCommand_HudChange(NetworkPacket* pkt)
  974. {
  975. std::string sdata;
  976. v2f v2fdata;
  977. v3f v3fdata;
  978. u32 intdata = 0;
  979. v2s32 v2s32data;
  980. u32 server_id;
  981. u8 stat;
  982. *pkt >> server_id >> stat;
  983. // Keep in sync with:server.cpp -> SendHUDChange
  984. switch ((HudElementStat)stat) {
  985. case HUD_STAT_POS:
  986. case HUD_STAT_SCALE:
  987. case HUD_STAT_ALIGN:
  988. case HUD_STAT_OFFSET:
  989. *pkt >> v2fdata;
  990. break;
  991. case HUD_STAT_NAME:
  992. case HUD_STAT_TEXT:
  993. case HUD_STAT_TEXT2:
  994. *pkt >> sdata;
  995. break;
  996. case HUD_STAT_WORLD_POS:
  997. *pkt >> v3fdata;
  998. break;
  999. case HUD_STAT_SIZE:
  1000. *pkt >> v2s32data;
  1001. break;
  1002. default:
  1003. *pkt >> intdata;
  1004. break;
  1005. }
  1006. ClientEvent *event = new ClientEvent();
  1007. event->type = CE_HUDCHANGE;
  1008. event->hudchange = new ClientEventHudChange();
  1009. event->hudchange->id = server_id;
  1010. event->hudchange->stat = static_cast<HudElementStat>(stat);
  1011. event->hudchange->v2fdata = v2fdata;
  1012. event->hudchange->v3fdata = v3fdata;
  1013. event->hudchange->sdata = sdata;
  1014. event->hudchange->data = intdata;
  1015. event->hudchange->v2s32data = v2s32data;
  1016. m_client_event_queue.push(event);
  1017. }
  1018. void Client::handleCommand_HudSetFlags(NetworkPacket* pkt)
  1019. {
  1020. u32 flags, mask;
  1021. *pkt >> flags >> mask;
  1022. LocalPlayer *player = m_env.getLocalPlayer();
  1023. assert(player != NULL);
  1024. bool was_minimap_visible = player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE;
  1025. bool was_minimap_radar_visible = player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE;
  1026. player->hud_flags &= ~mask;
  1027. player->hud_flags |= flags;
  1028. m_minimap_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE);
  1029. bool m_minimap_radar_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE);
  1030. // Not so satisying code to keep compatibility with old fixed mode system
  1031. // -->
  1032. // Hide minimap if it has been disabled by the server
  1033. if (m_minimap && m_minimap_disabled_by_server && was_minimap_visible)
  1034. // defers a minimap update, therefore only call it if really
  1035. // needed, by checking that minimap was visible before
  1036. m_minimap->setModeIndex(0);
  1037. // If radar has been disabled, try to find a non radar mode or fall back to 0
  1038. if (m_minimap && m_minimap_radar_disabled_by_server
  1039. && was_minimap_radar_visible) {
  1040. while (m_minimap->getModeIndex() > 0 &&
  1041. m_minimap->getModeDef().type == MINIMAP_TYPE_RADAR)
  1042. m_minimap->nextMode();
  1043. }
  1044. // <--
  1045. // End of 'not so satifying code'
  1046. }
  1047. void Client::handleCommand_HudSetParam(NetworkPacket* pkt)
  1048. {
  1049. u16 param; std::string value;
  1050. *pkt >> param >> value;
  1051. LocalPlayer *player = m_env.getLocalPlayer();
  1052. assert(player != NULL);
  1053. if (param == HUD_PARAM_HOTBAR_ITEMCOUNT && value.size() == 4) {
  1054. s32 hotbar_itemcount = readS32((u8*) value.c_str());
  1055. if (hotbar_itemcount > 0 && hotbar_itemcount <= HUD_HOTBAR_ITEMCOUNT_MAX)
  1056. player->hud_hotbar_itemcount = hotbar_itemcount;
  1057. }
  1058. else if (param == HUD_PARAM_HOTBAR_IMAGE) {
  1059. player->hotbar_image = value;
  1060. }
  1061. else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) {
  1062. player->hotbar_selected_image = value;
  1063. }
  1064. }
  1065. void Client::handleCommand_HudSetSky(NetworkPacket* pkt)
  1066. {
  1067. if (m_proto_ver < 39) {
  1068. // Handle Protocol 38 and below servers with old set_sky,
  1069. // ensuring the classic look is kept.
  1070. std::string datastring(pkt->getString(0), pkt->getSize());
  1071. std::istringstream is(datastring, std::ios_base::binary);
  1072. SkyboxParams skybox;
  1073. skybox.bgcolor = video::SColor(readARGB8(is));
  1074. skybox.type = std::string(deSerializeString16(is));
  1075. u16 count = readU16(is);
  1076. for (size_t i = 0; i < count; i++)
  1077. skybox.textures.emplace_back(deSerializeString16(is));
  1078. skybox.clouds = true;
  1079. try {
  1080. skybox.clouds = readU8(is);
  1081. } catch (...) {}
  1082. // Use default skybox settings:
  1083. SunParams sun = SkyboxDefaults::getSunDefaults();
  1084. MoonParams moon = SkyboxDefaults::getMoonDefaults();
  1085. StarParams stars = SkyboxDefaults::getStarDefaults();
  1086. // Fix for "regular" skies, as color isn't kept:
  1087. if (skybox.type == "regular") {
  1088. skybox.sky_color = SkyboxDefaults::getSkyColorDefaults();
  1089. skybox.fog_tint_type = "default";
  1090. skybox.fog_moon_tint = video::SColor(255, 255, 255, 255);
  1091. skybox.fog_sun_tint = video::SColor(255, 255, 255, 255);
  1092. } else {
  1093. sun.visible = false;
  1094. sun.sunrise_visible = false;
  1095. moon.visible = false;
  1096. stars.visible = false;
  1097. }
  1098. // Skybox, sun, moon and stars ClientEvents:
  1099. ClientEvent *sky_event = new ClientEvent();
  1100. sky_event->type = CE_SET_SKY;
  1101. sky_event->set_sky = new SkyboxParams(skybox);
  1102. m_client_event_queue.push(sky_event);
  1103. ClientEvent *sun_event = new ClientEvent();
  1104. sun_event->type = CE_SET_SUN;
  1105. sun_event->sun_params = new SunParams(sun);
  1106. m_client_event_queue.push(sun_event);
  1107. ClientEvent *moon_event = new ClientEvent();
  1108. moon_event->type = CE_SET_MOON;
  1109. moon_event->moon_params = new MoonParams(moon);
  1110. m_client_event_queue.push(moon_event);
  1111. ClientEvent *star_event = new ClientEvent();
  1112. star_event->type = CE_SET_STARS;
  1113. star_event->star_params = new StarParams(stars);
  1114. m_client_event_queue.push(star_event);
  1115. } else {
  1116. SkyboxParams skybox;
  1117. u16 texture_count;
  1118. std::string texture;
  1119. *pkt >> skybox.bgcolor >> skybox.type >> skybox.clouds >>
  1120. skybox.fog_sun_tint >> skybox.fog_moon_tint >> skybox.fog_tint_type;
  1121. if (skybox.type == "skybox") {
  1122. *pkt >> texture_count;
  1123. for (int i = 0; i < texture_count; i++) {
  1124. *pkt >> texture;
  1125. skybox.textures.emplace_back(texture);
  1126. }
  1127. }
  1128. else if (skybox.type == "regular") {
  1129. *pkt >> skybox.sky_color.day_sky >> skybox.sky_color.day_horizon
  1130. >> skybox.sky_color.dawn_sky >> skybox.sky_color.dawn_horizon
  1131. >> skybox.sky_color.night_sky >> skybox.sky_color.night_horizon
  1132. >> skybox.sky_color.indoors;
  1133. }
  1134. ClientEvent *event = new ClientEvent();
  1135. event->type = CE_SET_SKY;
  1136. event->set_sky = new SkyboxParams(skybox);
  1137. m_client_event_queue.push(event);
  1138. }
  1139. }
  1140. void Client::handleCommand_HudSetSun(NetworkPacket *pkt)
  1141. {
  1142. SunParams sun;
  1143. *pkt >> sun.visible >> sun.texture>> sun.tonemap
  1144. >> sun.sunrise >> sun.sunrise_visible >> sun.scale;
  1145. ClientEvent *event = new ClientEvent();
  1146. event->type = CE_SET_SUN;
  1147. event->sun_params = new SunParams(sun);
  1148. m_client_event_queue.push(event);
  1149. }
  1150. void Client::handleCommand_HudSetMoon(NetworkPacket *pkt)
  1151. {
  1152. MoonParams moon;
  1153. *pkt >> moon.visible >> moon.texture
  1154. >> moon.tonemap >> moon.scale;
  1155. ClientEvent *event = new ClientEvent();
  1156. event->type = CE_SET_MOON;
  1157. event->moon_params = new MoonParams(moon);
  1158. m_client_event_queue.push(event);
  1159. }
  1160. void Client::handleCommand_HudSetStars(NetworkPacket *pkt)
  1161. {
  1162. StarParams stars = SkyboxDefaults::getStarDefaults();
  1163. *pkt >> stars.visible >> stars.count
  1164. >> stars.starcolor >> stars.scale;
  1165. try {
  1166. *pkt >> stars.day_opacity;
  1167. } catch (PacketError &e) {};
  1168. ClientEvent *event = new ClientEvent();
  1169. event->type = CE_SET_STARS;
  1170. event->star_params = new StarParams(stars);
  1171. m_client_event_queue.push(event);
  1172. }
  1173. void Client::handleCommand_CloudParams(NetworkPacket* pkt)
  1174. {
  1175. f32 density;
  1176. video::SColor color_bright;
  1177. video::SColor color_ambient;
  1178. f32 height;
  1179. f32 thickness;
  1180. v2f speed;
  1181. *pkt >> density >> color_bright >> color_ambient
  1182. >> height >> thickness >> speed;
  1183. ClientEvent *event = new ClientEvent();
  1184. event->type = CE_CLOUD_PARAMS;
  1185. event->cloud_params.density = density;
  1186. // use the underlying u32 representation, because we can't
  1187. // use struct members with constructors here, and this way
  1188. // we avoid using new() and delete() for no good reason
  1189. event->cloud_params.color_bright = color_bright.color;
  1190. event->cloud_params.color_ambient = color_ambient.color;
  1191. event->cloud_params.height = height;
  1192. event->cloud_params.thickness = thickness;
  1193. // same here: deconstruct to skip constructor
  1194. event->cloud_params.speed_x = speed.X;
  1195. event->cloud_params.speed_y = speed.Y;
  1196. m_client_event_queue.push(event);
  1197. }
  1198. void Client::handleCommand_OverrideDayNightRatio(NetworkPacket* pkt)
  1199. {
  1200. bool do_override;
  1201. u16 day_night_ratio_u;
  1202. *pkt >> do_override >> day_night_ratio_u;
  1203. float day_night_ratio_f = (float)day_night_ratio_u / 65536;
  1204. ClientEvent *event = new ClientEvent();
  1205. event->type = CE_OVERRIDE_DAY_NIGHT_RATIO;
  1206. event->override_day_night_ratio.do_override = do_override;
  1207. event->override_day_night_ratio.ratio_f = day_night_ratio_f;
  1208. m_client_event_queue.push(event);
  1209. }
  1210. void Client::handleCommand_LocalPlayerAnimations(NetworkPacket* pkt)
  1211. {
  1212. LocalPlayer *player = m_env.getLocalPlayer();
  1213. assert(player != NULL);
  1214. *pkt >> player->local_animations[0];
  1215. *pkt >> player->local_animations[1];
  1216. *pkt >> player->local_animations[2];
  1217. *pkt >> player->local_animations[3];
  1218. *pkt >> player->local_animation_speed;
  1219. player->last_animation = -1;
  1220. }
  1221. void Client::handleCommand_EyeOffset(NetworkPacket* pkt)
  1222. {
  1223. LocalPlayer *player = m_env.getLocalPlayer();
  1224. assert(player != NULL);
  1225. *pkt >> player->eye_offset_first >> player->eye_offset_third;
  1226. }
  1227. void Client::handleCommand_UpdatePlayerList(NetworkPacket* pkt)
  1228. {
  1229. u8 type;
  1230. u16 num_players;
  1231. *pkt >> type >> num_players;
  1232. PlayerListModifer notice_type = (PlayerListModifer) type;
  1233. for (u16 i = 0; i < num_players; i++) {
  1234. std::string name;
  1235. *pkt >> name;
  1236. switch (notice_type) {
  1237. case PLAYER_LIST_INIT:
  1238. case PLAYER_LIST_ADD:
  1239. m_env.addPlayerName(name);
  1240. continue;
  1241. case PLAYER_LIST_REMOVE:
  1242. m_env.removePlayerName(name);
  1243. continue;
  1244. }
  1245. }
  1246. }
  1247. void Client::handleCommand_SrpBytesSandB(NetworkPacket* pkt)
  1248. {
  1249. if (m_chosen_auth_mech != AUTH_MECHANISM_SRP &&
  1250. m_chosen_auth_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
  1251. errorstream << "Client: Received SRP S_B login message,"
  1252. << " but wasn't supposed to (chosen_mech="
  1253. << m_chosen_auth_mech << ")." << std::endl;
  1254. return;
  1255. }
  1256. char *bytes_M = 0;
  1257. size_t len_M = 0;
  1258. SRPUser *usr = (SRPUser *) m_auth_data;
  1259. std::string s;
  1260. std::string B;
  1261. *pkt >> s >> B;
  1262. infostream << "Client: Received TOCLIENT_SRP_BYTES_S_B." << std::endl;
  1263. srp_user_process_challenge(usr, (const unsigned char *) s.c_str(), s.size(),
  1264. (const unsigned char *) B.c_str(), B.size(),
  1265. (unsigned char **) &bytes_M, &len_M);
  1266. if ( !bytes_M ) {
  1267. errorstream << "Client: SRP-6a S_B safety check violation!" << std::endl;
  1268. return;
  1269. }
  1270. NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_M, 0);
  1271. resp_pkt << std::string(bytes_M, len_M);
  1272. Send(&resp_pkt);
  1273. }
  1274. void Client::handleCommand_FormspecPrepend(NetworkPacket *pkt)
  1275. {
  1276. LocalPlayer *player = m_env.getLocalPlayer();
  1277. assert(player != NULL);
  1278. // Store formspec in LocalPlayer
  1279. *pkt >> player->formspec_prepend;
  1280. }
  1281. void Client::handleCommand_CSMRestrictionFlags(NetworkPacket *pkt)
  1282. {
  1283. *pkt >> m_csm_restriction_flags >> m_csm_restriction_noderange;
  1284. // Restrictions were received -> load mods if it's enabled
  1285. // Note: this should be moved after mods receptions from server instead
  1286. loadMods();
  1287. }
  1288. void Client::handleCommand_PlayerSpeed(NetworkPacket *pkt)
  1289. {
  1290. v3f added_vel;
  1291. *pkt >> added_vel;
  1292. LocalPlayer *player = m_env.getLocalPlayer();
  1293. assert(player != NULL);
  1294. player->addVelocity(added_vel);
  1295. }
  1296. void Client::handleCommand_MediaPush(NetworkPacket *pkt)
  1297. {
  1298. std::string raw_hash, filename, filedata;
  1299. u32 token;
  1300. bool cached;
  1301. *pkt >> raw_hash >> filename >> cached;
  1302. if (m_proto_ver >= 40)
  1303. *pkt >> token;
  1304. else
  1305. filedata = pkt->readLongString();
  1306. if (raw_hash.size() != 20 || filename.empty() ||
  1307. (m_proto_ver < 40 && filedata.empty()) ||
  1308. !string_allowed(filename, TEXTURENAME_ALLOWED_CHARS)) {
  1309. throw PacketError("Illegal filename, data or hash");
  1310. }
  1311. verbosestream << "Server pushes media file \"" << filename << "\" ";
  1312. if (filedata.empty())
  1313. verbosestream << "to be fetched ";
  1314. else
  1315. verbosestream << "with " << filedata.size() << " bytes ";
  1316. verbosestream << "(cached=" << cached << ")" << std::endl;
  1317. if (m_media_pushed_files.count(filename) != 0) {
  1318. // Ignore (but acknowledge). Previously this was for sync purposes,
  1319. // but even in new versions media cannot be replaced at runtime.
  1320. if (m_proto_ver >= 40)
  1321. sendHaveMedia({ token });
  1322. return;
  1323. }
  1324. if (!filedata.empty()) {
  1325. // LEGACY CODEPATH
  1326. // Compute and check checksum of data
  1327. std::string computed_hash;
  1328. {
  1329. SHA1 ctx;
  1330. ctx.addBytes(filedata.c_str(), filedata.size());
  1331. unsigned char *buf = ctx.getDigest();
  1332. computed_hash.assign((char*) buf, 20);
  1333. free(buf);
  1334. }
  1335. if (raw_hash != computed_hash) {
  1336. verbosestream << "Hash of file data mismatches, ignoring." << std::endl;
  1337. return;
  1338. }
  1339. // Actually load media
  1340. loadMedia(filedata, filename, true);
  1341. m_media_pushed_files.insert(filename);
  1342. // Cache file for the next time when this client joins the same server
  1343. if (cached)
  1344. clientMediaUpdateCache(raw_hash, filedata);
  1345. return;
  1346. }
  1347. m_media_pushed_files.insert(filename);
  1348. // create a downloader for this file
  1349. auto downloader(std::make_shared<SingleMediaDownloader>(cached));
  1350. m_pending_media_downloads.emplace_back(token, downloader);
  1351. downloader->addFile(filename, raw_hash);
  1352. for (const auto &baseurl : m_remote_media_servers)
  1353. downloader->addRemoteServer(baseurl);
  1354. downloader->step(this);
  1355. }
  1356. /*
  1357. * Mod channels
  1358. */
  1359. void Client::handleCommand_ModChannelMsg(NetworkPacket *pkt)
  1360. {
  1361. std::string channel_name, sender, channel_msg;
  1362. *pkt >> channel_name >> sender >> channel_msg;
  1363. verbosestream << "Mod channel message received from server " << pkt->getPeerId()
  1364. << " on channel " << channel_name << ". sender: `" << sender << "`, message: "
  1365. << channel_msg << std::endl;
  1366. if (!m_modchannel_mgr->channelRegistered(channel_name)) {
  1367. verbosestream << "Server sent us messages on unregistered channel "
  1368. << channel_name << ", ignoring." << std::endl;
  1369. return;
  1370. }
  1371. m_script->on_modchannel_message(channel_name, sender, channel_msg);
  1372. }
  1373. void Client::handleCommand_ModChannelSignal(NetworkPacket *pkt)
  1374. {
  1375. u8 signal_tmp;
  1376. ModChannelSignal signal;
  1377. std::string channel;
  1378. *pkt >> signal_tmp >> channel;
  1379. signal = (ModChannelSignal)signal_tmp;
  1380. bool valid_signal = true;
  1381. // @TODO: send Signal to Lua API
  1382. switch (signal) {
  1383. case MODCHANNEL_SIGNAL_JOIN_OK:
  1384. m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE);
  1385. infostream << "Server ack our mod channel join on channel `" << channel
  1386. << "`, joining." << std::endl;
  1387. break;
  1388. case MODCHANNEL_SIGNAL_JOIN_FAILURE:
  1389. // Unable to join, remove channel
  1390. m_modchannel_mgr->leaveChannel(channel, 0);
  1391. infostream << "Server refused our mod channel join on channel `" << channel
  1392. << "`" << std::endl;
  1393. break;
  1394. case MODCHANNEL_SIGNAL_LEAVE_OK:
  1395. #ifndef NDEBUG
  1396. infostream << "Server ack our mod channel leave on channel " << channel
  1397. << "`, leaving." << std::endl;
  1398. #endif
  1399. break;
  1400. case MODCHANNEL_SIGNAL_LEAVE_FAILURE:
  1401. infostream << "Server refused our mod channel leave on channel `" << channel
  1402. << "`" << std::endl;
  1403. break;
  1404. case MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED:
  1405. #ifndef NDEBUG
  1406. // Generally unused, but ensure we don't do an implementation error
  1407. infostream << "Server tells us we sent a message on channel `" << channel
  1408. << "` but we are not registered. Message was dropped." << std::endl;
  1409. #endif
  1410. break;
  1411. case MODCHANNEL_SIGNAL_SET_STATE: {
  1412. u8 state;
  1413. *pkt >> state;
  1414. if (state == MODCHANNEL_STATE_INIT || state >= MODCHANNEL_STATE_MAX) {
  1415. infostream << "Received wrong channel state " << state
  1416. << ", ignoring." << std::endl;
  1417. return;
  1418. }
  1419. m_modchannel_mgr->setChannelState(channel, (ModChannelState) state);
  1420. infostream << "Server sets mod channel `" << channel
  1421. << "` in read-only mode." << std::endl;
  1422. break;
  1423. }
  1424. default:
  1425. #ifndef NDEBUG
  1426. warningstream << "Received unhandled mod channel signal ID "
  1427. << signal << ", ignoring." << std::endl;
  1428. #endif
  1429. valid_signal = false;
  1430. break;
  1431. }
  1432. // If signal is valid, forward it to client side mods
  1433. if (valid_signal)
  1434. m_script->on_modchannel_signal(channel, signal);
  1435. }
  1436. void Client::handleCommand_MinimapModes(NetworkPacket *pkt)
  1437. {
  1438. u16 count; // modes
  1439. u16 mode; // wanted current mode index after change
  1440. *pkt >> count >> mode;
  1441. if (m_minimap)
  1442. m_minimap->clearModes();
  1443. for (size_t index = 0; index < count; index++) {
  1444. u16 type;
  1445. std::string label;
  1446. u16 size;
  1447. std::string texture;
  1448. u16 scale;
  1449. *pkt >> type >> label >> size >> texture >> scale;
  1450. if (m_minimap)
  1451. m_minimap->addMode(MinimapType(type), size, label, texture, scale);
  1452. }
  1453. if (m_minimap)
  1454. m_minimap->setModeIndex(mode);
  1455. }
  1456. void Client::handleCommand_SetLighting(NetworkPacket *pkt)
  1457. {
  1458. Lighting& lighting = m_env.getLocalPlayer()->getLighting();
  1459. if (pkt->getRemainingBytes() >= 4)
  1460. *pkt >> lighting.shadow_intensity;
  1461. }