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 "util/auth.h"
38 #include "util/base64.h"
39 #include "util/pointedthing.h"
40 #include "util/serialize.h"
43 void Server::handleCommand_Deprecated(NetworkPacket* pkt)
45 infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
46 << " not supported anymore" << std::endl;
49 void Server::handleCommand_Init(NetworkPacket* pkt)
52 if(pkt->getSize() < 1)
55 session_t peer_id = pkt->getPeerId();
56 RemoteClient *client = getClient(peer_id, CS_Created);
60 Address address = getPeerAddress(peer_id);
61 addr_s = address.serializeString();
63 catch (con::PeerNotFoundException &e) {
65 * no peer for this packet found
66 * most common reason is peer timeout, e.g. peer didn't
67 * respond for some time, your server was overloaded or
70 infostream << "Server::ProcessData(): Canceling: peer " << peer_id <<
71 " not found" << std::endl;
75 // If net_proto_version is set, this client has already been handled
76 if (client->getState() > CS_Created) {
77 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " <<
78 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
82 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s <<
83 " (peer_id=" << peer_id << ")" << std::endl;
85 // Do not allow multiple players in simple singleplayer mode.
86 // This isn't a perfect way to do it, but will suffice for now
87 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
88 infostream << "Server: Not allowing another client (" << addr_s <<
89 ") to connect in simple singleplayer mode" << std::endl;
90 DenyAccess(peer_id, SERVER_ACCESSDENIED_SINGLEPLAYER);
94 // First byte after command is maximum supported
95 // serialization version
98 u16 min_net_proto_version = 0;
99 u16 max_net_proto_version;
100 std::string playerName;
102 *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
103 >> max_net_proto_version >> playerName;
105 u8 our_max = SER_FMT_VER_HIGHEST_READ;
106 // Use the highest version supported by both
107 u8 depl_serial_v = std::min(client_max, our_max);
108 // If it's lower than the lowest supported, give up.
109 if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
110 depl_serial_v = SER_FMT_VER_INVALID;
112 if (depl_serial_v == SER_FMT_VER_INVALID) {
113 actionstream << "Server: A mismatched client tried to connect from " <<
114 addr_s << " client_max=" << (int)client_max << std::endl;
115 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
119 client->setPendingSerializationVersion(depl_serial_v);
122 Read and check network protocol version
125 u16 net_proto_version = 0;
127 // Figure out a working version if it is possible at all
128 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
129 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
130 // If maximum is larger than our maximum, go with our maximum
131 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
132 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
133 // Else go with client's maximum
135 net_proto_version = max_net_proto_version;
138 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
139 << min_net_proto_version << ", max: " << max_net_proto_version
140 << ", chosen: " << net_proto_version << std::endl;
142 client->net_proto_version = net_proto_version;
144 if ((g_settings->getBool("strict_protocol_version_checking") &&
145 net_proto_version != LATEST_PROTOCOL_VERSION) ||
146 net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
147 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
148 actionstream << "Server: A mismatched client tried to connect from " <<
150 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
157 const char* playername = playerName.c_str();
159 size_t pns = playerName.size();
160 if (pns == 0 || pns > PLAYERNAME_SIZE) {
161 actionstream << "Server: Player with " <<
162 ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty") <<
163 " name tried to connect from " << addr_s << std::endl;
164 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
168 if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
169 actionstream << "Server: Player with an invalid name tried to connect "
170 "from " << addr_s << std::endl;
171 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
175 m_clients.setPlayerName(peer_id, playername);
176 //TODO (later) case insensitivity
178 std::string legacyPlayerNameCasing = playerName;
180 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
181 actionstream << "Server: Player with the name \"singleplayer\" tried "
182 "to connect from " << addr_s << std::endl;
183 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
189 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
190 actionstream << "Server: Player with the name \"" << playerName <<
191 "\" tried to connect from " << addr_s <<
192 " but it was disallowed for the following reason: " << reason <<
194 DenyAccess(peer_id, SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
199 infostream << "Server: New connection: \"" << playerName << "\" from " <<
200 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
202 // Enforce user limit.
203 // Don't enforce for users that have some admin right or mod permits it.
204 if (m_clients.isUserLimitReached() &&
205 playername != g_settings->get("name") &&
206 !m_script->can_bypass_userlimit(playername, addr_s)) {
207 actionstream << "Server: " << playername << " tried to join from " <<
208 addr_s << ", but there are already max_users=" <<
209 g_settings->getU16("max_users") << " players." << std::endl;
210 DenyAccess(peer_id, SERVER_ACCESSDENIED_TOO_MANY_USERS);
215 Compose auth methods for answer
217 std::string encpwd; // encrypted Password field for the user
218 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
221 client->chosen_mech = AUTH_MECHANISM_NONE;
224 std::vector<std::string> pwd_components = str_split(encpwd, '#');
225 if (pwd_components.size() == 4) {
226 if (pwd_components[1] == "1") { // 1 means srp
227 auth_mechs |= AUTH_MECHANISM_SRP;
228 client->enc_pwd = encpwd;
230 actionstream << "User " << playername << " tried to log in, "
231 "but password field was invalid (unknown mechcode)." <<
233 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
236 } else if (base64_is_valid(encpwd)) {
237 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
238 client->enc_pwd = encpwd;
240 actionstream << "User " << playername << " tried to log in, but "
241 "password field was invalid (invalid base64)." << std::endl;
242 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
246 std::string default_password = g_settings->get("default_password");
247 if (default_password.length() == 0) {
248 auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
250 // Take care of default passwords.
251 client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
252 auth_mechs |= AUTH_MECHANISM_SRP;
253 // Allocate player in db, but only on successful login.
254 client->create_player_on_auth_success = true;
259 Answer with a TOCLIENT_HELLO
262 verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
263 << auth_mechs << std::endl;
265 NetworkPacket resp_pkt(TOCLIENT_HELLO,
266 1 + 4 + legacyPlayerNameCasing.size(), peer_id);
268 u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
269 resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
270 << auth_mechs << legacyPlayerNameCasing;
274 client->allowed_auth_mechs = auth_mechs;
275 client->setDeployedCompressionMode(depl_compress_mode);
277 m_clients.event(peer_id, CSE_Hello);
280 void Server::handleCommand_Init2(NetworkPacket* pkt)
282 session_t peer_id = pkt->getPeerId();
283 verbosestream << "Server: Got TOSERVER_INIT2 from " << peer_id << std::endl;
285 m_clients.event(peer_id, CSE_GotInit2);
286 u16 protocol_version = m_clients.getProtocolVersion(peer_id);
289 if (pkt->getSize() > 0)
293 Send some initialization data
296 infostream << "Server: Sending content to " << getPlayerName(peer_id) <<
299 // Send item definitions
300 SendItemDef(peer_id, m_itemdef, protocol_version);
302 // Send node definitions
303 SendNodeDef(peer_id, m_nodedef, protocol_version);
305 m_clients.event(peer_id, CSE_SetDefinitionsSent);
307 // Send media announcement
308 sendMediaAnnouncement(peer_id, lang);
310 RemoteClient *client = getClient(peer_id, CS_InitDone);
312 // Keep client language for server translations
313 client->setLangCode(lang);
315 // Send active objects
317 PlayerSAO *sao = getPlayerSAO(peer_id);
319 SendActiveObjectRemoveAdd(client, sao);
322 // Send detached inventories
323 sendDetachedInventories(peer_id, false);
325 // Send player movement settings
326 SendMovement(peer_id);
329 u16 time = m_env->getTimeOfDay();
330 float time_speed = g_settings->getFloat("time_speed");
331 SendTimeOfDay(peer_id, time, time_speed);
333 SendCSMRestrictionFlags(peer_id);
335 // Warnings about protocol version can be issued here
336 if (client->net_proto_version < LATEST_PROTOCOL_VERSION) {
337 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
338 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
339 L"WITH THIS SERVER!"));
343 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
345 std::vector<std::string> tosend;
350 session_t peer_id = pkt->getPeerId();
351 infostream << "Sending " << numfiles << " files to " <<
352 getPlayerName(peer_id) << std::endl;
353 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
355 for (u16 i = 0; i < numfiles; i++) {
360 tosend.push_back(name);
361 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
362 << name << std::endl;
365 sendRequestedMedia(peer_id, tosend);
368 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
370 session_t peer_id = pkt->getPeerId();
372 PlayerSAO* playersao = StageTwoClientInit(peer_id);
374 if (playersao == NULL) {
375 errorstream << "TOSERVER_CLIENT_READY stage 2 client init failed "
376 "peer_id=" << peer_id << std::endl;
377 DisconnectPeer(peer_id);
382 if (pkt->getSize() < 8) {
383 errorstream << "TOSERVER_CLIENT_READY client sent inconsistent data, "
384 "disconnecting peer_id: " << peer_id << std::endl;
385 DisconnectPeer(peer_id);
389 u8 major_ver, minor_ver, patch_ver, reserved;
390 std::string full_ver;
391 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
393 m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver,
396 if (pkt->getRemainingBytes() >= 2)
397 *pkt >> playersao->getPlayer()->formspec_version;
399 const std::vector<std::string> &players = m_clients.getPlayerNames();
400 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
401 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
402 for (const std::string &player: players) {
405 m_clients.send(peer_id, 0, &list_pkt, true);
407 NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
408 // (u16) 1 + std::string represents a pseudo vector serialization representation
409 notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
410 m_clients.sendToAll(¬ice_pkt);
412 m_clients.event(peer_id, CSE_SetClientReady);
413 m_script->on_joinplayer(playersao);
414 // Send shutdown timer if shutdown has been scheduled
415 if (m_shutdown_state.isTimerRunning()) {
416 SendChatMessage(peer_id, m_shutdown_state.getShutdownTimerMessage());
420 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
422 if (pkt->getSize() < 1)
436 RemoteClient *client = getClient(pkt->getPeerId());
438 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
439 throw con::InvalidIncomingDataException
440 ("GOTBLOCKS length is too short");
443 for (u16 i = 0; i < count; i++) {
450 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
453 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
457 s32 f32pitch, f32yaw;
465 f32 pitch = (f32)f32pitch / 100.0f;
466 f32 yaw = (f32)f32yaw / 100.0f;
469 // default behavior (in case an old client doesn't send these)
475 fov = (f32)f32fov / 80.0f;
476 *pkt >> wanted_range;
478 v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
479 v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
481 pitch = modulo360f(pitch);
482 yaw = wrapDegrees_0_360(yaw);
484 playersao->setBasePosition(position);
485 player->setSpeed(speed);
486 playersao->setLookPitch(pitch);
487 playersao->setPlayerYaw(yaw);
488 playersao->setFov(fov);
489 playersao->setWantedRange(wanted_range);
490 player->keyPressed = keyPressed;
491 player->control.up = (keyPressed & 1);
492 player->control.down = (keyPressed & 2);
493 player->control.left = (keyPressed & 4);
494 player->control.right = (keyPressed & 8);
495 player->control.jump = (keyPressed & 16);
496 player->control.aux1 = (keyPressed & 32);
497 player->control.sneak = (keyPressed & 64);
498 player->control.LMB = (keyPressed & 128);
499 player->control.RMB = (keyPressed & 256);
501 if (playersao->checkMovementCheat()) {
503 m_script->on_cheat(playersao, "moved_too_fast");
504 SendMovePlayer(pkt->getPeerId());
508 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
510 session_t peer_id = pkt->getPeerId();
511 RemotePlayer *player = m_env->getPlayer(peer_id);
512 if (player == NULL) {
514 "Server::ProcessData(): Canceling: No player for peer_id=" <<
515 peer_id << " disconnecting peer!" << std::endl;
516 DisconnectPeer(peer_id);
520 PlayerSAO *playersao = player->getPlayerSAO();
521 if (playersao == NULL) {
523 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
524 peer_id << " disconnecting peer!" << std::endl;
525 DisconnectPeer(peer_id);
529 // If player is dead we don't care of this packet
530 if (playersao->isDead()) {
531 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
532 << " is dead. Ignoring packet";
536 process_PlayerPos(player, playersao, pkt);
539 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
541 if (pkt->getSize() < 1)
555 RemoteClient *client = getClient(pkt->getPeerId());
557 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
558 throw con::InvalidIncomingDataException
559 ("DELETEDBLOCKS length is too short");
562 for (u16 i = 0; i < count; i++) {
565 client->SetBlockNotSent(p);
569 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
571 session_t peer_id = pkt->getPeerId();
572 RemotePlayer *player = m_env->getPlayer(peer_id);
574 if (player == NULL) {
576 "Server::ProcessData(): Canceling: No player for peer_id=" <<
577 peer_id << " disconnecting peer!" << std::endl;
578 DisconnectPeer(peer_id);
582 PlayerSAO *playersao = player->getPlayerSAO();
583 if (playersao == NULL) {
585 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
586 peer_id << " disconnecting peer!" << std::endl;
587 DisconnectPeer(peer_id);
591 // Strip command and create a stream
592 std::string datastring(pkt->getString(0), pkt->getSize());
593 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
595 std::istringstream is(datastring, std::ios_base::binary);
597 InventoryAction *a = InventoryAction::deSerialize(is);
599 infostream << "TOSERVER_INVENTORY_ACTION: "
600 << "InventoryAction::deSerialize() returned NULL"
605 // If something goes wrong, this player is to blame
606 RollbackScopeActor rollback_scope(m_rollback,
607 std::string("player:")+player->getName());
610 Note: Always set inventory not sent, to repair cases
611 where the client made a bad prediction.
615 Handle restrictions and special cases of the move action
617 if (a->getType() == IAction::Move) {
618 IMoveAction *ma = (IMoveAction*)a;
620 ma->from_inv.applyCurrentPlayer(player->getName());
621 ma->to_inv.applyCurrentPlayer(player->getName());
623 setInventoryModified(ma->from_inv);
624 if (ma->from_inv != ma->to_inv)
625 setInventoryModified(ma->to_inv);
627 bool from_inv_is_current_player =
628 (ma->from_inv.type == InventoryLocation::PLAYER) &&
629 (ma->from_inv.name == player->getName());
631 bool to_inv_is_current_player =
632 (ma->to_inv.type == InventoryLocation::PLAYER) &&
633 (ma->to_inv.name == player->getName());
635 InventoryLocation *remote = from_inv_is_current_player ?
636 &ma->to_inv : &ma->from_inv;
638 // Check for out-of-range interaction
639 if (remote->type == InventoryLocation::NODEMETA) {
640 v3f node_pos = intToFloat(remote->p, BS);
641 v3f player_pos = player->getPlayerSAO()->getEyePosition();
642 f32 d = player_pos.getDistanceFrom(node_pos);
643 if (!checkInteractDistance(player, d, "inventory"))
648 Disable moving items out of craftpreview
650 if (ma->from_list == "craftpreview") {
651 infostream << "Ignoring IMoveAction from "
652 << (ma->from_inv.dump()) << ":" << ma->from_list
653 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
654 << " because src is " << ma->from_list << std::endl;
660 Disable moving items into craftresult and craftpreview
662 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
663 infostream << "Ignoring IMoveAction from "
664 << (ma->from_inv.dump()) << ":" << ma->from_list
665 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
666 << " because dst is " << ma->to_list << std::endl;
671 // Disallow moving items in elsewhere than player's inventory
672 // if not allowed to interact
673 if (!checkPriv(player->getName(), "interact") &&
674 (!from_inv_is_current_player ||
675 !to_inv_is_current_player)) {
676 infostream << "Cannot move outside of player's inventory: "
677 << "No interact privilege" << std::endl;
683 Handle restrictions and special cases of the drop action
685 else if (a->getType() == IAction::Drop) {
686 IDropAction *da = (IDropAction*)a;
688 da->from_inv.applyCurrentPlayer(player->getName());
690 setInventoryModified(da->from_inv);
693 Disable dropping items out of craftpreview
695 if (da->from_list == "craftpreview") {
696 infostream << "Ignoring IDropAction from "
697 << (da->from_inv.dump()) << ":" << da->from_list
698 << " because src is " << da->from_list << std::endl;
703 // Disallow dropping items if not allowed to interact
704 if (!checkPriv(player->getName(), "interact")) {
709 // Disallow dropping items if dead
710 if (playersao->isDead()) {
711 infostream << "Ignoring IDropAction from "
712 << (da->from_inv.dump()) << ":" << da->from_list
713 << " because player is dead." << std::endl;
719 Handle restrictions and special cases of the craft action
721 else if (a->getType() == IAction::Craft) {
722 ICraftAction *ca = (ICraftAction*)a;
724 ca->craft_inv.applyCurrentPlayer(player->getName());
726 setInventoryModified(ca->craft_inv);
728 //bool craft_inv_is_current_player =
729 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
730 // (ca->craft_inv.name == player->getName());
732 // Disallow crafting if not allowed to interact
733 if (!checkPriv(player->getName(), "interact")) {
734 infostream << "Cannot craft: "
735 << "No interact privilege" << std::endl;
742 a->apply(this, playersao, this);
747 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
757 std::wstring message;
758 for (u16 i = 0; i < len; i++) {
762 message += (wchar_t)tmp_wchar;
765 session_t peer_id = pkt->getPeerId();
766 RemotePlayer *player = m_env->getPlayer(peer_id);
767 if (player == NULL) {
769 "Server::ProcessData(): Canceling: No player for peer_id=" <<
770 peer_id << " disconnecting peer!" << std::endl;
771 DisconnectPeer(peer_id);
775 // Get player name of this client
776 std::string name = player->getName();
777 std::wstring wname = narrow_to_wide(name);
779 std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
780 if (!answer_to_sender.empty()) {
781 // Send the answer to sender
782 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_NORMAL,
783 answer_to_sender, wname));
787 void Server::handleCommand_Damage(NetworkPacket* pkt)
793 session_t peer_id = pkt->getPeerId();
794 RemotePlayer *player = m_env->getPlayer(peer_id);
796 if (player == NULL) {
798 "Server::ProcessData(): Canceling: No player for peer_id=" <<
799 peer_id << " disconnecting peer!" << std::endl;
800 DisconnectPeer(peer_id);
804 PlayerSAO *playersao = player->getPlayerSAO();
805 if (playersao == NULL) {
807 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
808 peer_id << " disconnecting peer!" << std::endl;
809 DisconnectPeer(peer_id);
813 if (!playersao->isImmortal()) {
814 if (playersao->isDead()) {
815 verbosestream << "Server::ProcessData(): Info: "
816 "Ignoring damage as player " << player->getName()
817 << " is already dead." << std::endl;
821 actionstream << player->getName() << " damaged by "
822 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
825 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
826 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
827 SendPlayerHPOrDie(playersao, reason);
831 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
833 if (pkt->getSize() < 2)
836 session_t peer_id = pkt->getPeerId();
837 RemotePlayer *player = m_env->getPlayer(peer_id);
839 if (player == NULL) {
841 "Server::ProcessData(): Canceling: No player for peer_id=" <<
842 peer_id << " disconnecting peer!" << std::endl;
843 DisconnectPeer(peer_id);
847 PlayerSAO *playersao = player->getPlayerSAO();
848 if (playersao == NULL) {
850 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
851 peer_id << " disconnecting peer!" << std::endl;
852 DisconnectPeer(peer_id);
860 playersao->getPlayer()->setWieldIndex(item);
863 void Server::handleCommand_Respawn(NetworkPacket* pkt)
865 session_t peer_id = pkt->getPeerId();
866 RemotePlayer *player = m_env->getPlayer(peer_id);
867 if (player == NULL) {
869 "Server::ProcessData(): Canceling: No player for peer_id=" <<
870 peer_id << " disconnecting peer!" << std::endl;
871 DisconnectPeer(peer_id);
875 PlayerSAO *playersao = player->getPlayerSAO();
878 if (!playersao->isDead())
881 RespawnPlayer(peer_id);
883 actionstream << player->getName() << " respawns at "
884 << PP(playersao->getBasePosition() / BS) << std::endl;
886 // ActiveObject is added to environment in AsyncRunStep after
887 // the previous addition has been successfully removed
890 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
892 ItemStack selected_item, hand_item;
893 player->getWieldedItem(&selected_item, &hand_item);
894 f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
895 hand_item.getDefinition(m_itemdef));
897 // Cube diagonal * 1.5 for maximal supported node extents:
898 // sqrt(3) * 1.5 ≅ 2.6
899 if (d > max_d + 2.6f * BS) {
900 actionstream << "Player " << player->getName()
901 << " tried to access " << what
903 << "d=" << d << ", max_d=" << max_d
904 << "; ignoring." << std::endl;
906 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
912 void Server::handleCommand_Interact(NetworkPacket *pkt)
918 [5] u32 length of the next item (plen)
919 [9] serialized PointedThing
920 [9 + plen] player position information
923 InteractAction action;
926 *pkt >> (u8 &)action;
929 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
930 PointedThing pointed;
931 pointed.deSerialize(tmp_is);
933 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
934 << item_i << ", pointed=" << pointed.dump() << std::endl;
936 session_t peer_id = pkt->getPeerId();
937 RemotePlayer *player = m_env->getPlayer(peer_id);
939 if (player == NULL) {
941 "Server::ProcessData(): Canceling: No player for peer_id=" <<
942 peer_id << " disconnecting peer!" << std::endl;
943 DisconnectPeer(peer_id);
947 PlayerSAO *playersao = player->getPlayerSAO();
948 if (playersao == NULL) {
950 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
951 peer_id << " disconnecting peer!" << std::endl;
952 DisconnectPeer(peer_id);
956 if (playersao->isDead()) {
957 actionstream << "Server: " << player->getName()
958 << " tried to interact while dead; ignoring." << std::endl;
959 if (pointed.type == POINTEDTHING_NODE) {
960 // Re-send block to revert change on client-side
961 RemoteClient *client = getClient(peer_id);
962 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
963 client->SetBlockNotSent(blockpos);
966 m_script->on_cheat(playersao, "interacted_while_dead");
970 process_PlayerPos(player, playersao, pkt);
972 v3f player_pos = playersao->getLastGoodPosition();
974 // Update wielded item
975 playersao->getPlayer()->setWieldIndex(item_i);
977 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
978 v3s16 p_under = pointed.node_undersurface;
979 v3s16 p_above = pointed.node_abovesurface;
981 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
982 ServerActiveObject *pointed_object = NULL;
983 if (pointed.type == POINTEDTHING_OBJECT) {
984 pointed_object = m_env->getActiveObject(pointed.object_id);
985 if (pointed_object == NULL) {
986 verbosestream << "TOSERVER_INTERACT: "
987 "pointed object is NULL" << std::endl;
993 v3f pointed_pos_under = player_pos;
994 v3f pointed_pos_above = player_pos;
995 if (pointed.type == POINTEDTHING_NODE) {
996 pointed_pos_under = intToFloat(p_under, BS);
997 pointed_pos_above = intToFloat(p_above, BS);
999 else if (pointed.type == POINTEDTHING_OBJECT) {
1000 pointed_pos_under = pointed_object->getBasePosition();
1001 pointed_pos_above = pointed_pos_under;
1005 Make sure the player is allowed to do it
1007 if (!checkPriv(player->getName(), "interact")) {
1008 actionstream << player->getName() << " attempted to interact with " <<
1009 pointed.dump() << " without 'interact' privilege" << std::endl;
1011 // Re-send block to revert change on client-side
1012 RemoteClient *client = getClient(peer_id);
1013 // Digging completed -> under
1014 if (action == INTERACT_DIGGING_COMPLETED) {
1015 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1016 client->SetBlockNotSent(blockpos);
1018 // Placement -> above
1019 else if (action == INTERACT_PLACE) {
1020 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1021 client->SetBlockNotSent(blockpos);
1027 Check that target is reasonably close
1028 (only when digging or placing things)
1030 static thread_local const bool enable_anticheat =
1031 !g_settings->getBool("disable_anticheat");
1033 if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1034 action == INTERACT_PLACE || action == INTERACT_USE) &&
1035 enable_anticheat && !isSingleplayer()) {
1036 float d = playersao->getEyePosition().getDistanceFrom(pointed_pos_under);
1038 if (!checkInteractDistance(player, d, pointed.dump())) {
1039 // Re-send block to revert change on client-side
1040 RemoteClient *client = getClient(peer_id);
1041 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1042 client->SetBlockNotSent(blockpos);
1048 If something goes wrong, this player is to blame
1050 RollbackScopeActor rollback_scope(m_rollback,
1051 std::string("player:")+player->getName());
1054 0: start digging or punch object
1056 if (action == INTERACT_START_DIGGING) {
1057 if (pointed.type == POINTEDTHING_NODE) {
1058 MapNode n(CONTENT_IGNORE);
1061 n = m_env->getMap().getNode(p_under, &pos_ok);
1063 infostream << "Server: Not punching: Node not found. "
1064 "Adding block to emerge queue." << std::endl;
1065 m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above),
1069 if (n.getContent() != CONTENT_IGNORE)
1070 m_script->node_on_punch(p_under, n, playersao, pointed);
1073 playersao->noCheatDigStart(p_under);
1075 else if (pointed.type == POINTEDTHING_OBJECT) {
1076 // Skip if object can't be interacted with anymore
1077 if (pointed_object->isGone())
1080 ItemStack selected_item, hand_item;
1081 ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
1082 ToolCapabilities toolcap =
1083 tool_item.getToolCapabilities(m_itemdef);
1084 v3f dir = (pointed_object->getBasePosition() -
1085 (playersao->getBasePosition() + playersao->getEyeOffset())
1087 float time_from_last_punch =
1088 playersao->resetTimeFromLastPunch();
1090 u16 src_original_hp = pointed_object->getHP();
1091 u16 dst_origin_hp = playersao->getHP();
1093 u16 wear = pointed_object->punch(dir, &toolcap, playersao,
1094 time_from_last_punch);
1096 // Callback may have changed item, so get it again
1097 playersao->getWieldedItem(&selected_item);
1098 bool changed = selected_item.addWear(wear, m_itemdef);
1100 playersao->setWieldedItem(selected_item);
1102 // If the object is a player and its HP changed
1103 if (src_original_hp != pointed_object->getHP() &&
1104 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1105 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1106 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1109 // If the puncher is a player and its HP changed
1110 if (dst_origin_hp != playersao->getHP())
1111 SendPlayerHPOrDie(playersao,
1112 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1115 } // action == INTERACT_START_DIGGING
1120 else if (action == INTERACT_STOP_DIGGING) {
1121 } // action == INTERACT_STOP_DIGGING
1124 2: Digging completed
1126 else if (action == INTERACT_DIGGING_COMPLETED) {
1127 // Only digging of nodes
1128 if (pointed.type == POINTEDTHING_NODE) {
1130 MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1132 infostream << "Server: Not finishing digging: Node not found. "
1133 "Adding block to emerge queue." << std::endl;
1134 m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above),
1138 /* Cheat prevention */
1139 bool is_valid_dig = true;
1140 if (enable_anticheat && !isSingleplayer()) {
1141 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1142 float nocheat_t = playersao->getNoCheatDigTime();
1143 playersao->noCheatDigEnd();
1144 // If player didn't start digging this, ignore dig
1145 if (nocheat_p != p_under) {
1146 infostream << "Server: " << player->getName()
1147 << " started digging "
1148 << PP(nocheat_p) << " and completed digging "
1149 << PP(p_under) << "; not digging." << std::endl;
1150 is_valid_dig = false;
1152 m_script->on_cheat(playersao, "finished_unknown_dig");
1155 // Get player's wielded item
1156 // See also: Game::handleDigging
1157 ItemStack selected_item, hand_item;
1158 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1160 // Get diggability and expected digging time
1161 DigParams params = getDigParams(m_nodedef->get(n).groups,
1162 &selected_item.getToolCapabilities(m_itemdef));
1163 // If can't dig, try hand
1164 if (!params.diggable) {
1165 params = getDigParams(m_nodedef->get(n).groups,
1166 &hand_item.getToolCapabilities(m_itemdef));
1168 // If can't dig, ignore dig
1169 if (!params.diggable) {
1170 infostream << "Server: " << player->getName()
1171 << " completed digging " << PP(p_under)
1172 << ", which is not diggable with tool; not digging."
1174 is_valid_dig = false;
1176 m_script->on_cheat(playersao, "dug_unbreakable");
1178 // Check digging time
1179 // If already invalidated, we don't have to
1180 if (!is_valid_dig) {
1181 // Well not our problem then
1183 // Clean and long dig
1184 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1185 // All is good, but grab time from pool; don't care if
1186 // it's actually available
1187 playersao->getDigPool().grab(params.time);
1189 // Short or laggy dig
1190 // Try getting the time from pool
1191 else if (playersao->getDigPool().grab(params.time)) {
1196 infostream << "Server: " << player->getName()
1197 << " completed digging " << PP(p_under)
1198 << "too fast; not digging." << std::endl;
1199 is_valid_dig = false;
1201 m_script->on_cheat(playersao, "dug_too_fast");
1205 /* Actually dig node */
1207 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1208 m_script->node_on_dig(p_under, n, playersao);
1210 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1211 RemoteClient *client = getClient(peer_id);
1212 // Send unusual result (that is, node not being removed)
1213 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR) {
1214 // Re-send block to revert change on client-side
1215 client->SetBlockNotSent(blockpos);
1218 client->ResendBlockIfOnWire(blockpos);
1221 } // action == INTERACT_DIGGING_COMPLETED
1224 3: place block or right-click object
1226 else if (action == INTERACT_PLACE) {
1227 ItemStack selected_item;
1228 playersao->getWieldedItem(&selected_item, nullptr);
1230 // Reset build time counter
1231 if (pointed.type == POINTEDTHING_NODE &&
1232 selected_item.getDefinition(m_itemdef).type == ITEM_NODE)
1233 getClient(peer_id)->m_time_from_building = 0.0;
1235 if (pointed.type == POINTEDTHING_OBJECT) {
1236 // Right click object
1238 // Skip if object can't be interacted with anymore
1239 if (pointed_object->isGone())
1242 actionstream << player->getName() << " right-clicks object "
1243 << pointed.object_id << ": "
1244 << pointed_object->getDescription() << std::endl;
1247 if (m_script->item_OnSecondaryUse(
1248 selected_item, playersao, pointed)) {
1249 if (playersao->setWieldedItem(selected_item)) {
1250 SendInventory(playersao, true);
1254 pointed_object->rightClick(playersao);
1255 } else if (m_script->item_OnPlace(
1256 selected_item, playersao, pointed)) {
1257 // Placement was handled in lua
1259 // Apply returned ItemStack
1260 if (playersao->setWieldedItem(selected_item)) {
1261 SendInventory(playersao, true);
1265 // If item has node placement prediction, always send the
1266 // blocks to make sure the client knows what exactly happened
1267 RemoteClient *client = getClient(peer_id);
1268 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1269 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1270 if (!selected_item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
1271 client->SetBlockNotSent(blockpos);
1272 if (blockpos2 != blockpos) {
1273 client->SetBlockNotSent(blockpos2);
1277 client->ResendBlockIfOnWire(blockpos);
1278 if (blockpos2 != blockpos) {
1279 client->ResendBlockIfOnWire(blockpos2);
1282 } // action == INTERACT_PLACE
1287 else if (action == INTERACT_USE) {
1288 ItemStack selected_item;
1289 playersao->getWieldedItem(&selected_item, nullptr);
1291 actionstream << player->getName() << " uses " << selected_item.name
1292 << ", pointing at " << pointed.dump() << std::endl;
1294 if (m_script->item_OnUse(
1295 selected_item, playersao, pointed)) {
1296 // Apply returned ItemStack
1297 if (playersao->setWieldedItem(selected_item)) {
1298 SendInventory(playersao, true);
1302 } // action == INTERACT_USE
1307 else if (action == INTERACT_ACTIVATE) {
1308 ItemStack selected_item;
1309 playersao->getWieldedItem(&selected_item, nullptr);
1311 actionstream << player->getName() << " activates "
1312 << selected_item.name << std::endl;
1314 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1316 if (m_script->item_OnSecondaryUse(
1317 selected_item, playersao, pointed)) {
1318 if (playersao->setWieldedItem(selected_item)) {
1319 SendInventory(playersao, true);
1322 } // action == INTERACT_ACTIVATE
1326 Catch invalid actions
1329 warningstream << "Server: Invalid action "
1330 << action << std::endl;
1334 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1338 for (u16 k = 0; k < num; k++) {
1343 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1344 m_playing_sounds.find(id);
1345 if (i == m_playing_sounds.end())
1348 ServerPlayingSound &psound = i->second;
1349 psound.clients.erase(pkt->getPeerId());
1350 if (psound.clients.empty())
1351 m_playing_sounds.erase(i++);
1355 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1358 std::string formname;
1361 *pkt >> p >> formname >> num;
1364 for (u16 k = 0; k < num; k++) {
1365 std::string fieldname;
1367 fields[fieldname] = pkt->readLongString();
1370 session_t peer_id = pkt->getPeerId();
1371 RemotePlayer *player = m_env->getPlayer(peer_id);
1373 if (player == NULL) {
1375 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1376 peer_id << " disconnecting peer!" << std::endl;
1377 DisconnectPeer(peer_id);
1381 PlayerSAO *playersao = player->getPlayerSAO();
1382 if (playersao == NULL) {
1384 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1385 peer_id << " disconnecting peer!" << std::endl;
1386 DisconnectPeer(peer_id);
1390 // If something goes wrong, this player is to blame
1391 RollbackScopeActor rollback_scope(m_rollback,
1392 std::string("player:")+player->getName());
1394 // Check the target node for rollback data; leave others unnoticed
1395 RollbackNode rn_old(&m_env->getMap(), p, this);
1397 m_script->node_on_receive_fields(p, formname, fields, playersao);
1399 // Report rollback data
1400 RollbackNode rn_new(&m_env->getMap(), p, this);
1401 if (rollback() && rn_new != rn_old) {
1402 RollbackAction action;
1403 action.setSetNode(p, rn_old, rn_new);
1404 rollback()->reportAction(action);
1408 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1410 std::string client_formspec_name;
1413 *pkt >> client_formspec_name >> num;
1416 for (u16 k = 0; k < num; k++) {
1417 std::string fieldname;
1419 fields[fieldname] = pkt->readLongString();
1422 session_t peer_id = pkt->getPeerId();
1423 RemotePlayer *player = m_env->getPlayer(peer_id);
1425 if (player == NULL) {
1427 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1428 peer_id << " disconnecting peer!" << std::endl;
1429 DisconnectPeer(peer_id);
1433 PlayerSAO *playersao = player->getPlayerSAO();
1434 if (playersao == NULL) {
1436 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1437 peer_id << " disconnecting peer!" << std::endl;
1438 DisconnectPeer(peer_id);
1442 if (client_formspec_name.empty()) { // pass through inventory submits
1443 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1447 // verify that we displayed the formspec to the user
1448 const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1449 if (peer_state_iterator != m_formspec_state_data.end()) {
1450 const std::string &server_formspec_name = peer_state_iterator->second;
1451 if (client_formspec_name == server_formspec_name) {
1452 auto it = fields.find("quit");
1453 if (it != fields.end() && it->second == "true")
1454 m_formspec_state_data.erase(peer_state_iterator);
1456 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1459 actionstream << "'" << player->getName()
1460 << "' submitted formspec ('" << client_formspec_name
1461 << "') but the name of the formspec doesn't match the"
1462 " expected name ('" << server_formspec_name << "')";
1465 actionstream << "'" << player->getName()
1466 << "' submitted formspec ('" << client_formspec_name
1467 << "') but server hasn't sent formspec to client";
1469 actionstream << ", possible exploitation attempt" << std::endl;
1472 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1474 session_t peer_id = pkt->getPeerId();
1475 RemoteClient *client = getClient(peer_id, CS_Invalid);
1476 ClientState cstate = client->getState();
1478 std::string playername = client->getName();
1481 std::string verification_key;
1483 std::string addr_s = getPeerAddress(peer_id).serializeString();
1486 *pkt >> salt >> verification_key >> is_empty;
1488 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1489 << ", with is_empty=" << (is_empty == 1) << std::endl;
1491 // Either this packet is sent because the user is new or to change the password
1492 if (cstate == CS_HelloSent) {
1493 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1494 actionstream << "Server: Client from " << addr_s
1495 << " tried to set password without being "
1496 << "authenticated, or the username being new." << std::endl;
1497 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1501 if (!isSingleplayer() &&
1502 g_settings->getBool("disallow_empty_password") &&
1504 actionstream << "Server: " << playername
1505 << " supplied empty password from " << addr_s << std::endl;
1506 DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1510 std::string initial_ver_key;
1512 initial_ver_key = encode_srp_verifier(verification_key, salt);
1513 m_script->createAuth(playername, initial_ver_key);
1515 acceptAuth(peer_id, false);
1517 if (cstate < CS_SudoMode) {
1518 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1519 << addr_s << ": " << "Client has wrong state " << cstate << "."
1523 m_clients.event(peer_id, CSE_SudoLeave);
1524 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1525 bool success = m_script->setPassword(playername, pw_db_field);
1527 actionstream << playername << " changes password" << std::endl;
1528 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1529 L"Password change successful."));
1531 actionstream << playername <<
1532 " tries to change password but it fails" << std::endl;
1533 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1534 L"Password change failed or unavailable."));
1539 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1541 session_t peer_id = pkt->getPeerId();
1542 RemoteClient *client = getClient(peer_id, CS_Invalid);
1543 ClientState cstate = client->getState();
1545 bool wantSudo = (cstate == CS_Active);
1547 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1548 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1549 " from " << getPeerAddress(peer_id).serializeString() <<
1550 ". Ignoring." << std::endl;
1554 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1555 actionstream << "Server: got SRP _A packet, while auth is already "
1556 "going on with mech " << client->chosen_mech << " from " <<
1557 getPeerAddress(peer_id).serializeString() <<
1558 " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1560 DenySudoAccess(peer_id);
1564 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1568 std::string bytes_A;
1570 *pkt >> bytes_A >> based_on;
1572 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1573 << "based_on=" << int(based_on) << " and len_A="
1574 << bytes_A.length() << "." << std::endl;
1576 AuthMechanism chosen = (based_on == 0) ?
1577 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1580 if (!client->isSudoMechAllowed(chosen)) {
1581 actionstream << "Server: Player \"" << client->getName() <<
1582 "\" at " << getPeerAddress(peer_id).serializeString() <<
1583 " tried to change password using unallowed mech " << chosen <<
1585 DenySudoAccess(peer_id);
1589 if (!client->isMechAllowed(chosen)) {
1590 actionstream << "Server: Client tried to authenticate from " <<
1591 getPeerAddress(peer_id).serializeString() <<
1592 " using unallowed mech " << chosen << "." << std::endl;
1593 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1598 client->chosen_mech = chosen;
1601 std::string verifier;
1603 if (based_on == 0) {
1605 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1607 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1608 // Non-base64 errors should have been catched in the init handler
1609 actionstream << "Server: User " << client->getName() <<
1610 " tried to log in, but srp verifier field was invalid (most likely "
1611 "invalid base64)." << std::endl;
1612 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1619 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1620 client->getName().c_str(),
1621 (const unsigned char *) salt.c_str(), salt.size(),
1622 (const unsigned char *) verifier.c_str(), verifier.size(),
1623 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1625 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1628 actionstream << "Server: User " << client->getName()
1629 << " tried to log in, SRP-6a safety check violated in _A handler."
1632 DenySudoAccess(peer_id);
1636 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1640 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1641 resp_pkt << salt << std::string(bytes_B, len_B);
1645 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1647 session_t peer_id = pkt->getPeerId();
1648 RemoteClient *client = getClient(peer_id, CS_Invalid);
1649 ClientState cstate = client->getState();
1651 bool wantSudo = (cstate == CS_Active);
1653 verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
1655 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1656 actionstream << "Server: got SRP _M packet in wrong state " << cstate <<
1657 " from " << getPeerAddress(peer_id).serializeString() <<
1658 ". Ignoring." << std::endl;
1662 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1663 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1664 actionstream << "Server: got SRP _M packet, while auth is going on "
1665 "with mech " << client->chosen_mech << " from " <<
1666 getPeerAddress(peer_id).serializeString() <<
1667 " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1669 DenySudoAccess(peer_id);
1673 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1677 std::string bytes_M;
1680 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1681 != bytes_M.size()) {
1682 actionstream << "Server: User " << client->getName() << " at " <<
1683 getPeerAddress(peer_id).serializeString() <<
1684 " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1685 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1689 unsigned char *bytes_HAMK = 0;
1691 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1692 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1696 actionstream << "Server: User " << client->getName() << " at " <<
1697 getPeerAddress(peer_id).serializeString() <<
1698 " tried to change their password, but supplied wrong (SRP) "
1699 "password for authentication." << std::endl;
1700 DenySudoAccess(peer_id);
1704 std::string ip = getPeerAddress(peer_id).serializeString();
1705 actionstream << "Server: User " << client->getName() << " at " << ip <<
1706 " supplied wrong password (auth mechanism: SRP)." << std::endl;
1707 m_script->on_auth_failure(client->getName(), ip);
1708 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1712 if (client->create_player_on_auth_success) {
1713 std::string playername = client->getName();
1714 m_script->createAuth(playername, client->enc_pwd);
1716 std::string checkpwd; // not used, but needed for passing something
1717 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1718 actionstream << "Server: " << playername <<
1719 " cannot be authenticated (auth handler does not work?)" <<
1721 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1724 client->create_player_on_auth_success = false;
1727 acceptAuth(peer_id, wantSudo);
1734 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1736 std::string channel_name;
1737 *pkt >> channel_name;
1739 session_t peer_id = pkt->getPeerId();
1740 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1741 1 + 2 + channel_name.size(), peer_id);
1743 // Send signal to client to notify join succeed or not
1744 if (g_settings->getBool("enable_mod_channels") &&
1745 m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1746 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1747 infostream << "Peer " << peer_id << " joined channel " <<
1748 channel_name << std::endl;
1751 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1752 infostream << "Peer " << peer_id << " tried to join channel " <<
1753 channel_name << ", but was already registered." << std::endl;
1755 resp_pkt << channel_name;
1759 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1761 std::string channel_name;
1762 *pkt >> channel_name;
1764 session_t peer_id = pkt->getPeerId();
1765 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1766 1 + 2 + channel_name.size(), peer_id);
1768 // Send signal to client to notify join succeed or not
1769 if (g_settings->getBool("enable_mod_channels") &&
1770 m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1771 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1772 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1775 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1776 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1777 ", but was not registered." << std::endl;
1779 resp_pkt << channel_name;
1783 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1785 std::string channel_name, channel_msg;
1786 *pkt >> channel_name >> channel_msg;
1788 session_t peer_id = pkt->getPeerId();
1789 verbosestream << "Mod channel message received from peer " << peer_id <<
1790 " on channel " << channel_name << " message: " << channel_msg <<
1793 // If mod channels are not enabled, discard message
1794 if (!g_settings->getBool("enable_mod_channels")) {
1798 // If channel not registered, signal it and ignore message
1799 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1800 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1801 1 + 2 + channel_name.size(), peer_id);
1802 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1807 // @TODO: filter, rate limit
1809 broadcastModChannelMessage(channel_name, channel_msg, peer_id);