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->setLookPitch(pitch);
477 playersao->setPlayerYaw(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 if (ma->from_inv != ma->to_inv) {
613 setInventoryModified(ma->to_inv, false);
616 bool from_inv_is_current_player =
617 (ma->from_inv.type == InventoryLocation::PLAYER) &&
618 (ma->from_inv.name == player->getName());
620 bool to_inv_is_current_player =
621 (ma->to_inv.type == InventoryLocation::PLAYER) &&
622 (ma->to_inv.name == player->getName());
624 InventoryLocation *remote = from_inv_is_current_player ?
625 &ma->to_inv : &ma->from_inv;
627 // Check for out-of-range interaction
628 if (remote->type == InventoryLocation::NODEMETA) {
629 v3f node_pos = intToFloat(remote->p, BS);
630 v3f player_pos = player->getPlayerSAO()->getEyePosition();
631 f32 d = player_pos.getDistanceFrom(node_pos);
632 if (!checkInteractDistance(player, d, "inventory"))
637 Disable moving items out of craftpreview
639 if (ma->from_list == "craftpreview") {
640 infostream << "Ignoring IMoveAction from "
641 << (ma->from_inv.dump()) << ":" << ma->from_list
642 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
643 << " because src is " << ma->from_list << std::endl;
649 Disable moving items into craftresult and craftpreview
651 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
652 infostream << "Ignoring IMoveAction from "
653 << (ma->from_inv.dump()) << ":" << ma->from_list
654 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
655 << " because dst is " << ma->to_list << std::endl;
660 // Disallow moving items in elsewhere than player's inventory
661 // if not allowed to interact
662 if (!checkPriv(player->getName(), "interact") &&
663 (!from_inv_is_current_player ||
664 !to_inv_is_current_player)) {
665 infostream << "Cannot move outside of player's inventory: "
666 << "No interact privilege" << std::endl;
672 Handle restrictions and special cases of the drop action
674 else if (a->getType() == IAction::Drop) {
675 IDropAction *da = (IDropAction*)a;
677 da->from_inv.applyCurrentPlayer(player->getName());
679 setInventoryModified(da->from_inv, false);
682 Disable dropping items out of craftpreview
684 if (da->from_list == "craftpreview") {
685 infostream << "Ignoring IDropAction from "
686 << (da->from_inv.dump()) << ":" << da->from_list
687 << " because src is " << da->from_list << std::endl;
692 // Disallow dropping items if not allowed to interact
693 if (!checkPriv(player->getName(), "interact")) {
698 // Disallow dropping items if dead
699 if (playersao->isDead()) {
700 infostream << "Ignoring IDropAction from "
701 << (da->from_inv.dump()) << ":" << da->from_list
702 << " because player is dead." << std::endl;
708 Handle restrictions and special cases of the craft action
710 else if (a->getType() == IAction::Craft) {
711 ICraftAction *ca = (ICraftAction*)a;
713 ca->craft_inv.applyCurrentPlayer(player->getName());
715 setInventoryModified(ca->craft_inv, false);
717 //bool craft_inv_is_current_player =
718 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
719 // (ca->craft_inv.name == player->getName());
721 // Disallow crafting if not allowed to interact
722 if (!checkPriv(player->getName(), "interact")) {
723 infostream << "Cannot craft: "
724 << "No interact privilege" << std::endl;
731 a->apply(this, playersao, this);
735 SendInventory(playersao);
738 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
748 std::wstring message;
749 for (u16 i = 0; i < len; i++) {
753 message += (wchar_t)tmp_wchar;
756 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
757 if (player == NULL) {
758 errorstream << "Server::ProcessData(): Canceling: "
759 "No player for peer_id=" << pkt->getPeerId()
760 << " disconnecting peer!" << std::endl;
761 DisconnectPeer(pkt->getPeerId());
765 // Get player name of this client
766 std::string name = player->getName();
767 std::wstring wname = narrow_to_wide(name);
769 std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
770 if (!answer_to_sender.empty()) {
771 // Send the answer to sender
772 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
773 answer_to_sender, wname));
777 void Server::handleCommand_Damage(NetworkPacket* pkt)
783 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
785 if (player == NULL) {
786 errorstream << "Server::ProcessData(): Canceling: "
787 "No player for peer_id=" << pkt->getPeerId()
788 << " disconnecting peer!" << std::endl;
789 DisconnectPeer(pkt->getPeerId());
793 PlayerSAO *playersao = player->getPlayerSAO();
794 if (playersao == NULL) {
795 errorstream << "Server::ProcessData(): Canceling: "
796 "No player object for peer_id=" << pkt->getPeerId()
797 << " disconnecting peer!" << std::endl;
798 DisconnectPeer(pkt->getPeerId());
802 if (!playersao->isImmortal()) {
803 if (playersao->isDead()) {
804 verbosestream << "Server::ProcessData(): Info: "
805 "Ignoring damage as player " << player->getName()
806 << " is already dead." << std::endl;
810 actionstream << player->getName() << " damaged by "
811 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
814 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
815 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
816 SendPlayerHPOrDie(playersao, reason);
820 void Server::handleCommand_Password(NetworkPacket* pkt)
822 if (pkt->getSize() != PASSWORD_SIZE * 2)
828 // Deny for clients using the new protocol
829 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
830 if (client->net_proto_version >= 25) {
831 infostream << "Server::handleCommand_Password(): Denying change: "
832 << " Client protocol version for peer_id=" << pkt->getPeerId()
833 << " too new!" << std::endl;
837 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
838 char c = pkt->getChar(i);
844 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
845 char c = pkt->getChar(PASSWORD_SIZE + i);
851 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
852 if (player == NULL) {
853 errorstream << "Server::ProcessData(): Canceling: "
854 "No player for peer_id=" << pkt->getPeerId()
855 << " disconnecting peer!" << std::endl;
856 DisconnectPeer(pkt->getPeerId());
860 if (!base64_is_valid(newpwd)) {
861 infostream<<"Server: " << player->getName() <<
862 " supplied invalid password hash" << std::endl;
863 // Wrong old password supplied!!
864 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
865 L"Invalid new password hash supplied. Password NOT changed."));
869 infostream << "Server: Client requests a password change from "
870 << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
872 std::string playername = player->getName();
874 std::string checkpwd;
875 m_script->getAuth(playername, &checkpwd, NULL);
877 if (oldpwd != checkpwd) {
878 infostream << "Server: invalid old password" << std::endl;
879 // Wrong old password supplied!!
880 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
881 L"Invalid old password supplied. Password NOT changed."));
885 bool success = m_script->setPassword(playername, newpwd);
887 actionstream << player->getName() << " changes password" << std::endl;
888 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
889 L"Password change successful."));
891 actionstream << player->getName() << " tries to change password but "
892 << "it fails" << std::endl;
893 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
894 L"Password change failed or unavailable."));
898 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
900 if (pkt->getSize() < 2)
903 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
905 if (player == NULL) {
906 errorstream << "Server::ProcessData(): Canceling: "
907 "No player for peer_id=" << pkt->getPeerId()
908 << " disconnecting peer!" << std::endl;
909 DisconnectPeer(pkt->getPeerId());
913 PlayerSAO *playersao = player->getPlayerSAO();
914 if (playersao == NULL) {
915 errorstream << "Server::ProcessData(): Canceling: "
916 "No player object for peer_id=" << pkt->getPeerId()
917 << " disconnecting peer!" << std::endl;
918 DisconnectPeer(pkt->getPeerId());
926 playersao->getPlayer()->setWieldIndex(item);
929 void Server::handleCommand_Respawn(NetworkPacket* pkt)
931 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
932 if (player == NULL) {
933 errorstream << "Server::ProcessData(): Canceling: "
934 "No player for peer_id=" << pkt->getPeerId()
935 << " disconnecting peer!" << std::endl;
936 DisconnectPeer(pkt->getPeerId());
940 PlayerSAO *playersao = player->getPlayerSAO();
943 if (!playersao->isDead())
946 RespawnPlayer(pkt->getPeerId());
948 actionstream << player->getName() << " respawns at "
949 << PP(playersao->getBasePosition() / BS) << std::endl;
951 // ActiveObject is added to environment in AsyncRunStep after
952 // the previous addition has been successfully removed
955 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
957 ItemStack selected_item, hand_item;
958 player->getWieldedItem(&selected_item, &hand_item);
959 f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
960 hand_item.getDefinition(m_itemdef));
962 // Cube diagonal * 1.5 for maximal supported node extents:
963 // sqrt(3) * 1.5 ≅ 2.6
964 if (d > max_d + 2.6f * BS) {
965 actionstream << "Player " << player->getName()
966 << " tried to access " << what
968 << "d=" << d <<", max_d=" << max_d
969 << ". ignoring." << std::endl;
971 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
977 void Server::handleCommand_Interact(NetworkPacket *pkt)
983 [5] u32 length of the next item (plen)
984 [9] serialized PointedThing
985 [9 + plen] player position information
988 InteractAction action;
991 *pkt >> (u8 &)action;
994 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
995 PointedThing pointed;
996 pointed.deSerialize(tmp_is);
998 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
999 << item_i << ", pointed=" << pointed.dump() << std::endl;
1001 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1003 if (player == NULL) {
1004 errorstream << "Server::ProcessData(): Canceling: "
1005 "No player for peer_id=" << pkt->getPeerId()
1006 << " disconnecting peer!" << std::endl;
1007 DisconnectPeer(pkt->getPeerId());
1011 PlayerSAO *playersao = player->getPlayerSAO();
1012 if (playersao == NULL) {
1013 errorstream << "Server::ProcessData(): Canceling: "
1014 "No player object for peer_id=" << pkt->getPeerId()
1015 << " disconnecting peer!" << std::endl;
1016 DisconnectPeer(pkt->getPeerId());
1020 if (playersao->isDead()) {
1021 actionstream << "Server: NoCheat: " << player->getName()
1022 << " tried to interact while dead; ignoring." << std::endl;
1023 if (pointed.type == POINTEDTHING_NODE) {
1024 // Re-send block to revert change on client-side
1025 RemoteClient *client = getClient(pkt->getPeerId());
1026 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1027 client->SetBlockNotSent(blockpos);
1030 m_script->on_cheat(playersao, "interacted_while_dead");
1034 process_PlayerPos(player, playersao, pkt);
1036 v3f player_pos = playersao->getLastGoodPosition();
1038 // Update wielded item
1039 playersao->getPlayer()->setWieldIndex(item_i);
1041 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1042 v3s16 p_under = pointed.node_undersurface;
1043 v3s16 p_above = pointed.node_abovesurface;
1045 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1046 ServerActiveObject *pointed_object = NULL;
1047 if (pointed.type == POINTEDTHING_OBJECT) {
1048 pointed_object = m_env->getActiveObject(pointed.object_id);
1049 if (pointed_object == NULL) {
1050 verbosestream << "TOSERVER_INTERACT: "
1051 "pointed object is NULL" << std::endl;
1057 v3f pointed_pos_under = player_pos;
1058 v3f pointed_pos_above = player_pos;
1059 if (pointed.type == POINTEDTHING_NODE) {
1060 pointed_pos_under = intToFloat(p_under, BS);
1061 pointed_pos_above = intToFloat(p_above, BS);
1063 else if (pointed.type == POINTEDTHING_OBJECT) {
1064 pointed_pos_under = pointed_object->getBasePosition();
1065 pointed_pos_above = pointed_pos_under;
1069 Make sure the player is allowed to do it
1071 if (!checkPriv(player->getName(), "interact")) {
1072 actionstream << player->getName() << " attempted to interact with " <<
1073 pointed.dump() << " without 'interact' privilege" << std::endl;
1075 // Re-send block to revert change on client-side
1076 RemoteClient *client = getClient(pkt->getPeerId());
1077 // Digging completed -> under
1078 if (action == INTERACT_DIGGING_COMPLETED) {
1079 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1080 client->SetBlockNotSent(blockpos);
1082 // Placement -> above
1083 else if (action == INTERACT_PLACE) {
1084 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1085 client->SetBlockNotSent(blockpos);
1091 Check that target is reasonably close
1092 (only when digging or placing things)
1094 static thread_local const bool enable_anticheat =
1095 !g_settings->getBool("disable_anticheat");
1097 if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1098 action == INTERACT_PLACE || action == INTERACT_USE) &&
1099 enable_anticheat && !isSingleplayer()) {
1100 float d = playersao->getEyePosition().getDistanceFrom(pointed_pos_under);
1102 if (!checkInteractDistance(player, d, pointed.dump())) {
1103 // Re-send block to revert change on client-side
1104 RemoteClient *client = getClient(pkt->getPeerId());
1105 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1106 client->SetBlockNotSent(blockpos);
1112 If something goes wrong, this player is to blame
1114 RollbackScopeActor rollback_scope(m_rollback,
1115 std::string("player:")+player->getName());
1118 0: start digging or punch object
1120 if (action == INTERACT_START_DIGGING) {
1121 if (pointed.type == POINTEDTHING_NODE) {
1122 MapNode n(CONTENT_IGNORE);
1125 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1127 infostream << "Server: Not punching: Node not found."
1128 << " Adding block to emerge queue."
1130 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1131 getNodeBlockPos(p_above), false);
1134 if (n.getContent() != CONTENT_IGNORE)
1135 m_script->node_on_punch(p_under, n, playersao, pointed);
1138 playersao->noCheatDigStart(p_under);
1140 else if (pointed.type == POINTEDTHING_OBJECT) {
1141 // Skip if object can't be interacted with anymore
1142 if (pointed_object->isGone())
1145 ItemStack punchitem = playersao->getWieldedItem();
1146 ToolCapabilities toolcap =
1147 punchitem.getToolCapabilities(m_itemdef);
1148 v3f dir = (pointed_object->getBasePosition() -
1149 (playersao->getBasePosition() + playersao->getEyeOffset())
1151 float time_from_last_punch =
1152 playersao->resetTimeFromLastPunch();
1154 u16 src_original_hp = pointed_object->getHP();
1155 u16 dst_origin_hp = playersao->getHP();
1157 pointed_object->punch(dir, &toolcap, playersao,
1158 time_from_last_punch);
1160 // If the object is a player and its HP changed
1161 if (src_original_hp != pointed_object->getHP() &&
1162 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1163 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1164 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1167 // If the puncher is a player and its HP changed
1168 if (dst_origin_hp != playersao->getHP())
1169 SendPlayerHPOrDie(playersao,
1170 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1173 } // action == INTERACT_START_DIGGING
1178 else if (action == INTERACT_STOP_DIGGING) {
1179 } // action == INTERACT_STOP_DIGGING
1182 2: Digging completed
1184 else if (action == INTERACT_DIGGING_COMPLETED) {
1185 // Only digging of nodes
1186 if (pointed.type == POINTEDTHING_NODE) {
1188 MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1190 infostream << "Server: Not finishing digging: Node not found."
1191 << " Adding block to emerge queue."
1193 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1194 getNodeBlockPos(p_above), false);
1197 /* Cheat prevention */
1198 bool is_valid_dig = true;
1199 if (enable_anticheat && !isSingleplayer()) {
1200 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1201 float nocheat_t = playersao->getNoCheatDigTime();
1202 playersao->noCheatDigEnd();
1203 // If player didn't start digging this, ignore dig
1204 if (nocheat_p != p_under) {
1205 infostream << "Server: NoCheat: " << player->getName()
1206 << " started digging "
1207 << PP(nocheat_p) << " and completed digging "
1208 << PP(p_under) << "; not digging." << std::endl;
1209 is_valid_dig = false;
1211 m_script->on_cheat(playersao, "finished_unknown_dig");
1214 // Get player's wielded item
1215 // See also: Game::handleDigging
1216 ItemStack selected_item, hand_item;
1217 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1219 // Get diggability and expected digging time
1220 DigParams params = getDigParams(m_nodedef->get(n).groups,
1221 &selected_item.getToolCapabilities(m_itemdef));
1222 // If can't dig, try hand
1223 if (!params.diggable) {
1224 params = getDigParams(m_nodedef->get(n).groups,
1225 &hand_item.getToolCapabilities(m_itemdef));
1227 // If can't dig, ignore dig
1228 if (!params.diggable) {
1229 infostream << "Server: NoCheat: " << player->getName()
1230 << " completed digging " << PP(p_under)
1231 << ", which is not diggable with tool. not digging."
1233 is_valid_dig = false;
1235 m_script->on_cheat(playersao, "dug_unbreakable");
1237 // Check digging time
1238 // If already invalidated, we don't have to
1239 if (!is_valid_dig) {
1240 // Well not our problem then
1242 // Clean and long dig
1243 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1244 // All is good, but grab time from pool; don't care if
1245 // it's actually available
1246 playersao->getDigPool().grab(params.time);
1248 // Short or laggy dig
1249 // Try getting the time from pool
1250 else if (playersao->getDigPool().grab(params.time)) {
1255 infostream << "Server: NoCheat: " << player->getName()
1256 << " completed digging " << PP(p_under)
1257 << "too fast; not digging." << std::endl;
1258 is_valid_dig = false;
1260 m_script->on_cheat(playersao, "dug_too_fast");
1264 /* Actually dig node */
1266 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1267 m_script->node_on_dig(p_under, n, playersao);
1269 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1270 RemoteClient *client = getClient(pkt->getPeerId());
1271 // Send unusual result (that is, node not being removed)
1272 if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1273 // Re-send block to revert change on client-side
1274 client->SetBlockNotSent(blockpos);
1277 client->ResendBlockIfOnWire(blockpos);
1280 } // action == INTERACT_DIGGING_COMPLETED
1283 3: place block or right-click object
1285 else if (action == INTERACT_PLACE) {
1286 ItemStack item = playersao->getWieldedItem();
1288 // Reset build time counter
1289 if (pointed.type == POINTEDTHING_NODE &&
1290 item.getDefinition(m_itemdef).type == ITEM_NODE)
1291 getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1293 if (pointed.type == POINTEDTHING_OBJECT) {
1294 // Right click object
1296 // Skip if object can't be interacted with anymore
1297 if (pointed_object->isGone())
1300 actionstream << player->getName() << " right-clicks object "
1301 << pointed.object_id << ": "
1302 << pointed_object->getDescription() << std::endl;
1305 pointed_object->rightClick(playersao);
1307 else if (m_script->item_OnPlace(
1308 item, playersao, pointed)) {
1309 // Placement was handled in lua
1311 // Apply returned ItemStack
1312 if (playersao->setWieldedItem(item)) {
1313 SendInventory(playersao);
1317 // If item has node placement prediction, always send the
1318 // blocks to make sure the client knows what exactly happened
1319 RemoteClient *client = getClient(pkt->getPeerId());
1320 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1321 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1322 if (!item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
1323 client->SetBlockNotSent(blockpos);
1324 if (blockpos2 != blockpos) {
1325 client->SetBlockNotSent(blockpos2);
1329 client->ResendBlockIfOnWire(blockpos);
1330 if (blockpos2 != blockpos) {
1331 client->ResendBlockIfOnWire(blockpos2);
1334 } // action == INTERACT_PLACE
1339 else if (action == INTERACT_USE) {
1340 ItemStack item = playersao->getWieldedItem();
1342 actionstream << player->getName() << " uses " << item.name
1343 << ", pointing at " << pointed.dump() << std::endl;
1345 if (m_script->item_OnUse(
1346 item, playersao, pointed)) {
1347 // Apply returned ItemStack
1348 if (playersao->setWieldedItem(item)) {
1349 SendInventory(playersao);
1353 } // action == INTERACT_USE
1358 else if (action == INTERACT_ACTIVATE) {
1359 ItemStack item = playersao->getWieldedItem();
1361 actionstream << player->getName() << " activates "
1362 << item.name << std::endl;
1364 if (m_script->item_OnSecondaryUse(
1366 if( playersao->setWieldedItem(item)) {
1367 SendInventory(playersao);
1370 } // action == INTERACT_ACTIVATE
1374 Catch invalid actions
1377 warningstream << "Server: Invalid action "
1378 << action << std::endl;
1382 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1386 for (u16 k = 0; k < num; k++) {
1391 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1392 m_playing_sounds.find(id);
1393 if (i == m_playing_sounds.end())
1396 ServerPlayingSound &psound = i->second;
1397 psound.clients.erase(pkt->getPeerId());
1398 if (psound.clients.empty())
1399 m_playing_sounds.erase(i++);
1403 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1406 std::string formname;
1409 *pkt >> p >> formname >> num;
1412 for (u16 k = 0; k < num; k++) {
1413 std::string fieldname;
1415 fields[fieldname] = pkt->readLongString();
1418 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1420 if (player == NULL) {
1421 errorstream << "Server::ProcessData(): Canceling: "
1422 "No player for peer_id=" << pkt->getPeerId()
1423 << " disconnecting peer!" << std::endl;
1424 DisconnectPeer(pkt->getPeerId());
1428 PlayerSAO *playersao = player->getPlayerSAO();
1429 if (playersao == NULL) {
1430 errorstream << "Server::ProcessData(): Canceling: "
1431 "No player object for peer_id=" << pkt->getPeerId()
1432 << " disconnecting peer!" << std::endl;
1433 DisconnectPeer(pkt->getPeerId());
1437 // If something goes wrong, this player is to blame
1438 RollbackScopeActor rollback_scope(m_rollback,
1439 std::string("player:")+player->getName());
1441 // Check the target node for rollback data; leave others unnoticed
1442 RollbackNode rn_old(&m_env->getMap(), p, this);
1444 m_script->node_on_receive_fields(p, formname, fields, playersao);
1446 // Report rollback data
1447 RollbackNode rn_new(&m_env->getMap(), p, this);
1448 if (rollback() && rn_new != rn_old) {
1449 RollbackAction action;
1450 action.setSetNode(p, rn_old, rn_new);
1451 rollback()->reportAction(action);
1455 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1457 std::string client_formspec_name;
1460 *pkt >> client_formspec_name >> num;
1463 for (u16 k = 0; k < num; k++) {
1464 std::string fieldname;
1466 fields[fieldname] = pkt->readLongString();
1469 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1471 if (player == NULL) {
1472 errorstream << "Server::ProcessData(): Canceling: "
1473 "No player for peer_id=" << pkt->getPeerId()
1474 << " disconnecting peer!" << std::endl;
1475 DisconnectPeer(pkt->getPeerId());
1479 PlayerSAO *playersao = player->getPlayerSAO();
1480 if (playersao == NULL) {
1481 errorstream << "Server::ProcessData(): Canceling: "
1482 "No player object for peer_id=" << pkt->getPeerId()
1483 << " disconnecting peer!" << std::endl;
1484 DisconnectPeer(pkt->getPeerId());
1488 if (client_formspec_name.empty()) { // pass through inventory submits
1489 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1493 // verify that we displayed the formspec to the user
1494 const auto peer_state_iterator = m_formspec_state_data.find(pkt->getPeerId());
1495 if (peer_state_iterator != m_formspec_state_data.end()) {
1496 const std::string &server_formspec_name = peer_state_iterator->second;
1497 if (client_formspec_name == server_formspec_name) {
1498 auto it = fields.find("quit");
1499 if (it != fields.end() && it->second == "true")
1500 m_formspec_state_data.erase(peer_state_iterator);
1502 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1505 actionstream << "'" << player->getName()
1506 << "' submitted formspec ('" << client_formspec_name
1507 << "') but the name of the formspec doesn't match the"
1508 " expected name ('" << server_formspec_name << "')";
1511 actionstream << "'" << player->getName()
1512 << "' submitted formspec ('" << client_formspec_name
1513 << "') but server hasn't sent formspec to client";
1515 actionstream << ", possible exploitation attempt" << std::endl;
1518 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1520 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1521 ClientState cstate = client->getState();
1523 std::string playername = client->getName();
1526 std::string verification_key;
1528 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1531 *pkt >> salt >> verification_key >> is_empty;
1533 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1534 << ", with is_empty=" << (is_empty == 1) << std::endl;
1536 // Either this packet is sent because the user is new or to change the password
1537 if (cstate == CS_HelloSent) {
1538 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1539 actionstream << "Server: Client from " << addr_s
1540 << " tried to set password without being "
1541 << "authenticated, or the username being new." << std::endl;
1542 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1546 if (!isSingleplayer() &&
1547 g_settings->getBool("disallow_empty_password") &&
1549 actionstream << "Server: " << playername
1550 << " supplied empty password from " << addr_s << std::endl;
1551 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1555 std::string initial_ver_key;
1557 initial_ver_key = encode_srp_verifier(verification_key, salt);
1558 m_script->createAuth(playername, initial_ver_key);
1560 acceptAuth(pkt->getPeerId(), false);
1562 if (cstate < CS_SudoMode) {
1563 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1564 << addr_s << ": " << "Client has wrong state " << cstate << "."
1568 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1569 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1570 bool success = m_script->setPassword(playername, pw_db_field);
1572 actionstream << playername << " changes password" << std::endl;
1573 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1574 L"Password change successful."));
1576 actionstream << playername << " tries to change password but "
1577 << "it fails" << std::endl;
1578 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1579 L"Password change failed or unavailable."));
1584 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1586 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1587 ClientState cstate = client->getState();
1589 bool wantSudo = (cstate == CS_Active);
1591 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1592 actionstream << "Server: got SRP _A packet in wrong state "
1593 << cstate << " from "
1594 << getPeerAddress(pkt->getPeerId()).serializeString()
1595 << ". Ignoring." << std::endl;
1599 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1600 actionstream << "Server: got SRP _A packet, while auth"
1601 << "is already going on with mech " << client->chosen_mech
1602 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1603 << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1605 DenySudoAccess(pkt->getPeerId());
1609 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1613 std::string bytes_A;
1615 *pkt >> bytes_A >> based_on;
1617 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1618 << "based_on=" << int(based_on) << " and len_A="
1619 << bytes_A.length() << "." << std::endl;
1621 AuthMechanism chosen = (based_on == 0) ?
1622 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1625 if (!client->isSudoMechAllowed(chosen)) {
1626 actionstream << "Server: Player \"" << client->getName()
1627 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1628 << " tried to change password using unallowed mech "
1629 << chosen << "." << std::endl;
1630 DenySudoAccess(pkt->getPeerId());
1634 if (!client->isMechAllowed(chosen)) {
1635 actionstream << "Server: Client tried to authenticate from "
1636 << getPeerAddress(pkt->getPeerId()).serializeString()
1637 << " using unallowed mech " << chosen << "." << std::endl;
1638 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1643 client->chosen_mech = chosen;
1646 std::string verifier;
1648 if (based_on == 0) {
1650 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1652 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1653 // Non-base64 errors should have been catched in the init handler
1654 actionstream << "Server: User " << client->getName()
1655 << " tried to log in, but srp verifier field"
1656 << " was invalid (most likely invalid base64)." << std::endl;
1657 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1664 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1665 client->getName().c_str(),
1666 (const unsigned char *) salt.c_str(), salt.size(),
1667 (const unsigned char *) verifier.c_str(), verifier.size(),
1668 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1670 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1673 actionstream << "Server: User " << client->getName()
1674 << " tried to log in, SRP-6a safety check violated in _A handler."
1677 DenySudoAccess(pkt->getPeerId());
1681 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1685 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1686 resp_pkt << salt << std::string(bytes_B, len_B);
1690 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1692 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1693 ClientState cstate = client->getState();
1695 bool wantSudo = (cstate == CS_Active);
1697 verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
1699 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1700 actionstream << "Server: got SRP _M packet in wrong state "
1701 << cstate << " from "
1702 << getPeerAddress(pkt->getPeerId()).serializeString()
1703 << ". Ignoring." << std::endl;
1707 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1708 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1709 actionstream << "Server: got SRP _M packet, while auth"
1710 << "is going on with mech " << client->chosen_mech
1711 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1712 << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1714 DenySudoAccess(pkt->getPeerId());
1718 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1722 std::string bytes_M;
1725 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1726 != bytes_M.size()) {
1727 actionstream << "Server: User " << client->getName()
1728 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1729 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1730 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1734 unsigned char *bytes_HAMK = 0;
1736 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1737 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1741 actionstream << "Server: User " << client->getName()
1742 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1743 << " tried to change their password, but supplied wrong"
1744 << " (SRP) password for authentication." << std::endl;
1745 DenySudoAccess(pkt->getPeerId());
1749 std::string ip = getPeerAddress(pkt->getPeerId()).serializeString();
1750 actionstream << "Server: User " << client->getName()
1752 << " supplied wrong password (auth mechanism: SRP)."
1754 m_script->on_auth_failure(client->getName(), ip);
1755 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
1759 if (client->create_player_on_auth_success) {
1760 std::string playername = client->getName();
1761 m_script->createAuth(playername, client->enc_pwd);
1763 std::string checkpwd; // not used, but needed for passing something
1764 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1765 actionstream << "Server: " << playername << " cannot be authenticated"
1766 << " (auth handler does not work?)" << std::endl;
1767 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1770 client->create_player_on_auth_success = false;
1773 acceptAuth(pkt->getPeerId(), wantSudo);
1780 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1782 std::string channel_name;
1783 *pkt >> channel_name;
1785 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1788 // Send signal to client to notify join succeed or not
1789 if (g_settings->getBool("enable_mod_channels") &&
1790 m_modchannel_mgr->joinChannel(channel_name, pkt->getPeerId())) {
1791 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1792 infostream << "Peer " << pkt->getPeerId() << " joined channel " << channel_name
1796 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1797 infostream << "Peer " << pkt->getPeerId() << " tried to join channel "
1798 << channel_name << ", but was already registered." << std::endl;
1800 resp_pkt << channel_name;
1804 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1806 std::string channel_name;
1807 *pkt >> channel_name;
1809 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1812 // Send signal to client to notify join succeed or not
1813 if (g_settings->getBool("enable_mod_channels") &&
1814 m_modchannel_mgr->leaveChannel(channel_name, pkt->getPeerId())) {
1815 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1816 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1819 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1820 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1821 << ", but was not registered." << std::endl;
1823 resp_pkt << channel_name;
1827 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1829 std::string channel_name, channel_msg;
1830 *pkt >> channel_name >> channel_msg;
1832 verbosestream << "Mod channel message received from peer " << pkt->getPeerId()
1833 << " on channel " << channel_name << " message: " << channel_msg << std::endl;
1835 // If mod channels are not enabled, discard message
1836 if (!g_settings->getBool("enable_mod_channels")) {
1840 // If channel not registered, signal it and ignore message
1841 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1842 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1844 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1849 // @TODO: filter, rate limit
1851 broadcastModChannelMessage(channel_name, channel_msg, pkt->getPeerId());