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"
44 void Server::handleCommand_Deprecated(NetworkPacket* pkt)
46 infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
47 << " not supported anymore" << std::endl;
50 void Server::handleCommand_Init(NetworkPacket* pkt)
53 if(pkt->getSize() < 1)
56 session_t peer_id = pkt->getPeerId();
57 RemoteClient *client = getClient(peer_id, CS_Created);
62 addr = m_con->GetPeerAddress(peer_id);
63 addr_s = addr.serializeString();
64 } catch (con::PeerNotFoundException &e) {
66 * no peer for this packet found
67 * most common reason is peer timeout, e.g. peer didn't
68 * respond for some time, your server was overloaded or
71 infostream << "Server::ProcessData(): Canceling: peer " << peer_id <<
72 " not found" << std::endl;
76 if (client->getState() > CS_Created) {
77 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " <<
78 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
82 client->setCachedAddress(addr);
84 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s <<
85 " (peer_id=" << peer_id << ")" << std::endl;
87 // Do not allow multiple players in simple singleplayer mode.
88 // This isn't a perfect way to do it, but will suffice for now
89 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
90 infostream << "Server: Not allowing another client (" << addr_s <<
91 ") to connect in simple singleplayer mode" << std::endl;
92 DenyAccess(peer_id, SERVER_ACCESSDENIED_SINGLEPLAYER);
96 // First byte after command is maximum supported
97 // serialization version
100 u16 min_net_proto_version = 0;
101 u16 max_net_proto_version;
102 std::string playerName;
104 *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
105 >> max_net_proto_version >> playerName;
107 u8 our_max = SER_FMT_VER_HIGHEST_READ;
108 // Use the highest version supported by both
109 u8 depl_serial_v = std::min(client_max, our_max);
110 // If it's lower than the lowest supported, give up.
111 if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
112 depl_serial_v = SER_FMT_VER_INVALID;
114 if (depl_serial_v == SER_FMT_VER_INVALID) {
115 actionstream << "Server: A mismatched client tried to connect from " <<
116 addr_s << " ser_fmt_max=" << (int)client_max << std::endl;
117 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
121 client->setPendingSerializationVersion(depl_serial_v);
124 Read and check network protocol version
127 u16 net_proto_version = 0;
129 // Figure out a working version if it is possible at all
130 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
131 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
132 // If maximum is larger than our maximum, go with our maximum
133 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
134 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
135 // Else go with client's maximum
137 net_proto_version = max_net_proto_version;
140 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
141 << min_net_proto_version << ", max: " << max_net_proto_version
142 << ", chosen: " << net_proto_version << std::endl;
144 client->net_proto_version = net_proto_version;
146 if ((g_settings->getBool("strict_protocol_version_checking") &&
147 net_proto_version != LATEST_PROTOCOL_VERSION) ||
148 net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
149 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
150 actionstream << "Server: A mismatched client tried to connect from " <<
151 addr_s << " proto_max=" << (int)max_net_proto_version << std::endl;
152 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
159 const char* playername = playerName.c_str();
161 size_t pns = playerName.size();
162 if (pns == 0 || pns > PLAYERNAME_SIZE) {
163 actionstream << "Server: Player with " <<
164 ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty") <<
165 " name tried to connect from " << addr_s << std::endl;
166 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
170 if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
171 actionstream << "Server: Player with an invalid name tried to connect "
172 "from " << addr_s << std::endl;
173 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
177 RemotePlayer *player = m_env->getPlayer(playername);
179 // If player is already connected, cancel
180 if (player && player->getPeerId() != PEER_ID_INEXISTENT) {
181 actionstream << "Server: Player with name \"" << playername <<
182 "\" tried to connect, but player with same name is already connected" << std::endl;
183 DenyAccess(peer_id, SERVER_ACCESSDENIED_ALREADY_CONNECTED);
187 m_clients.setPlayerName(peer_id, playername);
188 //TODO (later) case insensitivity
190 std::string legacyPlayerNameCasing = playerName;
192 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
193 actionstream << "Server: Player with the name \"singleplayer\" tried "
194 "to connect from " << addr_s << std::endl;
195 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
201 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
202 actionstream << "Server: Player with the name \"" << playerName <<
203 "\" tried to connect from " << addr_s <<
204 " but it was disallowed for the following reason: " << reason <<
206 DenyAccess(peer_id, SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
211 infostream << "Server: New connection: \"" << playerName << "\" from " <<
212 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
214 // Enforce user limit.
215 // Don't enforce for users that have some admin right or mod permits it.
216 if (m_clients.isUserLimitReached() &&
217 playername != g_settings->get("name") &&
218 !m_script->can_bypass_userlimit(playername, addr_s)) {
219 actionstream << "Server: " << playername << " tried to join from " <<
220 addr_s << ", but there are already max_users=" <<
221 g_settings->getU16("max_users") << " players." << std::endl;
222 DenyAccess(peer_id, SERVER_ACCESSDENIED_TOO_MANY_USERS);
227 Compose auth methods for answer
229 std::string encpwd; // encrypted Password field for the user
230 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
233 client->chosen_mech = AUTH_MECHANISM_NONE;
236 std::vector<std::string> pwd_components = str_split(encpwd, '#');
237 if (pwd_components.size() == 4) {
238 if (pwd_components[1] == "1") { // 1 means srp
239 auth_mechs |= AUTH_MECHANISM_SRP;
240 client->enc_pwd = encpwd;
242 actionstream << "User " << playername << " tried to log in, "
243 "but password field was invalid (unknown mechcode)." <<
245 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
248 } else if (base64_is_valid(encpwd)) {
249 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
250 client->enc_pwd = encpwd;
252 actionstream << "User " << playername << " tried to log in, but "
253 "password field was invalid (invalid base64)." << std::endl;
254 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
258 std::string default_password = g_settings->get("default_password");
259 if (default_password.length() == 0) {
260 auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
262 // Take care of default passwords.
263 client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
264 auth_mechs |= AUTH_MECHANISM_SRP;
265 // Allocate player in db, but only on successful login.
266 client->create_player_on_auth_success = true;
271 Answer with a TOCLIENT_HELLO
274 verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
275 << auth_mechs << std::endl;
277 NetworkPacket resp_pkt(TOCLIENT_HELLO,
278 1 + 4 + legacyPlayerNameCasing.size(), peer_id);
280 u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
281 resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
282 << auth_mechs << legacyPlayerNameCasing;
286 client->allowed_auth_mechs = auth_mechs;
287 client->setDeployedCompressionMode(depl_compress_mode);
289 m_clients.event(peer_id, CSE_Hello);
292 void Server::handleCommand_Init2(NetworkPacket* pkt)
294 session_t peer_id = pkt->getPeerId();
295 verbosestream << "Server: Got TOSERVER_INIT2 from " << peer_id << std::endl;
297 m_clients.event(peer_id, CSE_GotInit2);
298 u16 protocol_version = m_clients.getProtocolVersion(peer_id);
301 if (pkt->getSize() > 0)
305 Send some initialization data
308 infostream << "Server: Sending content to " << getPlayerName(peer_id) <<
311 // Send item definitions
312 SendItemDef(peer_id, m_itemdef, protocol_version);
314 // Send node definitions
315 SendNodeDef(peer_id, m_nodedef, protocol_version);
317 m_clients.event(peer_id, CSE_SetDefinitionsSent);
319 // Send media announcement
320 sendMediaAnnouncement(peer_id, lang);
322 RemoteClient *client = getClient(peer_id, CS_InitDone);
324 // Keep client language for server translations
325 client->setLangCode(lang);
327 // Send active objects
329 PlayerSAO *sao = getPlayerSAO(peer_id);
331 SendActiveObjectRemoveAdd(client, sao);
334 // Send detached inventories
335 sendDetachedInventories(peer_id, false);
337 // Send player movement settings
338 SendMovement(peer_id);
341 u16 time = m_env->getTimeOfDay();
342 float time_speed = g_settings->getFloat("time_speed");
343 SendTimeOfDay(peer_id, time, time_speed);
345 SendCSMRestrictionFlags(peer_id);
347 // Warnings about protocol version can be issued here
348 if (client->net_proto_version < LATEST_PROTOCOL_VERSION) {
349 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
350 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
351 L"WITH THIS SERVER!"));
355 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
357 std::vector<std::string> tosend;
362 session_t peer_id = pkt->getPeerId();
363 infostream << "Sending " << numfiles << " files to " <<
364 getPlayerName(peer_id) << std::endl;
365 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
367 for (u16 i = 0; i < numfiles; i++) {
372 tosend.push_back(name);
373 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
374 << name << std::endl;
377 sendRequestedMedia(peer_id, tosend);
380 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
382 session_t peer_id = pkt->getPeerId();
384 PlayerSAO* playersao = StageTwoClientInit(peer_id);
386 if (playersao == NULL) {
387 errorstream << "TOSERVER_CLIENT_READY stage 2 client init failed "
388 "peer_id=" << peer_id << std::endl;
389 DisconnectPeer(peer_id);
394 if (pkt->getSize() < 8) {
395 errorstream << "TOSERVER_CLIENT_READY client sent inconsistent data, "
396 "disconnecting peer_id: " << peer_id << std::endl;
397 DisconnectPeer(peer_id);
401 u8 major_ver, minor_ver, patch_ver, reserved;
402 std::string full_ver;
403 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
405 m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver,
408 if (pkt->getRemainingBytes() >= 2)
409 *pkt >> playersao->getPlayer()->formspec_version;
411 const std::vector<std::string> &players = m_clients.getPlayerNames();
412 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
413 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
414 for (const std::string &player: players) {
417 m_clients.send(peer_id, 0, &list_pkt, true);
419 NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
420 // (u16) 1 + std::string represents a pseudo vector serialization representation
421 notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
422 m_clients.sendToAll(¬ice_pkt);
423 m_clients.event(peer_id, CSE_SetClientReady);
426 m_script->getAuth(playersao->getPlayer()->getName(), nullptr, nullptr, &last_login);
427 m_script->on_joinplayer(playersao, last_login);
429 // Send shutdown timer if shutdown has been scheduled
430 if (m_shutdown_state.isTimerRunning()) {
431 SendChatMessage(peer_id, m_shutdown_state.getShutdownTimerMessage());
435 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
437 if (pkt->getSize() < 1)
451 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
452 throw con::InvalidIncomingDataException
453 ("GOTBLOCKS length is too short");
457 RemoteClient *client = m_clients.lockedGetClientNoEx(pkt->getPeerId());
459 for (u16 i = 0; i < count; i++) {
467 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
470 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
474 s32 f32pitch, f32yaw;
482 f32 pitch = (f32)f32pitch / 100.0f;
483 f32 yaw = (f32)f32yaw / 100.0f;
486 // default behavior (in case an old client doesn't send these)
492 fov = (f32)f32fov / 80.0f;
493 *pkt >> wanted_range;
495 v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
496 v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
498 pitch = modulo360f(pitch);
499 yaw = wrapDegrees_0_360(yaw);
501 if (!playersao->isAttached()) {
502 // Only update player positions when moving freely
503 // to not interfere with attachment handling
504 playersao->setBasePosition(position);
505 player->setSpeed(speed);
507 playersao->setLookPitch(pitch);
508 playersao->setPlayerYaw(yaw);
509 playersao->setFov(fov);
510 playersao->setWantedRange(wanted_range);
512 player->keyPressed = keyPressed;
513 player->control.jump = (keyPressed & (0x1 << 4));
514 player->control.aux1 = (keyPressed & (0x1 << 5));
515 player->control.sneak = (keyPressed & (0x1 << 6));
516 player->control.dig = (keyPressed & (0x1 << 7));
517 player->control.place = (keyPressed & (0x1 << 8));
518 player->control.zoom = (keyPressed & (0x1 << 9));
520 if (playersao->checkMovementCheat()) {
522 m_script->on_cheat(playersao, "moved_too_fast");
523 SendMovePlayer(pkt->getPeerId());
527 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
529 session_t peer_id = pkt->getPeerId();
530 RemotePlayer *player = m_env->getPlayer(peer_id);
531 if (player == NULL) {
533 "Server::ProcessData(): Canceling: No player for peer_id=" <<
534 peer_id << " disconnecting peer!" << std::endl;
535 DisconnectPeer(peer_id);
539 PlayerSAO *playersao = player->getPlayerSAO();
540 if (playersao == NULL) {
542 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
543 peer_id << " disconnecting peer!" << std::endl;
544 DisconnectPeer(peer_id);
548 // If player is dead we don't care of this packet
549 if (playersao->isDead()) {
550 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
551 << " is dead. Ignoring packet";
555 process_PlayerPos(player, playersao, pkt);
558 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
560 if (pkt->getSize() < 1)
574 RemoteClient *client = getClient(pkt->getPeerId());
576 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
577 throw con::InvalidIncomingDataException
578 ("DELETEDBLOCKS length is too short");
581 for (u16 i = 0; i < count; i++) {
584 client->SetBlockNotSent(p);
588 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
590 session_t peer_id = pkt->getPeerId();
591 RemotePlayer *player = m_env->getPlayer(peer_id);
593 if (player == NULL) {
595 "Server::ProcessData(): Canceling: No player for peer_id=" <<
596 peer_id << " disconnecting peer!" << std::endl;
597 DisconnectPeer(peer_id);
601 PlayerSAO *playersao = player->getPlayerSAO();
602 if (playersao == NULL) {
604 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
605 peer_id << " disconnecting peer!" << std::endl;
606 DisconnectPeer(peer_id);
610 // Strip command and create a stream
611 std::string datastring(pkt->getString(0), pkt->getSize());
612 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
614 std::istringstream is(datastring, std::ios_base::binary);
616 std::unique_ptr<InventoryAction> a(InventoryAction::deSerialize(is));
618 infostream << "TOSERVER_INVENTORY_ACTION: "
619 << "InventoryAction::deSerialize() returned NULL"
624 // If something goes wrong, this player is to blame
625 RollbackScopeActor rollback_scope(m_rollback,
626 std::string("player:")+player->getName());
629 Note: Always set inventory not sent, to repair cases
630 where the client made a bad prediction.
633 const bool player_has_interact = checkPriv(player->getName(), "interact");
635 auto check_inv_access = [player, player_has_interact, this] (
636 const InventoryLocation &loc) -> bool {
638 // Players without interact may modify their own inventory
639 if (!player_has_interact && loc.type != InventoryLocation::PLAYER) {
640 infostream << "Cannot modify foreign inventory: "
641 << "No interact privilege" << std::endl;
646 case InventoryLocation::CURRENT_PLAYER:
647 // Only used internally on the client, never sent
649 case InventoryLocation::PLAYER:
650 // Allow access to own inventory in all cases
651 return loc.name == player->getName();
652 case InventoryLocation::NODEMETA:
654 // Check for out-of-range interaction
655 v3f node_pos = intToFloat(loc.p, BS);
656 v3f player_pos = player->getPlayerSAO()->getEyePosition();
657 f32 d = player_pos.getDistanceFrom(node_pos);
658 return checkInteractDistance(player, d, "inventory");
660 case InventoryLocation::DETACHED:
661 return getInventoryMgr()->checkDetachedInventoryAccess(loc, player->getName());
668 Handle restrictions and special cases of the move action
670 if (a->getType() == IAction::Move) {
671 IMoveAction *ma = (IMoveAction*)a.get();
673 ma->from_inv.applyCurrentPlayer(player->getName());
674 ma->to_inv.applyCurrentPlayer(player->getName());
676 m_inventory_mgr->setInventoryModified(ma->from_inv);
677 if (ma->from_inv != ma->to_inv)
678 m_inventory_mgr->setInventoryModified(ma->to_inv);
680 if (!check_inv_access(ma->from_inv) ||
681 !check_inv_access(ma->to_inv))
685 Disable moving items out of craftpreview
687 if (ma->from_list == "craftpreview") {
688 infostream << "Ignoring IMoveAction from "
689 << (ma->from_inv.dump()) << ":" << ma->from_list
690 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
691 << " because src is " << ma->from_list << std::endl;
696 Disable moving items into craftresult and craftpreview
698 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
699 infostream << "Ignoring IMoveAction from "
700 << (ma->from_inv.dump()) << ":" << ma->from_list
701 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
702 << " because dst is " << ma->to_list << std::endl;
707 Handle restrictions and special cases of the drop action
709 else if (a->getType() == IAction::Drop) {
710 IDropAction *da = (IDropAction*)a.get();
712 da->from_inv.applyCurrentPlayer(player->getName());
714 m_inventory_mgr->setInventoryModified(da->from_inv);
717 Disable dropping items out of craftpreview
719 if (da->from_list == "craftpreview") {
720 infostream << "Ignoring IDropAction from "
721 << (da->from_inv.dump()) << ":" << da->from_list
722 << " because src is " << da->from_list << std::endl;
726 // Disallow dropping items if not allowed to interact
727 if (!player_has_interact || !check_inv_access(da->from_inv))
730 // Disallow dropping items if dead
731 if (playersao->isDead()) {
732 infostream << "Ignoring IDropAction from "
733 << (da->from_inv.dump()) << ":" << da->from_list
734 << " because player is dead." << std::endl;
739 Handle restrictions and special cases of the craft action
741 else if (a->getType() == IAction::Craft) {
742 ICraftAction *ca = (ICraftAction*)a.get();
744 ca->craft_inv.applyCurrentPlayer(player->getName());
746 m_inventory_mgr->setInventoryModified(ca->craft_inv);
748 // Disallow crafting if not allowed to interact
749 if (!player_has_interact) {
750 infostream << "Cannot craft: "
751 << "No interact privilege" << std::endl;
755 if (!check_inv_access(ca->craft_inv))
758 // Unknown action. Ignored.
763 a->apply(m_inventory_mgr.get(), playersao, this);
766 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
768 std::wstring message;
771 session_t peer_id = pkt->getPeerId();
772 RemotePlayer *player = m_env->getPlayer(peer_id);
773 if (player == NULL) {
775 "Server::ProcessData(): Canceling: No player for peer_id=" <<
776 peer_id << " disconnecting peer!" << std::endl;
777 DisconnectPeer(peer_id);
781 std::string name = player->getName();
783 std::wstring answer_to_sender = handleChat(name, message, true, player);
784 if (!answer_to_sender.empty()) {
785 // Send the answer to sender
786 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
791 void Server::handleCommand_Damage(NetworkPacket* pkt)
797 session_t peer_id = pkt->getPeerId();
798 RemotePlayer *player = m_env->getPlayer(peer_id);
800 if (player == NULL) {
802 "Server::ProcessData(): Canceling: No player for peer_id=" <<
803 peer_id << " disconnecting peer!" << std::endl;
804 DisconnectPeer(peer_id);
808 PlayerSAO *playersao = player->getPlayerSAO();
809 if (playersao == NULL) {
811 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
812 peer_id << " disconnecting peer!" << std::endl;
813 DisconnectPeer(peer_id);
817 if (!playersao->isImmortal()) {
818 if (playersao->isDead()) {
819 verbosestream << "Server::ProcessData(): Info: "
820 "Ignoring damage as player " << player->getName()
821 << " is already dead." << std::endl;
825 actionstream << player->getName() << " damaged by "
826 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
829 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
830 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
831 SendPlayerHPOrDie(playersao, reason);
835 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
837 if (pkt->getSize() < 2)
840 session_t peer_id = pkt->getPeerId();
841 RemotePlayer *player = m_env->getPlayer(peer_id);
843 if (player == NULL) {
845 "Server::ProcessData(): Canceling: No player for peer_id=" <<
846 peer_id << " disconnecting peer!" << std::endl;
847 DisconnectPeer(peer_id);
851 PlayerSAO *playersao = player->getPlayerSAO();
852 if (playersao == NULL) {
854 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
855 peer_id << " disconnecting peer!" << std::endl;
856 DisconnectPeer(peer_id);
864 if (item >= player->getHotbarItemcount()) {
865 actionstream << "Player: " << player->getName()
866 << " tried to access item=" << item
867 << " out of hotbar_itemcount="
868 << player->getHotbarItemcount()
869 << "; ignoring." << std::endl;
873 playersao->getPlayer()->setWieldIndex(item);
876 void Server::handleCommand_Respawn(NetworkPacket* pkt)
878 session_t peer_id = pkt->getPeerId();
879 RemotePlayer *player = m_env->getPlayer(peer_id);
880 if (player == NULL) {
882 "Server::ProcessData(): Canceling: No player for peer_id=" <<
883 peer_id << " disconnecting peer!" << std::endl;
884 DisconnectPeer(peer_id);
888 PlayerSAO *playersao = player->getPlayerSAO();
891 if (!playersao->isDead())
894 RespawnPlayer(peer_id);
896 actionstream << player->getName() << " respawns at "
897 << PP(playersao->getBasePosition() / BS) << std::endl;
899 // ActiveObject is added to environment in AsyncRunStep after
900 // the previous addition has been successfully removed
903 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
905 ItemStack selected_item, hand_item;
906 player->getWieldedItem(&selected_item, &hand_item);
907 f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
908 hand_item.getDefinition(m_itemdef));
910 // Cube diagonal * 1.5 for maximal supported node extents:
911 // sqrt(3) * 1.5 ≅ 2.6
912 if (d > max_d + 2.6f * BS) {
913 actionstream << "Player " << player->getName()
914 << " tried to access " << what
916 << "d=" << d << ", max_d=" << max_d
917 << "; ignoring." << std::endl;
919 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
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 u16 src_original_hp = pointed_object->getHP();
1117 u16 dst_origin_hp = playersao->getHP();
1119 u16 wear = pointed_object->punch(dir, &toolcap, playersao,
1120 time_from_last_punch);
1122 // Callback may have changed item, so get it again
1123 playersao->getWieldedItem(&selected_item);
1124 bool changed = selected_item.addWear(wear, m_itemdef);
1126 playersao->setWieldedItem(selected_item);
1128 // If the object is a player and its HP changed
1129 if (src_original_hp != pointed_object->getHP() &&
1130 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1131 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1132 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1135 // If the puncher is a player and its HP changed
1136 if (dst_origin_hp != playersao->getHP())
1137 SendPlayerHPOrDie(playersao,
1138 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1141 } // action == INTERACT_START_DIGGING
1143 case INTERACT_STOP_DIGGING:
1147 case INTERACT_DIGGING_COMPLETED: {
1148 // Only digging of nodes
1149 if (pointed.type != POINTEDTHING_NODE)
1152 v3s16 p_under = pointed.node_undersurface;
1153 MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1155 infostream << "Server: Not finishing digging: Node not found. "
1156 "Adding block to emerge queue." << std::endl;
1157 m_emerge->enqueueBlockEmerge(peer_id,
1158 getNodeBlockPos(pointed.node_abovesurface), false);
1161 /* Cheat prevention */
1162 bool is_valid_dig = true;
1163 if (enable_anticheat && !isSingleplayer()) {
1164 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1165 float nocheat_t = playersao->getNoCheatDigTime();
1166 playersao->noCheatDigEnd();
1167 // If player didn't start digging this, ignore dig
1168 if (nocheat_p != p_under) {
1169 infostream << "Server: " << player->getName()
1170 << " started digging "
1171 << PP(nocheat_p) << " and completed digging "
1172 << PP(p_under) << "; not digging." << std::endl;
1173 is_valid_dig = false;
1175 m_script->on_cheat(playersao, "finished_unknown_dig");
1178 // Get player's wielded item
1179 // See also: Game::handleDigging
1180 ItemStack selected_item, hand_item;
1181 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1183 // Get diggability and expected digging time
1184 DigParams params = getDigParams(m_nodedef->get(n).groups,
1185 &selected_item.getToolCapabilities(m_itemdef));
1186 // If can't dig, try hand
1187 if (!params.diggable) {
1188 params = getDigParams(m_nodedef->get(n).groups,
1189 &hand_item.getToolCapabilities(m_itemdef));
1191 // If can't dig, ignore dig
1192 if (!params.diggable) {
1193 infostream << "Server: " << player->getName()
1194 << " completed digging " << PP(p_under)
1195 << ", which is not diggable with tool; not digging."
1197 is_valid_dig = false;
1199 m_script->on_cheat(playersao, "dug_unbreakable");
1201 // Check digging time
1202 // If already invalidated, we don't have to
1203 if (!is_valid_dig) {
1204 // Well not our problem then
1206 // Clean and long dig
1207 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1208 // All is good, but grab time from pool; don't care if
1209 // it's actually available
1210 playersao->getDigPool().grab(params.time);
1212 // Short or laggy dig
1213 // Try getting the time from pool
1214 else if (playersao->getDigPool().grab(params.time)) {
1219 infostream << "Server: " << player->getName()
1220 << " completed digging " << PP(p_under)
1221 << "too fast; not digging." << std::endl;
1222 is_valid_dig = false;
1224 m_script->on_cheat(playersao, "dug_too_fast");
1228 /* Actually dig node */
1230 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1231 m_script->node_on_dig(p_under, n, playersao);
1233 v3s16 blockpos = getNodeBlockPos(p_under);
1234 RemoteClient *client = getClient(peer_id);
1235 // Send unusual result (that is, node not being removed)
1236 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR)
1237 // Re-send block to revert change on client-side
1238 client->SetBlockNotSent(blockpos);
1240 client->ResendBlockIfOnWire(blockpos);
1243 } // action == INTERACT_DIGGING_COMPLETED
1245 // Place block or right-click object
1246 case INTERACT_PLACE: {
1247 ItemStack selected_item;
1248 playersao->getWieldedItem(&selected_item, nullptr);
1250 // Reset build time counter
1251 if (pointed.type == POINTEDTHING_NODE &&
1252 selected_item.getDefinition(m_itemdef).type == ITEM_NODE)
1253 getClient(peer_id)->m_time_from_building = 0.0;
1255 if (pointed.type == POINTEDTHING_OBJECT) {
1256 // Right click object
1258 // Skip if object can't be interacted with anymore
1259 if (pointed_object->isGone())
1262 actionstream << player->getName() << " right-clicks object "
1263 << pointed.object_id << ": "
1264 << pointed_object->getDescription() << std::endl;
1267 if (m_script->item_OnSecondaryUse(
1268 selected_item, playersao, pointed)) {
1269 if (playersao->setWieldedItem(selected_item)) {
1270 SendInventory(playersao, true);
1274 pointed_object->rightClick(playersao);
1275 } else if (m_script->item_OnPlace(selected_item, playersao, pointed)) {
1276 // Placement was handled in lua
1278 // Apply returned ItemStack
1279 if (playersao->setWieldedItem(selected_item))
1280 SendInventory(playersao, true);
1283 if (pointed.type != POINTEDTHING_NODE)
1286 // If item has node placement prediction, always send the
1287 // blocks to make sure the client knows what exactly happened
1288 RemoteClient *client = getClient(peer_id);
1289 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1290 v3s16 blockpos2 = getNodeBlockPos(pointed.node_undersurface);
1291 if (!selected_item.getDefinition(m_itemdef
1292 ).node_placement_prediction.empty()) {
1293 client->SetBlockNotSent(blockpos);
1294 if (blockpos2 != blockpos)
1295 client->SetBlockNotSent(blockpos2);
1297 client->ResendBlockIfOnWire(blockpos);
1298 if (blockpos2 != blockpos)
1299 client->ResendBlockIfOnWire(blockpos2);
1303 } // action == INTERACT_PLACE
1305 case INTERACT_USE: {
1306 ItemStack selected_item;
1307 playersao->getWieldedItem(&selected_item, nullptr);
1309 actionstream << player->getName() << " uses " << selected_item.name
1310 << ", pointing at " << pointed.dump() << std::endl;
1312 if (m_script->item_OnUse(selected_item, playersao, pointed)) {
1313 // Apply returned ItemStack
1314 if (playersao->setWieldedItem(selected_item))
1315 SendInventory(playersao, true);
1322 case INTERACT_ACTIVATE: {
1323 ItemStack selected_item;
1324 playersao->getWieldedItem(&selected_item, nullptr);
1326 actionstream << player->getName() << " activates "
1327 << selected_item.name << std::endl;
1329 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1331 if (m_script->item_OnSecondaryUse(selected_item, playersao, pointed)) {
1332 if (playersao->setWieldedItem(selected_item))
1333 SendInventory(playersao, true);
1340 warningstream << "Server: Invalid action " << action << std::endl;
1345 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1349 for (u16 k = 0; k < num; k++) {
1354 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1355 m_playing_sounds.find(id);
1356 if (i == m_playing_sounds.end())
1359 ServerPlayingSound &psound = i->second;
1360 psound.clients.erase(pkt->getPeerId());
1361 if (psound.clients.empty())
1362 m_playing_sounds.erase(i++);
1366 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1369 std::string formname;
1372 *pkt >> p >> formname >> num;
1375 for (u16 k = 0; k < num; k++) {
1376 std::string fieldname;
1378 fields[fieldname] = pkt->readLongString();
1381 session_t peer_id = pkt->getPeerId();
1382 RemotePlayer *player = m_env->getPlayer(peer_id);
1384 if (player == NULL) {
1386 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1387 peer_id << " disconnecting peer!" << std::endl;
1388 DisconnectPeer(peer_id);
1392 PlayerSAO *playersao = player->getPlayerSAO();
1393 if (playersao == NULL) {
1395 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1396 peer_id << " disconnecting peer!" << std::endl;
1397 DisconnectPeer(peer_id);
1401 // If something goes wrong, this player is to blame
1402 RollbackScopeActor rollback_scope(m_rollback,
1403 std::string("player:")+player->getName());
1405 // Check the target node for rollback data; leave others unnoticed
1406 RollbackNode rn_old(&m_env->getMap(), p, this);
1408 m_script->node_on_receive_fields(p, formname, fields, playersao);
1410 // Report rollback data
1411 RollbackNode rn_new(&m_env->getMap(), p, this);
1412 if (rollback() && rn_new != rn_old) {
1413 RollbackAction action;
1414 action.setSetNode(p, rn_old, rn_new);
1415 rollback()->reportAction(action);
1419 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1421 std::string client_formspec_name;
1424 *pkt >> client_formspec_name >> num;
1427 for (u16 k = 0; k < num; k++) {
1428 std::string fieldname;
1430 fields[fieldname] = pkt->readLongString();
1433 session_t peer_id = pkt->getPeerId();
1434 RemotePlayer *player = m_env->getPlayer(peer_id);
1436 if (player == NULL) {
1438 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1439 peer_id << " disconnecting peer!" << std::endl;
1440 DisconnectPeer(peer_id);
1444 PlayerSAO *playersao = player->getPlayerSAO();
1445 if (playersao == NULL) {
1447 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1448 peer_id << " disconnecting peer!" << std::endl;
1449 DisconnectPeer(peer_id);
1453 if (client_formspec_name.empty()) { // pass through inventory submits
1454 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1458 // verify that we displayed the formspec to the user
1459 const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1460 if (peer_state_iterator != m_formspec_state_data.end()) {
1461 const std::string &server_formspec_name = peer_state_iterator->second;
1462 if (client_formspec_name == server_formspec_name) {
1463 auto it = fields.find("quit");
1464 if (it != fields.end() && it->second == "true")
1465 m_formspec_state_data.erase(peer_state_iterator);
1467 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1470 actionstream << "'" << player->getName()
1471 << "' submitted formspec ('" << client_formspec_name
1472 << "') but the name of the formspec doesn't match the"
1473 " expected name ('" << server_formspec_name << "')";
1476 actionstream << "'" << player->getName()
1477 << "' submitted formspec ('" << client_formspec_name
1478 << "') but server hasn't sent formspec to client";
1480 actionstream << ", possible exploitation attempt" << std::endl;
1483 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1485 session_t peer_id = pkt->getPeerId();
1486 RemoteClient *client = getClient(peer_id, CS_Invalid);
1487 ClientState cstate = client->getState();
1489 std::string playername = client->getName();
1492 std::string verification_key;
1494 std::string addr_s = getPeerAddress(peer_id).serializeString();
1497 *pkt >> salt >> verification_key >> is_empty;
1499 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1500 << ", with is_empty=" << (is_empty == 1) << std::endl;
1502 // Either this packet is sent because the user is new or to change the password
1503 if (cstate == CS_HelloSent) {
1504 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1505 actionstream << "Server: Client from " << addr_s
1506 << " tried to set password without being "
1507 << "authenticated, or the username being new." << std::endl;
1508 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1512 if (!isSingleplayer() &&
1513 g_settings->getBool("disallow_empty_password") &&
1515 actionstream << "Server: " << playername
1516 << " supplied empty password from " << addr_s << std::endl;
1517 DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1521 std::string initial_ver_key;
1523 initial_ver_key = encode_srp_verifier(verification_key, salt);
1524 m_script->createAuth(playername, initial_ver_key);
1525 m_script->on_authplayer(playername, addr_s, true);
1527 acceptAuth(peer_id, false);
1529 if (cstate < CS_SudoMode) {
1530 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1531 << addr_s << ": " << "Client has wrong state " << cstate << "."
1535 m_clients.event(peer_id, CSE_SudoLeave);
1536 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1537 bool success = m_script->setPassword(playername, pw_db_field);
1539 actionstream << playername << " changes password" << std::endl;
1540 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1541 L"Password change successful."));
1543 actionstream << playername <<
1544 " tries to change password but it fails" << std::endl;
1545 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1546 L"Password change failed or unavailable."));
1551 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1553 session_t peer_id = pkt->getPeerId();
1554 RemoteClient *client = getClient(peer_id, CS_Invalid);
1555 ClientState cstate = client->getState();
1557 bool wantSudo = (cstate == CS_Active);
1559 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1560 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1561 " from " << getPeerAddress(peer_id).serializeString() <<
1562 ". Ignoring." << std::endl;
1566 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1567 actionstream << "Server: got SRP _A packet, while auth is already "
1568 "going on with mech " << client->chosen_mech << " from " <<
1569 getPeerAddress(peer_id).serializeString() <<
1570 " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1572 DenySudoAccess(peer_id);
1576 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1580 std::string bytes_A;
1582 *pkt >> bytes_A >> based_on;
1584 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1585 << "based_on=" << int(based_on) << " and len_A="
1586 << bytes_A.length() << "." << std::endl;
1588 AuthMechanism chosen = (based_on == 0) ?
1589 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1592 if (!client->isSudoMechAllowed(chosen)) {
1593 actionstream << "Server: Player \"" << client->getName() <<
1594 "\" at " << getPeerAddress(peer_id).serializeString() <<
1595 " tried to change password using unallowed mech " << chosen <<
1597 DenySudoAccess(peer_id);
1601 if (!client->isMechAllowed(chosen)) {
1602 actionstream << "Server: Client tried to authenticate from " <<
1603 getPeerAddress(peer_id).serializeString() <<
1604 " using unallowed mech " << chosen << "." << std::endl;
1605 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1610 client->chosen_mech = chosen;
1613 std::string verifier;
1615 if (based_on == 0) {
1617 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1619 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1620 // Non-base64 errors should have been catched in the init handler
1621 actionstream << "Server: User " << client->getName() <<
1622 " tried to log in, but srp verifier field was invalid (most likely "
1623 "invalid base64)." << std::endl;
1624 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1631 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1632 client->getName().c_str(),
1633 (const unsigned char *) salt.c_str(), salt.size(),
1634 (const unsigned char *) verifier.c_str(), verifier.size(),
1635 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1637 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1640 actionstream << "Server: User " << client->getName()
1641 << " tried to log in, SRP-6a safety check violated in _A handler."
1644 DenySudoAccess(peer_id);
1648 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1652 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1653 resp_pkt << salt << std::string(bytes_B, len_B);
1657 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1659 session_t peer_id = pkt->getPeerId();
1660 RemoteClient *client = getClient(peer_id, CS_Invalid);
1661 ClientState cstate = client->getState();
1662 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1663 std::string playername = client->getName();
1665 bool wantSudo = (cstate == CS_Active);
1667 verbosestream << "Server: Received TOSERVER_SRP_BYTES_M." << std::endl;
1669 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1670 warningstream << "Server: got SRP_M packet in wrong state "
1671 << cstate << " from " << addr_s << ". Ignoring." << std::endl;
1675 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1676 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1677 warningstream << "Server: got SRP_M packet, while auth "
1678 "is going on with mech " << client->chosen_mech << " from "
1679 << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1681 DenySudoAccess(peer_id);
1685 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1689 std::string bytes_M;
1692 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1693 != bytes_M.size()) {
1694 actionstream << "Server: User " << playername << " at " << addr_s
1695 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1696 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1700 unsigned char *bytes_HAMK = 0;
1702 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1703 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1707 actionstream << "Server: User " << playername << " at " << addr_s
1708 << " tried to change their password, but supplied wrong"
1709 << " (SRP) password for authentication." << std::endl;
1710 DenySudoAccess(peer_id);
1714 actionstream << "Server: User " << playername << " at " << addr_s
1715 << " supplied wrong password (auth mechanism: SRP)." << std::endl;
1716 m_script->on_authplayer(playername, addr_s, false);
1717 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1721 if (client->create_player_on_auth_success) {
1722 m_script->createAuth(playername, client->enc_pwd);
1724 std::string checkpwd; // not used, but needed for passing something
1725 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1726 errorstream << "Server: " << playername <<
1727 " cannot be authenticated (auth handler does not work?)" <<
1729 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1732 client->create_player_on_auth_success = false;
1735 m_script->on_authplayer(playername, addr_s, true);
1736 acceptAuth(peer_id, wantSudo);
1743 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1745 std::string channel_name;
1746 *pkt >> channel_name;
1748 session_t peer_id = pkt->getPeerId();
1749 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1750 1 + 2 + channel_name.size(), peer_id);
1752 // Send signal to client to notify join succeed or not
1753 if (g_settings->getBool("enable_mod_channels") &&
1754 m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1755 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1756 infostream << "Peer " << peer_id << " joined channel " <<
1757 channel_name << std::endl;
1760 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1761 infostream << "Peer " << peer_id << " tried to join channel " <<
1762 channel_name << ", but was already registered." << std::endl;
1764 resp_pkt << channel_name;
1768 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1770 std::string channel_name;
1771 *pkt >> channel_name;
1773 session_t peer_id = pkt->getPeerId();
1774 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1775 1 + 2 + channel_name.size(), peer_id);
1777 // Send signal to client to notify join succeed or not
1778 if (g_settings->getBool("enable_mod_channels") &&
1779 m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1780 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1781 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1784 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1785 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1786 ", but was not registered." << std::endl;
1788 resp_pkt << channel_name;
1792 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1794 std::string channel_name, channel_msg;
1795 *pkt >> channel_name >> channel_msg;
1797 session_t peer_id = pkt->getPeerId();
1798 verbosestream << "Mod channel message received from peer " << peer_id <<
1799 " on channel " << channel_name << " message: " << channel_msg <<
1802 // If mod channels are not enabled, discard message
1803 if (!g_settings->getBool("enable_mod_channels")) {
1807 // If channel not registered, signal it and ignore message
1808 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1809 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1810 1 + 2 + channel_name.size(), peer_id);
1811 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1816 // @TODO: filter, rate limit
1818 broadcastModChannelMessage(channel_name, channel_msg, peer_id);