3 Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "chatmessage.h"
25 #include "modchannels.h"
27 #include "remoteplayer.h"
28 #include "rollback_interface.h"
29 #include "scripting_server.h"
33 #include "network/connection.h"
34 #include "network/networkprotocol.h"
35 #include "network/serveropcodes.h"
36 #include "server/player_sao.h"
37 #include "server/serverinventorymgr.h"
38 #include "util/auth.h"
39 #include "util/base64.h"
40 #include "util/pointedthing.h"
41 #include "util/serialize.h"
43 #include "clientdynamicinfo.h"
45 void Server::handleCommand_Deprecated(NetworkPacket* pkt)
47 infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
48 << " not supported anymore" << std::endl;
51 void Server::handleCommand_Init(NetworkPacket* pkt)
54 if(pkt->getSize() < 1)
57 session_t peer_id = pkt->getPeerId();
58 RemoteClient *client = getClient(peer_id, CS_Created);
63 addr = m_con->GetPeerAddress(peer_id);
64 addr_s = addr.serializeString();
65 } catch (con::PeerNotFoundException &e) {
67 * no peer for this packet found
68 * most common reason is peer timeout, e.g. peer didn't
69 * respond for some time, your server was overloaded or
72 infostream << "Server::ProcessData(): Canceling: peer " << peer_id <<
73 " not found" << std::endl;
77 if (client->getState() > CS_Created) {
78 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " <<
79 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
83 client->setCachedAddress(addr);
85 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s <<
86 " (peer_id=" << peer_id << ")" << std::endl;
88 // Do not allow multiple players in simple singleplayer mode.
89 // This isn't a perfect way to do it, but will suffice for now
90 if (m_simple_singleplayer_mode && !m_clients.getClientIDs().empty()) {
91 infostream << "Server: Not allowing another client (" << addr_s <<
92 ") to connect in simple singleplayer mode" << std::endl;
93 DenyAccess(peer_id, SERVER_ACCESSDENIED_SINGLEPLAYER);
97 // First byte after command is maximum supported
98 // serialization version
100 u16 supp_compr_modes;
101 u16 min_net_proto_version = 0;
102 u16 max_net_proto_version;
103 std::string playerName;
105 *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
106 >> max_net_proto_version >> playerName;
108 u8 our_max = SER_FMT_VER_HIGHEST_READ;
109 // Use the highest version supported by both
110 u8 depl_serial_v = std::min(client_max, our_max);
111 // If it's lower than the lowest supported, give up.
112 #if SER_FMT_VER_LOWEST_READ > 0
113 if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
114 depl_serial_v = SER_FMT_VER_INVALID;
117 if (depl_serial_v == SER_FMT_VER_INVALID) {
118 actionstream << "Server: A mismatched client tried to connect from " <<
119 addr_s << " ser_fmt_max=" << (int)client_max << std::endl;
120 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
124 client->setPendingSerializationVersion(depl_serial_v);
127 Read and check network protocol version
130 u16 net_proto_version = 0;
132 // Figure out a working version if it is possible at all
133 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
134 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
135 // If maximum is larger than our maximum, go with our maximum
136 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
137 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
138 // Else go with client's maximum
140 net_proto_version = max_net_proto_version;
143 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
144 << min_net_proto_version << ", max: " << max_net_proto_version
145 << ", chosen: " << net_proto_version << std::endl;
147 client->net_proto_version = net_proto_version;
149 if ((g_settings->getBool("strict_protocol_version_checking") &&
150 net_proto_version != LATEST_PROTOCOL_VERSION) ||
151 net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
152 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
153 actionstream << "Server: A mismatched client tried to connect from " <<
154 addr_s << " proto_max=" << (int)max_net_proto_version << std::endl;
155 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
162 const char* playername = playerName.c_str();
164 size_t pns = playerName.size();
165 if (pns == 0 || pns > PLAYERNAME_SIZE) {
166 actionstream << "Server: Player with " <<
167 ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty") <<
168 " name tried to connect from " << addr_s << std::endl;
169 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
173 if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
174 actionstream << "Server: Player with an invalid name tried to connect "
175 "from " << addr_s << std::endl;
176 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
180 RemotePlayer *player = m_env->getPlayer(playername);
182 // If player is already connected, cancel
183 if (player && player->getPeerId() != PEER_ID_INEXISTENT) {
184 actionstream << "Server: Player with name \"" << playername <<
185 "\" tried to connect, but player with same name is already connected" << std::endl;
186 DenyAccess(peer_id, SERVER_ACCESSDENIED_ALREADY_CONNECTED);
190 m_clients.setPlayerName(peer_id, playername);
191 //TODO (later) case insensitivity
193 std::string legacyPlayerNameCasing = playerName;
195 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
196 actionstream << "Server: Player with the name \"singleplayer\" tried "
197 "to connect from " << addr_s << std::endl;
198 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
204 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
205 actionstream << "Server: Player with the name \"" << playerName <<
206 "\" tried to connect from " << addr_s <<
207 " but it was disallowed for the following reason: " << reason <<
209 DenyAccess(peer_id, SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
214 infostream << "Server: New connection: \"" << playerName << "\" from " <<
215 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
217 // Enforce user limit.
218 // Don't enforce for users that have some admin right or mod permits it.
219 if (m_clients.isUserLimitReached() &&
220 playername != g_settings->get("name") &&
221 !m_script->can_bypass_userlimit(playername, addr_s)) {
222 actionstream << "Server: " << playername << " tried to join from " <<
223 addr_s << ", but there are already max_users=" <<
224 g_settings->getU16("max_users") << " players." << std::endl;
225 DenyAccess(peer_id, SERVER_ACCESSDENIED_TOO_MANY_USERS);
230 Compose auth methods for answer
232 std::string encpwd; // encrypted Password field for the user
233 bool has_auth = m_script->getAuth(playername, &encpwd, nullptr);
236 client->chosen_mech = AUTH_MECHANISM_NONE;
239 std::vector<std::string> pwd_components = str_split(encpwd, '#');
240 if (pwd_components.size() == 4) {
241 if (pwd_components[1] == "1") { // 1 means srp
242 auth_mechs |= AUTH_MECHANISM_SRP;
243 client->enc_pwd = encpwd;
245 actionstream << "User " << playername << " tried to log in, "
246 "but password field was invalid (unknown mechcode)." <<
248 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
251 } else if (base64_is_valid(encpwd)) {
252 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
253 client->enc_pwd = encpwd;
255 actionstream << "User " << playername << " tried to log in, but "
256 "password field was invalid (invalid base64)." << std::endl;
257 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
261 std::string default_password = g_settings->get("default_password");
262 if (default_password.length() == 0) {
263 auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
265 // Take care of default passwords.
266 client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
267 auth_mechs |= AUTH_MECHANISM_SRP;
268 // Allocate player in db, but only on successful login.
269 client->create_player_on_auth_success = true;
274 Answer with a TOCLIENT_HELLO
277 verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
278 << auth_mechs << std::endl;
280 NetworkPacket resp_pkt(TOCLIENT_HELLO,
281 1 + 4 + legacyPlayerNameCasing.size(), peer_id);
283 u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
284 resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
285 << auth_mechs << legacyPlayerNameCasing;
289 client->allowed_auth_mechs = auth_mechs;
290 client->setDeployedCompressionMode(depl_compress_mode);
292 m_clients.event(peer_id, CSE_Hello);
295 void Server::handleCommand_Init2(NetworkPacket* pkt)
297 session_t peer_id = pkt->getPeerId();
298 verbosestream << "Server: Got TOSERVER_INIT2 from " << peer_id << std::endl;
300 m_clients.event(peer_id, CSE_GotInit2);
301 u16 protocol_version = m_clients.getProtocolVersion(peer_id);
304 if (pkt->getSize() > 0)
308 Send some initialization data
311 infostream << "Server: Sending content to " << getPlayerName(peer_id) <<
314 // Send item definitions
315 SendItemDef(peer_id, m_itemdef, protocol_version);
317 // Send node definitions
318 SendNodeDef(peer_id, m_nodedef, protocol_version);
320 m_clients.event(peer_id, CSE_SetDefinitionsSent);
322 // Send media announcement
323 sendMediaAnnouncement(peer_id, lang);
325 RemoteClient *client = getClient(peer_id, CS_InitDone);
327 // Keep client language for server translations
328 client->setLangCode(lang);
330 // Send active objects
332 PlayerSAO *sao = getPlayerSAO(peer_id);
334 SendActiveObjectRemoveAdd(client, sao);
337 // Send detached inventories
338 sendDetachedInventories(peer_id, false);
340 // Send player movement settings
341 SendMovement(peer_id);
344 u16 time = m_env->getTimeOfDay();
345 float time_speed = g_settings->getFloat("time_speed");
346 SendTimeOfDay(peer_id, time, time_speed);
348 SendCSMRestrictionFlags(peer_id);
350 // Warnings about protocol version can be issued here
351 if (client->net_proto_version < LATEST_PROTOCOL_VERSION) {
352 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
353 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
354 L"WITH THIS SERVER!"));
358 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
360 std::vector<std::string> tosend;
365 session_t peer_id = pkt->getPeerId();
366 infostream << "Sending " << numfiles << " files to " <<
367 getPlayerName(peer_id) << std::endl;
368 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file(s)" << std::endl;
370 for (u16 i = 0; i < numfiles; i++) {
375 tosend.emplace_back(name);
376 verbosestream << " " << name << std::endl;
379 sendRequestedMedia(peer_id, tosend);
382 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
384 session_t peer_id = pkt->getPeerId();
386 // decode all information first
387 u8 major_ver, minor_ver, patch_ver, reserved;
388 u16 formspec_ver = 1; // v1 for clients older than 5.1.0-dev
389 std::string full_ver;
391 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
392 if (pkt->getRemainingBytes() >= 2)
393 *pkt >> formspec_ver;
395 m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver,
399 PlayerSAO* playersao = StageTwoClientInit(peer_id);
401 errorstream << "Server: stage 2 client init failed "
402 "peer_id=" << peer_id << std::endl;
403 DisconnectPeer(peer_id);
407 playersao->getPlayer()->formspec_version = formspec_ver;
408 m_clients.event(peer_id, CSE_SetClientReady);
410 // Send player list to this client
412 const std::vector<std::string> &players = m_clients.getPlayerNames();
413 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
414 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
415 for (const auto &player : players)
417 Send(peer_id, &list_pkt);
421 m_script->getAuth(playersao->getPlayer()->getName(), nullptr, nullptr, &last_login);
422 m_script->on_joinplayer(playersao, last_login);
424 // Send shutdown timer if shutdown has been scheduled
425 if (m_shutdown_state.isTimerRunning())
426 SendChatMessage(peer_id, m_shutdown_state.getShutdownTimerMessage());
429 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
431 if (pkt->getSize() < 1)
445 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
446 throw con::InvalidIncomingDataException
447 ("GOTBLOCKS length is too short");
450 ClientInterface::AutoLock lock(m_clients);
451 RemoteClient *client = m_clients.lockedGetClientNoEx(pkt->getPeerId());
453 for (u16 i = 0; i < count; i++) {
460 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
463 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
467 s32 f32pitch, f32yaw;
475 f32 pitch = (f32)f32pitch / 100.0f;
476 f32 yaw = (f32)f32yaw / 100.0f;
484 fov = (f32)f32fov / 80.0f;
485 *pkt >> wanted_range;
487 v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
488 v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
490 pitch = modulo360f(pitch);
491 yaw = wrapDegrees_0_360(yaw);
493 if (!playersao->isAttached()) {
494 // Only update player positions when moving freely
495 // to not interfere with attachment handling
496 playersao->setBasePosition(position);
497 player->setSpeed(speed);
499 playersao->setLookPitch(pitch);
500 playersao->setPlayerYaw(yaw);
501 playersao->setFov(fov);
502 playersao->setWantedRange(wanted_range);
504 player->control.unpackKeysPressed(keyPressed);
506 if (playersao->checkMovementCheat()) {
508 m_script->on_cheat(playersao, "moved_too_fast");
509 SendMovePlayer(pkt->getPeerId());
513 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
515 session_t peer_id = pkt->getPeerId();
516 RemotePlayer *player = m_env->getPlayer(peer_id);
517 if (player == NULL) {
519 "Server::ProcessData(): Canceling: No player for peer_id=" <<
520 peer_id << " disconnecting peer!" << std::endl;
521 DisconnectPeer(peer_id);
525 PlayerSAO *playersao = player->getPlayerSAO();
526 if (playersao == NULL) {
528 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
529 peer_id << " disconnecting peer!" << std::endl;
530 DisconnectPeer(peer_id);
534 // If player is dead we don't care of this packet
535 if (playersao->isDead()) {
536 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
537 << " is dead. Ignoring packet";
541 process_PlayerPos(player, playersao, pkt);
544 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
546 if (pkt->getSize() < 1)
560 RemoteClient *client = getClient(pkt->getPeerId());
562 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
563 throw con::InvalidIncomingDataException
564 ("DELETEDBLOCKS length is too short");
567 for (u16 i = 0; i < count; i++) {
570 client->SetBlockNotSent(p);
574 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
576 session_t peer_id = pkt->getPeerId();
577 RemotePlayer *player = m_env->getPlayer(peer_id);
579 if (player == NULL) {
581 "Server::ProcessData(): Canceling: No player for peer_id=" <<
582 peer_id << " disconnecting peer!" << std::endl;
583 DisconnectPeer(peer_id);
587 PlayerSAO *playersao = player->getPlayerSAO();
588 if (playersao == NULL) {
590 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
591 peer_id << " disconnecting peer!" << std::endl;
592 DisconnectPeer(peer_id);
596 // Strip command and create a stream
597 std::string datastring(pkt->getString(0), pkt->getSize());
598 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
600 std::istringstream is(datastring, std::ios_base::binary);
602 std::unique_ptr<InventoryAction> a(InventoryAction::deSerialize(is));
604 infostream << "TOSERVER_INVENTORY_ACTION: "
605 << "InventoryAction::deSerialize() returned NULL"
610 // If something goes wrong, this player is to blame
611 RollbackScopeActor rollback_scope(m_rollback,
612 std::string("player:")+player->getName());
615 Note: Always set inventory not sent, to repair cases
616 where the client made a bad prediction.
619 const bool player_has_interact = checkPriv(player->getName(), "interact");
621 auto check_inv_access = [player, player_has_interact, this] (
622 const InventoryLocation &loc) -> bool {
624 // Players without interact may modify their own inventory
625 if (!player_has_interact && loc.type != InventoryLocation::PLAYER) {
626 infostream << "Cannot modify foreign inventory: "
627 << "No interact privilege" << std::endl;
632 case InventoryLocation::CURRENT_PLAYER:
633 // Only used internally on the client, never sent
635 case InventoryLocation::PLAYER:
636 // Allow access to own inventory in all cases
637 return loc.name == player->getName();
638 case InventoryLocation::NODEMETA:
640 // Check for out-of-range interaction
641 v3f node_pos = intToFloat(loc.p, BS);
642 v3f player_pos = player->getPlayerSAO()->getEyePosition();
643 f32 d = player_pos.getDistanceFrom(node_pos);
644 return checkInteractDistance(player, d, "inventory");
646 case InventoryLocation::DETACHED:
647 return getInventoryMgr()->checkDetachedInventoryAccess(loc, player->getName());
654 Handle restrictions and special cases of the move action
656 if (a->getType() == IAction::Move) {
657 IMoveAction *ma = (IMoveAction*)a.get();
659 ma->from_inv.applyCurrentPlayer(player->getName());
660 ma->to_inv.applyCurrentPlayer(player->getName());
662 m_inventory_mgr->setInventoryModified(ma->from_inv);
663 if (ma->from_inv != ma->to_inv)
664 m_inventory_mgr->setInventoryModified(ma->to_inv);
666 if (!check_inv_access(ma->from_inv) ||
667 !check_inv_access(ma->to_inv))
671 Disable moving items out of craftpreview
673 if (ma->from_list == "craftpreview") {
674 infostream << "Ignoring IMoveAction from "
675 << (ma->from_inv.dump()) << ":" << ma->from_list
676 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
677 << " because src is " << ma->from_list << std::endl;
682 Disable moving items into craftresult and craftpreview
684 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
685 infostream << "Ignoring IMoveAction from "
686 << (ma->from_inv.dump()) << ":" << ma->from_list
687 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
688 << " because dst is " << ma->to_list << std::endl;
693 Handle restrictions and special cases of the drop action
695 else if (a->getType() == IAction::Drop) {
696 IDropAction *da = (IDropAction*)a.get();
698 da->from_inv.applyCurrentPlayer(player->getName());
700 m_inventory_mgr->setInventoryModified(da->from_inv);
703 Disable dropping items out of craftpreview
705 if (da->from_list == "craftpreview") {
706 infostream << "Ignoring IDropAction from "
707 << (da->from_inv.dump()) << ":" << da->from_list
708 << " because src is " << da->from_list << std::endl;
712 // Disallow dropping items if not allowed to interact
713 if (!player_has_interact || !check_inv_access(da->from_inv))
716 // Disallow dropping items if dead
717 if (playersao->isDead()) {
718 infostream << "Ignoring IDropAction from "
719 << (da->from_inv.dump()) << ":" << da->from_list
720 << " because player is dead." << std::endl;
725 Handle restrictions and special cases of the craft action
727 else if (a->getType() == IAction::Craft) {
728 ICraftAction *ca = (ICraftAction*)a.get();
730 ca->craft_inv.applyCurrentPlayer(player->getName());
732 m_inventory_mgr->setInventoryModified(ca->craft_inv);
734 // Disallow crafting if not allowed to interact
735 if (!player_has_interact) {
736 infostream << "Cannot craft: "
737 << "No interact privilege" << std::endl;
741 if (!check_inv_access(ca->craft_inv))
744 // Unknown action. Ignored.
749 a->apply(m_inventory_mgr.get(), playersao, this);
752 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
754 std::wstring message;
757 session_t peer_id = pkt->getPeerId();
758 RemotePlayer *player = m_env->getPlayer(peer_id);
759 if (player == NULL) {
761 "Server::ProcessData(): Canceling: No player for peer_id=" <<
762 peer_id << " disconnecting peer!" << std::endl;
763 DisconnectPeer(peer_id);
767 std::string name = player->getName();
769 std::wstring answer_to_sender = handleChat(name, message, true, player);
770 if (!answer_to_sender.empty()) {
771 // Send the answer to sender
772 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
777 void Server::handleCommand_Damage(NetworkPacket* pkt)
783 session_t peer_id = pkt->getPeerId();
784 RemotePlayer *player = m_env->getPlayer(peer_id);
786 if (player == NULL) {
788 "Server::ProcessData(): Canceling: No player for peer_id=" <<
789 peer_id << " disconnecting peer!" << std::endl;
790 DisconnectPeer(peer_id);
794 PlayerSAO *playersao = player->getPlayerSAO();
795 if (playersao == NULL) {
797 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
798 peer_id << " disconnecting peer!" << std::endl;
799 DisconnectPeer(peer_id);
803 if (!playersao->isImmortal()) {
804 if (playersao->isDead()) {
805 verbosestream << "Server::ProcessData(): Info: "
806 "Ignoring damage as player " << player->getName()
807 << " is already dead." << std::endl;
811 actionstream << player->getName() << " damaged by "
812 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
815 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
816 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason, true);
820 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
822 if (pkt->getSize() < 2)
825 session_t peer_id = pkt->getPeerId();
826 RemotePlayer *player = m_env->getPlayer(peer_id);
828 if (player == NULL) {
830 "Server::ProcessData(): Canceling: No player for peer_id=" <<
831 peer_id << " disconnecting peer!" << std::endl;
832 DisconnectPeer(peer_id);
836 PlayerSAO *playersao = player->getPlayerSAO();
837 if (playersao == NULL) {
839 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
840 peer_id << " disconnecting peer!" << std::endl;
841 DisconnectPeer(peer_id);
849 if (item >= player->getHotbarItemcount()) {
850 actionstream << "Player: " << player->getName()
851 << " tried to access item=" << item
852 << " out of hotbar_itemcount="
853 << player->getHotbarItemcount()
854 << "; ignoring." << std::endl;
858 playersao->getPlayer()->setWieldIndex(item);
861 void Server::handleCommand_Respawn(NetworkPacket* pkt)
863 session_t peer_id = pkt->getPeerId();
864 RemotePlayer *player = m_env->getPlayer(peer_id);
865 if (player == NULL) {
867 "Server::ProcessData(): Canceling: No player for peer_id=" <<
868 peer_id << " disconnecting peer!" << std::endl;
869 DisconnectPeer(peer_id);
873 PlayerSAO *playersao = player->getPlayerSAO();
876 if (!playersao->isDead())
879 RespawnPlayer(peer_id);
881 actionstream << player->getName() << " respawns at "
882 << PP(playersao->getBasePosition() / BS) << std::endl;
884 // ActiveObject is added to environment in AsyncRunStep after
885 // the previous addition has been successfully removed
888 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
890 ItemStack selected_item, main_item;
891 player->getWieldedItem(&selected_item, &main_item);
892 f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
893 main_item.getDefinition(m_itemdef));
895 // Cube diagonal * 1.5 for maximal supported node extents:
896 // sqrt(3) * 1.5 ≅ 2.6
897 if (d > max_d + 2.6f * BS) {
898 actionstream << "Player " << player->getName()
899 << " tried to access " << what
901 << "d=" << d << ", max_d=" << max_d
902 << "; ignoring." << std::endl;
904 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
910 // Tiny helper to retrieve the selected item into an Optional
911 static inline void getWieldedItem(const PlayerSAO *playersao, Optional<ItemStack> &ret)
914 playersao->getWieldedItem(&(*ret));
917 static inline bool getOffhandWieldedItem(const PlayerSAO *playersao, Optional<ItemStack> &offhand,
918 Optional<ItemStack> &place, IItemDefManager *idef, const PointedThing &pointed)
920 offhand = ItemStack();
922 return playersao->getOffhandWieldedItem(&(*offhand), &(*place), idef, pointed);
925 void Server::handleCommand_Interact(NetworkPacket *pkt)
931 [5] u32 length of the next item (plen)
932 [9] serialized PointedThing
933 [9 + plen] player position information
936 InteractAction action;
939 *pkt >> (u8 &)action;
942 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
943 PointedThing pointed;
944 pointed.deSerialize(tmp_is);
946 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
947 << item_i << ", pointed=" << pointed.dump() << std::endl;
949 session_t peer_id = pkt->getPeerId();
950 RemotePlayer *player = m_env->getPlayer(peer_id);
952 if (player == NULL) {
954 "Server::ProcessData(): Canceling: No player for peer_id=" <<
955 peer_id << " disconnecting peer!" << std::endl;
956 DisconnectPeer(peer_id);
960 PlayerSAO *playersao = player->getPlayerSAO();
961 if (playersao == NULL) {
963 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
964 peer_id << " disconnecting peer!" << std::endl;
965 DisconnectPeer(peer_id);
969 if (playersao->isDead()) {
970 actionstream << "Server: " << player->getName()
971 << " tried to interact while dead; ignoring." << std::endl;
972 if (pointed.type == POINTEDTHING_NODE) {
973 // Re-send block to revert change on client-side
974 RemoteClient *client = getClient(peer_id);
975 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
976 client->SetBlockNotSent(blockpos);
979 m_script->on_cheat(playersao, "interacted_while_dead");
983 process_PlayerPos(player, playersao, pkt);
985 v3f player_pos = playersao->getLastGoodPosition();
987 // Update wielded item
989 if (item_i >= player->getHotbarItemcount()) {
990 actionstream << "Player: " << player->getName()
991 << " tried to access item=" << item_i
992 << " out of hotbar_itemcount="
993 << player->getHotbarItemcount()
994 << "; ignoring." << std::endl;
998 playersao->getPlayer()->setWieldIndex(item_i);
1000 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1001 ServerActiveObject *pointed_object = NULL;
1002 if (pointed.type == POINTEDTHING_OBJECT) {
1003 pointed_object = m_env->getActiveObject(pointed.object_id);
1004 if (pointed_object == NULL) {
1005 verbosestream << "TOSERVER_INTERACT: "
1006 "pointed object is NULL" << std::endl;
1013 Make sure the player is allowed to do it
1015 if (!checkPriv(player->getName(), "interact")) {
1016 actionstream << player->getName() << " attempted to interact with " <<
1017 pointed.dump() << " without 'interact' privilege" << std::endl;
1019 if (pointed.type != POINTEDTHING_NODE)
1022 // Re-send block to revert change on client-side
1023 RemoteClient *client = getClient(peer_id);
1024 // Digging completed -> under
1025 if (action == INTERACT_DIGGING_COMPLETED) {
1026 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1027 client->SetBlockNotSent(blockpos);
1029 // Placement -> above
1030 else if (action == INTERACT_PLACE) {
1031 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1032 client->SetBlockNotSent(blockpos);
1038 Check that target is reasonably close
1040 static thread_local const bool enable_anticheat =
1041 !g_settings->getBool("disable_anticheat");
1043 if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1044 action == INTERACT_PLACE || action == INTERACT_USE) &&
1045 enable_anticheat && !isSingleplayer()) {
1046 v3f target_pos = player_pos;
1047 if (pointed.type == POINTEDTHING_NODE) {
1048 target_pos = intToFloat(pointed.node_undersurface, BS);
1049 } else if (pointed.type == POINTEDTHING_OBJECT) {
1050 if (playersao->getId() == pointed_object->getId()) {
1051 actionstream << "Server: " << player->getName()
1052 << " attempted to interact with themselves" << std::endl;
1053 m_script->on_cheat(playersao, "interacted_with_self");
1056 target_pos = pointed_object->getBasePosition();
1058 float d = playersao->getEyePosition().getDistanceFrom(target_pos);
1060 if (!checkInteractDistance(player, d, pointed.dump())) {
1061 if (pointed.type == POINTEDTHING_NODE) {
1062 // Re-send block to revert change on client-side
1063 RemoteClient *client = getClient(peer_id);
1064 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1065 client->SetBlockNotSent(blockpos);
1072 If something goes wrong, this player is to blame
1074 RollbackScopeActor rollback_scope(m_rollback,
1075 std::string("player:")+player->getName());
1078 // Start digging or punch object
1079 case INTERACT_START_DIGGING: {
1080 if (pointed.type == POINTEDTHING_NODE) {
1081 MapNode n(CONTENT_IGNORE);
1084 v3s16 p_under = pointed.node_undersurface;
1085 n = m_env->getMap().getNode(p_under, &pos_ok);
1087 infostream << "Server: Not punching: Node not found. "
1088 "Adding block to emerge queue." << std::endl;
1089 m_emerge->enqueueBlockEmerge(peer_id,
1090 getNodeBlockPos(pointed.node_abovesurface), false);
1093 if (n.getContent() != CONTENT_IGNORE)
1094 m_script->node_on_punch(p_under, n, playersao, pointed);
1097 playersao->noCheatDigStart(p_under);
1102 // Skip if the object can't be interacted with anymore
1103 if (pointed.type != POINTEDTHING_OBJECT || pointed_object->isGone())
1106 ItemStack selected_item, hand_item;
1107 ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
1108 ToolCapabilities toolcap =
1109 tool_item.getToolCapabilities(m_itemdef);
1110 v3f dir = (pointed_object->getBasePosition() -
1111 (playersao->getBasePosition() + playersao->getEyeOffset())
1113 float time_from_last_punch =
1114 playersao->resetTimeFromLastPunch();
1116 u32 wear = pointed_object->punch(dir, &toolcap, playersao,
1117 time_from_last_punch, tool_item.wear);
1119 // Callback may have changed item, so get it again
1120 playersao->getWieldedItem(&selected_item);
1121 bool changed = selected_item.addWear(wear, m_itemdef);
1123 playersao->setWieldedItem(selected_item);
1126 } // action == INTERACT_START_DIGGING
1128 case INTERACT_STOP_DIGGING:
1132 case INTERACT_DIGGING_COMPLETED: {
1133 // Only digging of nodes
1134 if (pointed.type != POINTEDTHING_NODE)
1137 v3s16 p_under = pointed.node_undersurface;
1138 MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1140 infostream << "Server: Not finishing digging: Node not found. "
1141 "Adding block to emerge queue." << std::endl;
1142 m_emerge->enqueueBlockEmerge(peer_id,
1143 getNodeBlockPos(pointed.node_abovesurface), false);
1146 /* Cheat prevention */
1147 bool is_valid_dig = true;
1148 if (enable_anticheat && !isSingleplayer()) {
1149 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1150 float nocheat_t = playersao->getNoCheatDigTime();
1151 playersao->noCheatDigEnd();
1152 // If player didn't start digging this, ignore dig
1153 if (nocheat_p != p_under) {
1154 infostream << "Server: " << player->getName()
1155 << " started digging "
1156 << PP(nocheat_p) << " and completed digging "
1157 << PP(p_under) << "; not digging." << std::endl;
1158 is_valid_dig = false;
1160 m_script->on_cheat(playersao, "finished_unknown_dig");
1163 // Get player's wielded item
1164 // See also: Game::handleDigging
1165 ItemStack selected_item, main_item;
1166 playersao->getPlayer()->getWieldedItem(&selected_item, &main_item);
1168 // Get diggability and expected digging time
1169 DigParams params = getDigParams(m_nodedef->get(n).groups,
1170 &selected_item.getToolCapabilities(m_itemdef),
1171 selected_item.wear);
1172 // If can't dig, try hand
1173 if (!params.diggable) {
1174 params = getDigParams(m_nodedef->get(n).groups,
1175 &main_item.getToolCapabilities(m_itemdef));
1177 // If can't dig, ignore dig
1178 if (!params.diggable) {
1179 infostream << "Server: " << player->getName()
1180 << " completed digging " << PP(p_under)
1181 << ", which is not diggable with tool; not digging."
1183 is_valid_dig = false;
1185 m_script->on_cheat(playersao, "dug_unbreakable");
1187 // Check digging time
1188 // If already invalidated, we don't have to
1189 if (!is_valid_dig) {
1190 // Well not our problem then
1192 // Clean and long dig
1193 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1194 // All is good, but grab time from pool; don't care if
1195 // it's actually available
1196 playersao->getDigPool().grab(params.time);
1198 // Short or laggy dig
1199 // Try getting the time from pool
1200 else if (playersao->getDigPool().grab(params.time)) {
1205 infostream << "Server: " << player->getName()
1206 << " completed digging " << PP(p_under)
1207 << "too fast; not digging." << std::endl;
1208 is_valid_dig = false;
1210 m_script->on_cheat(playersao, "dug_too_fast");
1214 /* Actually dig node */
1216 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1217 m_script->node_on_dig(p_under, n, playersao);
1219 v3s16 blockpos = getNodeBlockPos(p_under);
1220 RemoteClient *client = getClient(peer_id);
1221 // Send unusual result (that is, node not being removed)
1222 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR)
1223 // Re-send block to revert change on client-side
1224 client->SetBlockNotSent(blockpos);
1226 client->ResendBlockIfOnWire(blockpos);
1229 } // action == INTERACT_DIGGING_COMPLETED
1231 // Place block or right-click object
1232 case INTERACT_PLACE: {
1233 Optional<ItemStack> main_item, offhand_item, place_item;
1234 getWieldedItem(playersao, main_item);
1235 bool use_offhand = getOffhandWieldedItem(playersao, offhand_item, place_item, m_itemdef, pointed);
1237 // Reset build time counter
1238 if (pointed.type == POINTEDTHING_NODE &&
1239 place_item->getDefinition(m_itemdef).type == ITEM_NODE)
1240 getClient(peer_id)->m_time_from_building = 0.0;
1242 const bool had_prediction = !place_item->getDefinition(m_itemdef).
1243 node_placement_prediction.empty();
1245 if (pointed.type == POINTEDTHING_OBJECT) {
1246 // Right click object
1248 // Skip if object can't be interacted with anymore
1249 if (pointed_object->isGone())
1252 actionstream << player->getName() << " right-clicks object "
1253 << pointed.object_id << ": "
1254 << pointed_object->getDescription() << std::endl;
1257 if (m_script->item_OnSecondaryUse(use_offhand ? offhand_item : main_item, playersao, pointed)) {
1259 ? (offhand_item.has_value() && playersao->setOffhandWieldedItem(*offhand_item))
1260 : (main_item.has_value() && playersao->setWieldedItem(*main_item)))
1261 SendInventory(playersao, true);
1264 pointed_object->rightClick(playersao);
1265 } else if (m_script->item_OnPlace(use_offhand ? offhand_item : main_item, playersao, pointed)) {
1266 // Placement was handled in lua
1268 // Apply returned ItemStack
1270 ? (offhand_item.has_value() && playersao->setOffhandWieldedItem(*offhand_item))
1271 : (main_item.has_value() && playersao->setWieldedItem(*main_item)))
1272 SendInventory(playersao, true);
1275 if (pointed.type != POINTEDTHING_NODE)
1278 // If item has node placement prediction, always send the
1279 // blocks to make sure the client knows what exactly happened
1280 RemoteClient *client = getClient(peer_id);
1281 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1282 v3s16 blockpos2 = getNodeBlockPos(pointed.node_undersurface);
1283 if (had_prediction) {
1284 client->SetBlockNotSent(blockpos);
1285 if (blockpos2 != blockpos)
1286 client->SetBlockNotSent(blockpos2);
1288 client->ResendBlockIfOnWire(blockpos);
1289 if (blockpos2 != blockpos)
1290 client->ResendBlockIfOnWire(blockpos2);
1294 } // action == INTERACT_PLACE
1296 case INTERACT_USE: {
1297 Optional<ItemStack> selected_item;
1298 getWieldedItem(playersao, selected_item);
1300 actionstream << player->getName() << " uses " << selected_item->name
1301 << ", pointing at " << pointed.dump() << std::endl;
1303 if (m_script->item_OnUse(selected_item, playersao, pointed)) {
1304 // Apply returned ItemStack
1305 if (selected_item.has_value() && playersao->setWieldedItem(*selected_item))
1306 SendInventory(playersao, true);
1313 case INTERACT_ACTIVATE: {
1314 Optional<ItemStack> main_item, offhand_item, place_item;
1315 getWieldedItem(playersao, main_item);
1316 bool use_offhand = getOffhandWieldedItem(playersao, offhand_item, place_item, m_itemdef, pointed);
1318 actionstream << player->getName() << " activates "
1319 << place_item->name << std::endl;
1321 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1323 if (m_script->item_OnSecondaryUse(use_offhand ? offhand_item : main_item, playersao, pointed)) {
1324 // Apply returned ItemStack
1326 ? (offhand_item.has_value() && playersao->setOffhandWieldedItem(*offhand_item))
1327 : (main_item.has_value() && playersao->setWieldedItem(*main_item)))
1328 SendInventory(playersao, true);
1335 warningstream << "Server: Invalid action " << action << std::endl;
1340 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1344 for (u16 k = 0; k < num; k++) {
1349 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1350 m_playing_sounds.find(id);
1351 if (i == m_playing_sounds.end())
1354 ServerPlayingSound &psound = i->second;
1355 psound.clients.erase(pkt->getPeerId());
1356 if (psound.clients.empty())
1357 m_playing_sounds.erase(i++);
1361 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1364 std::string formname;
1367 *pkt >> p >> formname >> num;
1370 for (u16 k = 0; k < num; k++) {
1371 std::string fieldname;
1373 fields[fieldname] = pkt->readLongString();
1376 session_t peer_id = pkt->getPeerId();
1377 RemotePlayer *player = m_env->getPlayer(peer_id);
1379 if (player == NULL) {
1381 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1382 peer_id << " disconnecting peer!" << std::endl;
1383 DisconnectPeer(peer_id);
1387 PlayerSAO *playersao = player->getPlayerSAO();
1388 if (playersao == NULL) {
1390 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1391 peer_id << " disconnecting peer!" << std::endl;
1392 DisconnectPeer(peer_id);
1396 // If something goes wrong, this player is to blame
1397 RollbackScopeActor rollback_scope(m_rollback,
1398 std::string("player:")+player->getName());
1400 // Check the target node for rollback data; leave others unnoticed
1401 RollbackNode rn_old(&m_env->getMap(), p, this);
1403 m_script->node_on_receive_fields(p, formname, fields, playersao);
1405 // Report rollback data
1406 RollbackNode rn_new(&m_env->getMap(), p, this);
1407 if (rollback() && rn_new != rn_old) {
1408 RollbackAction action;
1409 action.setSetNode(p, rn_old, rn_new);
1410 rollback()->reportAction(action);
1414 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1416 std::string client_formspec_name;
1419 *pkt >> client_formspec_name >> num;
1422 for (u16 k = 0; k < num; k++) {
1423 std::string fieldname;
1425 fields[fieldname] = pkt->readLongString();
1428 session_t peer_id = pkt->getPeerId();
1429 RemotePlayer *player = m_env->getPlayer(peer_id);
1431 if (player == NULL) {
1433 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1434 peer_id << " disconnecting peer!" << std::endl;
1435 DisconnectPeer(peer_id);
1439 PlayerSAO *playersao = player->getPlayerSAO();
1440 if (playersao == NULL) {
1442 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1443 peer_id << " disconnecting peer!" << std::endl;
1444 DisconnectPeer(peer_id);
1448 if (client_formspec_name.empty()) { // pass through inventory submits
1449 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1453 // verify that we displayed the formspec to the user
1454 const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1455 if (peer_state_iterator != m_formspec_state_data.end()) {
1456 const std::string &server_formspec_name = peer_state_iterator->second;
1457 if (client_formspec_name == server_formspec_name) {
1458 auto it = fields.find("quit");
1459 if (it != fields.end() && it->second == "true")
1460 m_formspec_state_data.erase(peer_state_iterator);
1462 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1465 actionstream << "'" << player->getName()
1466 << "' submitted formspec ('" << client_formspec_name
1467 << "') but the name of the formspec doesn't match the"
1468 " expected name ('" << server_formspec_name << "')";
1471 actionstream << "'" << player->getName()
1472 << "' submitted formspec ('" << client_formspec_name
1473 << "') but server hasn't sent formspec to client";
1475 actionstream << ", possible exploitation attempt" << std::endl;
1478 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1480 session_t peer_id = pkt->getPeerId();
1481 RemoteClient *client = getClient(peer_id, CS_Invalid);
1482 ClientState cstate = client->getState();
1483 const std::string playername = client->getName();
1485 std::string salt, verification_key;
1487 std::string addr_s = getPeerAddress(peer_id).serializeString();
1490 *pkt >> salt >> verification_key >> is_empty;
1492 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1493 << ", with is_empty=" << (is_empty == 1) << std::endl;
1495 const bool empty_disallowed = !isSingleplayer() && is_empty == 1 &&
1496 g_settings->getBool("disallow_empty_password");
1498 // Either this packet is sent because the user is new or to change the password
1499 if (cstate == CS_HelloSent) {
1500 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1501 actionstream << "Server: Client from " << addr_s
1502 << " tried to set password without being "
1503 << "authenticated, or the username being new." << std::endl;
1504 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1508 if (empty_disallowed) {
1509 actionstream << "Server: " << playername
1510 << " supplied empty password from " << addr_s << std::endl;
1511 DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1515 std::string initial_ver_key;
1516 initial_ver_key = encode_srp_verifier(verification_key, salt);
1518 // It is possible for multiple connections to get this far with the same
1519 // player name. In the end only one player with a given name will be emerged
1520 // (see Server::StateTwoClientInit) but we still have to be careful here.
1521 if (m_script->getAuth(playername, nullptr, nullptr)) {
1522 // Another client beat us to it
1523 actionstream << "Server: Client from " << addr_s
1524 << " tried to register " << playername << " a second time."
1526 DenyAccess(peer_id, SERVER_ACCESSDENIED_ALREADY_CONNECTED);
1529 m_script->createAuth(playername, initial_ver_key);
1530 m_script->on_authplayer(playername, addr_s, true);
1532 acceptAuth(peer_id, false);
1534 if (cstate < CS_SudoMode) {
1535 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1536 << addr_s << ": " << "Client has wrong state " << cstate << "."
1540 m_clients.event(peer_id, CSE_SudoLeave);
1542 if (empty_disallowed) {
1543 actionstream << "Server: " << playername
1544 << " supplied empty password" << std::endl;
1545 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1546 L"Changing to an empty password is not allowed."));
1550 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1551 bool success = m_script->setPassword(playername, pw_db_field);
1553 actionstream << playername << " changes password" << std::endl;
1554 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1555 L"Password change successful."));
1557 actionstream << playername <<
1558 " tries to change password but it fails" << std::endl;
1559 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1560 L"Password change failed or unavailable."));
1565 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1567 session_t peer_id = pkt->getPeerId();
1568 RemoteClient *client = getClient(peer_id, CS_Invalid);
1569 ClientState cstate = client->getState();
1571 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1572 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1573 " from " << getPeerAddress(peer_id).serializeString() <<
1574 ". Ignoring." << std::endl;
1578 const bool wantSudo = (cstate == CS_Active);
1580 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1581 actionstream << "Server: got SRP _A packet, while auth is already "
1582 "going on with mech " << client->chosen_mech << " from " <<
1583 getPeerAddress(peer_id).serializeString() <<
1584 " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1586 DenySudoAccess(peer_id);
1590 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1594 std::string bytes_A;
1596 *pkt >> bytes_A >> based_on;
1598 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1599 << "based_on=" << int(based_on) << " and len_A="
1600 << bytes_A.length() << "." << std::endl;
1602 AuthMechanism chosen = (based_on == 0) ?
1603 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1606 if (!client->isSudoMechAllowed(chosen)) {
1607 actionstream << "Server: Player \"" << client->getName() <<
1608 "\" at " << getPeerAddress(peer_id).serializeString() <<
1609 " tried to change password using unallowed mech " << chosen <<
1611 DenySudoAccess(peer_id);
1615 if (!client->isMechAllowed(chosen)) {
1616 actionstream << "Server: Client tried to authenticate from " <<
1617 getPeerAddress(peer_id).serializeString() <<
1618 " using unallowed mech " << chosen << "." << std::endl;
1619 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1624 client->chosen_mech = chosen;
1626 std::string salt, verifier;
1628 if (based_on == 0) {
1630 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1632 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1633 // Non-base64 errors should have been catched in the init handler
1634 actionstream << "Server: User " << client->getName() <<
1635 " tried to log in, but srp verifier field was invalid (most likely "
1636 "invalid base64)." << std::endl;
1637 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1644 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1645 client->getName().c_str(),
1646 (const unsigned char *) salt.c_str(), salt.size(),
1647 (const unsigned char *) verifier.c_str(), verifier.size(),
1648 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1650 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1653 actionstream << "Server: User " << client->getName()
1654 << " tried to log in, SRP-6a safety check violated in _A handler."
1657 DenySudoAccess(peer_id);
1658 client->resetChosenMech();
1662 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1666 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1667 resp_pkt << salt << std::string(bytes_B, len_B);
1671 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1673 session_t peer_id = pkt->getPeerId();
1674 RemoteClient *client = getClient(peer_id, CS_Invalid);
1675 ClientState cstate = client->getState();
1676 const std::string addr_s = client->getAddress().serializeString();
1677 const std::string playername = client->getName();
1679 const bool wantSudo = (cstate == CS_Active);
1681 verbosestream << "Server: Received TOSERVER_SRP_BYTES_M." << std::endl;
1683 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1684 warningstream << "Server: got SRP_M packet in wrong state "
1685 << cstate << " from " << addr_s << ". Ignoring." << std::endl;
1689 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1690 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1691 warningstream << "Server: got SRP_M packet, while auth "
1692 "is going on with mech " << client->chosen_mech << " from "
1693 << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1695 DenySudoAccess(peer_id);
1699 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1703 std::string bytes_M;
1706 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1707 != bytes_M.size()) {
1708 actionstream << "Server: User " << playername << " at " << addr_s
1709 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1710 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1714 unsigned char *bytes_HAMK = 0;
1716 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1717 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1721 actionstream << "Server: User " << playername << " at " << addr_s
1722 << " tried to change their password, but supplied wrong"
1723 << " (SRP) password for authentication." << std::endl;
1724 DenySudoAccess(peer_id);
1725 client->resetChosenMech();
1729 actionstream << "Server: User " << playername << " at " << addr_s
1730 << " supplied wrong password (auth mechanism: SRP)." << std::endl;
1731 m_script->on_authplayer(playername, addr_s, false);
1732 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1736 if (client->create_player_on_auth_success) {
1737 m_script->createAuth(playername, client->enc_pwd);
1739 if (!m_script->getAuth(playername, nullptr, nullptr)) {
1740 errorstream << "Server: " << playername <<
1741 " cannot be authenticated (auth handler does not work?)" <<
1743 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1746 client->create_player_on_auth_success = false;
1749 m_script->on_authplayer(playername, addr_s, true);
1750 acceptAuth(peer_id, wantSudo);
1757 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1759 std::string channel_name;
1760 *pkt >> channel_name;
1762 session_t peer_id = pkt->getPeerId();
1763 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1764 1 + 2 + channel_name.size(), peer_id);
1766 // Send signal to client to notify join succeed or not
1767 if (g_settings->getBool("enable_mod_channels") &&
1768 m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1769 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1770 infostream << "Peer " << peer_id << " joined channel " <<
1771 channel_name << std::endl;
1774 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1775 infostream << "Peer " << peer_id << " tried to join channel " <<
1776 channel_name << ", but was already registered." << std::endl;
1778 resp_pkt << channel_name;
1782 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1784 std::string channel_name;
1785 *pkt >> channel_name;
1787 session_t peer_id = pkt->getPeerId();
1788 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1789 1 + 2 + channel_name.size(), peer_id);
1791 // Send signal to client to notify join succeed or not
1792 if (g_settings->getBool("enable_mod_channels") &&
1793 m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1794 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1795 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1798 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1799 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1800 ", but was not registered." << std::endl;
1802 resp_pkt << channel_name;
1806 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1808 std::string channel_name, channel_msg;
1809 *pkt >> channel_name >> channel_msg;
1811 session_t peer_id = pkt->getPeerId();
1812 verbosestream << "Mod channel message received from peer " << peer_id <<
1813 " on channel " << channel_name << " message: " << channel_msg <<
1816 // If mod channels are not enabled, discard message
1817 if (!g_settings->getBool("enable_mod_channels")) {
1821 // If channel not registered, signal it and ignore message
1822 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1823 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1824 1 + 2 + channel_name.size(), peer_id);
1825 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1830 // @TODO: filter, rate limit
1832 broadcastModChannelMessage(channel_name, channel_msg, peer_id);
1835 void Server::handleCommand_HaveMedia(NetworkPacket *pkt)
1837 std::vector<u32> tokens;
1841 for (u16 i = 0; i < numtokens; i++) {
1844 tokens.emplace_back(n);
1847 const session_t peer_id = pkt->getPeerId();
1848 auto player = m_env->getPlayer(peer_id);
1850 for (const u32 token : tokens) {
1851 auto it = m_pending_dyn_media.find(token);
1852 if (it == m_pending_dyn_media.end())
1854 if (it->second.waiting_players.count(peer_id)) {
1855 it->second.waiting_players.erase(peer_id);
1857 getScriptIface()->on_dynamic_media_added(token, player->getName());
1862 void Server::handleCommand_UpdateClientInfo(NetworkPacket *pkt)
1864 ClientDynamicInfo info;
1865 *pkt >> info.render_target_size.X;
1866 *pkt >> info.render_target_size.Y;
1867 *pkt >> info.real_gui_scaling;
1868 *pkt >> info.real_hud_scaling;
1869 *pkt >> info.max_fs_size.X;
1870 *pkt >> info.max_fs_size.Y;
1872 session_t peer_id = pkt->getPeerId();
1873 RemoteClient *client = getClient(peer_id, CS_Invalid);
1874 client->setDynamicInfo(info);