serverpackethandler.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  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 "chatmessage.h"
  17. #include "server.h"
  18. #include "log.h"
  19. #include "content_sao.h"
  20. #include "emerge.h"
  21. #include "mapblock.h"
  22. #include "modchannels.h"
  23. #include "nodedef.h"
  24. #include "remoteplayer.h"
  25. #include "rollback_interface.h"
  26. #include "scripting_server.h"
  27. #include "settings.h"
  28. #include "tool.h"
  29. #include "version.h"
  30. #include "network/connection.h"
  31. #include "network/networkprotocol.h"
  32. #include "network/serveropcodes.h"
  33. #include "util/auth.h"
  34. #include "util/base64.h"
  35. #include "util/pointedthing.h"
  36. #include "util/serialize.h"
  37. #include "util/srp.h"
  38. void Server::handleCommand_Deprecated(NetworkPacket* pkt)
  39. {
  40. infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
  41. << " not supported anymore" << std::endl;
  42. }
  43. void Server::handleCommand_Init(NetworkPacket* pkt)
  44. {
  45. if(pkt->getSize() < 1)
  46. return;
  47. RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
  48. std::string addr_s;
  49. try {
  50. Address address = getPeerAddress(pkt->getPeerId());
  51. addr_s = address.serializeString();
  52. }
  53. catch (con::PeerNotFoundException &e) {
  54. /*
  55. * no peer for this packet found
  56. * most common reason is peer timeout, e.g. peer didn't
  57. * respond for some time, your server was overloaded or
  58. * things like that.
  59. */
  60. infostream << "Server::ProcessData(): Canceling: peer "
  61. << pkt->getPeerId() << " not found" << std::endl;
  62. return;
  63. }
  64. // If net_proto_version is set, this client has already been handled
  65. if (client->getState() > CS_Created) {
  66. verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
  67. << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
  68. return;
  69. }
  70. verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
  71. << pkt->getPeerId() << ")" << std::endl;
  72. // Do not allow multiple players in simple singleplayer mode.
  73. // This isn't a perfect way to do it, but will suffice for now
  74. if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
  75. infostream << "Server: Not allowing another client (" << addr_s
  76. << ") to connect in simple singleplayer mode" << std::endl;
  77. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SINGLEPLAYER);
  78. return;
  79. }
  80. // First byte after command is maximum supported
  81. // serialization version
  82. u8 client_max;
  83. u16 supp_compr_modes;
  84. u16 min_net_proto_version = 0;
  85. u16 max_net_proto_version;
  86. std::string playerName;
  87. *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
  88. >> max_net_proto_version >> playerName;
  89. u8 our_max = SER_FMT_VER_HIGHEST_READ;
  90. // Use the highest version supported by both
  91. u8 depl_serial_v = std::min(client_max, our_max);
  92. // If it's lower than the lowest supported, give up.
  93. if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
  94. depl_serial_v = SER_FMT_VER_INVALID;
  95. if (depl_serial_v == SER_FMT_VER_INVALID) {
  96. actionstream << "Server: A mismatched client tried to connect from "
  97. << addr_s << std::endl;
  98. infostream<<"Server: Cannot negotiate serialization version with "
  99. << addr_s << std::endl;
  100. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
  101. return;
  102. }
  103. client->setPendingSerializationVersion(depl_serial_v);
  104. /*
  105. Read and check network protocol version
  106. */
  107. u16 net_proto_version = 0;
  108. // Figure out a working version if it is possible at all
  109. if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
  110. min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
  111. // If maximum is larger than our maximum, go with our maximum
  112. if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
  113. net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
  114. // Else go with client's maximum
  115. else
  116. net_proto_version = max_net_proto_version;
  117. }
  118. verbosestream << "Server: " << addr_s << ": Protocol version: min: "
  119. << min_net_proto_version << ", max: " << max_net_proto_version
  120. << ", chosen: " << net_proto_version << std::endl;
  121. client->net_proto_version = net_proto_version;
  122. if ((g_settings->getBool("strict_protocol_version_checking") &&
  123. net_proto_version != LATEST_PROTOCOL_VERSION) ||
  124. net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
  125. net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
  126. actionstream << "Server: A mismatched client tried to connect from "
  127. << addr_s << std::endl;
  128. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
  129. return;
  130. }
  131. /*
  132. Validate player name
  133. */
  134. const char* playername = playerName.c_str();
  135. size_t pns = playerName.size();
  136. if (pns == 0 || pns > PLAYERNAME_SIZE) {
  137. actionstream << "Server: Player with "
  138. << ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty")
  139. << " name tried to connect from " << addr_s << std::endl;
  140. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
  141. return;
  142. }
  143. if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
  144. actionstream << "Server: Player with an invalid name "
  145. << "tried to connect from " << addr_s << std::endl;
  146. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
  147. return;
  148. }
  149. m_clients.setPlayerName(pkt->getPeerId(), playername);
  150. //TODO (later) case insensitivity
  151. std::string legacyPlayerNameCasing = playerName;
  152. if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
  153. actionstream << "Server: Player with the name \"singleplayer\" "
  154. << "tried to connect from " << addr_s << std::endl;
  155. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
  156. return;
  157. }
  158. {
  159. std::string reason;
  160. if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
  161. actionstream << "Server: Player with the name \"" << playerName << "\" "
  162. << "tried to connect from " << addr_s << " "
  163. << "but it was disallowed for the following reason: "
  164. << reason << std::endl;
  165. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
  166. return;
  167. }
  168. }
  169. infostream << "Server: New connection: \"" << playerName << "\" from "
  170. << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
  171. // Enforce user limit.
  172. // Don't enforce for users that have some admin right or mod permits it.
  173. if (m_clients.isUserLimitReached() &&
  174. playername != g_settings->get("name") &&
  175. !m_script->can_bypass_userlimit(playername, addr_s)) {
  176. actionstream << "Server: " << playername << " tried to join from "
  177. << addr_s << ", but there" << " are already max_users="
  178. << g_settings->getU16("max_users") << " players." << std::endl;
  179. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_TOO_MANY_USERS);
  180. return;
  181. }
  182. /*
  183. Compose auth methods for answer
  184. */
  185. std::string encpwd; // encrypted Password field for the user
  186. bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
  187. u32 auth_mechs = 0;
  188. client->chosen_mech = AUTH_MECHANISM_NONE;
  189. if (has_auth) {
  190. std::vector<std::string> pwd_components = str_split(encpwd, '#');
  191. if (pwd_components.size() == 4) {
  192. if (pwd_components[1] == "1") { // 1 means srp
  193. auth_mechs |= AUTH_MECHANISM_SRP;
  194. client->enc_pwd = encpwd;
  195. } else {
  196. actionstream << "User " << playername
  197. << " tried to log in, but password field"
  198. << " was invalid (unknown mechcode)." << std::endl;
  199. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
  200. return;
  201. }
  202. } else if (base64_is_valid(encpwd)) {
  203. auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
  204. client->enc_pwd = encpwd;
  205. } else {
  206. actionstream << "User " << playername
  207. << " tried to log in, but password field"
  208. << " was invalid (invalid base64)." << std::endl;
  209. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
  210. return;
  211. }
  212. } else {
  213. std::string default_password = g_settings->get("default_password");
  214. if (default_password.length() == 0) {
  215. auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
  216. } else {
  217. // Take care of default passwords.
  218. client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
  219. auth_mechs |= AUTH_MECHANISM_SRP;
  220. // Allocate player in db, but only on successful login.
  221. client->create_player_on_auth_success = true;
  222. }
  223. }
  224. /*
  225. Answer with a TOCLIENT_HELLO
  226. */
  227. verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
  228. << auth_mechs << std::endl;
  229. NetworkPacket resp_pkt(TOCLIENT_HELLO, 1 + 4
  230. + legacyPlayerNameCasing.size(), pkt->getPeerId());
  231. u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
  232. resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
  233. << auth_mechs << legacyPlayerNameCasing;
  234. Send(&resp_pkt);
  235. client->allowed_auth_mechs = auth_mechs;
  236. client->setDeployedCompressionMode(depl_compress_mode);
  237. m_clients.event(pkt->getPeerId(), CSE_Hello);
  238. }
  239. void Server::handleCommand_Init2(NetworkPacket* pkt)
  240. {
  241. verbosestream << "Server: Got TOSERVER_INIT2 from "
  242. << pkt->getPeerId() << std::endl;
  243. m_clients.event(pkt->getPeerId(), CSE_GotInit2);
  244. u16 protocol_version = m_clients.getProtocolVersion(pkt->getPeerId());
  245. std::string lang;
  246. if (pkt->getSize() > 0)
  247. *pkt >> lang;
  248. /*
  249. Send some initialization data
  250. */
  251. infostream << "Server: Sending content to "
  252. << getPlayerName(pkt->getPeerId()) << std::endl;
  253. // Send player movement settings
  254. SendMovement(pkt->getPeerId());
  255. // Send item definitions
  256. SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
  257. // Send node definitions
  258. SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
  259. m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
  260. // Send media announcement
  261. sendMediaAnnouncement(pkt->getPeerId(), lang);
  262. // Send detached inventories
  263. sendDetachedInventories(pkt->getPeerId());
  264. // Send time of day
  265. u16 time = m_env->getTimeOfDay();
  266. float time_speed = g_settings->getFloat("time_speed");
  267. SendTimeOfDay(pkt->getPeerId(), time, time_speed);
  268. SendCSMFlavourLimits(pkt->getPeerId());
  269. // Warnings about protocol version can be issued here
  270. if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
  271. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  272. L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
  273. L"WITH THIS SERVER!"));
  274. }
  275. }
  276. void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
  277. {
  278. std::vector<std::string> tosend;
  279. u16 numfiles;
  280. *pkt >> numfiles;
  281. infostream << "Sending " << numfiles << " files to "
  282. << getPlayerName(pkt->getPeerId()) << std::endl;
  283. verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
  284. for (u16 i = 0; i < numfiles; i++) {
  285. std::string name;
  286. *pkt >> name;
  287. tosend.push_back(name);
  288. verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
  289. << name << std::endl;
  290. }
  291. sendRequestedMedia(pkt->getPeerId(), tosend);
  292. }
  293. void Server::handleCommand_ClientReady(NetworkPacket* pkt)
  294. {
  295. session_t peer_id = pkt->getPeerId();
  296. PlayerSAO* playersao = StageTwoClientInit(peer_id);
  297. if (playersao == NULL) {
  298. actionstream
  299. << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
  300. << peer_id << std::endl;
  301. DisconnectPeer(peer_id);
  302. return;
  303. }
  304. if (pkt->getSize() < 8) {
  305. errorstream
  306. << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
  307. << peer_id << std::endl;
  308. DisconnectPeer(peer_id);
  309. return;
  310. }
  311. u8 major_ver, minor_ver, patch_ver, reserved;
  312. std::string full_ver;
  313. *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
  314. m_clients.setClientVersion(
  315. peer_id, major_ver, minor_ver, patch_ver,
  316. full_ver);
  317. const std::vector<std::string> &players = m_clients.getPlayerNames();
  318. NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
  319. list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
  320. for (const std::string &player: players) {
  321. list_pkt << player;
  322. }
  323. m_clients.send(peer_id, 0, &list_pkt, true);
  324. NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
  325. // (u16) 1 + std::string represents a pseudo vector serialization representation
  326. notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
  327. m_clients.sendToAll(&notice_pkt);
  328. m_clients.event(peer_id, CSE_SetClientReady);
  329. m_script->on_joinplayer(playersao);
  330. // Send shutdown timer if shutdown has been scheduled
  331. if (m_shutdown_timer > 0.0f) {
  332. std::wstringstream ws;
  333. ws << L"*** Server shutting down in "
  334. << duration_to_string(myround(m_shutdown_timer)).c_str() << ".";
  335. SendChatMessage(pkt->getPeerId(), ws.str());
  336. }
  337. }
  338. void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
  339. {
  340. if (pkt->getSize() < 1)
  341. return;
  342. /*
  343. [0] u16 command
  344. [2] u8 count
  345. [3] v3s16 pos_0
  346. [3+6] v3s16 pos_1
  347. ...
  348. */
  349. u8 count;
  350. *pkt >> count;
  351. RemoteClient *client = getClient(pkt->getPeerId());
  352. if ((s16)pkt->getSize() < 1 + (int)count * 6) {
  353. throw con::InvalidIncomingDataException
  354. ("GOTBLOCKS length is too short");
  355. }
  356. for (u16 i = 0; i < count; i++) {
  357. v3s16 p;
  358. *pkt >> p;
  359. client->GotBlock(p);
  360. }
  361. }
  362. void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
  363. NetworkPacket *pkt)
  364. {
  365. if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
  366. return;
  367. v3s32 ps, ss;
  368. s32 f32pitch, f32yaw;
  369. u8 f32fov;
  370. *pkt >> ps;
  371. *pkt >> ss;
  372. *pkt >> f32pitch;
  373. *pkt >> f32yaw;
  374. f32 pitch = (f32)f32pitch / 100.0f;
  375. f32 yaw = (f32)f32yaw / 100.0f;
  376. u32 keyPressed = 0;
  377. // default behavior (in case an old client doesn't send these)
  378. f32 fov = 0;
  379. u8 wanted_range = 0;
  380. *pkt >> keyPressed;
  381. *pkt >> f32fov;
  382. fov = (f32)f32fov / 80.0f;
  383. *pkt >> wanted_range;
  384. v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
  385. v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
  386. pitch = modulo360f(pitch);
  387. yaw = wrapDegrees_0_360(yaw);
  388. playersao->setBasePosition(position);
  389. player->setSpeed(speed);
  390. playersao->setPitch(pitch);
  391. playersao->setYaw(yaw);
  392. playersao->setFov(fov);
  393. playersao->setWantedRange(wanted_range);
  394. player->keyPressed = keyPressed;
  395. player->control.up = (keyPressed & 1);
  396. player->control.down = (keyPressed & 2);
  397. player->control.left = (keyPressed & 4);
  398. player->control.right = (keyPressed & 8);
  399. player->control.jump = (keyPressed & 16);
  400. player->control.aux1 = (keyPressed & 32);
  401. player->control.sneak = (keyPressed & 64);
  402. player->control.LMB = (keyPressed & 128);
  403. player->control.RMB = (keyPressed & 256);
  404. if (playersao->checkMovementCheat()) {
  405. // Call callbacks
  406. m_script->on_cheat(playersao, "moved_too_fast");
  407. SendMovePlayer(pkt->getPeerId());
  408. }
  409. }
  410. void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
  411. {
  412. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  413. if (player == NULL) {
  414. errorstream << "Server::ProcessData(): Canceling: "
  415. "No player for peer_id=" << pkt->getPeerId()
  416. << " disconnecting peer!" << std::endl;
  417. DisconnectPeer(pkt->getPeerId());
  418. return;
  419. }
  420. PlayerSAO *playersao = player->getPlayerSAO();
  421. if (playersao == NULL) {
  422. errorstream << "Server::ProcessData(): Canceling: "
  423. "No player object for peer_id=" << pkt->getPeerId()
  424. << " disconnecting peer!" << std::endl;
  425. DisconnectPeer(pkt->getPeerId());
  426. return;
  427. }
  428. // If player is dead we don't care of this packet
  429. if (playersao->isDead()) {
  430. verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
  431. << " is dead. Ignoring packet";
  432. return;
  433. }
  434. process_PlayerPos(player, playersao, pkt);
  435. }
  436. void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
  437. {
  438. if (pkt->getSize() < 1)
  439. return;
  440. /*
  441. [0] u16 command
  442. [2] u8 count
  443. [3] v3s16 pos_0
  444. [3+6] v3s16 pos_1
  445. ...
  446. */
  447. u8 count;
  448. *pkt >> count;
  449. RemoteClient *client = getClient(pkt->getPeerId());
  450. if ((s16)pkt->getSize() < 1 + (int)count * 6) {
  451. throw con::InvalidIncomingDataException
  452. ("DELETEDBLOCKS length is too short");
  453. }
  454. for (u16 i = 0; i < count; i++) {
  455. v3s16 p;
  456. *pkt >> p;
  457. client->SetBlockNotSent(p);
  458. }
  459. }
  460. void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
  461. {
  462. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  463. if (player == NULL) {
  464. errorstream << "Server::ProcessData(): Canceling: "
  465. "No player for peer_id=" << pkt->getPeerId()
  466. << " disconnecting peer!" << std::endl;
  467. DisconnectPeer(pkt->getPeerId());
  468. return;
  469. }
  470. PlayerSAO *playersao = player->getPlayerSAO();
  471. if (playersao == NULL) {
  472. errorstream << "Server::ProcessData(): Canceling: "
  473. "No player object for peer_id=" << pkt->getPeerId()
  474. << " disconnecting peer!" << std::endl;
  475. DisconnectPeer(pkt->getPeerId());
  476. return;
  477. }
  478. // Strip command and create a stream
  479. std::string datastring(pkt->getString(0), pkt->getSize());
  480. verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
  481. << std::endl;
  482. std::istringstream is(datastring, std::ios_base::binary);
  483. // Create an action
  484. InventoryAction *a = InventoryAction::deSerialize(is);
  485. if (!a) {
  486. infostream << "TOSERVER_INVENTORY_ACTION: "
  487. << "InventoryAction::deSerialize() returned NULL"
  488. << std::endl;
  489. return;
  490. }
  491. // If something goes wrong, this player is to blame
  492. RollbackScopeActor rollback_scope(m_rollback,
  493. std::string("player:")+player->getName());
  494. /*
  495. Note: Always set inventory not sent, to repair cases
  496. where the client made a bad prediction.
  497. */
  498. /*
  499. Handle restrictions and special cases of the move action
  500. */
  501. if (a->getType() == IAction::Move) {
  502. IMoveAction *ma = (IMoveAction*)a;
  503. ma->from_inv.applyCurrentPlayer(player->getName());
  504. ma->to_inv.applyCurrentPlayer(player->getName());
  505. setInventoryModified(ma->from_inv, false);
  506. setInventoryModified(ma->to_inv, false);
  507. bool from_inv_is_current_player =
  508. (ma->from_inv.type == InventoryLocation::PLAYER) &&
  509. (ma->from_inv.name == player->getName());
  510. bool to_inv_is_current_player =
  511. (ma->to_inv.type == InventoryLocation::PLAYER) &&
  512. (ma->to_inv.name == player->getName());
  513. InventoryLocation *remote = from_inv_is_current_player ?
  514. &ma->to_inv : &ma->from_inv;
  515. // Check for out-of-range interaction
  516. if (remote->type == InventoryLocation::NODEMETA) {
  517. v3f node_pos = intToFloat(remote->p, BS);
  518. v3f player_pos = player->getPlayerSAO()->getBasePosition();
  519. f32 d = player_pos.getDistanceFrom(node_pos);
  520. if (!checkInteractDistance(player, d, "inventory"))
  521. return;
  522. }
  523. /*
  524. Disable moving items out of craftpreview
  525. */
  526. if (ma->from_list == "craftpreview") {
  527. infostream << "Ignoring IMoveAction from "
  528. << (ma->from_inv.dump()) << ":" << ma->from_list
  529. << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
  530. << " because src is " << ma->from_list << std::endl;
  531. delete a;
  532. return;
  533. }
  534. /*
  535. Disable moving items into craftresult and craftpreview
  536. */
  537. if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
  538. infostream << "Ignoring IMoveAction from "
  539. << (ma->from_inv.dump()) << ":" << ma->from_list
  540. << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
  541. << " because dst is " << ma->to_list << std::endl;
  542. delete a;
  543. return;
  544. }
  545. // Disallow moving items in elsewhere than player's inventory
  546. // if not allowed to interact
  547. if (!checkPriv(player->getName(), "interact") &&
  548. (!from_inv_is_current_player ||
  549. !to_inv_is_current_player)) {
  550. infostream << "Cannot move outside of player's inventory: "
  551. << "No interact privilege" << std::endl;
  552. delete a;
  553. return;
  554. }
  555. }
  556. /*
  557. Handle restrictions and special cases of the drop action
  558. */
  559. else if (a->getType() == IAction::Drop) {
  560. IDropAction *da = (IDropAction*)a;
  561. da->from_inv.applyCurrentPlayer(player->getName());
  562. setInventoryModified(da->from_inv, false);
  563. /*
  564. Disable dropping items out of craftpreview
  565. */
  566. if (da->from_list == "craftpreview") {
  567. infostream << "Ignoring IDropAction from "
  568. << (da->from_inv.dump()) << ":" << da->from_list
  569. << " because src is " << da->from_list << std::endl;
  570. delete a;
  571. return;
  572. }
  573. // Disallow dropping items if not allowed to interact
  574. if (!checkPriv(player->getName(), "interact")) {
  575. delete a;
  576. return;
  577. }
  578. // Disallow dropping items if dead
  579. if (playersao->isDead()) {
  580. infostream << "Ignoring IDropAction from "
  581. << (da->from_inv.dump()) << ":" << da->from_list
  582. << " because player is dead." << std::endl;
  583. delete a;
  584. return;
  585. }
  586. }
  587. /*
  588. Handle restrictions and special cases of the craft action
  589. */
  590. else if (a->getType() == IAction::Craft) {
  591. ICraftAction *ca = (ICraftAction*)a;
  592. ca->craft_inv.applyCurrentPlayer(player->getName());
  593. setInventoryModified(ca->craft_inv, false);
  594. //bool craft_inv_is_current_player =
  595. // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
  596. // (ca->craft_inv.name == player->getName());
  597. // Disallow crafting if not allowed to interact
  598. if (!checkPriv(player->getName(), "interact")) {
  599. infostream << "Cannot craft: "
  600. << "No interact privilege" << std::endl;
  601. delete a;
  602. return;
  603. }
  604. }
  605. // Do the action
  606. a->apply(this, playersao, this);
  607. // Eat the action
  608. delete a;
  609. SendInventory(playersao);
  610. }
  611. void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
  612. {
  613. /*
  614. u16 command
  615. u16 length
  616. wstring message
  617. */
  618. u16 len;
  619. *pkt >> len;
  620. std::wstring message;
  621. for (u16 i = 0; i < len; i++) {
  622. u16 tmp_wchar;
  623. *pkt >> tmp_wchar;
  624. message += (wchar_t)tmp_wchar;
  625. }
  626. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  627. if (player == NULL) {
  628. errorstream << "Server::ProcessData(): Canceling: "
  629. "No player for peer_id=" << pkt->getPeerId()
  630. << " disconnecting peer!" << std::endl;
  631. DisconnectPeer(pkt->getPeerId());
  632. return;
  633. }
  634. // Get player name of this client
  635. std::string name = player->getName();
  636. std::wstring wname = narrow_to_wide(name);
  637. std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
  638. if (!answer_to_sender.empty()) {
  639. // Send the answer to sender
  640. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
  641. answer_to_sender, wname));
  642. }
  643. }
  644. void Server::handleCommand_Damage(NetworkPacket* pkt)
  645. {
  646. u8 damage;
  647. *pkt >> damage;
  648. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  649. if (player == NULL) {
  650. errorstream << "Server::ProcessData(): Canceling: "
  651. "No player for peer_id=" << pkt->getPeerId()
  652. << " disconnecting peer!" << std::endl;
  653. DisconnectPeer(pkt->getPeerId());
  654. return;
  655. }
  656. PlayerSAO *playersao = player->getPlayerSAO();
  657. if (playersao == NULL) {
  658. errorstream << "Server::ProcessData(): Canceling: "
  659. "No player object for peer_id=" << pkt->getPeerId()
  660. << " disconnecting peer!" << std::endl;
  661. DisconnectPeer(pkt->getPeerId());
  662. return;
  663. }
  664. if (g_settings->getBool("enable_damage")) {
  665. if (playersao->isDead()) {
  666. verbosestream << "Server::ProcessData(): Info: "
  667. "Ignoring damage as player " << player->getName()
  668. << " is already dead." << std::endl;
  669. return;
  670. }
  671. actionstream << player->getName() << " damaged by "
  672. << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
  673. << std::endl;
  674. PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
  675. playersao->setHP(playersao->getHP() - damage, reason);
  676. SendPlayerHPOrDie(playersao, reason);
  677. }
  678. }
  679. void Server::handleCommand_Password(NetworkPacket* pkt)
  680. {
  681. if (pkt->getSize() != PASSWORD_SIZE * 2)
  682. return;
  683. std::string oldpwd;
  684. std::string newpwd;
  685. // Deny for clients using the new protocol
  686. RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
  687. if (client->net_proto_version >= 25) {
  688. infostream << "Server::handleCommand_Password(): Denying change: "
  689. << " Client protocol version for peer_id=" << pkt->getPeerId()
  690. << " too new!" << std::endl;
  691. return;
  692. }
  693. for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
  694. char c = pkt->getChar(i);
  695. if (c == 0)
  696. break;
  697. oldpwd += c;
  698. }
  699. for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
  700. char c = pkt->getChar(PASSWORD_SIZE + i);
  701. if (c == 0)
  702. break;
  703. newpwd += c;
  704. }
  705. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  706. if (player == NULL) {
  707. errorstream << "Server::ProcessData(): Canceling: "
  708. "No player for peer_id=" << pkt->getPeerId()
  709. << " disconnecting peer!" << std::endl;
  710. DisconnectPeer(pkt->getPeerId());
  711. return;
  712. }
  713. if (!base64_is_valid(newpwd)) {
  714. infostream<<"Server: " << player->getName() <<
  715. " supplied invalid password hash" << std::endl;
  716. // Wrong old password supplied!!
  717. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  718. L"Invalid new password hash supplied. Password NOT changed."));
  719. return;
  720. }
  721. infostream << "Server: Client requests a password change from "
  722. << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
  723. std::string playername = player->getName();
  724. std::string checkpwd;
  725. m_script->getAuth(playername, &checkpwd, NULL);
  726. if (oldpwd != checkpwd) {
  727. infostream << "Server: invalid old password" << std::endl;
  728. // Wrong old password supplied!!
  729. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  730. L"Invalid old password supplied. Password NOT changed."));
  731. return;
  732. }
  733. bool success = m_script->setPassword(playername, newpwd);
  734. if (success) {
  735. actionstream << player->getName() << " changes password" << std::endl;
  736. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  737. L"Password change successful."));
  738. } else {
  739. actionstream << player->getName() << " tries to change password but "
  740. << "it fails" << std::endl;
  741. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  742. L"Password change failed or unavailable."));
  743. }
  744. }
  745. void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
  746. {
  747. if (pkt->getSize() < 2)
  748. return;
  749. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  750. if (player == NULL) {
  751. errorstream << "Server::ProcessData(): Canceling: "
  752. "No player for peer_id=" << pkt->getPeerId()
  753. << " disconnecting peer!" << std::endl;
  754. DisconnectPeer(pkt->getPeerId());
  755. return;
  756. }
  757. PlayerSAO *playersao = player->getPlayerSAO();
  758. if (playersao == NULL) {
  759. errorstream << "Server::ProcessData(): Canceling: "
  760. "No player object for peer_id=" << pkt->getPeerId()
  761. << " disconnecting peer!" << std::endl;
  762. DisconnectPeer(pkt->getPeerId());
  763. return;
  764. }
  765. u16 item;
  766. *pkt >> item;
  767. playersao->setWieldIndex(item);
  768. }
  769. void Server::handleCommand_Respawn(NetworkPacket* pkt)
  770. {
  771. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  772. if (player == NULL) {
  773. errorstream << "Server::ProcessData(): Canceling: "
  774. "No player for peer_id=" << pkt->getPeerId()
  775. << " disconnecting peer!" << std::endl;
  776. DisconnectPeer(pkt->getPeerId());
  777. return;
  778. }
  779. PlayerSAO *playersao = player->getPlayerSAO();
  780. assert(playersao);
  781. if (!playersao->isDead())
  782. return;
  783. RespawnPlayer(pkt->getPeerId());
  784. actionstream << player->getName() << " respawns at "
  785. << PP(playersao->getBasePosition() / BS) << std::endl;
  786. // ActiveObject is added to environment in AsyncRunStep after
  787. // the previous addition has been successfully removed
  788. }
  789. bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string what)
  790. {
  791. PlayerSAO *playersao = player->getPlayerSAO();
  792. const InventoryList *hlist = playersao->getInventory()->getList("hand");
  793. const ItemDefinition &playeritem_def =
  794. playersao->getWieldedItem().getDefinition(m_itemdef);
  795. const ItemDefinition &hand_def =
  796. hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
  797. float max_d = BS * playeritem_def.range;
  798. float max_d_hand = BS * hand_def.range;
  799. if (max_d < 0 && max_d_hand >= 0)
  800. max_d = max_d_hand;
  801. else if (max_d < 0)
  802. max_d = BS * 4.0f;
  803. // cube diagonal: sqrt(3) = 1.732
  804. if (d > max_d * 1.732) {
  805. actionstream << "Player " << player->getName()
  806. << " tried to access " << what
  807. << " from too far: "
  808. << "d=" << d <<", max_d=" << max_d
  809. << ". ignoring." << std::endl;
  810. // Call callbacks
  811. m_script->on_cheat(playersao, "interacted_too_far");
  812. return false;
  813. }
  814. return true;
  815. }
  816. void Server::handleCommand_Interact(NetworkPacket* pkt)
  817. {
  818. /*
  819. [0] u16 command
  820. [2] u8 action
  821. [3] u16 item
  822. [5] u32 length of the next item (plen)
  823. [9] serialized PointedThing
  824. [9 + plen] player position information
  825. actions:
  826. 0: start digging (from undersurface) or use
  827. 1: stop digging (all parameters ignored)
  828. 2: digging completed
  829. 3: place block or item (to abovesurface)
  830. 4: use item
  831. 5: rightclick air ("activate")
  832. */
  833. u8 action;
  834. u16 item_i;
  835. *pkt >> action;
  836. *pkt >> item_i;
  837. std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
  838. PointedThing pointed;
  839. pointed.deSerialize(tmp_is);
  840. verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
  841. << item_i << ", pointed=" << pointed.dump() << std::endl;
  842. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  843. if (player == NULL) {
  844. errorstream << "Server::ProcessData(): Canceling: "
  845. "No player for peer_id=" << pkt->getPeerId()
  846. << " disconnecting peer!" << std::endl;
  847. DisconnectPeer(pkt->getPeerId());
  848. return;
  849. }
  850. PlayerSAO *playersao = player->getPlayerSAO();
  851. if (playersao == NULL) {
  852. errorstream << "Server::ProcessData(): Canceling: "
  853. "No player object for peer_id=" << pkt->getPeerId()
  854. << " disconnecting peer!" << std::endl;
  855. DisconnectPeer(pkt->getPeerId());
  856. return;
  857. }
  858. if (playersao->isDead()) {
  859. actionstream << "Server: NoCheat: " << player->getName()
  860. << " tried to interact while dead; ignoring." << std::endl;
  861. if (pointed.type == POINTEDTHING_NODE) {
  862. // Re-send block to revert change on client-side
  863. RemoteClient *client = getClient(pkt->getPeerId());
  864. v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
  865. client->SetBlockNotSent(blockpos);
  866. }
  867. // Call callbacks
  868. m_script->on_cheat(playersao, "interacted_while_dead");
  869. return;
  870. }
  871. process_PlayerPos(player, playersao, pkt);
  872. v3f player_pos = playersao->getLastGoodPosition();
  873. // Update wielded item
  874. playersao->setWieldIndex(item_i);
  875. // Get pointed to node (undefined if not POINTEDTYPE_NODE)
  876. v3s16 p_under = pointed.node_undersurface;
  877. v3s16 p_above = pointed.node_abovesurface;
  878. // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
  879. ServerActiveObject *pointed_object = NULL;
  880. if (pointed.type == POINTEDTHING_OBJECT) {
  881. pointed_object = m_env->getActiveObject(pointed.object_id);
  882. if (pointed_object == NULL) {
  883. verbosestream << "TOSERVER_INTERACT: "
  884. "pointed object is NULL" << std::endl;
  885. return;
  886. }
  887. }
  888. v3f pointed_pos_under = player_pos;
  889. v3f pointed_pos_above = player_pos;
  890. if (pointed.type == POINTEDTHING_NODE) {
  891. pointed_pos_under = intToFloat(p_under, BS);
  892. pointed_pos_above = intToFloat(p_above, BS);
  893. }
  894. else if (pointed.type == POINTEDTHING_OBJECT) {
  895. pointed_pos_under = pointed_object->getBasePosition();
  896. pointed_pos_above = pointed_pos_under;
  897. }
  898. /*
  899. Make sure the player is allowed to do it
  900. */
  901. if (!checkPriv(player->getName(), "interact")) {
  902. actionstream<<player->getName()<<" attempted to interact with "
  903. <<pointed.dump()<<" without 'interact' privilege"
  904. <<std::endl;
  905. // Re-send block to revert change on client-side
  906. RemoteClient *client = getClient(pkt->getPeerId());
  907. // Digging completed -> under
  908. if (action == 2) {
  909. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
  910. client->SetBlockNotSent(blockpos);
  911. }
  912. // Placement -> above
  913. else if (action == 3) {
  914. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
  915. client->SetBlockNotSent(blockpos);
  916. }
  917. return;
  918. }
  919. /*
  920. Check that target is reasonably close
  921. (only when digging or placing things)
  922. */
  923. static thread_local const bool enable_anticheat =
  924. !g_settings->getBool("disable_anticheat");
  925. if ((action == 0 || action == 2 || action == 3 || action == 4) &&
  926. enable_anticheat && !isSingleplayer()) {
  927. float d = player_pos.getDistanceFrom(pointed_pos_under);
  928. if (!checkInteractDistance(player, d, pointed.dump())) {
  929. // Re-send block to revert change on client-side
  930. RemoteClient *client = getClient(pkt->getPeerId());
  931. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
  932. client->SetBlockNotSent(blockpos);
  933. return;
  934. }
  935. }
  936. /*
  937. If something goes wrong, this player is to blame
  938. */
  939. RollbackScopeActor rollback_scope(m_rollback,
  940. std::string("player:")+player->getName());
  941. /*
  942. 0: start digging or punch object
  943. */
  944. if (action == 0) {
  945. if (pointed.type == POINTEDTHING_NODE) {
  946. MapNode n(CONTENT_IGNORE);
  947. bool pos_ok;
  948. n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
  949. if (!pos_ok) {
  950. infostream << "Server: Not punching: Node not found."
  951. << " Adding block to emerge queue."
  952. << std::endl;
  953. m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
  954. getNodeBlockPos(p_above), false);
  955. }
  956. if (n.getContent() != CONTENT_IGNORE)
  957. m_script->node_on_punch(p_under, n, playersao, pointed);
  958. // Cheat prevention
  959. playersao->noCheatDigStart(p_under);
  960. }
  961. else if (pointed.type == POINTEDTHING_OBJECT) {
  962. // Skip if object can't be interacted with anymore
  963. if (pointed_object->isGone())
  964. return;
  965. actionstream<<player->getName()<<" punches object "
  966. <<pointed.object_id<<": "
  967. <<pointed_object->getDescription()<<std::endl;
  968. ItemStack punchitem = playersao->getWieldedItemOrHand();
  969. ToolCapabilities toolcap =
  970. punchitem.getToolCapabilities(m_itemdef);
  971. v3f dir = (pointed_object->getBasePosition() -
  972. (playersao->getBasePosition() + playersao->getEyeOffset())
  973. ).normalize();
  974. float time_from_last_punch =
  975. playersao->resetTimeFromLastPunch();
  976. s16 src_original_hp = pointed_object->getHP();
  977. s16 dst_origin_hp = playersao->getHP();
  978. pointed_object->punch(dir, &toolcap, playersao,
  979. time_from_last_punch);
  980. // If the object is a player and its HP changed
  981. if (src_original_hp != pointed_object->getHP() &&
  982. pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
  983. SendPlayerHPOrDie((PlayerSAO *)pointed_object,
  984. PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
  985. }
  986. // If the puncher is a player and its HP changed
  987. if (dst_origin_hp != playersao->getHP())
  988. SendPlayerHPOrDie(playersao,
  989. PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
  990. }
  991. } // action == 0
  992. /*
  993. 1: stop digging
  994. */
  995. else if (action == 1) {
  996. } // action == 1
  997. /*
  998. 2: Digging completed
  999. */
  1000. else if (action == 2) {
  1001. // Only digging of nodes
  1002. if (pointed.type == POINTEDTHING_NODE) {
  1003. bool pos_ok;
  1004. MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
  1005. if (!pos_ok) {
  1006. infostream << "Server: Not finishing digging: Node not found."
  1007. << " Adding block to emerge queue."
  1008. << std::endl;
  1009. m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
  1010. getNodeBlockPos(p_above), false);
  1011. }
  1012. /* Cheat prevention */
  1013. bool is_valid_dig = true;
  1014. if (enable_anticheat && !isSingleplayer()) {
  1015. v3s16 nocheat_p = playersao->getNoCheatDigPos();
  1016. float nocheat_t = playersao->getNoCheatDigTime();
  1017. playersao->noCheatDigEnd();
  1018. // If player didn't start digging this, ignore dig
  1019. if (nocheat_p != p_under) {
  1020. infostream << "Server: NoCheat: " << player->getName()
  1021. << " started digging "
  1022. << PP(nocheat_p) << " and completed digging "
  1023. << PP(p_under) << "; not digging." << std::endl;
  1024. is_valid_dig = false;
  1025. // Call callbacks
  1026. m_script->on_cheat(playersao, "finished_unknown_dig");
  1027. }
  1028. // Get player's wielded item
  1029. ItemStack playeritem = playersao->getWieldedItemOrHand();
  1030. ToolCapabilities playeritem_toolcap =
  1031. playeritem.getToolCapabilities(m_itemdef);
  1032. // Get diggability and expected digging time
  1033. DigParams params = getDigParams(m_nodedef->get(n).groups,
  1034. &playeritem_toolcap);
  1035. // If can't dig, try hand
  1036. if (!params.diggable) {
  1037. InventoryList *hlist = playersao->getInventory()->getList("hand");
  1038. const ToolCapabilities *tp = hlist
  1039. ? &hlist->getItem(0).getToolCapabilities(m_itemdef)
  1040. : m_itemdef->get("").tool_capabilities;
  1041. if (tp)
  1042. params = getDigParams(m_nodedef->get(n).groups, tp);
  1043. }
  1044. // If can't dig, ignore dig
  1045. if (!params.diggable) {
  1046. infostream << "Server: NoCheat: " << player->getName()
  1047. << " completed digging " << PP(p_under)
  1048. << ", which is not diggable with tool. not digging."
  1049. << std::endl;
  1050. is_valid_dig = false;
  1051. // Call callbacks
  1052. m_script->on_cheat(playersao, "dug_unbreakable");
  1053. }
  1054. // Check digging time
  1055. // If already invalidated, we don't have to
  1056. if (!is_valid_dig) {
  1057. // Well not our problem then
  1058. }
  1059. // Clean and long dig
  1060. else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
  1061. // All is good, but grab time from pool; don't care if
  1062. // it's actually available
  1063. playersao->getDigPool().grab(params.time);
  1064. }
  1065. // Short or laggy dig
  1066. // Try getting the time from pool
  1067. else if (playersao->getDigPool().grab(params.time)) {
  1068. // All is good
  1069. }
  1070. // Dig not possible
  1071. else {
  1072. infostream << "Server: NoCheat: " << player->getName()
  1073. << " completed digging " << PP(p_under)
  1074. << "too fast; not digging." << std::endl;
  1075. is_valid_dig = false;
  1076. // Call callbacks
  1077. m_script->on_cheat(playersao, "dug_too_fast");
  1078. }
  1079. }
  1080. /* Actually dig node */
  1081. if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
  1082. m_script->node_on_dig(p_under, n, playersao);
  1083. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
  1084. RemoteClient *client = getClient(pkt->getPeerId());
  1085. // Send unusual result (that is, node not being removed)
  1086. if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
  1087. // Re-send block to revert change on client-side
  1088. client->SetBlockNotSent(blockpos);
  1089. }
  1090. else {
  1091. client->ResendBlockIfOnWire(blockpos);
  1092. }
  1093. }
  1094. } // action == 2
  1095. /*
  1096. 3: place block or right-click object
  1097. */
  1098. else if (action == 3) {
  1099. ItemStack item = playersao->getWieldedItem();
  1100. // Reset build time counter
  1101. if (pointed.type == POINTEDTHING_NODE &&
  1102. item.getDefinition(m_itemdef).type == ITEM_NODE)
  1103. getClient(pkt->getPeerId())->m_time_from_building = 0.0;
  1104. if (pointed.type == POINTEDTHING_OBJECT) {
  1105. // Right click object
  1106. // Skip if object can't be interacted with anymore
  1107. if (pointed_object->isGone())
  1108. return;
  1109. actionstream << player->getName() << " right-clicks object "
  1110. << pointed.object_id << ": "
  1111. << pointed_object->getDescription() << std::endl;
  1112. // Do stuff
  1113. pointed_object->rightClick(playersao);
  1114. }
  1115. else if (m_script->item_OnPlace(
  1116. item, playersao, pointed)) {
  1117. // Placement was handled in lua
  1118. // Apply returned ItemStack
  1119. if (playersao->setWieldedItem(item)) {
  1120. SendInventory(playersao);
  1121. }
  1122. }
  1123. // If item has node placement prediction, always send the
  1124. // blocks to make sure the client knows what exactly happened
  1125. RemoteClient *client = getClient(pkt->getPeerId());
  1126. v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
  1127. v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
  1128. if (!item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
  1129. client->SetBlockNotSent(blockpos);
  1130. if (blockpos2 != blockpos) {
  1131. client->SetBlockNotSent(blockpos2);
  1132. }
  1133. }
  1134. else {
  1135. client->ResendBlockIfOnWire(blockpos);
  1136. if (blockpos2 != blockpos) {
  1137. client->ResendBlockIfOnWire(blockpos2);
  1138. }
  1139. }
  1140. } // action == 3
  1141. /*
  1142. 4: use
  1143. */
  1144. else if (action == 4) {
  1145. ItemStack item = playersao->getWieldedItem();
  1146. actionstream << player->getName() << " uses " << item.name
  1147. << ", pointing at " << pointed.dump() << std::endl;
  1148. if (m_script->item_OnUse(
  1149. item, playersao, pointed)) {
  1150. // Apply returned ItemStack
  1151. if (playersao->setWieldedItem(item)) {
  1152. SendInventory(playersao);
  1153. }
  1154. }
  1155. } // action == 4
  1156. /*
  1157. 5: rightclick air
  1158. */
  1159. else if (action == 5) {
  1160. ItemStack item = playersao->getWieldedItem();
  1161. actionstream << player->getName() << " activates "
  1162. << item.name << std::endl;
  1163. if (m_script->item_OnSecondaryUse(
  1164. item, playersao)) {
  1165. if( playersao->setWieldedItem(item)) {
  1166. SendInventory(playersao);
  1167. }
  1168. }
  1169. }
  1170. /*
  1171. Catch invalid actions
  1172. */
  1173. else {
  1174. warningstream << "Server: Invalid action "
  1175. << action << std::endl;
  1176. }
  1177. }
  1178. void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
  1179. {
  1180. u16 num;
  1181. *pkt >> num;
  1182. for (u16 k = 0; k < num; k++) {
  1183. s32 id;
  1184. *pkt >> id;
  1185. std::unordered_map<s32, ServerPlayingSound>::iterator i =
  1186. m_playing_sounds.find(id);
  1187. if (i == m_playing_sounds.end())
  1188. continue;
  1189. ServerPlayingSound &psound = i->second;
  1190. psound.clients.erase(pkt->getPeerId());
  1191. if (psound.clients.empty())
  1192. m_playing_sounds.erase(i++);
  1193. }
  1194. }
  1195. void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
  1196. {
  1197. v3s16 p;
  1198. std::string formname;
  1199. u16 num;
  1200. *pkt >> p >> formname >> num;
  1201. StringMap fields;
  1202. for (u16 k = 0; k < num; k++) {
  1203. std::string fieldname;
  1204. *pkt >> fieldname;
  1205. fields[fieldname] = pkt->readLongString();
  1206. }
  1207. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  1208. if (player == NULL) {
  1209. errorstream << "Server::ProcessData(): Canceling: "
  1210. "No player for peer_id=" << pkt->getPeerId()
  1211. << " disconnecting peer!" << std::endl;
  1212. DisconnectPeer(pkt->getPeerId());
  1213. return;
  1214. }
  1215. PlayerSAO *playersao = player->getPlayerSAO();
  1216. if (playersao == NULL) {
  1217. errorstream << "Server::ProcessData(): Canceling: "
  1218. "No player object for peer_id=" << pkt->getPeerId()
  1219. << " disconnecting peer!" << std::endl;
  1220. DisconnectPeer(pkt->getPeerId());
  1221. return;
  1222. }
  1223. // If something goes wrong, this player is to blame
  1224. RollbackScopeActor rollback_scope(m_rollback,
  1225. std::string("player:")+player->getName());
  1226. // Check the target node for rollback data; leave others unnoticed
  1227. RollbackNode rn_old(&m_env->getMap(), p, this);
  1228. m_script->node_on_receive_fields(p, formname, fields, playersao);
  1229. // Report rollback data
  1230. RollbackNode rn_new(&m_env->getMap(), p, this);
  1231. if (rollback() && rn_new != rn_old) {
  1232. RollbackAction action;
  1233. action.setSetNode(p, rn_old, rn_new);
  1234. rollback()->reportAction(action);
  1235. }
  1236. }
  1237. void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
  1238. {
  1239. std::string client_formspec_name;
  1240. u16 num;
  1241. *pkt >> client_formspec_name >> num;
  1242. StringMap fields;
  1243. for (u16 k = 0; k < num; k++) {
  1244. std::string fieldname;
  1245. *pkt >> fieldname;
  1246. fields[fieldname] = pkt->readLongString();
  1247. }
  1248. RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
  1249. if (player == NULL) {
  1250. errorstream << "Server::ProcessData(): Canceling: "
  1251. "No player for peer_id=" << pkt->getPeerId()
  1252. << " disconnecting peer!" << std::endl;
  1253. DisconnectPeer(pkt->getPeerId());
  1254. return;
  1255. }
  1256. PlayerSAO *playersao = player->getPlayerSAO();
  1257. if (playersao == NULL) {
  1258. errorstream << "Server::ProcessData(): Canceling: "
  1259. "No player object for peer_id=" << pkt->getPeerId()
  1260. << " disconnecting peer!" << std::endl;
  1261. DisconnectPeer(pkt->getPeerId());
  1262. return;
  1263. }
  1264. if (client_formspec_name.empty()) { // pass through inventory submits
  1265. m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
  1266. return;
  1267. }
  1268. // verify that we displayed the formspec to the user
  1269. const auto peer_state_iterator = m_formspec_state_data.find(pkt->getPeerId());
  1270. if (peer_state_iterator != m_formspec_state_data.end()) {
  1271. const std::string &server_formspec_name = peer_state_iterator->second;
  1272. if (client_formspec_name == server_formspec_name) {
  1273. if (fields["quit"] == "true")
  1274. m_formspec_state_data.erase(peer_state_iterator);
  1275. m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
  1276. return;
  1277. }
  1278. actionstream << "'" << player->getName()
  1279. << "' submitted formspec ('" << client_formspec_name
  1280. << "') but the name of the formspec doesn't match the"
  1281. " expected name ('" << server_formspec_name << "')";
  1282. } else {
  1283. actionstream << "'" << player->getName()
  1284. << "' submitted formspec ('" << client_formspec_name
  1285. << "') but server hasn't sent formspec to client";
  1286. }
  1287. actionstream << ", possible exploitation attempt" << std::endl;
  1288. }
  1289. void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
  1290. {
  1291. RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
  1292. ClientState cstate = client->getState();
  1293. std::string playername = client->getName();
  1294. std::string salt;
  1295. std::string verification_key;
  1296. std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
  1297. u8 is_empty;
  1298. *pkt >> salt >> verification_key >> is_empty;
  1299. verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
  1300. << ", with is_empty=" << (is_empty == 1) << std::endl;
  1301. // Either this packet is sent because the user is new or to change the password
  1302. if (cstate == CS_HelloSent) {
  1303. if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
  1304. actionstream << "Server: Client from " << addr_s
  1305. << " tried to set password without being "
  1306. << "authenticated, or the username being new." << std::endl;
  1307. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1308. return;
  1309. }
  1310. if (!isSingleplayer() &&
  1311. g_settings->getBool("disallow_empty_password") &&
  1312. is_empty == 1) {
  1313. actionstream << "Server: " << playername
  1314. << " supplied empty password from " << addr_s << std::endl;
  1315. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
  1316. return;
  1317. }
  1318. std::string initial_ver_key;
  1319. initial_ver_key = encode_srp_verifier(verification_key, salt);
  1320. m_script->createAuth(playername, initial_ver_key);
  1321. acceptAuth(pkt->getPeerId(), false);
  1322. } else {
  1323. if (cstate < CS_SudoMode) {
  1324. infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
  1325. << addr_s << ": " << "Client has wrong state " << cstate << "."
  1326. << std::endl;
  1327. return;
  1328. }
  1329. m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
  1330. std::string pw_db_field = encode_srp_verifier(verification_key, salt);
  1331. bool success = m_script->setPassword(playername, pw_db_field);
  1332. if (success) {
  1333. actionstream << playername << " changes password" << std::endl;
  1334. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  1335. L"Password change successful."));
  1336. } else {
  1337. actionstream << playername << " tries to change password but "
  1338. << "it fails" << std::endl;
  1339. SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  1340. L"Password change failed or unavailable."));
  1341. }
  1342. }
  1343. }
  1344. void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
  1345. {
  1346. RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
  1347. ClientState cstate = client->getState();
  1348. bool wantSudo = (cstate == CS_Active);
  1349. if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
  1350. actionstream << "Server: got SRP _A packet in wrong state "
  1351. << cstate << " from "
  1352. << getPeerAddress(pkt->getPeerId()).serializeString()
  1353. << ". Ignoring." << std::endl;
  1354. return;
  1355. }
  1356. if (client->chosen_mech != AUTH_MECHANISM_NONE) {
  1357. actionstream << "Server: got SRP _A packet, while auth"
  1358. << "is already going on with mech " << client->chosen_mech
  1359. << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
  1360. << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
  1361. if (wantSudo) {
  1362. DenySudoAccess(pkt->getPeerId());
  1363. return;
  1364. }
  1365. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1366. return;
  1367. }
  1368. std::string bytes_A;
  1369. u8 based_on;
  1370. *pkt >> bytes_A >> based_on;
  1371. infostream << "Server: TOSERVER_SRP_BYTES_A received with "
  1372. << "based_on=" << int(based_on) << " and len_A="
  1373. << bytes_A.length() << "." << std::endl;
  1374. AuthMechanism chosen = (based_on == 0) ?
  1375. AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
  1376. if (wantSudo) {
  1377. if (!client->isSudoMechAllowed(chosen)) {
  1378. actionstream << "Server: Player \"" << client->getName()
  1379. << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
  1380. << " tried to change password using unallowed mech "
  1381. << chosen << "." << std::endl;
  1382. DenySudoAccess(pkt->getPeerId());
  1383. return;
  1384. }
  1385. } else {
  1386. if (!client->isMechAllowed(chosen)) {
  1387. actionstream << "Server: Client tried to authenticate from "
  1388. << getPeerAddress(pkt->getPeerId()).serializeString()
  1389. << " using unallowed mech " << chosen << "." << std::endl;
  1390. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1391. return;
  1392. }
  1393. }
  1394. client->chosen_mech = chosen;
  1395. std::string salt;
  1396. std::string verifier;
  1397. if (based_on == 0) {
  1398. generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
  1399. &verifier, &salt);
  1400. } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
  1401. // Non-base64 errors should have been catched in the init handler
  1402. actionstream << "Server: User " << client->getName()
  1403. << " tried to log in, but srp verifier field"
  1404. << " was invalid (most likely invalid base64)." << std::endl;
  1405. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
  1406. return;
  1407. }
  1408. char *bytes_B = 0;
  1409. size_t len_B = 0;
  1410. client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
  1411. client->getName().c_str(),
  1412. (const unsigned char *) salt.c_str(), salt.size(),
  1413. (const unsigned char *) verifier.c_str(), verifier.size(),
  1414. (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
  1415. NULL, 0,
  1416. (unsigned char **) &bytes_B, &len_B, NULL, NULL);
  1417. if (!bytes_B) {
  1418. actionstream << "Server: User " << client->getName()
  1419. << " tried to log in, SRP-6a safety check violated in _A handler."
  1420. << std::endl;
  1421. if (wantSudo) {
  1422. DenySudoAccess(pkt->getPeerId());
  1423. return;
  1424. }
  1425. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1426. return;
  1427. }
  1428. NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
  1429. resp_pkt << salt << std::string(bytes_B, len_B);
  1430. Send(&resp_pkt);
  1431. }
  1432. void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
  1433. {
  1434. RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
  1435. ClientState cstate = client->getState();
  1436. bool wantSudo = (cstate == CS_Active);
  1437. verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
  1438. if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
  1439. actionstream << "Server: got SRP _M packet in wrong state "
  1440. << cstate << " from "
  1441. << getPeerAddress(pkt->getPeerId()).serializeString()
  1442. << ". Ignoring." << std::endl;
  1443. return;
  1444. }
  1445. if (client->chosen_mech != AUTH_MECHANISM_SRP &&
  1446. client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
  1447. actionstream << "Server: got SRP _M packet, while auth"
  1448. << "is going on with mech " << client->chosen_mech
  1449. << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
  1450. << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
  1451. if (wantSudo) {
  1452. DenySudoAccess(pkt->getPeerId());
  1453. return;
  1454. }
  1455. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1456. return;
  1457. }
  1458. std::string bytes_M;
  1459. *pkt >> bytes_M;
  1460. if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
  1461. != bytes_M.size()) {
  1462. actionstream << "Server: User " << client->getName()
  1463. << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
  1464. << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
  1465. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
  1466. return;
  1467. }
  1468. unsigned char *bytes_HAMK = 0;
  1469. srp_verifier_verify_session((SRPVerifier *) client->auth_data,
  1470. (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
  1471. if (!bytes_HAMK) {
  1472. if (wantSudo) {
  1473. actionstream << "Server: User " << client->getName()
  1474. << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
  1475. << " tried to change their password, but supplied wrong"
  1476. << " (SRP) password for authentication." << std::endl;
  1477. DenySudoAccess(pkt->getPeerId());
  1478. return;
  1479. }
  1480. std::string ip = getPeerAddress(pkt->getPeerId()).serializeString();
  1481. actionstream << "Server: User " << client->getName()
  1482. << " at " << ip
  1483. << " supplied wrong password (auth mechanism: SRP)."
  1484. << std::endl;
  1485. m_script->on_auth_failure(client->getName(), ip);
  1486. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
  1487. return;
  1488. }
  1489. if (client->create_player_on_auth_success) {
  1490. std::string playername = client->getName();
  1491. m_script->createAuth(playername, client->enc_pwd);
  1492. std::string checkpwd; // not used, but needed for passing something
  1493. if (!m_script->getAuth(playername, &checkpwd, NULL)) {
  1494. actionstream << "Server: " << playername << " cannot be authenticated"
  1495. << " (auth handler does not work?)" << std::endl;
  1496. DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
  1497. return;
  1498. }
  1499. client->create_player_on_auth_success = false;
  1500. }
  1501. acceptAuth(pkt->getPeerId(), wantSudo);
  1502. }
  1503. /*
  1504. * Mod channels
  1505. */
  1506. void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
  1507. {
  1508. std::string channel_name;
  1509. *pkt >> channel_name;
  1510. NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
  1511. pkt->getPeerId());
  1512. // Send signal to client to notify join succeed or not
  1513. if (g_settings->getBool("enable_mod_channels") &&
  1514. m_modchannel_mgr->joinChannel(channel_name, pkt->getPeerId())) {
  1515. resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
  1516. infostream << "Peer " << pkt->getPeerId() << " joined channel " << channel_name
  1517. << std::endl;
  1518. }
  1519. else {
  1520. resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
  1521. infostream << "Peer " << pkt->getPeerId() << " tried to join channel "
  1522. << channel_name << ", but was already registered." << std::endl;
  1523. }
  1524. resp_pkt << channel_name;
  1525. Send(&resp_pkt);
  1526. }
  1527. void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
  1528. {
  1529. std::string channel_name;
  1530. *pkt >> channel_name;
  1531. NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
  1532. pkt->getPeerId());
  1533. // Send signal to client to notify join succeed or not
  1534. if (g_settings->getBool("enable_mod_channels") &&
  1535. m_modchannel_mgr->leaveChannel(channel_name, pkt->getPeerId())) {
  1536. resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
  1537. infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
  1538. << std::endl;
  1539. } else {
  1540. resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
  1541. infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
  1542. << ", but was not registered." << std::endl;
  1543. }
  1544. resp_pkt << channel_name;
  1545. Send(&resp_pkt);
  1546. }
  1547. void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
  1548. {
  1549. std::string channel_name, channel_msg;
  1550. *pkt >> channel_name >> channel_msg;
  1551. verbosestream << "Mod channel message received from peer " << pkt->getPeerId()
  1552. << " on channel " << channel_name << " message: " << channel_msg << std::endl;
  1553. // If mod channels are not enabled, discard message
  1554. if (!g_settings->getBool("enable_mod_channels")) {
  1555. return;
  1556. }
  1557. // If channel not registered, signal it and ignore message
  1558. if (!m_modchannel_mgr->channelRegistered(channel_name)) {
  1559. NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
  1560. pkt->getPeerId());
  1561. resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
  1562. Send(&resp_pkt);
  1563. return;
  1564. }
  1565. // @TODO: filter, rate limit
  1566. broadcastModChannelMessage(channel_name, channel_msg, pkt->getPeerId());
  1567. }