3 Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "chatmessage.h"
25 #include "modchannels.h"
27 #include "remoteplayer.h"
28 #include "rollback_interface.h"
29 #include "scripting_server.h"
33 #include "network/connection.h"
34 #include "network/networkprotocol.h"
35 #include "network/serveropcodes.h"
36 #include "server/player_sao.h"
37 #include "server/serverinventorymgr.h"
38 #include "util/auth.h"
39 #include "util/base64.h"
40 #include "util/pointedthing.h"
41 #include "util/serialize.h"
44 void Server::handleCommand_Deprecated(NetworkPacket* pkt)
46 infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
47 << " not supported anymore" << std::endl;
50 void Server::handleCommand_Init(NetworkPacket* pkt)
53 if(pkt->getSize() < 1)
56 session_t peer_id = pkt->getPeerId();
57 RemoteClient *client = getClient(peer_id, CS_Created);
62 addr = m_con->GetPeerAddress(peer_id);
63 addr_s = addr.serializeString();
64 } catch (con::PeerNotFoundException &e) {
66 * no peer for this packet found
67 * most common reason is peer timeout, e.g. peer didn't
68 * respond for some time, your server was overloaded or
71 infostream << "Server::ProcessData(): Canceling: peer " << peer_id <<
72 " not found" << std::endl;
76 if (client->getState() > CS_Created) {
77 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " <<
78 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
82 client->setCachedAddress(addr);
84 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s <<
85 " (peer_id=" << peer_id << ")" << std::endl;
87 // Do not allow multiple players in simple singleplayer mode.
88 // This isn't a perfect way to do it, but will suffice for now
89 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
90 infostream << "Server: Not allowing another client (" << addr_s <<
91 ") to connect in simple singleplayer mode" << std::endl;
92 DenyAccess(peer_id, SERVER_ACCESSDENIED_SINGLEPLAYER);
96 // First byte after command is maximum supported
97 // serialization version
100 u16 min_net_proto_version = 0;
101 u16 max_net_proto_version;
102 std::string playerName;
104 *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
105 >> max_net_proto_version >> playerName;
107 u8 our_max = SER_FMT_VER_HIGHEST_READ;
108 // Use the highest version supported by both
109 u8 depl_serial_v = std::min(client_max, our_max);
110 // If it's lower than the lowest supported, give up.
111 if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
112 depl_serial_v = SER_FMT_VER_INVALID;
114 if (depl_serial_v == SER_FMT_VER_INVALID) {
115 actionstream << "Server: A mismatched client tried to connect from " <<
116 addr_s << " ser_fmt_max=" << (int)client_max << std::endl;
117 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
121 client->setPendingSerializationVersion(depl_serial_v);
124 Read and check network protocol version
127 u16 net_proto_version = 0;
129 // Figure out a working version if it is possible at all
130 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
131 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
132 // If maximum is larger than our maximum, go with our maximum
133 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
134 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
135 // Else go with client's maximum
137 net_proto_version = max_net_proto_version;
140 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
141 << min_net_proto_version << ", max: " << max_net_proto_version
142 << ", chosen: " << net_proto_version << std::endl;
144 client->net_proto_version = net_proto_version;
146 if ((g_settings->getBool("strict_protocol_version_checking") &&
147 net_proto_version != LATEST_PROTOCOL_VERSION) ||
148 net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
149 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
150 actionstream << "Server: A mismatched client tried to connect from " <<
151 addr_s << " proto_max=" << (int)max_net_proto_version << std::endl;
152 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
159 const char* playername = playerName.c_str();
161 size_t pns = playerName.size();
162 if (pns == 0 || pns > PLAYERNAME_SIZE) {
163 actionstream << "Server: Player with " <<
164 ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty") <<
165 " name tried to connect from " << addr_s << std::endl;
166 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
170 if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
171 actionstream << "Server: Player with an invalid name tried to connect "
172 "from " << addr_s << std::endl;
173 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
177 RemotePlayer *player = m_env->getPlayer(playername);
179 // If player is already connected, cancel
180 if (player && player->getPeerId() != PEER_ID_INEXISTENT) {
181 actionstream << "Server: Player with name \"" << playername <<
182 "\" tried to connect, but player with same name is already connected" << std::endl;
183 DenyAccess(peer_id, SERVER_ACCESSDENIED_ALREADY_CONNECTED);
187 m_clients.setPlayerName(peer_id, playername);
188 //TODO (later) case insensitivity
190 std::string legacyPlayerNameCasing = playerName;
192 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
193 actionstream << "Server: Player with the name \"singleplayer\" tried "
194 "to connect from " << addr_s << std::endl;
195 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
201 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
202 actionstream << "Server: Player with the name \"" << playerName <<
203 "\" tried to connect from " << addr_s <<
204 " but it was disallowed for the following reason: " << reason <<
206 DenyAccess(peer_id, SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
211 infostream << "Server: New connection: \"" << playerName << "\" from " <<
212 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
214 // Enforce user limit.
215 // Don't enforce for users that have some admin right or mod permits it.
216 if (m_clients.isUserLimitReached() &&
217 playername != g_settings->get("name") &&
218 !m_script->can_bypass_userlimit(playername, addr_s)) {
219 actionstream << "Server: " << playername << " tried to join from " <<
220 addr_s << ", but there are already max_users=" <<
221 g_settings->getU16("max_users") << " players." << std::endl;
222 DenyAccess(peer_id, SERVER_ACCESSDENIED_TOO_MANY_USERS);
227 Compose auth methods for answer
229 std::string encpwd; // encrypted Password field for the user
230 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
233 client->chosen_mech = AUTH_MECHANISM_NONE;
236 std::vector<std::string> pwd_components = str_split(encpwd, '#');
237 if (pwd_components.size() == 4) {
238 if (pwd_components[1] == "1") { // 1 means srp
239 auth_mechs |= AUTH_MECHANISM_SRP;
240 client->enc_pwd = encpwd;
242 actionstream << "User " << playername << " tried to log in, "
243 "but password field was invalid (unknown mechcode)." <<
245 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
248 } else if (base64_is_valid(encpwd)) {
249 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
250 client->enc_pwd = encpwd;
252 actionstream << "User " << playername << " tried to log in, but "
253 "password field was invalid (invalid base64)." << std::endl;
254 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
258 std::string default_password = g_settings->get("default_password");
259 if (default_password.length() == 0) {
260 auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
262 // Take care of default passwords.
263 client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
264 auth_mechs |= AUTH_MECHANISM_SRP;
265 // Allocate player in db, but only on successful login.
266 client->create_player_on_auth_success = true;
271 Answer with a TOCLIENT_HELLO
274 verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
275 << auth_mechs << std::endl;
277 NetworkPacket resp_pkt(TOCLIENT_HELLO,
278 1 + 4 + legacyPlayerNameCasing.size(), peer_id);
280 u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
281 resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
282 << auth_mechs << legacyPlayerNameCasing;
286 client->allowed_auth_mechs = auth_mechs;
287 client->setDeployedCompressionMode(depl_compress_mode);
289 m_clients.event(peer_id, CSE_Hello);
292 void Server::handleCommand_Init2(NetworkPacket* pkt)
294 session_t peer_id = pkt->getPeerId();
295 verbosestream << "Server: Got TOSERVER_INIT2 from " << peer_id << std::endl;
297 m_clients.event(peer_id, CSE_GotInit2);
298 u16 protocol_version = m_clients.getProtocolVersion(peer_id);
301 if (pkt->getSize() > 0)
305 Send some initialization data
308 infostream << "Server: Sending content to " << getPlayerName(peer_id) <<
311 // Send item definitions
312 SendItemDef(peer_id, m_itemdef, protocol_version);
314 // Send node definitions
315 SendNodeDef(peer_id, m_nodedef, protocol_version);
317 m_clients.event(peer_id, CSE_SetDefinitionsSent);
319 // Send media announcement
320 sendMediaAnnouncement(peer_id, lang);
322 RemoteClient *client = getClient(peer_id, CS_InitDone);
324 // Keep client language for server translations
325 client->setLangCode(lang);
327 // Send active objects
329 PlayerSAO *sao = getPlayerSAO(peer_id);
331 SendActiveObjectRemoveAdd(client, sao);
334 // Send detached inventories
335 sendDetachedInventories(peer_id, false);
337 // Send player movement settings
338 SendMovement(peer_id);
341 u16 time = m_env->getTimeOfDay();
342 float time_speed = g_settings->getFloat("time_speed");
343 SendTimeOfDay(peer_id, time, time_speed);
345 SendCSMRestrictionFlags(peer_id);
347 // Warnings about protocol version can be issued here
348 if (client->net_proto_version < LATEST_PROTOCOL_VERSION) {
349 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
350 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
351 L"WITH THIS SERVER!"));
355 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
357 std::vector<std::string> tosend;
362 session_t peer_id = pkt->getPeerId();
363 infostream << "Sending " << numfiles << " files to " <<
364 getPlayerName(peer_id) << std::endl;
365 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file(s)" << std::endl;
367 for (u16 i = 0; i < numfiles; i++) {
372 tosend.emplace_back(name);
373 verbosestream << " " << name << std::endl;
376 sendRequestedMedia(peer_id, tosend);
379 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
381 session_t peer_id = pkt->getPeerId();
383 PlayerSAO* playersao = StageTwoClientInit(peer_id);
385 if (playersao == NULL) {
386 errorstream << "TOSERVER_CLIENT_READY stage 2 client init failed "
387 "peer_id=" << peer_id << std::endl;
388 DisconnectPeer(peer_id);
393 if (pkt->getSize() < 8) {
394 errorstream << "TOSERVER_CLIENT_READY client sent inconsistent data, "
395 "disconnecting peer_id: " << peer_id << std::endl;
396 DisconnectPeer(peer_id);
400 u8 major_ver, minor_ver, patch_ver, reserved;
401 std::string full_ver;
402 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
404 m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver,
407 if (pkt->getRemainingBytes() >= 2)
408 *pkt >> playersao->getPlayer()->formspec_version;
410 const std::vector<std::string> &players = m_clients.getPlayerNames();
411 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
412 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
413 for (const std::string &player: players) {
416 m_clients.send(peer_id, 0, &list_pkt, true);
418 NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
419 // (u16) 1 + std::string represents a pseudo vector serialization representation
420 notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
421 m_clients.sendToAll(¬ice_pkt);
422 m_clients.event(peer_id, CSE_SetClientReady);
425 m_script->getAuth(playersao->getPlayer()->getName(), nullptr, nullptr, &last_login);
426 m_script->on_joinplayer(playersao, last_login);
428 // Send shutdown timer if shutdown has been scheduled
429 if (m_shutdown_state.isTimerRunning()) {
430 SendChatMessage(peer_id, m_shutdown_state.getShutdownTimerMessage());
434 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
436 if (pkt->getSize() < 1)
450 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
451 throw con::InvalidIncomingDataException
452 ("GOTBLOCKS length is too short");
456 RemoteClient *client = m_clients.lockedGetClientNoEx(pkt->getPeerId());
458 for (u16 i = 0; i < count; i++) {
466 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
469 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
473 s32 f32pitch, f32yaw;
481 f32 pitch = (f32)f32pitch / 100.0f;
482 f32 yaw = (f32)f32yaw / 100.0f;
485 // default behavior (in case an old client doesn't send these)
491 fov = (f32)f32fov / 80.0f;
492 *pkt >> wanted_range;
494 v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
495 v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
497 pitch = modulo360f(pitch);
498 yaw = wrapDegrees_0_360(yaw);
500 if (!playersao->isAttached()) {
501 // Only update player positions when moving freely
502 // to not interfere with attachment handling
503 playersao->setBasePosition(position);
504 player->setSpeed(speed);
506 playersao->setLookPitch(pitch);
507 playersao->setPlayerYaw(yaw);
508 playersao->setFov(fov);
509 playersao->setWantedRange(wanted_range);
511 player->keyPressed = keyPressed;
512 player->control.jump = (keyPressed & (0x1 << 4));
513 player->control.aux1 = (keyPressed & (0x1 << 5));
514 player->control.sneak = (keyPressed & (0x1 << 6));
515 player->control.dig = (keyPressed & (0x1 << 7));
516 player->control.place = (keyPressed & (0x1 << 8));
517 player->control.zoom = (keyPressed & (0x1 << 9));
519 if (playersao->checkMovementCheat()) {
521 m_script->on_cheat(playersao, "moved_too_fast");
522 SendMovePlayer(pkt->getPeerId());
526 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
528 session_t peer_id = pkt->getPeerId();
529 RemotePlayer *player = m_env->getPlayer(peer_id);
530 if (player == NULL) {
532 "Server::ProcessData(): Canceling: No player for peer_id=" <<
533 peer_id << " disconnecting peer!" << std::endl;
534 DisconnectPeer(peer_id);
538 PlayerSAO *playersao = player->getPlayerSAO();
539 if (playersao == NULL) {
541 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
542 peer_id << " disconnecting peer!" << std::endl;
543 DisconnectPeer(peer_id);
547 // If player is dead we don't care of this packet
548 if (playersao->isDead()) {
549 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
550 << " is dead. Ignoring packet";
554 process_PlayerPos(player, playersao, pkt);
557 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
559 if (pkt->getSize() < 1)
573 RemoteClient *client = getClient(pkt->getPeerId());
575 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
576 throw con::InvalidIncomingDataException
577 ("DELETEDBLOCKS length is too short");
580 for (u16 i = 0; i < count; i++) {
583 client->SetBlockNotSent(p);
587 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
589 session_t peer_id = pkt->getPeerId();
590 RemotePlayer *player = m_env->getPlayer(peer_id);
592 if (player == NULL) {
594 "Server::ProcessData(): Canceling: No player for peer_id=" <<
595 peer_id << " disconnecting peer!" << std::endl;
596 DisconnectPeer(peer_id);
600 PlayerSAO *playersao = player->getPlayerSAO();
601 if (playersao == NULL) {
603 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
604 peer_id << " disconnecting peer!" << std::endl;
605 DisconnectPeer(peer_id);
609 // Strip command and create a stream
610 std::string datastring(pkt->getString(0), pkt->getSize());
611 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
613 std::istringstream is(datastring, std::ios_base::binary);
615 std::unique_ptr<InventoryAction> a(InventoryAction::deSerialize(is));
617 infostream << "TOSERVER_INVENTORY_ACTION: "
618 << "InventoryAction::deSerialize() returned NULL"
623 // If something goes wrong, this player is to blame
624 RollbackScopeActor rollback_scope(m_rollback,
625 std::string("player:")+player->getName());
628 Note: Always set inventory not sent, to repair cases
629 where the client made a bad prediction.
632 const bool player_has_interact = checkPriv(player->getName(), "interact");
634 auto check_inv_access = [player, player_has_interact, this] (
635 const InventoryLocation &loc) -> bool {
637 // Players without interact may modify their own inventory
638 if (!player_has_interact && loc.type != InventoryLocation::PLAYER) {
639 infostream << "Cannot modify foreign inventory: "
640 << "No interact privilege" << std::endl;
645 case InventoryLocation::CURRENT_PLAYER:
646 // Only used internally on the client, never sent
648 case InventoryLocation::PLAYER:
649 // Allow access to own inventory in all cases
650 return loc.name == player->getName();
651 case InventoryLocation::NODEMETA:
653 // Check for out-of-range interaction
654 v3f node_pos = intToFloat(loc.p, BS);
655 v3f player_pos = player->getPlayerSAO()->getEyePosition();
656 f32 d = player_pos.getDistanceFrom(node_pos);
657 return checkInteractDistance(player, d, "inventory");
659 case InventoryLocation::DETACHED:
660 return getInventoryMgr()->checkDetachedInventoryAccess(loc, player->getName());
667 Handle restrictions and special cases of the move action
669 if (a->getType() == IAction::Move) {
670 IMoveAction *ma = (IMoveAction*)a.get();
672 ma->from_inv.applyCurrentPlayer(player->getName());
673 ma->to_inv.applyCurrentPlayer(player->getName());
675 m_inventory_mgr->setInventoryModified(ma->from_inv);
676 if (ma->from_inv != ma->to_inv)
677 m_inventory_mgr->setInventoryModified(ma->to_inv);
679 if (!check_inv_access(ma->from_inv) ||
680 !check_inv_access(ma->to_inv))
684 Disable moving items out of craftpreview
686 if (ma->from_list == "craftpreview") {
687 infostream << "Ignoring IMoveAction from "
688 << (ma->from_inv.dump()) << ":" << ma->from_list
689 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
690 << " because src is " << ma->from_list << std::endl;
695 Disable moving items into craftresult and craftpreview
697 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
698 infostream << "Ignoring IMoveAction from "
699 << (ma->from_inv.dump()) << ":" << ma->from_list
700 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
701 << " because dst is " << ma->to_list << std::endl;
706 Handle restrictions and special cases of the drop action
708 else if (a->getType() == IAction::Drop) {
709 IDropAction *da = (IDropAction*)a.get();
711 da->from_inv.applyCurrentPlayer(player->getName());
713 m_inventory_mgr->setInventoryModified(da->from_inv);
716 Disable dropping items out of craftpreview
718 if (da->from_list == "craftpreview") {
719 infostream << "Ignoring IDropAction from "
720 << (da->from_inv.dump()) << ":" << da->from_list
721 << " because src is " << da->from_list << std::endl;
725 // Disallow dropping items if not allowed to interact
726 if (!player_has_interact || !check_inv_access(da->from_inv))
729 // Disallow dropping items if dead
730 if (playersao->isDead()) {
731 infostream << "Ignoring IDropAction from "
732 << (da->from_inv.dump()) << ":" << da->from_list
733 << " because player is dead." << std::endl;
738 Handle restrictions and special cases of the craft action
740 else if (a->getType() == IAction::Craft) {
741 ICraftAction *ca = (ICraftAction*)a.get();
743 ca->craft_inv.applyCurrentPlayer(player->getName());
745 m_inventory_mgr->setInventoryModified(ca->craft_inv);
747 // Disallow crafting if not allowed to interact
748 if (!player_has_interact) {
749 infostream << "Cannot craft: "
750 << "No interact privilege" << std::endl;
754 if (!check_inv_access(ca->craft_inv))
757 // Unknown action. Ignored.
762 a->apply(m_inventory_mgr.get(), playersao, this);
765 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
767 std::wstring message;
770 session_t peer_id = pkt->getPeerId();
771 RemotePlayer *player = m_env->getPlayer(peer_id);
772 if (player == NULL) {
774 "Server::ProcessData(): Canceling: No player for peer_id=" <<
775 peer_id << " disconnecting peer!" << std::endl;
776 DisconnectPeer(peer_id);
780 std::string name = player->getName();
782 std::wstring answer_to_sender = handleChat(name, message, true, player);
783 if (!answer_to_sender.empty()) {
784 // Send the answer to sender
785 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
790 void Server::handleCommand_Damage(NetworkPacket* pkt)
796 session_t peer_id = pkt->getPeerId();
797 RemotePlayer *player = m_env->getPlayer(peer_id);
799 if (player == NULL) {
801 "Server::ProcessData(): Canceling: No player for peer_id=" <<
802 peer_id << " disconnecting peer!" << std::endl;
803 DisconnectPeer(peer_id);
807 PlayerSAO *playersao = player->getPlayerSAO();
808 if (playersao == NULL) {
810 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
811 peer_id << " disconnecting peer!" << std::endl;
812 DisconnectPeer(peer_id);
816 if (!playersao->isImmortal()) {
817 if (playersao->isDead()) {
818 verbosestream << "Server::ProcessData(): Info: "
819 "Ignoring damage as player " << player->getName()
820 << " is already dead." << std::endl;
824 actionstream << player->getName() << " damaged by "
825 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
828 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
829 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
833 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
835 if (pkt->getSize() < 2)
838 session_t peer_id = pkt->getPeerId();
839 RemotePlayer *player = m_env->getPlayer(peer_id);
841 if (player == NULL) {
843 "Server::ProcessData(): Canceling: No player for peer_id=" <<
844 peer_id << " disconnecting peer!" << std::endl;
845 DisconnectPeer(peer_id);
849 PlayerSAO *playersao = player->getPlayerSAO();
850 if (playersao == NULL) {
852 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
853 peer_id << " disconnecting peer!" << std::endl;
854 DisconnectPeer(peer_id);
862 if (item >= player->getHotbarItemcount()) {
863 actionstream << "Player: " << player->getName()
864 << " tried to access item=" << item
865 << " out of hotbar_itemcount="
866 << player->getHotbarItemcount()
867 << "; ignoring." << std::endl;
871 playersao->getPlayer()->setWieldIndex(item);
874 void Server::handleCommand_Respawn(NetworkPacket* pkt)
876 session_t peer_id = pkt->getPeerId();
877 RemotePlayer *player = m_env->getPlayer(peer_id);
878 if (player == NULL) {
880 "Server::ProcessData(): Canceling: No player for peer_id=" <<
881 peer_id << " disconnecting peer!" << std::endl;
882 DisconnectPeer(peer_id);
886 PlayerSAO *playersao = player->getPlayerSAO();
889 if (!playersao->isDead())
892 RespawnPlayer(peer_id);
894 actionstream << player->getName() << " respawns at "
895 << PP(playersao->getBasePosition() / BS) << std::endl;
897 // ActiveObject is added to environment in AsyncRunStep after
898 // the previous addition has been successfully removed
901 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
903 ItemStack selected_item, hand_item;
904 player->getWieldedItem(&selected_item, &hand_item);
905 f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
906 hand_item.getDefinition(m_itemdef));
908 // Cube diagonal * 1.5 for maximal supported node extents:
909 // sqrt(3) * 1.5 ≅ 2.6
910 if (d > max_d + 2.6f * BS) {
911 actionstream << "Player " << player->getName()
912 << " tried to access " << what
914 << "d=" << d << ", max_d=" << max_d
915 << "; ignoring." << std::endl;
917 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
923 void Server::handleCommand_Interact(NetworkPacket *pkt)
929 [5] u32 length of the next item (plen)
930 [9] serialized PointedThing
931 [9 + plen] player position information
934 InteractAction action;
937 *pkt >> (u8 &)action;
940 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
941 PointedThing pointed;
942 pointed.deSerialize(tmp_is);
944 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
945 << item_i << ", pointed=" << pointed.dump() << std::endl;
947 session_t peer_id = pkt->getPeerId();
948 RemotePlayer *player = m_env->getPlayer(peer_id);
950 if (player == NULL) {
952 "Server::ProcessData(): Canceling: No player for peer_id=" <<
953 peer_id << " disconnecting peer!" << std::endl;
954 DisconnectPeer(peer_id);
958 PlayerSAO *playersao = player->getPlayerSAO();
959 if (playersao == NULL) {
961 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
962 peer_id << " disconnecting peer!" << std::endl;
963 DisconnectPeer(peer_id);
967 if (playersao->isDead()) {
968 actionstream << "Server: " << player->getName()
969 << " tried to interact while dead; ignoring." << std::endl;
970 if (pointed.type == POINTEDTHING_NODE) {
971 // Re-send block to revert change on client-side
972 RemoteClient *client = getClient(peer_id);
973 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
974 client->SetBlockNotSent(blockpos);
977 m_script->on_cheat(playersao, "interacted_while_dead");
981 process_PlayerPos(player, playersao, pkt);
983 v3f player_pos = playersao->getLastGoodPosition();
985 // Update wielded item
987 if (item_i >= player->getHotbarItemcount()) {
988 actionstream << "Player: " << player->getName()
989 << " tried to access item=" << item_i
990 << " out of hotbar_itemcount="
991 << player->getHotbarItemcount()
992 << "; ignoring." << std::endl;
996 playersao->getPlayer()->setWieldIndex(item_i);
998 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
999 ServerActiveObject *pointed_object = NULL;
1000 if (pointed.type == POINTEDTHING_OBJECT) {
1001 pointed_object = m_env->getActiveObject(pointed.object_id);
1002 if (pointed_object == NULL) {
1003 verbosestream << "TOSERVER_INTERACT: "
1004 "pointed object is NULL" << std::endl;
1011 Make sure the player is allowed to do it
1013 if (!checkPriv(player->getName(), "interact")) {
1014 actionstream << player->getName() << " attempted to interact with " <<
1015 pointed.dump() << " without 'interact' privilege" << std::endl;
1017 if (pointed.type != POINTEDTHING_NODE)
1020 // Re-send block to revert change on client-side
1021 RemoteClient *client = getClient(peer_id);
1022 // Digging completed -> under
1023 if (action == INTERACT_DIGGING_COMPLETED) {
1024 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1025 client->SetBlockNotSent(blockpos);
1027 // Placement -> above
1028 else if (action == INTERACT_PLACE) {
1029 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1030 client->SetBlockNotSent(blockpos);
1036 Check that target is reasonably close
1038 static thread_local const bool enable_anticheat =
1039 !g_settings->getBool("disable_anticheat");
1041 if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1042 action == INTERACT_PLACE || action == INTERACT_USE) &&
1043 enable_anticheat && !isSingleplayer()) {
1044 v3f target_pos = player_pos;
1045 if (pointed.type == POINTEDTHING_NODE) {
1046 target_pos = intToFloat(pointed.node_undersurface, BS);
1047 } else if (pointed.type == POINTEDTHING_OBJECT) {
1048 if (playersao->getId() == pointed_object->getId()) {
1049 actionstream << "Server: " << player->getName()
1050 << " attempted to interact with themselves" << std::endl;
1051 m_script->on_cheat(playersao, "interacted_with_self");
1054 target_pos = pointed_object->getBasePosition();
1056 float d = playersao->getEyePosition().getDistanceFrom(target_pos);
1058 if (!checkInteractDistance(player, d, pointed.dump())) {
1059 if (pointed.type == POINTEDTHING_NODE) {
1060 // Re-send block to revert change on client-side
1061 RemoteClient *client = getClient(peer_id);
1062 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1063 client->SetBlockNotSent(blockpos);
1070 If something goes wrong, this player is to blame
1072 RollbackScopeActor rollback_scope(m_rollback,
1073 std::string("player:")+player->getName());
1076 // Start digging or punch object
1077 case INTERACT_START_DIGGING: {
1078 if (pointed.type == POINTEDTHING_NODE) {
1079 MapNode n(CONTENT_IGNORE);
1082 v3s16 p_under = pointed.node_undersurface;
1083 n = m_env->getMap().getNode(p_under, &pos_ok);
1085 infostream << "Server: Not punching: Node not found. "
1086 "Adding block to emerge queue." << std::endl;
1087 m_emerge->enqueueBlockEmerge(peer_id,
1088 getNodeBlockPos(pointed.node_abovesurface), false);
1091 if (n.getContent() != CONTENT_IGNORE)
1092 m_script->node_on_punch(p_under, n, playersao, pointed);
1095 playersao->noCheatDigStart(p_under);
1100 // Skip if the object can't be interacted with anymore
1101 if (pointed.type != POINTEDTHING_OBJECT || pointed_object->isGone())
1104 ItemStack selected_item, hand_item;
1105 ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
1106 ToolCapabilities toolcap =
1107 tool_item.getToolCapabilities(m_itemdef);
1108 v3f dir = (pointed_object->getBasePosition() -
1109 (playersao->getBasePosition() + playersao->getEyeOffset())
1111 float time_from_last_punch =
1112 playersao->resetTimeFromLastPunch();
1114 u16 wear = pointed_object->punch(dir, &toolcap, playersao,
1115 time_from_last_punch);
1117 // Callback may have changed item, so get it again
1118 playersao->getWieldedItem(&selected_item);
1119 bool changed = selected_item.addWear(wear, m_itemdef);
1121 playersao->setWieldedItem(selected_item);
1124 } // action == INTERACT_START_DIGGING
1126 case INTERACT_STOP_DIGGING:
1130 case INTERACT_DIGGING_COMPLETED: {
1131 // Only digging of nodes
1132 if (pointed.type != POINTEDTHING_NODE)
1135 v3s16 p_under = pointed.node_undersurface;
1136 MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1138 infostream << "Server: Not finishing digging: Node not found. "
1139 "Adding block to emerge queue." << std::endl;
1140 m_emerge->enqueueBlockEmerge(peer_id,
1141 getNodeBlockPos(pointed.node_abovesurface), false);
1144 /* Cheat prevention */
1145 bool is_valid_dig = true;
1146 if (enable_anticheat && !isSingleplayer()) {
1147 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1148 float nocheat_t = playersao->getNoCheatDigTime();
1149 playersao->noCheatDigEnd();
1150 // If player didn't start digging this, ignore dig
1151 if (nocheat_p != p_under) {
1152 infostream << "Server: " << player->getName()
1153 << " started digging "
1154 << PP(nocheat_p) << " and completed digging "
1155 << PP(p_under) << "; not digging." << std::endl;
1156 is_valid_dig = false;
1158 m_script->on_cheat(playersao, "finished_unknown_dig");
1161 // Get player's wielded item
1162 // See also: Game::handleDigging
1163 ItemStack selected_item, hand_item;
1164 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1166 // Get diggability and expected digging time
1167 DigParams params = getDigParams(m_nodedef->get(n).groups,
1168 &selected_item.getToolCapabilities(m_itemdef));
1169 // If can't dig, try hand
1170 if (!params.diggable) {
1171 params = getDigParams(m_nodedef->get(n).groups,
1172 &hand_item.getToolCapabilities(m_itemdef));
1174 // If can't dig, ignore dig
1175 if (!params.diggable) {
1176 infostream << "Server: " << player->getName()
1177 << " completed digging " << PP(p_under)
1178 << ", which is not diggable with tool; not digging."
1180 is_valid_dig = false;
1182 m_script->on_cheat(playersao, "dug_unbreakable");
1184 // Check digging time
1185 // If already invalidated, we don't have to
1186 if (!is_valid_dig) {
1187 // Well not our problem then
1189 // Clean and long dig
1190 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1191 // All is good, but grab time from pool; don't care if
1192 // it's actually available
1193 playersao->getDigPool().grab(params.time);
1195 // Short or laggy dig
1196 // Try getting the time from pool
1197 else if (playersao->getDigPool().grab(params.time)) {
1202 infostream << "Server: " << player->getName()
1203 << " completed digging " << PP(p_under)
1204 << "too fast; not digging." << std::endl;
1205 is_valid_dig = false;
1207 m_script->on_cheat(playersao, "dug_too_fast");
1211 /* Actually dig node */
1213 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1214 m_script->node_on_dig(p_under, n, playersao);
1216 v3s16 blockpos = getNodeBlockPos(p_under);
1217 RemoteClient *client = getClient(peer_id);
1218 // Send unusual result (that is, node not being removed)
1219 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR)
1220 // Re-send block to revert change on client-side
1221 client->SetBlockNotSent(blockpos);
1223 client->ResendBlockIfOnWire(blockpos);
1226 } // action == INTERACT_DIGGING_COMPLETED
1228 // Place block or right-click object
1229 case INTERACT_PLACE: {
1230 ItemStack selected_item;
1231 playersao->getWieldedItem(&selected_item, nullptr);
1233 // Reset build time counter
1234 if (pointed.type == POINTEDTHING_NODE &&
1235 selected_item.getDefinition(m_itemdef).type == ITEM_NODE)
1236 getClient(peer_id)->m_time_from_building = 0.0;
1238 if (pointed.type == POINTEDTHING_OBJECT) {
1239 // Right click object
1241 // Skip if object can't be interacted with anymore
1242 if (pointed_object->isGone())
1245 actionstream << player->getName() << " right-clicks object "
1246 << pointed.object_id << ": "
1247 << pointed_object->getDescription() << std::endl;
1250 if (m_script->item_OnSecondaryUse(
1251 selected_item, playersao, pointed)) {
1252 if (playersao->setWieldedItem(selected_item)) {
1253 SendInventory(playersao, true);
1257 pointed_object->rightClick(playersao);
1258 } else if (m_script->item_OnPlace(selected_item, playersao, pointed)) {
1259 // Placement was handled in lua
1261 // Apply returned ItemStack
1262 if (playersao->setWieldedItem(selected_item))
1263 SendInventory(playersao, true);
1266 if (pointed.type != POINTEDTHING_NODE)
1269 // If item has node placement prediction, always send the
1270 // blocks to make sure the client knows what exactly happened
1271 RemoteClient *client = getClient(peer_id);
1272 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1273 v3s16 blockpos2 = getNodeBlockPos(pointed.node_undersurface);
1274 if (!selected_item.getDefinition(m_itemdef
1275 ).node_placement_prediction.empty()) {
1276 client->SetBlockNotSent(blockpos);
1277 if (blockpos2 != blockpos)
1278 client->SetBlockNotSent(blockpos2);
1280 client->ResendBlockIfOnWire(blockpos);
1281 if (blockpos2 != blockpos)
1282 client->ResendBlockIfOnWire(blockpos2);
1286 } // action == INTERACT_PLACE
1288 case INTERACT_USE: {
1289 ItemStack selected_item;
1290 playersao->getWieldedItem(&selected_item, nullptr);
1292 actionstream << player->getName() << " uses " << selected_item.name
1293 << ", pointing at " << pointed.dump() << std::endl;
1295 if (m_script->item_OnUse(selected_item, playersao, pointed)) {
1296 // Apply returned ItemStack
1297 if (playersao->setWieldedItem(selected_item))
1298 SendInventory(playersao, true);
1305 case INTERACT_ACTIVATE: {
1306 ItemStack selected_item;
1307 playersao->getWieldedItem(&selected_item, nullptr);
1309 actionstream << player->getName() << " activates "
1310 << selected_item.name << std::endl;
1312 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1314 if (m_script->item_OnSecondaryUse(selected_item, playersao, pointed)) {
1315 if (playersao->setWieldedItem(selected_item))
1316 SendInventory(playersao, true);
1323 warningstream << "Server: Invalid action " << action << std::endl;
1328 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1332 for (u16 k = 0; k < num; k++) {
1337 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1338 m_playing_sounds.find(id);
1339 if (i == m_playing_sounds.end())
1342 ServerPlayingSound &psound = i->second;
1343 psound.clients.erase(pkt->getPeerId());
1344 if (psound.clients.empty())
1345 m_playing_sounds.erase(i++);
1349 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1352 std::string formname;
1355 *pkt >> p >> formname >> num;
1358 for (u16 k = 0; k < num; k++) {
1359 std::string fieldname;
1361 fields[fieldname] = pkt->readLongString();
1364 session_t peer_id = pkt->getPeerId();
1365 RemotePlayer *player = m_env->getPlayer(peer_id);
1367 if (player == NULL) {
1369 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1370 peer_id << " disconnecting peer!" << std::endl;
1371 DisconnectPeer(peer_id);
1375 PlayerSAO *playersao = player->getPlayerSAO();
1376 if (playersao == NULL) {
1378 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1379 peer_id << " disconnecting peer!" << std::endl;
1380 DisconnectPeer(peer_id);
1384 // If something goes wrong, this player is to blame
1385 RollbackScopeActor rollback_scope(m_rollback,
1386 std::string("player:")+player->getName());
1388 // Check the target node for rollback data; leave others unnoticed
1389 RollbackNode rn_old(&m_env->getMap(), p, this);
1391 m_script->node_on_receive_fields(p, formname, fields, playersao);
1393 // Report rollback data
1394 RollbackNode rn_new(&m_env->getMap(), p, this);
1395 if (rollback() && rn_new != rn_old) {
1396 RollbackAction action;
1397 action.setSetNode(p, rn_old, rn_new);
1398 rollback()->reportAction(action);
1402 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1404 std::string client_formspec_name;
1407 *pkt >> client_formspec_name >> num;
1410 for (u16 k = 0; k < num; k++) {
1411 std::string fieldname;
1413 fields[fieldname] = pkt->readLongString();
1416 session_t peer_id = pkt->getPeerId();
1417 RemotePlayer *player = m_env->getPlayer(peer_id);
1419 if (player == NULL) {
1421 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1422 peer_id << " disconnecting peer!" << std::endl;
1423 DisconnectPeer(peer_id);
1427 PlayerSAO *playersao = player->getPlayerSAO();
1428 if (playersao == NULL) {
1430 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1431 peer_id << " disconnecting peer!" << std::endl;
1432 DisconnectPeer(peer_id);
1436 if (client_formspec_name.empty()) { // pass through inventory submits
1437 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1441 // verify that we displayed the formspec to the user
1442 const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1443 if (peer_state_iterator != m_formspec_state_data.end()) {
1444 const std::string &server_formspec_name = peer_state_iterator->second;
1445 if (client_formspec_name == server_formspec_name) {
1446 auto it = fields.find("quit");
1447 if (it != fields.end() && it->second == "true")
1448 m_formspec_state_data.erase(peer_state_iterator);
1450 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1453 actionstream << "'" << player->getName()
1454 << "' submitted formspec ('" << client_formspec_name
1455 << "') but the name of the formspec doesn't match the"
1456 " expected name ('" << server_formspec_name << "')";
1459 actionstream << "'" << player->getName()
1460 << "' submitted formspec ('" << client_formspec_name
1461 << "') but server hasn't sent formspec to client";
1463 actionstream << ", possible exploitation attempt" << std::endl;
1466 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1468 session_t peer_id = pkt->getPeerId();
1469 RemoteClient *client = getClient(peer_id, CS_Invalid);
1470 ClientState cstate = client->getState();
1472 std::string playername = client->getName();
1475 std::string verification_key;
1477 std::string addr_s = getPeerAddress(peer_id).serializeString();
1480 *pkt >> salt >> verification_key >> is_empty;
1482 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1483 << ", with is_empty=" << (is_empty == 1) << std::endl;
1485 // Either this packet is sent because the user is new or to change the password
1486 if (cstate == CS_HelloSent) {
1487 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1488 actionstream << "Server: Client from " << addr_s
1489 << " tried to set password without being "
1490 << "authenticated, or the username being new." << std::endl;
1491 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1495 if (!isSingleplayer() &&
1496 g_settings->getBool("disallow_empty_password") &&
1498 actionstream << "Server: " << playername
1499 << " supplied empty password from " << addr_s << std::endl;
1500 DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1504 std::string initial_ver_key;
1506 initial_ver_key = encode_srp_verifier(verification_key, salt);
1507 m_script->createAuth(playername, initial_ver_key);
1508 m_script->on_authplayer(playername, addr_s, true);
1510 acceptAuth(peer_id, false);
1512 if (cstate < CS_SudoMode) {
1513 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1514 << addr_s << ": " << "Client has wrong state " << cstate << "."
1518 m_clients.event(peer_id, CSE_SudoLeave);
1519 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1520 bool success = m_script->setPassword(playername, pw_db_field);
1522 actionstream << playername << " changes password" << std::endl;
1523 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1524 L"Password change successful."));
1526 actionstream << playername <<
1527 " tries to change password but it fails" << std::endl;
1528 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1529 L"Password change failed or unavailable."));
1534 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1536 session_t peer_id = pkt->getPeerId();
1537 RemoteClient *client = getClient(peer_id, CS_Invalid);
1538 ClientState cstate = client->getState();
1540 bool wantSudo = (cstate == CS_Active);
1542 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1543 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1544 " from " << getPeerAddress(peer_id).serializeString() <<
1545 ". Ignoring." << std::endl;
1549 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1550 actionstream << "Server: got SRP _A packet, while auth is already "
1551 "going on with mech " << client->chosen_mech << " from " <<
1552 getPeerAddress(peer_id).serializeString() <<
1553 " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1555 DenySudoAccess(peer_id);
1559 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1563 std::string bytes_A;
1565 *pkt >> bytes_A >> based_on;
1567 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1568 << "based_on=" << int(based_on) << " and len_A="
1569 << bytes_A.length() << "." << std::endl;
1571 AuthMechanism chosen = (based_on == 0) ?
1572 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1575 if (!client->isSudoMechAllowed(chosen)) {
1576 actionstream << "Server: Player \"" << client->getName() <<
1577 "\" at " << getPeerAddress(peer_id).serializeString() <<
1578 " tried to change password using unallowed mech " << chosen <<
1580 DenySudoAccess(peer_id);
1584 if (!client->isMechAllowed(chosen)) {
1585 actionstream << "Server: Client tried to authenticate from " <<
1586 getPeerAddress(peer_id).serializeString() <<
1587 " using unallowed mech " << chosen << "." << std::endl;
1588 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1593 client->chosen_mech = chosen;
1596 std::string verifier;
1598 if (based_on == 0) {
1600 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1602 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1603 // Non-base64 errors should have been catched in the init handler
1604 actionstream << "Server: User " << client->getName() <<
1605 " tried to log in, but srp verifier field was invalid (most likely "
1606 "invalid base64)." << std::endl;
1607 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1614 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1615 client->getName().c_str(),
1616 (const unsigned char *) salt.c_str(), salt.size(),
1617 (const unsigned char *) verifier.c_str(), verifier.size(),
1618 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1620 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1623 actionstream << "Server: User " << client->getName()
1624 << " tried to log in, SRP-6a safety check violated in _A handler."
1627 DenySudoAccess(peer_id);
1631 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1635 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1636 resp_pkt << salt << std::string(bytes_B, len_B);
1640 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1642 session_t peer_id = pkt->getPeerId();
1643 RemoteClient *client = getClient(peer_id, CS_Invalid);
1644 ClientState cstate = client->getState();
1645 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1646 std::string playername = client->getName();
1648 bool wantSudo = (cstate == CS_Active);
1650 verbosestream << "Server: Received TOSERVER_SRP_BYTES_M." << std::endl;
1652 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1653 warningstream << "Server: got SRP_M packet in wrong state "
1654 << cstate << " from " << addr_s << ". Ignoring." << std::endl;
1658 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1659 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1660 warningstream << "Server: got SRP_M packet, while auth "
1661 "is going on with mech " << client->chosen_mech << " from "
1662 << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1664 DenySudoAccess(peer_id);
1668 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1672 std::string bytes_M;
1675 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1676 != bytes_M.size()) {
1677 actionstream << "Server: User " << playername << " at " << addr_s
1678 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1679 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1683 unsigned char *bytes_HAMK = 0;
1685 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1686 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1690 actionstream << "Server: User " << playername << " at " << addr_s
1691 << " tried to change their password, but supplied wrong"
1692 << " (SRP) password for authentication." << std::endl;
1693 DenySudoAccess(peer_id);
1697 actionstream << "Server: User " << playername << " at " << addr_s
1698 << " supplied wrong password (auth mechanism: SRP)." << std::endl;
1699 m_script->on_authplayer(playername, addr_s, false);
1700 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1704 if (client->create_player_on_auth_success) {
1705 m_script->createAuth(playername, client->enc_pwd);
1707 std::string checkpwd; // not used, but needed for passing something
1708 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1709 errorstream << "Server: " << playername <<
1710 " cannot be authenticated (auth handler does not work?)" <<
1712 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1715 client->create_player_on_auth_success = false;
1718 m_script->on_authplayer(playername, addr_s, true);
1719 acceptAuth(peer_id, wantSudo);
1726 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1728 std::string channel_name;
1729 *pkt >> channel_name;
1731 session_t peer_id = pkt->getPeerId();
1732 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1733 1 + 2 + channel_name.size(), peer_id);
1735 // Send signal to client to notify join succeed or not
1736 if (g_settings->getBool("enable_mod_channels") &&
1737 m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1738 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1739 infostream << "Peer " << peer_id << " joined channel " <<
1740 channel_name << std::endl;
1743 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1744 infostream << "Peer " << peer_id << " tried to join channel " <<
1745 channel_name << ", but was already registered." << std::endl;
1747 resp_pkt << channel_name;
1751 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1753 std::string channel_name;
1754 *pkt >> channel_name;
1756 session_t peer_id = pkt->getPeerId();
1757 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1758 1 + 2 + channel_name.size(), peer_id);
1760 // Send signal to client to notify join succeed or not
1761 if (g_settings->getBool("enable_mod_channels") &&
1762 m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1763 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1764 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1767 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1768 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1769 ", but was not registered." << std::endl;
1771 resp_pkt << channel_name;
1775 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1777 std::string channel_name, channel_msg;
1778 *pkt >> channel_name >> channel_msg;
1780 session_t peer_id = pkt->getPeerId();
1781 verbosestream << "Mod channel message received from peer " << peer_id <<
1782 " on channel " << channel_name << " message: " << channel_msg <<
1785 // If mod channels are not enabled, discard message
1786 if (!g_settings->getBool("enable_mod_channels")) {
1790 // If channel not registered, signal it and ignore message
1791 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1792 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1793 1 + 2 + channel_name.size(), peer_id);
1794 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1799 // @TODO: filter, rate limit
1801 broadcastModChannelMessage(channel_name, channel_msg, peer_id);
1804 void Server::handleCommand_HaveMedia(NetworkPacket *pkt)
1806 std::vector<u32> tokens;
1810 for (u16 i = 0; i < numtokens; i++) {
1813 tokens.emplace_back(n);
1816 const session_t peer_id = pkt->getPeerId();
1817 auto player = m_env->getPlayer(peer_id);
1819 for (const u32 token : tokens) {
1820 auto it = m_pending_dyn_media.find(token);
1821 if (it == m_pending_dyn_media.end())
1823 if (it->second.waiting_players.count(peer_id)) {
1824 it->second.waiting_players.erase(peer_id);
1826 getScriptIface()->on_dynamic_media_added(token, player->getName());