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 item definitions
302 SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
304 // Send node definitions
305 SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
307 m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
309 // Send media announcement
310 sendMediaAnnouncement(pkt->getPeerId(), lang);
312 RemoteClient *client = getClient(pkt->getPeerId(), CS_InitDone);
314 // Send active objects
316 PlayerSAO *sao = getPlayerSAO(pkt->getPeerId());
318 SendActiveObjectRemoveAdd(client, sao);
321 // Send detached inventories
322 sendDetachedInventories(pkt->getPeerId(), false);
324 // Send player movement settings
325 SendMovement(pkt->getPeerId());
328 u16 time = m_env->getTimeOfDay();
329 float time_speed = g_settings->getFloat("time_speed");
330 SendTimeOfDay(pkt->getPeerId(), time, time_speed);
332 SendCSMRestrictionFlags(pkt->getPeerId());
334 // Warnings about protocol version can be issued here
335 if (client->net_proto_version < LATEST_PROTOCOL_VERSION) {
336 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
337 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
338 L"WITH THIS SERVER!"));
342 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
344 std::vector<std::string> tosend;
349 infostream << "Sending " << numfiles << " files to "
350 << getPlayerName(pkt->getPeerId()) << std::endl;
351 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
353 for (u16 i = 0; i < numfiles; i++) {
358 tosend.push_back(name);
359 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
360 << name << std::endl;
363 sendRequestedMedia(pkt->getPeerId(), tosend);
366 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
368 session_t peer_id = pkt->getPeerId();
370 PlayerSAO* playersao = StageTwoClientInit(peer_id);
372 if (playersao == NULL) {
374 << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
375 << peer_id << std::endl;
376 DisconnectPeer(peer_id);
381 if (pkt->getSize() < 8) {
383 << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
384 << peer_id << std::endl;
385 DisconnectPeer(peer_id);
389 u8 major_ver, minor_ver, patch_ver, reserved;
390 std::string full_ver;
391 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
393 m_clients.setClientVersion(
394 peer_id, major_ver, minor_ver, patch_ver,
397 if (pkt->getRemainingBytes() >= 2)
398 *pkt >> playersao->getPlayer()->formspec_version;
400 const std::vector<std::string> &players = m_clients.getPlayerNames();
401 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
402 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
403 for (const std::string &player: players) {
406 m_clients.send(peer_id, 0, &list_pkt, true);
408 NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
409 // (u16) 1 + std::string represents a pseudo vector serialization representation
410 notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
411 m_clients.sendToAll(¬ice_pkt);
413 m_clients.event(peer_id, CSE_SetClientReady);
414 m_script->on_joinplayer(playersao);
415 // Send shutdown timer if shutdown has been scheduled
416 if (m_shutdown_state.isTimerRunning()) {
417 SendChatMessage(pkt->getPeerId(), m_shutdown_state.getShutdownTimerMessage());
421 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
423 if (pkt->getSize() < 1)
437 RemoteClient *client = getClient(pkt->getPeerId());
439 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
440 throw con::InvalidIncomingDataException
441 ("GOTBLOCKS length is too short");
444 for (u16 i = 0; i < count; i++) {
451 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
454 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
458 s32 f32pitch, f32yaw;
466 f32 pitch = (f32)f32pitch / 100.0f;
467 f32 yaw = (f32)f32yaw / 100.0f;
470 // default behavior (in case an old client doesn't send these)
476 fov = (f32)f32fov / 80.0f;
477 *pkt >> wanted_range;
479 v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
480 v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
482 pitch = modulo360f(pitch);
483 yaw = wrapDegrees_0_360(yaw);
485 playersao->setBasePosition(position);
486 player->setSpeed(speed);
487 playersao->setLookPitch(pitch);
488 playersao->setPlayerYaw(yaw);
489 playersao->setFov(fov);
490 playersao->setWantedRange(wanted_range);
491 player->keyPressed = keyPressed;
492 player->control.up = (keyPressed & 1);
493 player->control.down = (keyPressed & 2);
494 player->control.left = (keyPressed & 4);
495 player->control.right = (keyPressed & 8);
496 player->control.jump = (keyPressed & 16);
497 player->control.aux1 = (keyPressed & 32);
498 player->control.sneak = (keyPressed & 64);
499 player->control.LMB = (keyPressed & 128);
500 player->control.RMB = (keyPressed & 256);
502 if (playersao->checkMovementCheat()) {
504 m_script->on_cheat(playersao, "moved_too_fast");
505 SendMovePlayer(pkt->getPeerId());
509 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
511 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
512 if (player == NULL) {
513 errorstream << "Server::ProcessData(): Canceling: "
514 "No player for peer_id=" << pkt->getPeerId()
515 << " disconnecting peer!" << std::endl;
516 DisconnectPeer(pkt->getPeerId());
520 PlayerSAO *playersao = player->getPlayerSAO();
521 if (playersao == NULL) {
522 errorstream << "Server::ProcessData(): Canceling: "
523 "No player object for peer_id=" << pkt->getPeerId()
524 << " disconnecting peer!" << std::endl;
525 DisconnectPeer(pkt->getPeerId());
529 // If player is dead we don't care of this packet
530 if (playersao->isDead()) {
531 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
532 << " is dead. Ignoring packet";
536 process_PlayerPos(player, playersao, pkt);
539 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
541 if (pkt->getSize() < 1)
555 RemoteClient *client = getClient(pkt->getPeerId());
557 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
558 throw con::InvalidIncomingDataException
559 ("DELETEDBLOCKS length is too short");
562 for (u16 i = 0; i < count; i++) {
565 client->SetBlockNotSent(p);
569 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
571 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
573 if (player == NULL) {
574 errorstream << "Server::ProcessData(): Canceling: "
575 "No player for peer_id=" << pkt->getPeerId()
576 << " disconnecting peer!" << std::endl;
577 DisconnectPeer(pkt->getPeerId());
581 PlayerSAO *playersao = player->getPlayerSAO();
582 if (playersao == NULL) {
583 errorstream << "Server::ProcessData(): Canceling: "
584 "No player object for peer_id=" << pkt->getPeerId()
585 << " disconnecting peer!" << std::endl;
586 DisconnectPeer(pkt->getPeerId());
590 // Strip command and create a stream
591 std::string datastring(pkt->getString(0), pkt->getSize());
592 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
594 std::istringstream is(datastring, std::ios_base::binary);
596 InventoryAction *a = InventoryAction::deSerialize(is);
598 infostream << "TOSERVER_INVENTORY_ACTION: "
599 << "InventoryAction::deSerialize() returned NULL"
604 // If something goes wrong, this player is to blame
605 RollbackScopeActor rollback_scope(m_rollback,
606 std::string("player:")+player->getName());
609 Note: Always set inventory not sent, to repair cases
610 where the client made a bad prediction.
614 Handle restrictions and special cases of the move action
616 if (a->getType() == IAction::Move) {
617 IMoveAction *ma = (IMoveAction*)a;
619 ma->from_inv.applyCurrentPlayer(player->getName());
620 ma->to_inv.applyCurrentPlayer(player->getName());
622 setInventoryModified(ma->from_inv);
623 if (ma->from_inv != ma->to_inv)
624 setInventoryModified(ma->to_inv);
626 bool from_inv_is_current_player =
627 (ma->from_inv.type == InventoryLocation::PLAYER) &&
628 (ma->from_inv.name == player->getName());
630 bool to_inv_is_current_player =
631 (ma->to_inv.type == InventoryLocation::PLAYER) &&
632 (ma->to_inv.name == player->getName());
634 InventoryLocation *remote = from_inv_is_current_player ?
635 &ma->to_inv : &ma->from_inv;
637 // Check for out-of-range interaction
638 if (remote->type == InventoryLocation::NODEMETA) {
639 v3f node_pos = intToFloat(remote->p, BS);
640 v3f player_pos = player->getPlayerSAO()->getEyePosition();
641 f32 d = player_pos.getDistanceFrom(node_pos);
642 if (!checkInteractDistance(player, d, "inventory"))
647 Disable moving items out of craftpreview
649 if (ma->from_list == "craftpreview") {
650 infostream << "Ignoring IMoveAction from "
651 << (ma->from_inv.dump()) << ":" << ma->from_list
652 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
653 << " because src is " << ma->from_list << std::endl;
659 Disable moving items into craftresult and craftpreview
661 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
662 infostream << "Ignoring IMoveAction from "
663 << (ma->from_inv.dump()) << ":" << ma->from_list
664 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
665 << " because dst is " << ma->to_list << std::endl;
670 // Disallow moving items in elsewhere than player's inventory
671 // if not allowed to interact
672 if (!checkPriv(player->getName(), "interact") &&
673 (!from_inv_is_current_player ||
674 !to_inv_is_current_player)) {
675 infostream << "Cannot move outside of player's inventory: "
676 << "No interact privilege" << std::endl;
682 Handle restrictions and special cases of the drop action
684 else if (a->getType() == IAction::Drop) {
685 IDropAction *da = (IDropAction*)a;
687 da->from_inv.applyCurrentPlayer(player->getName());
689 setInventoryModified(da->from_inv);
692 Disable dropping items out of craftpreview
694 if (da->from_list == "craftpreview") {
695 infostream << "Ignoring IDropAction from "
696 << (da->from_inv.dump()) << ":" << da->from_list
697 << " because src is " << da->from_list << std::endl;
702 // Disallow dropping items if not allowed to interact
703 if (!checkPriv(player->getName(), "interact")) {
708 // Disallow dropping items if dead
709 if (playersao->isDead()) {
710 infostream << "Ignoring IDropAction from "
711 << (da->from_inv.dump()) << ":" << da->from_list
712 << " because player is dead." << std::endl;
718 Handle restrictions and special cases of the craft action
720 else if (a->getType() == IAction::Craft) {
721 ICraftAction *ca = (ICraftAction*)a;
723 ca->craft_inv.applyCurrentPlayer(player->getName());
725 setInventoryModified(ca->craft_inv);
727 //bool craft_inv_is_current_player =
728 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
729 // (ca->craft_inv.name == player->getName());
731 // Disallow crafting if not allowed to interact
732 if (!checkPriv(player->getName(), "interact")) {
733 infostream << "Cannot craft: "
734 << "No interact privilege" << std::endl;
741 a->apply(this, playersao, this);
746 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
756 std::wstring message;
757 for (u16 i = 0; i < len; i++) {
761 message += (wchar_t)tmp_wchar;
764 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
765 if (player == NULL) {
766 errorstream << "Server::ProcessData(): Canceling: "
767 "No player for peer_id=" << pkt->getPeerId()
768 << " disconnecting peer!" << std::endl;
769 DisconnectPeer(pkt->getPeerId());
773 // Get player name of this client
774 std::string name = player->getName();
775 std::wstring wname = narrow_to_wide(name);
777 std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
778 if (!answer_to_sender.empty()) {
779 // Send the answer to sender
780 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
781 answer_to_sender, wname));
785 void Server::handleCommand_Damage(NetworkPacket* pkt)
791 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
793 if (player == NULL) {
794 errorstream << "Server::ProcessData(): Canceling: "
795 "No player for peer_id=" << pkt->getPeerId()
796 << " disconnecting peer!" << std::endl;
797 DisconnectPeer(pkt->getPeerId());
801 PlayerSAO *playersao = player->getPlayerSAO();
802 if (playersao == NULL) {
803 errorstream << "Server::ProcessData(): Canceling: "
804 "No player object for peer_id=" << pkt->getPeerId()
805 << " disconnecting peer!" << std::endl;
806 DisconnectPeer(pkt->getPeerId());
810 if (!playersao->isImmortal()) {
811 if (playersao->isDead()) {
812 verbosestream << "Server::ProcessData(): Info: "
813 "Ignoring damage as player " << player->getName()
814 << " is already dead." << std::endl;
818 actionstream << player->getName() << " damaged by "
819 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
822 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
823 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
824 SendPlayerHPOrDie(playersao, reason);
828 void Server::handleCommand_Password(NetworkPacket* pkt)
830 if (pkt->getSize() != PASSWORD_SIZE * 2)
836 // Deny for clients using the new protocol
837 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
838 if (client->net_proto_version >= 25) {
839 infostream << "Server::handleCommand_Password(): Denying change: "
840 << " Client protocol version for peer_id=" << pkt->getPeerId()
841 << " too new!" << std::endl;
845 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
846 char c = pkt->getChar(i);
852 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
853 char c = pkt->getChar(PASSWORD_SIZE + i);
859 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
860 if (player == NULL) {
861 errorstream << "Server::ProcessData(): Canceling: "
862 "No player for peer_id=" << pkt->getPeerId()
863 << " disconnecting peer!" << std::endl;
864 DisconnectPeer(pkt->getPeerId());
868 if (!base64_is_valid(newpwd)) {
869 infostream<<"Server: " << player->getName() <<
870 " supplied invalid password hash" << std::endl;
871 // Wrong old password supplied!!
872 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
873 L"Invalid new password hash supplied. Password NOT changed."));
877 infostream << "Server: Client requests a password change from "
878 << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
880 std::string playername = player->getName();
882 std::string checkpwd;
883 m_script->getAuth(playername, &checkpwd, NULL);
885 if (oldpwd != checkpwd) {
886 infostream << "Server: invalid old password" << std::endl;
887 // Wrong old password supplied!!
888 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
889 L"Invalid old password supplied. Password NOT changed."));
893 bool success = m_script->setPassword(playername, newpwd);
895 actionstream << player->getName() << " changes password" << std::endl;
896 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
897 L"Password change successful."));
899 actionstream << player->getName() << " tries to change password but "
900 << "it fails" << std::endl;
901 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
902 L"Password change failed or unavailable."));
906 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
908 if (pkt->getSize() < 2)
911 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
913 if (player == NULL) {
914 errorstream << "Server::ProcessData(): Canceling: "
915 "No player for peer_id=" << pkt->getPeerId()
916 << " disconnecting peer!" << std::endl;
917 DisconnectPeer(pkt->getPeerId());
921 PlayerSAO *playersao = player->getPlayerSAO();
922 if (playersao == NULL) {
923 errorstream << "Server::ProcessData(): Canceling: "
924 "No player object for peer_id=" << pkt->getPeerId()
925 << " disconnecting peer!" << std::endl;
926 DisconnectPeer(pkt->getPeerId());
934 playersao->getPlayer()->setWieldIndex(item);
937 void Server::handleCommand_Respawn(NetworkPacket* pkt)
939 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
940 if (player == NULL) {
941 errorstream << "Server::ProcessData(): Canceling: "
942 "No player for peer_id=" << pkt->getPeerId()
943 << " disconnecting peer!" << std::endl;
944 DisconnectPeer(pkt->getPeerId());
948 PlayerSAO *playersao = player->getPlayerSAO();
951 if (!playersao->isDead())
954 RespawnPlayer(pkt->getPeerId());
956 actionstream << player->getName() << " respawns at "
957 << PP(playersao->getBasePosition() / BS) << std::endl;
959 // ActiveObject is added to environment in AsyncRunStep after
960 // the previous addition has been successfully removed
963 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
965 ItemStack selected_item, hand_item;
966 player->getWieldedItem(&selected_item, &hand_item);
967 f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
968 hand_item.getDefinition(m_itemdef));
970 // Cube diagonal * 1.5 for maximal supported node extents:
971 // sqrt(3) * 1.5 ≅ 2.6
972 if (d > max_d + 2.6f * BS) {
973 actionstream << "Player " << player->getName()
974 << " tried to access " << what
976 << "d=" << d <<", max_d=" << max_d
977 << ". ignoring." << std::endl;
979 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
985 void Server::handleCommand_Interact(NetworkPacket *pkt)
991 [5] u32 length of the next item (plen)
992 [9] serialized PointedThing
993 [9 + plen] player position information
996 InteractAction action;
999 *pkt >> (u8 &)action;
1002 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
1003 PointedThing pointed;
1004 pointed.deSerialize(tmp_is);
1006 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
1007 << item_i << ", pointed=" << pointed.dump() << std::endl;
1009 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1011 if (player == NULL) {
1012 errorstream << "Server::ProcessData(): Canceling: "
1013 "No player for peer_id=" << pkt->getPeerId()
1014 << " disconnecting peer!" << std::endl;
1015 DisconnectPeer(pkt->getPeerId());
1019 PlayerSAO *playersao = player->getPlayerSAO();
1020 if (playersao == NULL) {
1021 errorstream << "Server::ProcessData(): Canceling: "
1022 "No player object for peer_id=" << pkt->getPeerId()
1023 << " disconnecting peer!" << std::endl;
1024 DisconnectPeer(pkt->getPeerId());
1028 if (playersao->isDead()) {
1029 actionstream << "Server: NoCheat: " << player->getName()
1030 << " tried to interact while dead; ignoring." << std::endl;
1031 if (pointed.type == POINTEDTHING_NODE) {
1032 // Re-send block to revert change on client-side
1033 RemoteClient *client = getClient(pkt->getPeerId());
1034 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1035 client->SetBlockNotSent(blockpos);
1038 m_script->on_cheat(playersao, "interacted_while_dead");
1042 process_PlayerPos(player, playersao, pkt);
1044 v3f player_pos = playersao->getLastGoodPosition();
1046 // Update wielded item
1047 playersao->getPlayer()->setWieldIndex(item_i);
1049 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1050 v3s16 p_under = pointed.node_undersurface;
1051 v3s16 p_above = pointed.node_abovesurface;
1053 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1054 ServerActiveObject *pointed_object = NULL;
1055 if (pointed.type == POINTEDTHING_OBJECT) {
1056 pointed_object = m_env->getActiveObject(pointed.object_id);
1057 if (pointed_object == NULL) {
1058 verbosestream << "TOSERVER_INTERACT: "
1059 "pointed object is NULL" << std::endl;
1065 v3f pointed_pos_under = player_pos;
1066 v3f pointed_pos_above = player_pos;
1067 if (pointed.type == POINTEDTHING_NODE) {
1068 pointed_pos_under = intToFloat(p_under, BS);
1069 pointed_pos_above = intToFloat(p_above, BS);
1071 else if (pointed.type == POINTEDTHING_OBJECT) {
1072 pointed_pos_under = pointed_object->getBasePosition();
1073 pointed_pos_above = pointed_pos_under;
1077 Make sure the player is allowed to do it
1079 if (!checkPriv(player->getName(), "interact")) {
1080 actionstream << player->getName() << " attempted to interact with " <<
1081 pointed.dump() << " without 'interact' privilege" << std::endl;
1083 // Re-send block to revert change on client-side
1084 RemoteClient *client = getClient(pkt->getPeerId());
1085 // Digging completed -> under
1086 if (action == INTERACT_DIGGING_COMPLETED) {
1087 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1088 client->SetBlockNotSent(blockpos);
1090 // Placement -> above
1091 else if (action == INTERACT_PLACE) {
1092 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1093 client->SetBlockNotSent(blockpos);
1099 Check that target is reasonably close
1100 (only when digging or placing things)
1102 static thread_local const bool enable_anticheat =
1103 !g_settings->getBool("disable_anticheat");
1105 if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1106 action == INTERACT_PLACE || action == INTERACT_USE) &&
1107 enable_anticheat && !isSingleplayer()) {
1108 float d = playersao->getEyePosition().getDistanceFrom(pointed_pos_under);
1110 if (!checkInteractDistance(player, d, pointed.dump())) {
1111 // Re-send block to revert change on client-side
1112 RemoteClient *client = getClient(pkt->getPeerId());
1113 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1114 client->SetBlockNotSent(blockpos);
1120 If something goes wrong, this player is to blame
1122 RollbackScopeActor rollback_scope(m_rollback,
1123 std::string("player:")+player->getName());
1126 0: start digging or punch object
1128 if (action == INTERACT_START_DIGGING) {
1129 if (pointed.type == POINTEDTHING_NODE) {
1130 MapNode n(CONTENT_IGNORE);
1133 n = m_env->getMap().getNode(p_under, &pos_ok);
1135 infostream << "Server: Not punching: Node not found."
1136 << " Adding block to emerge queue."
1138 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1139 getNodeBlockPos(p_above), false);
1142 if (n.getContent() != CONTENT_IGNORE)
1143 m_script->node_on_punch(p_under, n, playersao, pointed);
1146 playersao->noCheatDigStart(p_under);
1148 else if (pointed.type == POINTEDTHING_OBJECT) {
1149 // Skip if object can't be interacted with anymore
1150 if (pointed_object->isGone())
1153 ItemStack selected_item, hand_item;
1154 ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
1155 ToolCapabilities toolcap =
1156 tool_item.getToolCapabilities(m_itemdef);
1157 v3f dir = (pointed_object->getBasePosition() -
1158 (playersao->getBasePosition() + playersao->getEyeOffset())
1160 float time_from_last_punch =
1161 playersao->resetTimeFromLastPunch();
1163 u16 src_original_hp = pointed_object->getHP();
1164 u16 dst_origin_hp = playersao->getHP();
1166 u16 wear = pointed_object->punch(dir, &toolcap, playersao,
1167 time_from_last_punch);
1169 // Callback may have changed item, so get it again
1170 playersao->getWieldedItem(&selected_item);
1171 bool changed = selected_item.addWear(wear, m_itemdef);
1173 playersao->setWieldedItem(selected_item);
1175 // If the object is a player and its HP changed
1176 if (src_original_hp != pointed_object->getHP() &&
1177 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1178 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1179 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1182 // If the puncher is a player and its HP changed
1183 if (dst_origin_hp != playersao->getHP())
1184 SendPlayerHPOrDie(playersao,
1185 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1188 } // action == INTERACT_START_DIGGING
1193 else if (action == INTERACT_STOP_DIGGING) {
1194 } // action == INTERACT_STOP_DIGGING
1197 2: Digging completed
1199 else if (action == INTERACT_DIGGING_COMPLETED) {
1200 // Only digging of nodes
1201 if (pointed.type == POINTEDTHING_NODE) {
1203 MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1205 infostream << "Server: Not finishing digging: Node not found."
1206 << " Adding block to emerge queue."
1208 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1209 getNodeBlockPos(p_above), false);
1212 /* Cheat prevention */
1213 bool is_valid_dig = true;
1214 if (enable_anticheat && !isSingleplayer()) {
1215 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1216 float nocheat_t = playersao->getNoCheatDigTime();
1217 playersao->noCheatDigEnd();
1218 // If player didn't start digging this, ignore dig
1219 if (nocheat_p != p_under) {
1220 infostream << "Server: NoCheat: " << player->getName()
1221 << " started digging "
1222 << PP(nocheat_p) << " and completed digging "
1223 << PP(p_under) << "; not digging." << std::endl;
1224 is_valid_dig = false;
1226 m_script->on_cheat(playersao, "finished_unknown_dig");
1229 // Get player's wielded item
1230 // See also: Game::handleDigging
1231 ItemStack selected_item, hand_item;
1232 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1234 // Get diggability and expected digging time
1235 DigParams params = getDigParams(m_nodedef->get(n).groups,
1236 &selected_item.getToolCapabilities(m_itemdef));
1237 // If can't dig, try hand
1238 if (!params.diggable) {
1239 params = getDigParams(m_nodedef->get(n).groups,
1240 &hand_item.getToolCapabilities(m_itemdef));
1242 // If can't dig, ignore dig
1243 if (!params.diggable) {
1244 infostream << "Server: NoCheat: " << player->getName()
1245 << " completed digging " << PP(p_under)
1246 << ", which is not diggable with tool. not digging."
1248 is_valid_dig = false;
1250 m_script->on_cheat(playersao, "dug_unbreakable");
1252 // Check digging time
1253 // If already invalidated, we don't have to
1254 if (!is_valid_dig) {
1255 // Well not our problem then
1257 // Clean and long dig
1258 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1259 // All is good, but grab time from pool; don't care if
1260 // it's actually available
1261 playersao->getDigPool().grab(params.time);
1263 // Short or laggy dig
1264 // Try getting the time from pool
1265 else if (playersao->getDigPool().grab(params.time)) {
1270 infostream << "Server: NoCheat: " << player->getName()
1271 << " completed digging " << PP(p_under)
1272 << "too fast; not digging." << std::endl;
1273 is_valid_dig = false;
1275 m_script->on_cheat(playersao, "dug_too_fast");
1279 /* Actually dig node */
1281 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1282 m_script->node_on_dig(p_under, n, playersao);
1284 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1285 RemoteClient *client = getClient(pkt->getPeerId());
1286 // Send unusual result (that is, node not being removed)
1287 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR) {
1288 // Re-send block to revert change on client-side
1289 client->SetBlockNotSent(blockpos);
1292 client->ResendBlockIfOnWire(blockpos);
1295 } // action == INTERACT_DIGGING_COMPLETED
1298 3: place block or right-click object
1300 else if (action == INTERACT_PLACE) {
1301 ItemStack selected_item;
1302 playersao->getWieldedItem(&selected_item, nullptr);
1304 // Reset build time counter
1305 if (pointed.type == POINTEDTHING_NODE &&
1306 selected_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 if (m_script->item_OnSecondaryUse(
1322 selected_item, playersao, pointed)) {
1323 if (playersao->setWieldedItem(selected_item)) {
1324 SendInventory(playersao, true);
1328 pointed_object->rightClick(playersao);
1329 } else if (m_script->item_OnPlace(
1330 selected_item, playersao, pointed)) {
1331 // Placement was handled in lua
1333 // Apply returned ItemStack
1334 if (playersao->setWieldedItem(selected_item)) {
1335 SendInventory(playersao, true);
1339 // If item has node placement prediction, always send the
1340 // blocks to make sure the client knows what exactly happened
1341 RemoteClient *client = getClient(pkt->getPeerId());
1342 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1343 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1344 if (!selected_item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
1345 client->SetBlockNotSent(blockpos);
1346 if (blockpos2 != blockpos) {
1347 client->SetBlockNotSent(blockpos2);
1351 client->ResendBlockIfOnWire(blockpos);
1352 if (blockpos2 != blockpos) {
1353 client->ResendBlockIfOnWire(blockpos2);
1356 } // action == INTERACT_PLACE
1361 else if (action == INTERACT_USE) {
1362 ItemStack selected_item;
1363 playersao->getWieldedItem(&selected_item, nullptr);
1365 actionstream << player->getName() << " uses " << selected_item.name
1366 << ", pointing at " << pointed.dump() << std::endl;
1368 if (m_script->item_OnUse(
1369 selected_item, playersao, pointed)) {
1370 // Apply returned ItemStack
1371 if (playersao->setWieldedItem(selected_item)) {
1372 SendInventory(playersao, true);
1376 } // action == INTERACT_USE
1381 else if (action == INTERACT_ACTIVATE) {
1382 ItemStack selected_item;
1383 playersao->getWieldedItem(&selected_item, nullptr);
1385 actionstream << player->getName() << " activates "
1386 << selected_item.name << std::endl;
1388 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1390 if (m_script->item_OnSecondaryUse(
1391 selected_item, playersao, pointed)) {
1392 if (playersao->setWieldedItem(selected_item)) {
1393 SendInventory(playersao, true);
1396 } // action == INTERACT_ACTIVATE
1400 Catch invalid actions
1403 warningstream << "Server: Invalid action "
1404 << action << std::endl;
1408 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1412 for (u16 k = 0; k < num; k++) {
1417 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1418 m_playing_sounds.find(id);
1419 if (i == m_playing_sounds.end())
1422 ServerPlayingSound &psound = i->second;
1423 psound.clients.erase(pkt->getPeerId());
1424 if (psound.clients.empty())
1425 m_playing_sounds.erase(i++);
1429 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1432 std::string formname;
1435 *pkt >> p >> formname >> num;
1438 for (u16 k = 0; k < num; k++) {
1439 std::string fieldname;
1441 fields[fieldname] = pkt->readLongString();
1444 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1446 if (player == NULL) {
1447 errorstream << "Server::ProcessData(): Canceling: "
1448 "No player for peer_id=" << pkt->getPeerId()
1449 << " disconnecting peer!" << std::endl;
1450 DisconnectPeer(pkt->getPeerId());
1454 PlayerSAO *playersao = player->getPlayerSAO();
1455 if (playersao == NULL) {
1456 errorstream << "Server::ProcessData(): Canceling: "
1457 "No player object for peer_id=" << pkt->getPeerId()
1458 << " disconnecting peer!" << std::endl;
1459 DisconnectPeer(pkt->getPeerId());
1463 // If something goes wrong, this player is to blame
1464 RollbackScopeActor rollback_scope(m_rollback,
1465 std::string("player:")+player->getName());
1467 // Check the target node for rollback data; leave others unnoticed
1468 RollbackNode rn_old(&m_env->getMap(), p, this);
1470 m_script->node_on_receive_fields(p, formname, fields, playersao);
1472 // Report rollback data
1473 RollbackNode rn_new(&m_env->getMap(), p, this);
1474 if (rollback() && rn_new != rn_old) {
1475 RollbackAction action;
1476 action.setSetNode(p, rn_old, rn_new);
1477 rollback()->reportAction(action);
1481 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1483 std::string client_formspec_name;
1486 *pkt >> client_formspec_name >> num;
1489 for (u16 k = 0; k < num; k++) {
1490 std::string fieldname;
1492 fields[fieldname] = pkt->readLongString();
1495 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1497 if (player == NULL) {
1498 errorstream << "Server::ProcessData(): Canceling: "
1499 "No player for peer_id=" << pkt->getPeerId()
1500 << " disconnecting peer!" << std::endl;
1501 DisconnectPeer(pkt->getPeerId());
1505 PlayerSAO *playersao = player->getPlayerSAO();
1506 if (playersao == NULL) {
1507 errorstream << "Server::ProcessData(): Canceling: "
1508 "No player object for peer_id=" << pkt->getPeerId()
1509 << " disconnecting peer!" << std::endl;
1510 DisconnectPeer(pkt->getPeerId());
1514 if (client_formspec_name.empty()) { // pass through inventory submits
1515 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1519 // verify that we displayed the formspec to the user
1520 const auto peer_state_iterator = m_formspec_state_data.find(pkt->getPeerId());
1521 if (peer_state_iterator != m_formspec_state_data.end()) {
1522 const std::string &server_formspec_name = peer_state_iterator->second;
1523 if (client_formspec_name == server_formspec_name) {
1524 auto it = fields.find("quit");
1525 if (it != fields.end() && it->second == "true")
1526 m_formspec_state_data.erase(peer_state_iterator);
1528 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1531 actionstream << "'" << player->getName()
1532 << "' submitted formspec ('" << client_formspec_name
1533 << "') but the name of the formspec doesn't match the"
1534 " expected name ('" << server_formspec_name << "')";
1537 actionstream << "'" << player->getName()
1538 << "' submitted formspec ('" << client_formspec_name
1539 << "') but server hasn't sent formspec to client";
1541 actionstream << ", possible exploitation attempt" << std::endl;
1544 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1546 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1547 ClientState cstate = client->getState();
1549 std::string playername = client->getName();
1552 std::string verification_key;
1554 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1557 *pkt >> salt >> verification_key >> is_empty;
1559 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1560 << ", with is_empty=" << (is_empty == 1) << std::endl;
1562 // Either this packet is sent because the user is new or to change the password
1563 if (cstate == CS_HelloSent) {
1564 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1565 actionstream << "Server: Client from " << addr_s
1566 << " tried to set password without being "
1567 << "authenticated, or the username being new." << std::endl;
1568 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1572 if (!isSingleplayer() &&
1573 g_settings->getBool("disallow_empty_password") &&
1575 actionstream << "Server: " << playername
1576 << " supplied empty password from " << addr_s << std::endl;
1577 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1581 std::string initial_ver_key;
1583 initial_ver_key = encode_srp_verifier(verification_key, salt);
1584 m_script->createAuth(playername, initial_ver_key);
1586 acceptAuth(pkt->getPeerId(), false);
1588 if (cstate < CS_SudoMode) {
1589 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1590 << addr_s << ": " << "Client has wrong state " << cstate << "."
1594 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1595 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1596 bool success = m_script->setPassword(playername, pw_db_field);
1598 actionstream << playername << " changes password" << std::endl;
1599 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1600 L"Password change successful."));
1602 actionstream << playername << " tries to change password but "
1603 << "it fails" << std::endl;
1604 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1605 L"Password change failed or unavailable."));
1610 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1612 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1613 ClientState cstate = client->getState();
1615 bool wantSudo = (cstate == CS_Active);
1617 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1618 actionstream << "Server: got SRP _A packet in wrong state "
1619 << cstate << " from "
1620 << getPeerAddress(pkt->getPeerId()).serializeString()
1621 << ". Ignoring." << std::endl;
1625 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1626 actionstream << "Server: got SRP _A packet, while auth"
1627 << "is already going on with mech " << client->chosen_mech
1628 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1629 << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1631 DenySudoAccess(pkt->getPeerId());
1635 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1639 std::string bytes_A;
1641 *pkt >> bytes_A >> based_on;
1643 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1644 << "based_on=" << int(based_on) << " and len_A="
1645 << bytes_A.length() << "." << std::endl;
1647 AuthMechanism chosen = (based_on == 0) ?
1648 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1651 if (!client->isSudoMechAllowed(chosen)) {
1652 actionstream << "Server: Player \"" << client->getName()
1653 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1654 << " tried to change password using unallowed mech "
1655 << chosen << "." << std::endl;
1656 DenySudoAccess(pkt->getPeerId());
1660 if (!client->isMechAllowed(chosen)) {
1661 actionstream << "Server: Client tried to authenticate from "
1662 << getPeerAddress(pkt->getPeerId()).serializeString()
1663 << " using unallowed mech " << chosen << "." << std::endl;
1664 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1669 client->chosen_mech = chosen;
1672 std::string verifier;
1674 if (based_on == 0) {
1676 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1678 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1679 // Non-base64 errors should have been catched in the init handler
1680 actionstream << "Server: User " << client->getName()
1681 << " tried to log in, but srp verifier field"
1682 << " was invalid (most likely invalid base64)." << std::endl;
1683 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1690 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1691 client->getName().c_str(),
1692 (const unsigned char *) salt.c_str(), salt.size(),
1693 (const unsigned char *) verifier.c_str(), verifier.size(),
1694 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1696 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1699 actionstream << "Server: User " << client->getName()
1700 << " tried to log in, SRP-6a safety check violated in _A handler."
1703 DenySudoAccess(pkt->getPeerId());
1707 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1711 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1712 resp_pkt << salt << std::string(bytes_B, len_B);
1716 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1718 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1719 ClientState cstate = client->getState();
1721 bool wantSudo = (cstate == CS_Active);
1723 verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
1725 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1726 actionstream << "Server: got SRP _M packet in wrong state "
1727 << cstate << " from "
1728 << getPeerAddress(pkt->getPeerId()).serializeString()
1729 << ". Ignoring." << std::endl;
1733 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1734 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1735 actionstream << "Server: got SRP _M packet, while auth"
1736 << "is going on with mech " << client->chosen_mech
1737 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1738 << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1740 DenySudoAccess(pkt->getPeerId());
1744 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1748 std::string bytes_M;
1751 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1752 != bytes_M.size()) {
1753 actionstream << "Server: User " << client->getName()
1754 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1755 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1756 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1760 unsigned char *bytes_HAMK = 0;
1762 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1763 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1767 actionstream << "Server: User " << client->getName()
1768 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1769 << " tried to change their password, but supplied wrong"
1770 << " (SRP) password for authentication." << std::endl;
1771 DenySudoAccess(pkt->getPeerId());
1775 std::string ip = getPeerAddress(pkt->getPeerId()).serializeString();
1776 actionstream << "Server: User " << client->getName()
1778 << " supplied wrong password (auth mechanism: SRP)."
1780 m_script->on_auth_failure(client->getName(), ip);
1781 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
1785 if (client->create_player_on_auth_success) {
1786 std::string playername = client->getName();
1787 m_script->createAuth(playername, client->enc_pwd);
1789 std::string checkpwd; // not used, but needed for passing something
1790 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1791 actionstream << "Server: " << playername << " cannot be authenticated"
1792 << " (auth handler does not work?)" << std::endl;
1793 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1796 client->create_player_on_auth_success = false;
1799 acceptAuth(pkt->getPeerId(), wantSudo);
1806 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1808 std::string channel_name;
1809 *pkt >> channel_name;
1811 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1814 // Send signal to client to notify join succeed or not
1815 if (g_settings->getBool("enable_mod_channels") &&
1816 m_modchannel_mgr->joinChannel(channel_name, pkt->getPeerId())) {
1817 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1818 infostream << "Peer " << pkt->getPeerId() << " joined channel " << channel_name
1822 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1823 infostream << "Peer " << pkt->getPeerId() << " tried to join channel "
1824 << channel_name << ", but was already registered." << std::endl;
1826 resp_pkt << channel_name;
1830 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1832 std::string channel_name;
1833 *pkt >> channel_name;
1835 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1838 // Send signal to client to notify join succeed or not
1839 if (g_settings->getBool("enable_mod_channels") &&
1840 m_modchannel_mgr->leaveChannel(channel_name, pkt->getPeerId())) {
1841 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1842 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1845 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1846 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1847 << ", but was not registered." << std::endl;
1849 resp_pkt << channel_name;
1853 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1855 std::string channel_name, channel_msg;
1856 *pkt >> channel_name >> channel_msg;
1858 verbosestream << "Mod channel message received from peer " << pkt->getPeerId()
1859 << " on channel " << channel_name << " message: " << channel_msg << std::endl;
1861 // If mod channels are not enabled, discard message
1862 if (!g_settings->getBool("enable_mod_channels")) {
1866 // If channel not registered, signal it and ignore message
1867 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1868 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1870 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1875 // @TODO: filter, rate limit
1877 broadcastModChannelMessage(channel_name, channel_msg, pkt->getPeerId());