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"
23 #include "content_sao.h"
26 #include "modchannels.h"
28 #include "remoteplayer.h"
29 #include "rollback_interface.h"
30 #include "scripting_server.h"
34 #include "network/connection.h"
35 #include "network/networkprotocol.h"
36 #include "network/serveropcodes.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 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
59 Address address = getPeerAddress(pkt->getPeerId());
60 addr_s = address.serializeString();
62 catch (con::PeerNotFoundException &e) {
64 * no peer for this packet found
65 * most common reason is peer timeout, e.g. peer didn't
66 * respond for some time, your server was overloaded or
69 infostream << "Server::ProcessData(): Canceling: peer "
70 << pkt->getPeerId() << " not found" << std::endl;
74 // If net_proto_version is set, this client has already been handled
75 if (client->getState() > CS_Created) {
76 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
77 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
81 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
82 << pkt->getPeerId() << ")" << std::endl;
84 // Do not allow multiple players in simple singleplayer mode.
85 // This isn't a perfect way to do it, but will suffice for now
86 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
87 infostream << "Server: Not allowing another client (" << addr_s
88 << ") to connect in simple singleplayer mode" << std::endl;
89 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SINGLEPLAYER);
93 // First byte after command is maximum supported
94 // serialization version
97 u16 min_net_proto_version = 0;
98 u16 max_net_proto_version;
99 std::string playerName;
101 *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
102 >> max_net_proto_version >> playerName;
104 u8 our_max = SER_FMT_VER_HIGHEST_READ;
105 // Use the highest version supported by both
106 u8 depl_serial_v = std::min(client_max, our_max);
107 // If it's lower than the lowest supported, give up.
108 if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
109 depl_serial_v = SER_FMT_VER_INVALID;
111 if (depl_serial_v == SER_FMT_VER_INVALID) {
112 actionstream << "Server: A mismatched client tried to connect from "
113 << addr_s << std::endl;
114 infostream<<"Server: Cannot negotiate serialization version with "
115 << addr_s << std::endl;
116 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
120 client->setPendingSerializationVersion(depl_serial_v);
123 Read and check network protocol version
126 u16 net_proto_version = 0;
128 // Figure out a working version if it is possible at all
129 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
130 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
131 // If maximum is larger than our maximum, go with our maximum
132 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
133 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
134 // Else go with client's maximum
136 net_proto_version = max_net_proto_version;
139 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
140 << min_net_proto_version << ", max: " << max_net_proto_version
141 << ", chosen: " << net_proto_version << std::endl;
143 client->net_proto_version = net_proto_version;
145 if ((g_settings->getBool("strict_protocol_version_checking") &&
146 net_proto_version != LATEST_PROTOCOL_VERSION) ||
147 net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
148 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
149 actionstream << "Server: A mismatched client tried to connect from "
150 << addr_s << std::endl;
151 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
158 const char* playername = playerName.c_str();
160 size_t pns = playerName.size();
161 if (pns == 0 || pns > PLAYERNAME_SIZE) {
162 actionstream << "Server: Player with "
163 << ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty")
164 << " name tried to connect from " << addr_s << std::endl;
165 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
169 if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
170 actionstream << "Server: Player with an invalid name "
171 << "tried to connect from " << addr_s << std::endl;
172 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
176 m_clients.setPlayerName(pkt->getPeerId(), playername);
177 //TODO (later) case insensitivity
179 std::string legacyPlayerNameCasing = playerName;
181 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
182 actionstream << "Server: Player with the name \"singleplayer\" "
183 << "tried to connect from " << addr_s << std::endl;
184 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
190 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
191 actionstream << "Server: Player with the name \"" << playerName << "\" "
192 << "tried to connect from " << addr_s << " "
193 << "but it was disallowed for the following reason: "
194 << reason << std::endl;
195 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
200 infostream << "Server: New connection: \"" << playerName << "\" from "
201 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
203 // Enforce user limit.
204 // Don't enforce for users that have some admin right or mod permits it.
205 if (m_clients.isUserLimitReached() &&
206 playername != g_settings->get("name") &&
207 !m_script->can_bypass_userlimit(playername, addr_s)) {
208 actionstream << "Server: " << playername << " tried to join from "
209 << addr_s << ", but there" << " are already max_users="
210 << g_settings->getU16("max_users") << " players." << std::endl;
211 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_TOO_MANY_USERS);
216 Compose auth methods for answer
218 std::string encpwd; // encrypted Password field for the user
219 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
222 client->chosen_mech = AUTH_MECHANISM_NONE;
225 std::vector<std::string> pwd_components = str_split(encpwd, '#');
226 if (pwd_components.size() == 4) {
227 if (pwd_components[1] == "1") { // 1 means srp
228 auth_mechs |= AUTH_MECHANISM_SRP;
229 client->enc_pwd = encpwd;
231 actionstream << "User " << playername
232 << " tried to log in, but password field"
233 << " was invalid (unknown mechcode)." << std::endl;
234 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
237 } else if (base64_is_valid(encpwd)) {
238 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
239 client->enc_pwd = encpwd;
241 actionstream << "User " << playername
242 << " tried to log in, but password field"
243 << " was invalid (invalid base64)." << std::endl;
244 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
248 std::string default_password = g_settings->get("default_password");
249 if (default_password.length() == 0) {
250 auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
252 // Take care of default passwords.
253 client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
254 auth_mechs |= AUTH_MECHANISM_SRP;
255 // Allocate player in db, but only on successful login.
256 client->create_player_on_auth_success = true;
261 Answer with a TOCLIENT_HELLO
264 verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
265 << auth_mechs << std::endl;
267 NetworkPacket resp_pkt(TOCLIENT_HELLO, 1 + 4
268 + legacyPlayerNameCasing.size(), pkt->getPeerId());
270 u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
271 resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
272 << auth_mechs << legacyPlayerNameCasing;
276 client->allowed_auth_mechs = auth_mechs;
277 client->setDeployedCompressionMode(depl_compress_mode);
279 m_clients.event(pkt->getPeerId(), CSE_Hello);
282 void Server::handleCommand_Init2(NetworkPacket* pkt)
284 verbosestream << "Server: Got TOSERVER_INIT2 from "
285 << pkt->getPeerId() << std::endl;
287 m_clients.event(pkt->getPeerId(), CSE_GotInit2);
288 u16 protocol_version = m_clients.getProtocolVersion(pkt->getPeerId());
291 if (pkt->getSize() > 0)
295 Send some initialization data
298 infostream << "Server: Sending content to "
299 << getPlayerName(pkt->getPeerId()) << std::endl;
301 // Send player movement settings
302 SendMovement(pkt->getPeerId());
304 // Send item definitions
305 SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
307 // Send node definitions
308 SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
310 m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
312 // Send media announcement
313 sendMediaAnnouncement(pkt->getPeerId(), lang);
315 // Send detached inventories
316 sendDetachedInventories(pkt->getPeerId());
319 u16 time = m_env->getTimeOfDay();
320 float time_speed = g_settings->getFloat("time_speed");
321 SendTimeOfDay(pkt->getPeerId(), time, time_speed);
323 SendCSMRestrictionFlags(pkt->getPeerId());
325 // Warnings about protocol version can be issued here
326 if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
327 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
328 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
329 L"WITH THIS SERVER!"));
334 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
336 std::vector<std::string> tosend;
341 infostream << "Sending " << numfiles << " files to "
342 << getPlayerName(pkt->getPeerId()) << std::endl;
343 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
345 for (u16 i = 0; i < numfiles; i++) {
350 tosend.push_back(name);
351 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
352 << name << std::endl;
355 sendRequestedMedia(pkt->getPeerId(), tosend);
358 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
360 session_t peer_id = pkt->getPeerId();
362 PlayerSAO* playersao = StageTwoClientInit(peer_id);
364 if (playersao == NULL) {
366 << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
367 << peer_id << std::endl;
368 DisconnectPeer(peer_id);
373 if (pkt->getSize() < 8) {
375 << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
376 << peer_id << std::endl;
377 DisconnectPeer(peer_id);
381 u8 major_ver, minor_ver, patch_ver, reserved;
382 std::string full_ver;
383 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
385 m_clients.setClientVersion(
386 peer_id, major_ver, minor_ver, patch_ver,
389 const std::vector<std::string> &players = m_clients.getPlayerNames();
390 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
391 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
392 for (const std::string &player: players) {
395 m_clients.send(peer_id, 0, &list_pkt, true);
397 NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
398 // (u16) 1 + std::string represents a pseudo vector serialization representation
399 notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
400 m_clients.sendToAll(¬ice_pkt);
402 m_clients.event(peer_id, CSE_SetClientReady);
403 m_script->on_joinplayer(playersao);
404 // Send shutdown timer if shutdown has been scheduled
405 if (m_shutdown_state.isTimerRunning()) {
406 SendChatMessage(pkt->getPeerId(), m_shutdown_state.getShutdownTimerMessage());
410 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
412 if (pkt->getSize() < 1)
426 RemoteClient *client = getClient(pkt->getPeerId());
428 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
429 throw con::InvalidIncomingDataException
430 ("GOTBLOCKS length is too short");
433 for (u16 i = 0; i < count; i++) {
440 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
443 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
447 s32 f32pitch, f32yaw;
455 f32 pitch = (f32)f32pitch / 100.0f;
456 f32 yaw = (f32)f32yaw / 100.0f;
459 // default behavior (in case an old client doesn't send these)
465 fov = (f32)f32fov / 80.0f;
466 *pkt >> wanted_range;
468 v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
469 v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
471 pitch = modulo360f(pitch);
472 yaw = wrapDegrees_0_360(yaw);
474 playersao->setBasePosition(position);
475 player->setSpeed(speed);
476 playersao->setPitch(pitch);
477 playersao->setYaw(yaw);
478 playersao->setFov(fov);
479 playersao->setWantedRange(wanted_range);
480 player->keyPressed = keyPressed;
481 player->control.up = (keyPressed & 1);
482 player->control.down = (keyPressed & 2);
483 player->control.left = (keyPressed & 4);
484 player->control.right = (keyPressed & 8);
485 player->control.jump = (keyPressed & 16);
486 player->control.aux1 = (keyPressed & 32);
487 player->control.sneak = (keyPressed & 64);
488 player->control.LMB = (keyPressed & 128);
489 player->control.RMB = (keyPressed & 256);
491 if (playersao->checkMovementCheat()) {
493 m_script->on_cheat(playersao, "moved_too_fast");
494 SendMovePlayer(pkt->getPeerId());
498 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
500 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
501 if (player == NULL) {
502 errorstream << "Server::ProcessData(): Canceling: "
503 "No player for peer_id=" << pkt->getPeerId()
504 << " disconnecting peer!" << std::endl;
505 DisconnectPeer(pkt->getPeerId());
509 PlayerSAO *playersao = player->getPlayerSAO();
510 if (playersao == NULL) {
511 errorstream << "Server::ProcessData(): Canceling: "
512 "No player object for peer_id=" << pkt->getPeerId()
513 << " disconnecting peer!" << std::endl;
514 DisconnectPeer(pkt->getPeerId());
518 // If player is dead we don't care of this packet
519 if (playersao->isDead()) {
520 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
521 << " is dead. Ignoring packet";
525 process_PlayerPos(player, playersao, pkt);
528 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
530 if (pkt->getSize() < 1)
544 RemoteClient *client = getClient(pkt->getPeerId());
546 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
547 throw con::InvalidIncomingDataException
548 ("DELETEDBLOCKS length is too short");
551 for (u16 i = 0; i < count; i++) {
554 client->SetBlockNotSent(p);
558 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
560 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
562 if (player == NULL) {
563 errorstream << "Server::ProcessData(): Canceling: "
564 "No player for peer_id=" << pkt->getPeerId()
565 << " disconnecting peer!" << std::endl;
566 DisconnectPeer(pkt->getPeerId());
570 PlayerSAO *playersao = player->getPlayerSAO();
571 if (playersao == NULL) {
572 errorstream << "Server::ProcessData(): Canceling: "
573 "No player object for peer_id=" << pkt->getPeerId()
574 << " disconnecting peer!" << std::endl;
575 DisconnectPeer(pkt->getPeerId());
579 // Strip command and create a stream
580 std::string datastring(pkt->getString(0), pkt->getSize());
581 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
583 std::istringstream is(datastring, std::ios_base::binary);
585 InventoryAction *a = InventoryAction::deSerialize(is);
587 infostream << "TOSERVER_INVENTORY_ACTION: "
588 << "InventoryAction::deSerialize() returned NULL"
593 // If something goes wrong, this player is to blame
594 RollbackScopeActor rollback_scope(m_rollback,
595 std::string("player:")+player->getName());
598 Note: Always set inventory not sent, to repair cases
599 where the client made a bad prediction.
603 Handle restrictions and special cases of the move action
605 if (a->getType() == IAction::Move) {
606 IMoveAction *ma = (IMoveAction*)a;
608 ma->from_inv.applyCurrentPlayer(player->getName());
609 ma->to_inv.applyCurrentPlayer(player->getName());
611 setInventoryModified(ma->from_inv, false);
612 setInventoryModified(ma->to_inv, false);
614 bool from_inv_is_current_player =
615 (ma->from_inv.type == InventoryLocation::PLAYER) &&
616 (ma->from_inv.name == player->getName());
618 bool to_inv_is_current_player =
619 (ma->to_inv.type == InventoryLocation::PLAYER) &&
620 (ma->to_inv.name == player->getName());
622 InventoryLocation *remote = from_inv_is_current_player ?
623 &ma->to_inv : &ma->from_inv;
625 // Check for out-of-range interaction
626 if (remote->type == InventoryLocation::NODEMETA) {
627 v3f node_pos = intToFloat(remote->p, BS);
628 v3f player_pos = player->getPlayerSAO()->getBasePosition();
629 f32 d = player_pos.getDistanceFrom(node_pos);
630 if (!checkInteractDistance(player, d, "inventory"))
635 Disable moving items out of craftpreview
637 if (ma->from_list == "craftpreview") {
638 infostream << "Ignoring IMoveAction from "
639 << (ma->from_inv.dump()) << ":" << ma->from_list
640 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
641 << " because src is " << ma->from_list << std::endl;
647 Disable moving items into craftresult and craftpreview
649 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
650 infostream << "Ignoring IMoveAction from "
651 << (ma->from_inv.dump()) << ":" << ma->from_list
652 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
653 << " because dst is " << ma->to_list << std::endl;
658 // Disallow moving items in elsewhere than player's inventory
659 // if not allowed to interact
660 if (!checkPriv(player->getName(), "interact") &&
661 (!from_inv_is_current_player ||
662 !to_inv_is_current_player)) {
663 infostream << "Cannot move outside of player's inventory: "
664 << "No interact privilege" << std::endl;
670 Handle restrictions and special cases of the drop action
672 else if (a->getType() == IAction::Drop) {
673 IDropAction *da = (IDropAction*)a;
675 da->from_inv.applyCurrentPlayer(player->getName());
677 setInventoryModified(da->from_inv, false);
680 Disable dropping items out of craftpreview
682 if (da->from_list == "craftpreview") {
683 infostream << "Ignoring IDropAction from "
684 << (da->from_inv.dump()) << ":" << da->from_list
685 << " because src is " << da->from_list << std::endl;
690 // Disallow dropping items if not allowed to interact
691 if (!checkPriv(player->getName(), "interact")) {
696 // Disallow dropping items if dead
697 if (playersao->isDead()) {
698 infostream << "Ignoring IDropAction from "
699 << (da->from_inv.dump()) << ":" << da->from_list
700 << " because player is dead." << std::endl;
706 Handle restrictions and special cases of the craft action
708 else if (a->getType() == IAction::Craft) {
709 ICraftAction *ca = (ICraftAction*)a;
711 ca->craft_inv.applyCurrentPlayer(player->getName());
713 setInventoryModified(ca->craft_inv, false);
715 //bool craft_inv_is_current_player =
716 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
717 // (ca->craft_inv.name == player->getName());
719 // Disallow crafting if not allowed to interact
720 if (!checkPriv(player->getName(), "interact")) {
721 infostream << "Cannot craft: "
722 << "No interact privilege" << std::endl;
729 a->apply(this, playersao, this);
733 SendInventory(playersao);
736 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
746 std::wstring message;
747 for (u16 i = 0; i < len; i++) {
751 message += (wchar_t)tmp_wchar;
754 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
755 if (player == NULL) {
756 errorstream << "Server::ProcessData(): Canceling: "
757 "No player for peer_id=" << pkt->getPeerId()
758 << " disconnecting peer!" << std::endl;
759 DisconnectPeer(pkt->getPeerId());
763 // Get player name of this client
764 std::string name = player->getName();
765 std::wstring wname = narrow_to_wide(name);
767 std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
768 if (!answer_to_sender.empty()) {
769 // Send the answer to sender
770 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
771 answer_to_sender, wname));
775 void Server::handleCommand_Damage(NetworkPacket* pkt)
781 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
783 if (player == NULL) {
784 errorstream << "Server::ProcessData(): Canceling: "
785 "No player for peer_id=" << pkt->getPeerId()
786 << " disconnecting peer!" << std::endl;
787 DisconnectPeer(pkt->getPeerId());
791 PlayerSAO *playersao = player->getPlayerSAO();
792 if (playersao == NULL) {
793 errorstream << "Server::ProcessData(): Canceling: "
794 "No player object for peer_id=" << pkt->getPeerId()
795 << " disconnecting peer!" << std::endl;
796 DisconnectPeer(pkt->getPeerId());
800 if (g_settings->getBool("enable_damage")) {
801 if (playersao->isDead()) {
802 verbosestream << "Server::ProcessData(): Info: "
803 "Ignoring damage as player " << player->getName()
804 << " is already dead." << std::endl;
808 actionstream << player->getName() << " damaged by "
809 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
812 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
813 playersao->setHP(playersao->getHP() - damage, reason);
814 SendPlayerHPOrDie(playersao, reason);
818 void Server::handleCommand_Password(NetworkPacket* pkt)
820 if (pkt->getSize() != PASSWORD_SIZE * 2)
826 // Deny for clients using the new protocol
827 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
828 if (client->net_proto_version >= 25) {
829 infostream << "Server::handleCommand_Password(): Denying change: "
830 << " Client protocol version for peer_id=" << pkt->getPeerId()
831 << " too new!" << std::endl;
835 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
836 char c = pkt->getChar(i);
842 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
843 char c = pkt->getChar(PASSWORD_SIZE + i);
849 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
850 if (player == NULL) {
851 errorstream << "Server::ProcessData(): Canceling: "
852 "No player for peer_id=" << pkt->getPeerId()
853 << " disconnecting peer!" << std::endl;
854 DisconnectPeer(pkt->getPeerId());
858 if (!base64_is_valid(newpwd)) {
859 infostream<<"Server: " << player->getName() <<
860 " supplied invalid password hash" << std::endl;
861 // Wrong old password supplied!!
862 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
863 L"Invalid new password hash supplied. Password NOT changed."));
867 infostream << "Server: Client requests a password change from "
868 << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
870 std::string playername = player->getName();
872 std::string checkpwd;
873 m_script->getAuth(playername, &checkpwd, NULL);
875 if (oldpwd != checkpwd) {
876 infostream << "Server: invalid old password" << std::endl;
877 // Wrong old password supplied!!
878 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
879 L"Invalid old password supplied. Password NOT changed."));
883 bool success = m_script->setPassword(playername, newpwd);
885 actionstream << player->getName() << " changes password" << std::endl;
886 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
887 L"Password change successful."));
889 actionstream << player->getName() << " tries to change password but "
890 << "it fails" << std::endl;
891 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
892 L"Password change failed or unavailable."));
896 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
898 if (pkt->getSize() < 2)
901 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
903 if (player == NULL) {
904 errorstream << "Server::ProcessData(): Canceling: "
905 "No player for peer_id=" << pkt->getPeerId()
906 << " disconnecting peer!" << std::endl;
907 DisconnectPeer(pkt->getPeerId());
911 PlayerSAO *playersao = player->getPlayerSAO();
912 if (playersao == NULL) {
913 errorstream << "Server::ProcessData(): Canceling: "
914 "No player object for peer_id=" << pkt->getPeerId()
915 << " disconnecting peer!" << std::endl;
916 DisconnectPeer(pkt->getPeerId());
924 playersao->setWieldIndex(item);
927 void Server::handleCommand_Respawn(NetworkPacket* pkt)
929 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
930 if (player == NULL) {
931 errorstream << "Server::ProcessData(): Canceling: "
932 "No player for peer_id=" << pkt->getPeerId()
933 << " disconnecting peer!" << std::endl;
934 DisconnectPeer(pkt->getPeerId());
938 PlayerSAO *playersao = player->getPlayerSAO();
941 if (!playersao->isDead())
944 RespawnPlayer(pkt->getPeerId());
946 actionstream << player->getName() << " respawns at "
947 << PP(playersao->getBasePosition() / BS) << std::endl;
949 // ActiveObject is added to environment in AsyncRunStep after
950 // the previous addition has been successfully removed
953 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string what)
955 PlayerSAO *playersao = player->getPlayerSAO();
956 const InventoryList *hlist = playersao->getInventory()->getList("hand");
957 const ItemDefinition &playeritem_def =
958 playersao->getWieldedItem().getDefinition(m_itemdef);
959 const ItemDefinition &hand_def =
960 hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
962 float max_d = BS * playeritem_def.range;
963 float max_d_hand = BS * hand_def.range;
965 if (max_d < 0 && max_d_hand >= 0)
970 // cube diagonal: sqrt(3) = 1.732
971 if (d > max_d * 1.732) {
972 actionstream << "Player " << player->getName()
973 << " tried to access " << what
975 << "d=" << d <<", max_d=" << max_d
976 << ". ignoring." << std::endl;
978 m_script->on_cheat(playersao, "interacted_too_far");
984 void Server::handleCommand_Interact(NetworkPacket* pkt)
990 [5] u32 length of the next item (plen)
991 [9] serialized PointedThing
992 [9 + plen] player position information
994 0: start digging (from undersurface) or use
995 1: stop digging (all parameters ignored)
997 3: place block or item (to abovesurface)
999 5: rightclick air ("activate")
1005 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
1006 PointedThing pointed;
1007 pointed.deSerialize(tmp_is);
1009 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
1010 << item_i << ", pointed=" << pointed.dump() << std::endl;
1012 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1014 if (player == NULL) {
1015 errorstream << "Server::ProcessData(): Canceling: "
1016 "No player for peer_id=" << pkt->getPeerId()
1017 << " disconnecting peer!" << std::endl;
1018 DisconnectPeer(pkt->getPeerId());
1022 PlayerSAO *playersao = player->getPlayerSAO();
1023 if (playersao == NULL) {
1024 errorstream << "Server::ProcessData(): Canceling: "
1025 "No player object for peer_id=" << pkt->getPeerId()
1026 << " disconnecting peer!" << std::endl;
1027 DisconnectPeer(pkt->getPeerId());
1031 if (playersao->isDead()) {
1032 actionstream << "Server: NoCheat: " << player->getName()
1033 << " tried to interact while dead; ignoring." << std::endl;
1034 if (pointed.type == POINTEDTHING_NODE) {
1035 // Re-send block to revert change on client-side
1036 RemoteClient *client = getClient(pkt->getPeerId());
1037 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1038 client->SetBlockNotSent(blockpos);
1041 m_script->on_cheat(playersao, "interacted_while_dead");
1045 process_PlayerPos(player, playersao, pkt);
1047 v3f player_pos = playersao->getLastGoodPosition();
1049 // Update wielded item
1050 playersao->setWieldIndex(item_i);
1052 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1053 v3s16 p_under = pointed.node_undersurface;
1054 v3s16 p_above = pointed.node_abovesurface;
1056 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1057 ServerActiveObject *pointed_object = NULL;
1058 if (pointed.type == POINTEDTHING_OBJECT) {
1059 pointed_object = m_env->getActiveObject(pointed.object_id);
1060 if (pointed_object == NULL) {
1061 verbosestream << "TOSERVER_INTERACT: "
1062 "pointed object is NULL" << std::endl;
1068 v3f pointed_pos_under = player_pos;
1069 v3f pointed_pos_above = player_pos;
1070 if (pointed.type == POINTEDTHING_NODE) {
1071 pointed_pos_under = intToFloat(p_under, BS);
1072 pointed_pos_above = intToFloat(p_above, BS);
1074 else if (pointed.type == POINTEDTHING_OBJECT) {
1075 pointed_pos_under = pointed_object->getBasePosition();
1076 pointed_pos_above = pointed_pos_under;
1080 Make sure the player is allowed to do it
1082 if (!checkPriv(player->getName(), "interact")) {
1083 actionstream<<player->getName()<<" attempted to interact with "
1084 <<pointed.dump()<<" without 'interact' privilege"
1086 // Re-send block to revert change on client-side
1087 RemoteClient *client = getClient(pkt->getPeerId());
1088 // Digging completed -> under
1090 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1091 client->SetBlockNotSent(blockpos);
1093 // Placement -> above
1094 else if (action == 3) {
1095 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1096 client->SetBlockNotSent(blockpos);
1102 Check that target is reasonably close
1103 (only when digging or placing things)
1105 static thread_local const bool enable_anticheat =
1106 !g_settings->getBool("disable_anticheat");
1108 if ((action == 0 || action == 2 || action == 3 || action == 4) &&
1109 enable_anticheat && !isSingleplayer()) {
1110 float d = player_pos.getDistanceFrom(pointed_pos_under);
1111 if (!checkInteractDistance(player, d, pointed.dump())) {
1112 // Re-send block to revert change on client-side
1113 RemoteClient *client = getClient(pkt->getPeerId());
1114 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1115 client->SetBlockNotSent(blockpos);
1121 If something goes wrong, this player is to blame
1123 RollbackScopeActor rollback_scope(m_rollback,
1124 std::string("player:")+player->getName());
1127 0: start digging or punch object
1130 if (pointed.type == POINTEDTHING_NODE) {
1131 MapNode n(CONTENT_IGNORE);
1134 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1136 infostream << "Server: Not punching: Node not found."
1137 << " Adding block to emerge queue."
1139 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1140 getNodeBlockPos(p_above), false);
1143 if (n.getContent() != CONTENT_IGNORE)
1144 m_script->node_on_punch(p_under, n, playersao, pointed);
1147 playersao->noCheatDigStart(p_under);
1149 else if (pointed.type == POINTEDTHING_OBJECT) {
1150 // Skip if object can't be interacted with anymore
1151 if (pointed_object->isGone())
1154 actionstream<<player->getName()<<" punches object "
1155 <<pointed.object_id<<": "
1156 <<pointed_object->getDescription()<<std::endl;
1158 ItemStack punchitem = playersao->getWieldedItemOrHand();
1159 ToolCapabilities toolcap =
1160 punchitem.getToolCapabilities(m_itemdef);
1161 v3f dir = (pointed_object->getBasePosition() -
1162 (playersao->getBasePosition() + playersao->getEyeOffset())
1164 float time_from_last_punch =
1165 playersao->resetTimeFromLastPunch();
1167 s16 src_original_hp = pointed_object->getHP();
1168 s16 dst_origin_hp = playersao->getHP();
1170 pointed_object->punch(dir, &toolcap, playersao,
1171 time_from_last_punch);
1173 // If the object is a player and its HP changed
1174 if (src_original_hp != pointed_object->getHP() &&
1175 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1176 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1177 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1180 // If the puncher is a player and its HP changed
1181 if (dst_origin_hp != playersao->getHP())
1182 SendPlayerHPOrDie(playersao,
1183 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1191 else if (action == 1) {
1195 2: Digging completed
1197 else if (action == 2) {
1198 // Only digging of nodes
1199 if (pointed.type == POINTEDTHING_NODE) {
1201 MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1203 infostream << "Server: Not finishing digging: Node not found."
1204 << " Adding block to emerge queue."
1206 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1207 getNodeBlockPos(p_above), false);
1210 /* Cheat prevention */
1211 bool is_valid_dig = true;
1212 if (enable_anticheat && !isSingleplayer()) {
1213 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1214 float nocheat_t = playersao->getNoCheatDigTime();
1215 playersao->noCheatDigEnd();
1216 // If player didn't start digging this, ignore dig
1217 if (nocheat_p != p_under) {
1218 infostream << "Server: NoCheat: " << player->getName()
1219 << " started digging "
1220 << PP(nocheat_p) << " and completed digging "
1221 << PP(p_under) << "; not digging." << std::endl;
1222 is_valid_dig = false;
1224 m_script->on_cheat(playersao, "finished_unknown_dig");
1226 // Get player's wielded item
1227 ItemStack playeritem = playersao->getWieldedItemOrHand();
1228 ToolCapabilities playeritem_toolcap =
1229 playeritem.getToolCapabilities(m_itemdef);
1230 // Get diggability and expected digging time
1231 DigParams params = getDigParams(m_nodedef->get(n).groups,
1232 &playeritem_toolcap);
1233 // If can't dig, try hand
1234 if (!params.diggable) {
1235 InventoryList *hlist = playersao->getInventory()->getList("hand");
1236 const ToolCapabilities *tp = hlist
1237 ? &hlist->getItem(0).getToolCapabilities(m_itemdef)
1238 : m_itemdef->get("").tool_capabilities;
1241 params = getDigParams(m_nodedef->get(n).groups, tp);
1243 // If can't dig, ignore dig
1244 if (!params.diggable) {
1245 infostream << "Server: NoCheat: " << player->getName()
1246 << " completed digging " << PP(p_under)
1247 << ", which is not diggable with tool. not digging."
1249 is_valid_dig = false;
1251 m_script->on_cheat(playersao, "dug_unbreakable");
1253 // Check digging time
1254 // If already invalidated, we don't have to
1255 if (!is_valid_dig) {
1256 // Well not our problem then
1258 // Clean and long dig
1259 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1260 // All is good, but grab time from pool; don't care if
1261 // it's actually available
1262 playersao->getDigPool().grab(params.time);
1264 // Short or laggy dig
1265 // Try getting the time from pool
1266 else if (playersao->getDigPool().grab(params.time)) {
1271 infostream << "Server: NoCheat: " << player->getName()
1272 << " completed digging " << PP(p_under)
1273 << "too fast; not digging." << std::endl;
1274 is_valid_dig = false;
1276 m_script->on_cheat(playersao, "dug_too_fast");
1280 /* Actually dig node */
1282 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1283 m_script->node_on_dig(p_under, n, playersao);
1285 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1286 RemoteClient *client = getClient(pkt->getPeerId());
1287 // Send unusual result (that is, node not being removed)
1288 if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1289 // Re-send block to revert change on client-side
1290 client->SetBlockNotSent(blockpos);
1293 client->ResendBlockIfOnWire(blockpos);
1299 3: place block or right-click object
1301 else if (action == 3) {
1302 ItemStack item = playersao->getWieldedItem();
1304 // Reset build time counter
1305 if (pointed.type == POINTEDTHING_NODE &&
1306 item.getDefinition(m_itemdef).type == ITEM_NODE)
1307 getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1309 if (pointed.type == POINTEDTHING_OBJECT) {
1310 // Right click object
1312 // Skip if object can't be interacted with anymore
1313 if (pointed_object->isGone())
1316 actionstream << player->getName() << " right-clicks object "
1317 << pointed.object_id << ": "
1318 << pointed_object->getDescription() << std::endl;
1321 pointed_object->rightClick(playersao);
1323 else if (m_script->item_OnPlace(
1324 item, playersao, pointed)) {
1325 // Placement was handled in lua
1327 // Apply returned ItemStack
1328 if (playersao->setWieldedItem(item)) {
1329 SendInventory(playersao);
1333 // If item has node placement prediction, always send the
1334 // blocks to make sure the client knows what exactly happened
1335 RemoteClient *client = getClient(pkt->getPeerId());
1336 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1337 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1338 if (!item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
1339 client->SetBlockNotSent(blockpos);
1340 if (blockpos2 != blockpos) {
1341 client->SetBlockNotSent(blockpos2);
1345 client->ResendBlockIfOnWire(blockpos);
1346 if (blockpos2 != blockpos) {
1347 client->ResendBlockIfOnWire(blockpos2);
1355 else if (action == 4) {
1356 ItemStack item = playersao->getWieldedItem();
1358 actionstream << player->getName() << " uses " << item.name
1359 << ", pointing at " << pointed.dump() << std::endl;
1361 if (m_script->item_OnUse(
1362 item, playersao, pointed)) {
1363 // Apply returned ItemStack
1364 if (playersao->setWieldedItem(item)) {
1365 SendInventory(playersao);
1374 else if (action == 5) {
1375 ItemStack item = playersao->getWieldedItem();
1377 actionstream << player->getName() << " activates "
1378 << item.name << std::endl;
1380 if (m_script->item_OnSecondaryUse(
1382 if( playersao->setWieldedItem(item)) {
1383 SendInventory(playersao);
1390 Catch invalid actions
1393 warningstream << "Server: Invalid action "
1394 << action << std::endl;
1398 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1402 for (u16 k = 0; k < num; k++) {
1407 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1408 m_playing_sounds.find(id);
1409 if (i == m_playing_sounds.end())
1412 ServerPlayingSound &psound = i->second;
1413 psound.clients.erase(pkt->getPeerId());
1414 if (psound.clients.empty())
1415 m_playing_sounds.erase(i++);
1419 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1422 std::string formname;
1425 *pkt >> p >> formname >> num;
1428 for (u16 k = 0; k < num; k++) {
1429 std::string fieldname;
1431 fields[fieldname] = pkt->readLongString();
1434 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1436 if (player == NULL) {
1437 errorstream << "Server::ProcessData(): Canceling: "
1438 "No player for peer_id=" << pkt->getPeerId()
1439 << " disconnecting peer!" << std::endl;
1440 DisconnectPeer(pkt->getPeerId());
1444 PlayerSAO *playersao = player->getPlayerSAO();
1445 if (playersao == NULL) {
1446 errorstream << "Server::ProcessData(): Canceling: "
1447 "No player object for peer_id=" << pkt->getPeerId()
1448 << " disconnecting peer!" << std::endl;
1449 DisconnectPeer(pkt->getPeerId());
1453 // If something goes wrong, this player is to blame
1454 RollbackScopeActor rollback_scope(m_rollback,
1455 std::string("player:")+player->getName());
1457 // Check the target node for rollback data; leave others unnoticed
1458 RollbackNode rn_old(&m_env->getMap(), p, this);
1460 m_script->node_on_receive_fields(p, formname, fields, playersao);
1462 // Report rollback data
1463 RollbackNode rn_new(&m_env->getMap(), p, this);
1464 if (rollback() && rn_new != rn_old) {
1465 RollbackAction action;
1466 action.setSetNode(p, rn_old, rn_new);
1467 rollback()->reportAction(action);
1471 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1473 std::string client_formspec_name;
1476 *pkt >> client_formspec_name >> num;
1479 for (u16 k = 0; k < num; k++) {
1480 std::string fieldname;
1482 fields[fieldname] = pkt->readLongString();
1485 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1487 if (player == NULL) {
1488 errorstream << "Server::ProcessData(): Canceling: "
1489 "No player for peer_id=" << pkt->getPeerId()
1490 << " disconnecting peer!" << std::endl;
1491 DisconnectPeer(pkt->getPeerId());
1495 PlayerSAO *playersao = player->getPlayerSAO();
1496 if (playersao == NULL) {
1497 errorstream << "Server::ProcessData(): Canceling: "
1498 "No player object for peer_id=" << pkt->getPeerId()
1499 << " disconnecting peer!" << std::endl;
1500 DisconnectPeer(pkt->getPeerId());
1504 if (client_formspec_name.empty()) { // pass through inventory submits
1505 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1509 // verify that we displayed the formspec to the user
1510 const auto peer_state_iterator = m_formspec_state_data.find(pkt->getPeerId());
1511 if (peer_state_iterator != m_formspec_state_data.end()) {
1512 const std::string &server_formspec_name = peer_state_iterator->second;
1513 if (client_formspec_name == server_formspec_name) {
1514 if (fields["quit"] == "true")
1515 m_formspec_state_data.erase(peer_state_iterator);
1517 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1520 actionstream << "'" << player->getName()
1521 << "' submitted formspec ('" << client_formspec_name
1522 << "') but the name of the formspec doesn't match the"
1523 " expected name ('" << server_formspec_name << "')";
1526 actionstream << "'" << player->getName()
1527 << "' submitted formspec ('" << client_formspec_name
1528 << "') but server hasn't sent formspec to client";
1530 actionstream << ", possible exploitation attempt" << std::endl;
1533 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1535 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1536 ClientState cstate = client->getState();
1538 std::string playername = client->getName();
1541 std::string verification_key;
1543 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1546 *pkt >> salt >> verification_key >> is_empty;
1548 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1549 << ", with is_empty=" << (is_empty == 1) << std::endl;
1551 // Either this packet is sent because the user is new or to change the password
1552 if (cstate == CS_HelloSent) {
1553 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1554 actionstream << "Server: Client from " << addr_s
1555 << " tried to set password without being "
1556 << "authenticated, or the username being new." << std::endl;
1557 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1561 if (!isSingleplayer() &&
1562 g_settings->getBool("disallow_empty_password") &&
1564 actionstream << "Server: " << playername
1565 << " supplied empty password from " << addr_s << std::endl;
1566 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1570 std::string initial_ver_key;
1572 initial_ver_key = encode_srp_verifier(verification_key, salt);
1573 m_script->createAuth(playername, initial_ver_key);
1575 acceptAuth(pkt->getPeerId(), false);
1577 if (cstate < CS_SudoMode) {
1578 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1579 << addr_s << ": " << "Client has wrong state " << cstate << "."
1583 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1584 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1585 bool success = m_script->setPassword(playername, pw_db_field);
1587 actionstream << playername << " changes password" << std::endl;
1588 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1589 L"Password change successful."));
1591 actionstream << playername << " tries to change password but "
1592 << "it fails" << std::endl;
1593 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1594 L"Password change failed or unavailable."));
1599 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1601 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1602 ClientState cstate = client->getState();
1604 bool wantSudo = (cstate == CS_Active);
1606 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1607 actionstream << "Server: got SRP _A packet in wrong state "
1608 << cstate << " from "
1609 << getPeerAddress(pkt->getPeerId()).serializeString()
1610 << ". Ignoring." << std::endl;
1614 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1615 actionstream << "Server: got SRP _A packet, while auth"
1616 << "is already going on with mech " << client->chosen_mech
1617 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1618 << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1620 DenySudoAccess(pkt->getPeerId());
1624 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1628 std::string bytes_A;
1630 *pkt >> bytes_A >> based_on;
1632 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1633 << "based_on=" << int(based_on) << " and len_A="
1634 << bytes_A.length() << "." << std::endl;
1636 AuthMechanism chosen = (based_on == 0) ?
1637 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1640 if (!client->isSudoMechAllowed(chosen)) {
1641 actionstream << "Server: Player \"" << client->getName()
1642 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1643 << " tried to change password using unallowed mech "
1644 << chosen << "." << std::endl;
1645 DenySudoAccess(pkt->getPeerId());
1649 if (!client->isMechAllowed(chosen)) {
1650 actionstream << "Server: Client tried to authenticate from "
1651 << getPeerAddress(pkt->getPeerId()).serializeString()
1652 << " using unallowed mech " << chosen << "." << std::endl;
1653 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1658 client->chosen_mech = chosen;
1661 std::string verifier;
1663 if (based_on == 0) {
1665 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1667 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1668 // Non-base64 errors should have been catched in the init handler
1669 actionstream << "Server: User " << client->getName()
1670 << " tried to log in, but srp verifier field"
1671 << " was invalid (most likely invalid base64)." << std::endl;
1672 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1679 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1680 client->getName().c_str(),
1681 (const unsigned char *) salt.c_str(), salt.size(),
1682 (const unsigned char *) verifier.c_str(), verifier.size(),
1683 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1685 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1688 actionstream << "Server: User " << client->getName()
1689 << " tried to log in, SRP-6a safety check violated in _A handler."
1692 DenySudoAccess(pkt->getPeerId());
1696 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1700 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1701 resp_pkt << salt << std::string(bytes_B, len_B);
1705 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1707 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1708 ClientState cstate = client->getState();
1710 bool wantSudo = (cstate == CS_Active);
1712 verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
1714 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1715 actionstream << "Server: got SRP _M packet in wrong state "
1716 << cstate << " from "
1717 << getPeerAddress(pkt->getPeerId()).serializeString()
1718 << ". Ignoring." << std::endl;
1722 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1723 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1724 actionstream << "Server: got SRP _M packet, while auth"
1725 << "is going on with mech " << client->chosen_mech
1726 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1727 << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1729 DenySudoAccess(pkt->getPeerId());
1733 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1737 std::string bytes_M;
1740 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1741 != bytes_M.size()) {
1742 actionstream << "Server: User " << client->getName()
1743 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1744 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1745 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1749 unsigned char *bytes_HAMK = 0;
1751 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1752 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1756 actionstream << "Server: User " << client->getName()
1757 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1758 << " tried to change their password, but supplied wrong"
1759 << " (SRP) password for authentication." << std::endl;
1760 DenySudoAccess(pkt->getPeerId());
1764 std::string ip = getPeerAddress(pkt->getPeerId()).serializeString();
1765 actionstream << "Server: User " << client->getName()
1767 << " supplied wrong password (auth mechanism: SRP)."
1769 m_script->on_auth_failure(client->getName(), ip);
1770 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
1774 if (client->create_player_on_auth_success) {
1775 std::string playername = client->getName();
1776 m_script->createAuth(playername, client->enc_pwd);
1778 std::string checkpwd; // not used, but needed for passing something
1779 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1780 actionstream << "Server: " << playername << " cannot be authenticated"
1781 << " (auth handler does not work?)" << std::endl;
1782 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1785 client->create_player_on_auth_success = false;
1788 acceptAuth(pkt->getPeerId(), wantSudo);
1795 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1797 std::string channel_name;
1798 *pkt >> channel_name;
1800 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1803 // Send signal to client to notify join succeed or not
1804 if (g_settings->getBool("enable_mod_channels") &&
1805 m_modchannel_mgr->joinChannel(channel_name, pkt->getPeerId())) {
1806 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1807 infostream << "Peer " << pkt->getPeerId() << " joined channel " << channel_name
1811 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1812 infostream << "Peer " << pkt->getPeerId() << " tried to join channel "
1813 << channel_name << ", but was already registered." << std::endl;
1815 resp_pkt << channel_name;
1819 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1821 std::string channel_name;
1822 *pkt >> channel_name;
1824 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1827 // Send signal to client to notify join succeed or not
1828 if (g_settings->getBool("enable_mod_channels") &&
1829 m_modchannel_mgr->leaveChannel(channel_name, pkt->getPeerId())) {
1830 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1831 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1834 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1835 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1836 << ", but was not registered." << std::endl;
1838 resp_pkt << channel_name;
1842 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1844 std::string channel_name, channel_msg;
1845 *pkt >> channel_name >> channel_msg;
1847 verbosestream << "Mod channel message received from peer " << pkt->getPeerId()
1848 << " on channel " << channel_name << " message: " << channel_msg << std::endl;
1850 // If mod channels are not enabled, discard message
1851 if (!g_settings->getBool("enable_mod_channels")) {
1855 // If channel not registered, signal it and ignore message
1856 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1857 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1859 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1864 // @TODO: filter, rate limit
1866 broadcastModChannelMessage(channel_name, channel_msg, pkt->getPeerId());