clientpackethandler.cpp 47 KB

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