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 m_clients.setPlayerName(peer_id, playername);
178 //TODO (later) case insensitivity
180 std::string legacyPlayerNameCasing = playerName;
182 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
183 actionstream << "Server: Player with the name \"singleplayer\" tried "
184 "to connect from " << addr_s << std::endl;
185 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
191 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
192 actionstream << "Server: Player with the name \"" << playerName <<
193 "\" tried to connect from " << addr_s <<
194 " but it was disallowed for the following reason: " << reason <<
196 DenyAccess(peer_id, SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
201 infostream << "Server: New connection: \"" << playerName << "\" from " <<
202 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
204 // Enforce user limit.
205 // Don't enforce for users that have some admin right or mod permits it.
206 if (m_clients.isUserLimitReached() &&
207 playername != g_settings->get("name") &&
208 !m_script->can_bypass_userlimit(playername, addr_s)) {
209 actionstream << "Server: " << playername << " tried to join from " <<
210 addr_s << ", but there are already max_users=" <<
211 g_settings->getU16("max_users") << " players." << std::endl;
212 DenyAccess(peer_id, SERVER_ACCESSDENIED_TOO_MANY_USERS);
217 Compose auth methods for answer
219 std::string encpwd; // encrypted Password field for the user
220 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
223 client->chosen_mech = AUTH_MECHANISM_NONE;
226 std::vector<std::string> pwd_components = str_split(encpwd, '#');
227 if (pwd_components.size() == 4) {
228 if (pwd_components[1] == "1") { // 1 means srp
229 auth_mechs |= AUTH_MECHANISM_SRP;
230 client->enc_pwd = encpwd;
232 actionstream << "User " << playername << " tried to log in, "
233 "but password field was invalid (unknown mechcode)." <<
235 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
238 } else if (base64_is_valid(encpwd)) {
239 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
240 client->enc_pwd = encpwd;
242 actionstream << "User " << playername << " tried to log in, but "
243 "password field was invalid (invalid base64)." << std::endl;
244 DenyAccess(peer_id, 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,
268 1 + 4 + legacyPlayerNameCasing.size(), peer_id);
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(peer_id, CSE_Hello);
282 void Server::handleCommand_Init2(NetworkPacket* pkt)
284 session_t peer_id = pkt->getPeerId();
285 verbosestream << "Server: Got TOSERVER_INIT2 from " << peer_id << std::endl;
287 m_clients.event(peer_id, CSE_GotInit2);
288 u16 protocol_version = m_clients.getProtocolVersion(peer_id);
291 if (pkt->getSize() > 0)
295 Send some initialization data
298 infostream << "Server: Sending content to " << getPlayerName(peer_id) <<
301 // Send item definitions
302 SendItemDef(peer_id, m_itemdef, protocol_version);
304 // Send node definitions
305 SendNodeDef(peer_id, m_nodedef, protocol_version);
307 m_clients.event(peer_id, CSE_SetDefinitionsSent);
309 // Send media announcement
310 sendMediaAnnouncement(peer_id, lang);
312 RemoteClient *client = getClient(peer_id, CS_InitDone);
314 // Keep client language for server translations
315 client->setLangCode(lang);
317 // Send active objects
319 PlayerSAO *sao = getPlayerSAO(peer_id);
321 SendActiveObjectRemoveAdd(client, sao);
324 // Send detached inventories
325 sendDetachedInventories(peer_id, false);
327 // Send player movement settings
328 SendMovement(peer_id);
331 u16 time = m_env->getTimeOfDay();
332 float time_speed = g_settings->getFloat("time_speed");
333 SendTimeOfDay(peer_id, time, time_speed);
335 SendCSMRestrictionFlags(peer_id);
337 // Warnings about protocol version can be issued here
338 if (client->net_proto_version < LATEST_PROTOCOL_VERSION) {
339 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
340 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
341 L"WITH THIS SERVER!"));
345 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
347 std::vector<std::string> tosend;
352 session_t peer_id = pkt->getPeerId();
353 infostream << "Sending " << numfiles << " files to " <<
354 getPlayerName(peer_id) << std::endl;
355 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
357 for (u16 i = 0; i < numfiles; i++) {
362 tosend.push_back(name);
363 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
364 << name << std::endl;
367 sendRequestedMedia(peer_id, tosend);
370 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
372 session_t peer_id = pkt->getPeerId();
374 PlayerSAO* playersao = StageTwoClientInit(peer_id);
376 if (playersao == NULL) {
377 errorstream << "TOSERVER_CLIENT_READY stage 2 client init failed "
378 "peer_id=" << peer_id << std::endl;
379 DisconnectPeer(peer_id);
384 if (pkt->getSize() < 8) {
385 errorstream << "TOSERVER_CLIENT_READY client sent inconsistent data, "
386 "disconnecting peer_id: " << peer_id << std::endl;
387 DisconnectPeer(peer_id);
391 u8 major_ver, minor_ver, patch_ver, reserved;
392 std::string full_ver;
393 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
395 m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver,
398 if (pkt->getRemainingBytes() >= 2)
399 *pkt >> playersao->getPlayer()->formspec_version;
401 const std::vector<std::string> &players = m_clients.getPlayerNames();
402 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
403 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
404 for (const std::string &player: players) {
407 m_clients.send(peer_id, 0, &list_pkt, true);
409 NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
410 // (u16) 1 + std::string represents a pseudo vector serialization representation
411 notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
412 m_clients.sendToAll(¬ice_pkt);
413 m_clients.event(peer_id, CSE_SetClientReady);
416 m_script->getAuth(playersao->getPlayer()->getName(), nullptr, nullptr, &last_login);
417 m_script->on_joinplayer(playersao, last_login);
419 // Send shutdown timer if shutdown has been scheduled
420 if (m_shutdown_state.isTimerRunning()) {
421 SendChatMessage(peer_id, m_shutdown_state.getShutdownTimerMessage());
425 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
427 if (pkt->getSize() < 1)
441 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
442 throw con::InvalidIncomingDataException
443 ("GOTBLOCKS length is too short");
447 RemoteClient *client = m_clients.lockedGetClientNoEx(pkt->getPeerId());
449 for (u16 i = 0; i < count; i++) {
457 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
460 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
464 s32 f32pitch, f32yaw;
472 f32 pitch = (f32)f32pitch / 100.0f;
473 f32 yaw = (f32)f32yaw / 100.0f;
476 // default behavior (in case an old client doesn't send these)
482 fov = (f32)f32fov / 80.0f;
483 *pkt >> wanted_range;
485 v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
486 v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
488 pitch = modulo360f(pitch);
489 yaw = wrapDegrees_0_360(yaw);
491 if (!playersao->isAttached()) {
492 // Only update player positions when moving freely
493 // to not interfere with attachment handling
494 playersao->setBasePosition(position);
495 player->setSpeed(speed);
497 playersao->setLookPitch(pitch);
498 playersao->setPlayerYaw(yaw);
499 playersao->setFov(fov);
500 playersao->setWantedRange(wanted_range);
502 player->keyPressed = keyPressed;
503 player->control.up = (keyPressed & (0x1 << 0));
504 player->control.down = (keyPressed & (0x1 << 1));
505 player->control.left = (keyPressed & (0x1 << 2));
506 player->control.right = (keyPressed & (0x1 << 3));
507 player->control.jump = (keyPressed & (0x1 << 4));
508 player->control.aux1 = (keyPressed & (0x1 << 5));
509 player->control.sneak = (keyPressed & (0x1 << 6));
510 player->control.dig = (keyPressed & (0x1 << 7));
511 player->control.place = (keyPressed & (0x1 << 8));
512 player->control.zoom = (keyPressed & (0x1 << 9));
514 if (playersao->checkMovementCheat()) {
516 m_script->on_cheat(playersao, "moved_too_fast");
517 SendMovePlayer(pkt->getPeerId());
521 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
523 session_t peer_id = pkt->getPeerId();
524 RemotePlayer *player = m_env->getPlayer(peer_id);
525 if (player == NULL) {
527 "Server::ProcessData(): Canceling: No player for peer_id=" <<
528 peer_id << " disconnecting peer!" << std::endl;
529 DisconnectPeer(peer_id);
533 PlayerSAO *playersao = player->getPlayerSAO();
534 if (playersao == NULL) {
536 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
537 peer_id << " disconnecting peer!" << std::endl;
538 DisconnectPeer(peer_id);
542 // If player is dead we don't care of this packet
543 if (playersao->isDead()) {
544 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
545 << " is dead. Ignoring packet";
549 process_PlayerPos(player, playersao, pkt);
552 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
554 if (pkt->getSize() < 1)
568 RemoteClient *client = getClient(pkt->getPeerId());
570 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
571 throw con::InvalidIncomingDataException
572 ("DELETEDBLOCKS length is too short");
575 for (u16 i = 0; i < count; i++) {
578 client->SetBlockNotSent(p);
582 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
584 session_t peer_id = pkt->getPeerId();
585 RemotePlayer *player = m_env->getPlayer(peer_id);
587 if (player == NULL) {
589 "Server::ProcessData(): Canceling: No player for peer_id=" <<
590 peer_id << " disconnecting peer!" << std::endl;
591 DisconnectPeer(peer_id);
595 PlayerSAO *playersao = player->getPlayerSAO();
596 if (playersao == NULL) {
598 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
599 peer_id << " disconnecting peer!" << std::endl;
600 DisconnectPeer(peer_id);
604 // Strip command and create a stream
605 std::string datastring(pkt->getString(0), pkt->getSize());
606 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
608 std::istringstream is(datastring, std::ios_base::binary);
610 std::unique_ptr<InventoryAction> a(InventoryAction::deSerialize(is));
612 infostream << "TOSERVER_INVENTORY_ACTION: "
613 << "InventoryAction::deSerialize() returned NULL"
618 // If something goes wrong, this player is to blame
619 RollbackScopeActor rollback_scope(m_rollback,
620 std::string("player:")+player->getName());
623 Note: Always set inventory not sent, to repair cases
624 where the client made a bad prediction.
627 const bool player_has_interact = checkPriv(player->getName(), "interact");
629 auto check_inv_access = [player, player_has_interact] (
630 const InventoryLocation &loc) -> bool {
631 if (loc.type == InventoryLocation::CURRENT_PLAYER)
632 return false; // Only used internally on the client, never sent
633 if (loc.type == InventoryLocation::PLAYER) {
634 // Allow access to own inventory in all cases
635 return loc.name == player->getName();
638 if (!player_has_interact) {
639 infostream << "Cannot modify foreign inventory: "
640 << "No interact privilege" << std::endl;
647 Handle restrictions and special cases of the move action
649 if (a->getType() == IAction::Move) {
650 IMoveAction *ma = (IMoveAction*)a.get();
652 ma->from_inv.applyCurrentPlayer(player->getName());
653 ma->to_inv.applyCurrentPlayer(player->getName());
655 m_inventory_mgr->setInventoryModified(ma->from_inv);
656 if (ma->from_inv != ma->to_inv)
657 m_inventory_mgr->setInventoryModified(ma->to_inv);
659 if (!check_inv_access(ma->from_inv) ||
660 !check_inv_access(ma->to_inv))
663 InventoryLocation *remote = ma->from_inv.type == InventoryLocation::PLAYER ?
664 &ma->to_inv : &ma->from_inv;
666 // Check for out-of-range interaction
667 if (remote->type == InventoryLocation::NODEMETA) {
668 v3f node_pos = intToFloat(remote->p, BS);
669 v3f player_pos = player->getPlayerSAO()->getEyePosition();
670 f32 d = player_pos.getDistanceFrom(node_pos);
671 if (!checkInteractDistance(player, d, "inventory"))
676 Disable moving items out of craftpreview
678 if (ma->from_list == "craftpreview") {
679 infostream << "Ignoring IMoveAction from "
680 << (ma->from_inv.dump()) << ":" << ma->from_list
681 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
682 << " because src is " << ma->from_list << std::endl;
687 Disable moving items into craftresult and craftpreview
689 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
690 infostream << "Ignoring IMoveAction from "
691 << (ma->from_inv.dump()) << ":" << ma->from_list
692 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
693 << " because dst is " << ma->to_list << std::endl;
698 Handle restrictions and special cases of the drop action
700 else if (a->getType() == IAction::Drop) {
701 IDropAction *da = (IDropAction*)a.get();
703 da->from_inv.applyCurrentPlayer(player->getName());
705 m_inventory_mgr->setInventoryModified(da->from_inv);
708 Disable dropping items out of craftpreview
710 if (da->from_list == "craftpreview") {
711 infostream << "Ignoring IDropAction from "
712 << (da->from_inv.dump()) << ":" << da->from_list
713 << " because src is " << da->from_list << std::endl;
717 // Disallow dropping items if not allowed to interact
718 if (!player_has_interact || !check_inv_access(da->from_inv))
721 // Disallow dropping items if dead
722 if (playersao->isDead()) {
723 infostream << "Ignoring IDropAction from "
724 << (da->from_inv.dump()) << ":" << da->from_list
725 << " because player is dead." << std::endl;
730 Handle restrictions and special cases of the craft action
732 else if (a->getType() == IAction::Craft) {
733 ICraftAction *ca = (ICraftAction*)a.get();
735 ca->craft_inv.applyCurrentPlayer(player->getName());
737 m_inventory_mgr->setInventoryModified(ca->craft_inv);
739 // Disallow crafting if not allowed to interact
740 if (!player_has_interact) {
741 infostream << "Cannot craft: "
742 << "No interact privilege" << std::endl;
746 if (!check_inv_access(ca->craft_inv))
749 // Unknown action. Ignored.
754 a->apply(m_inventory_mgr.get(), playersao, this);
757 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
759 std::wstring message;
762 session_t peer_id = pkt->getPeerId();
763 RemotePlayer *player = m_env->getPlayer(peer_id);
764 if (player == NULL) {
766 "Server::ProcessData(): Canceling: No player for peer_id=" <<
767 peer_id << " disconnecting peer!" << std::endl;
768 DisconnectPeer(peer_id);
772 std::string name = player->getName();
774 std::wstring answer_to_sender = handleChat(name, message, true, player);
775 if (!answer_to_sender.empty()) {
776 // Send the answer to sender
777 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
782 void Server::handleCommand_Damage(NetworkPacket* pkt)
788 session_t peer_id = pkt->getPeerId();
789 RemotePlayer *player = m_env->getPlayer(peer_id);
791 if (player == NULL) {
793 "Server::ProcessData(): Canceling: No player for peer_id=" <<
794 peer_id << " disconnecting peer!" << std::endl;
795 DisconnectPeer(peer_id);
799 PlayerSAO *playersao = player->getPlayerSAO();
800 if (playersao == NULL) {
802 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
803 peer_id << " disconnecting peer!" << std::endl;
804 DisconnectPeer(peer_id);
808 if (!playersao->isImmortal()) {
809 if (playersao->isDead()) {
810 verbosestream << "Server::ProcessData(): Info: "
811 "Ignoring damage as player " << player->getName()
812 << " is already dead." << std::endl;
816 actionstream << player->getName() << " damaged by "
817 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
820 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
821 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
822 SendPlayerHPOrDie(playersao, reason);
826 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
828 if (pkt->getSize() < 2)
831 session_t peer_id = pkt->getPeerId();
832 RemotePlayer *player = m_env->getPlayer(peer_id);
834 if (player == NULL) {
836 "Server::ProcessData(): Canceling: No player for peer_id=" <<
837 peer_id << " disconnecting peer!" << std::endl;
838 DisconnectPeer(peer_id);
842 PlayerSAO *playersao = player->getPlayerSAO();
843 if (playersao == NULL) {
845 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
846 peer_id << " disconnecting peer!" << std::endl;
847 DisconnectPeer(peer_id);
855 if (item >= player->getHotbarItemcount()) {
856 actionstream << "Player: " << player->getName()
857 << " tried to access item=" << item
858 << " out of hotbar_itemcount="
859 << player->getHotbarItemcount()
860 << "; ignoring." << std::endl;
864 playersao->getPlayer()->setWieldIndex(item);
867 void Server::handleCommand_Respawn(NetworkPacket* pkt)
869 session_t peer_id = pkt->getPeerId();
870 RemotePlayer *player = m_env->getPlayer(peer_id);
871 if (player == NULL) {
873 "Server::ProcessData(): Canceling: No player for peer_id=" <<
874 peer_id << " disconnecting peer!" << std::endl;
875 DisconnectPeer(peer_id);
879 PlayerSAO *playersao = player->getPlayerSAO();
882 if (!playersao->isDead())
885 RespawnPlayer(peer_id);
887 actionstream << player->getName() << " respawns at "
888 << PP(playersao->getBasePosition() / BS) << std::endl;
890 // ActiveObject is added to environment in AsyncRunStep after
891 // the previous addition has been successfully removed
894 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
896 ItemStack selected_item, hand_item;
897 player->getWieldedItem(&selected_item, &hand_item);
898 f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
899 hand_item.getDefinition(m_itemdef));
901 // Cube diagonal * 1.5 for maximal supported node extents:
902 // sqrt(3) * 1.5 ≅ 2.6
903 if (d > max_d + 2.6f * BS) {
904 actionstream << "Player " << player->getName()
905 << " tried to access " << what
907 << "d=" << d << ", max_d=" << max_d
908 << "; ignoring." << std::endl;
910 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
916 void Server::handleCommand_Interact(NetworkPacket *pkt)
922 [5] u32 length of the next item (plen)
923 [9] serialized PointedThing
924 [9 + plen] player position information
927 InteractAction action;
930 *pkt >> (u8 &)action;
933 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
934 PointedThing pointed;
935 pointed.deSerialize(tmp_is);
937 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
938 << item_i << ", pointed=" << pointed.dump() << std::endl;
940 session_t peer_id = pkt->getPeerId();
941 RemotePlayer *player = m_env->getPlayer(peer_id);
943 if (player == NULL) {
945 "Server::ProcessData(): Canceling: No player for peer_id=" <<
946 peer_id << " disconnecting peer!" << std::endl;
947 DisconnectPeer(peer_id);
951 PlayerSAO *playersao = player->getPlayerSAO();
952 if (playersao == NULL) {
954 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
955 peer_id << " disconnecting peer!" << std::endl;
956 DisconnectPeer(peer_id);
960 if (playersao->isDead()) {
961 actionstream << "Server: " << player->getName()
962 << " tried to interact while dead; ignoring." << std::endl;
963 if (pointed.type == POINTEDTHING_NODE) {
964 // Re-send block to revert change on client-side
965 RemoteClient *client = getClient(peer_id);
966 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
967 client->SetBlockNotSent(blockpos);
970 m_script->on_cheat(playersao, "interacted_while_dead");
974 process_PlayerPos(player, playersao, pkt);
976 v3f player_pos = playersao->getLastGoodPosition();
978 // Update wielded item
980 if (item_i >= player->getHotbarItemcount()) {
981 actionstream << "Player: " << player->getName()
982 << " tried to access item=" << item_i
983 << " out of hotbar_itemcount="
984 << player->getHotbarItemcount()
985 << "; ignoring." << std::endl;
989 playersao->getPlayer()->setWieldIndex(item_i);
991 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
992 ServerActiveObject *pointed_object = NULL;
993 if (pointed.type == POINTEDTHING_OBJECT) {
994 pointed_object = m_env->getActiveObject(pointed.object_id);
995 if (pointed_object == NULL) {
996 verbosestream << "TOSERVER_INTERACT: "
997 "pointed object is NULL" << std::endl;
1004 Make sure the player is allowed to do it
1006 if (!checkPriv(player->getName(), "interact")) {
1007 actionstream << player->getName() << " attempted to interact with " <<
1008 pointed.dump() << " without 'interact' privilege" << std::endl;
1010 if (pointed.type != POINTEDTHING_NODE)
1013 // Re-send block to revert change on client-side
1014 RemoteClient *client = getClient(peer_id);
1015 // Digging completed -> under
1016 if (action == INTERACT_DIGGING_COMPLETED) {
1017 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1018 client->SetBlockNotSent(blockpos);
1020 // Placement -> above
1021 else if (action == INTERACT_PLACE) {
1022 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1023 client->SetBlockNotSent(blockpos);
1029 Check that target is reasonably close
1031 static thread_local const bool enable_anticheat =
1032 !g_settings->getBool("disable_anticheat");
1034 if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1035 action == INTERACT_PLACE || action == INTERACT_USE) &&
1036 enable_anticheat && !isSingleplayer()) {
1037 v3f target_pos = player_pos;
1038 if (pointed.type == POINTEDTHING_NODE) {
1039 target_pos = intToFloat(pointed.node_undersurface, BS);
1040 } else if (pointed.type == POINTEDTHING_OBJECT) {
1041 target_pos = pointed_object->getBasePosition();
1043 float d = playersao->getEyePosition().getDistanceFrom(target_pos);
1045 if (!checkInteractDistance(player, d, pointed.dump())) {
1046 if (pointed.type == POINTEDTHING_NODE) {
1047 // Re-send block to revert change on client-side
1048 RemoteClient *client = getClient(peer_id);
1049 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1050 client->SetBlockNotSent(blockpos);
1057 If something goes wrong, this player is to blame
1059 RollbackScopeActor rollback_scope(m_rollback,
1060 std::string("player:")+player->getName());
1063 // Start digging or punch object
1064 case INTERACT_START_DIGGING: {
1065 if (pointed.type == POINTEDTHING_NODE) {
1066 MapNode n(CONTENT_IGNORE);
1069 v3s16 p_under = pointed.node_undersurface;
1070 n = m_env->getMap().getNode(p_under, &pos_ok);
1072 infostream << "Server: Not punching: Node not found. "
1073 "Adding block to emerge queue." << std::endl;
1074 m_emerge->enqueueBlockEmerge(peer_id,
1075 getNodeBlockPos(pointed.node_abovesurface), false);
1078 if (n.getContent() != CONTENT_IGNORE)
1079 m_script->node_on_punch(p_under, n, playersao, pointed);
1082 playersao->noCheatDigStart(p_under);
1087 // Skip if the object can't be interacted with anymore
1088 if (pointed.type != POINTEDTHING_OBJECT || pointed_object->isGone())
1091 ItemStack selected_item, hand_item;
1092 ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
1093 ToolCapabilities toolcap =
1094 tool_item.getToolCapabilities(m_itemdef);
1095 v3f dir = (pointed_object->getBasePosition() -
1096 (playersao->getBasePosition() + playersao->getEyeOffset())
1098 float time_from_last_punch =
1099 playersao->resetTimeFromLastPunch();
1101 u16 src_original_hp = pointed_object->getHP();
1102 u16 dst_origin_hp = playersao->getHP();
1104 u16 wear = pointed_object->punch(dir, &toolcap, playersao,
1105 time_from_last_punch);
1107 // Callback may have changed item, so get it again
1108 playersao->getWieldedItem(&selected_item);
1109 bool changed = selected_item.addWear(wear, m_itemdef);
1111 playersao->setWieldedItem(selected_item);
1113 // If the object is a player and its HP changed
1114 if (src_original_hp != pointed_object->getHP() &&
1115 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1116 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1117 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1120 // If the puncher is a player and its HP changed
1121 if (dst_origin_hp != playersao->getHP())
1122 SendPlayerHPOrDie(playersao,
1123 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1126 } // action == INTERACT_START_DIGGING
1128 case INTERACT_STOP_DIGGING:
1132 case INTERACT_DIGGING_COMPLETED: {
1133 // Only digging of nodes
1134 if (pointed.type != POINTEDTHING_NODE)
1137 v3s16 p_under = pointed.node_undersurface;
1138 MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1140 infostream << "Server: Not finishing digging: Node not found. "
1141 "Adding block to emerge queue." << std::endl;
1142 m_emerge->enqueueBlockEmerge(peer_id,
1143 getNodeBlockPos(pointed.node_abovesurface), false);
1146 /* Cheat prevention */
1147 bool is_valid_dig = true;
1148 if (enable_anticheat && !isSingleplayer()) {
1149 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1150 float nocheat_t = playersao->getNoCheatDigTime();
1151 playersao->noCheatDigEnd();
1152 // If player didn't start digging this, ignore dig
1153 if (nocheat_p != p_under) {
1154 infostream << "Server: " << player->getName()
1155 << " started digging "
1156 << PP(nocheat_p) << " and completed digging "
1157 << PP(p_under) << "; not digging." << std::endl;
1158 is_valid_dig = false;
1160 m_script->on_cheat(playersao, "finished_unknown_dig");
1163 // Get player's wielded item
1164 // See also: Game::handleDigging
1165 ItemStack selected_item, hand_item;
1166 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1168 // Get diggability and expected digging time
1169 DigParams params = getDigParams(m_nodedef->get(n).groups,
1170 &selected_item.getToolCapabilities(m_itemdef));
1171 // If can't dig, try hand
1172 if (!params.diggable) {
1173 params = getDigParams(m_nodedef->get(n).groups,
1174 &hand_item.getToolCapabilities(m_itemdef));
1176 // If can't dig, ignore dig
1177 if (!params.diggable) {
1178 infostream << "Server: " << player->getName()
1179 << " completed digging " << PP(p_under)
1180 << ", which is not diggable with tool; not digging."
1182 is_valid_dig = false;
1184 m_script->on_cheat(playersao, "dug_unbreakable");
1186 // Check digging time
1187 // If already invalidated, we don't have to
1188 if (!is_valid_dig) {
1189 // Well not our problem then
1191 // Clean and long dig
1192 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1193 // All is good, but grab time from pool; don't care if
1194 // it's actually available
1195 playersao->getDigPool().grab(params.time);
1197 // Short or laggy dig
1198 // Try getting the time from pool
1199 else if (playersao->getDigPool().grab(params.time)) {
1204 infostream << "Server: " << player->getName()
1205 << " completed digging " << PP(p_under)
1206 << "too fast; not digging." << std::endl;
1207 is_valid_dig = false;
1209 m_script->on_cheat(playersao, "dug_too_fast");
1213 /* Actually dig node */
1215 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1216 m_script->node_on_dig(p_under, n, playersao);
1218 v3s16 blockpos = getNodeBlockPos(p_under);
1219 RemoteClient *client = getClient(peer_id);
1220 // Send unusual result (that is, node not being removed)
1221 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR)
1222 // Re-send block to revert change on client-side
1223 client->SetBlockNotSent(blockpos);
1225 client->ResendBlockIfOnWire(blockpos);
1228 } // action == INTERACT_DIGGING_COMPLETED
1230 // Place block or right-click object
1231 case INTERACT_PLACE: {
1232 ItemStack selected_item;
1233 playersao->getWieldedItem(&selected_item, nullptr);
1235 // Reset build time counter
1236 if (pointed.type == POINTEDTHING_NODE &&
1237 selected_item.getDefinition(m_itemdef).type == ITEM_NODE)
1238 getClient(peer_id)->m_time_from_building = 0.0;
1240 if (pointed.type == POINTEDTHING_OBJECT) {
1241 // Right click object
1243 // Skip if object can't be interacted with anymore
1244 if (pointed_object->isGone())
1247 actionstream << player->getName() << " right-clicks object "
1248 << pointed.object_id << ": "
1249 << pointed_object->getDescription() << std::endl;
1252 if (m_script->item_OnSecondaryUse(
1253 selected_item, playersao, pointed)) {
1254 if (playersao->setWieldedItem(selected_item)) {
1255 SendInventory(playersao, true);
1259 pointed_object->rightClick(playersao);
1260 } else if (m_script->item_OnPlace(selected_item, playersao, pointed)) {
1261 // Placement was handled in lua
1263 // Apply returned ItemStack
1264 if (playersao->setWieldedItem(selected_item))
1265 SendInventory(playersao, true);
1268 if (pointed.type != POINTEDTHING_NODE)
1271 // If item has node placement prediction, always send the
1272 // blocks to make sure the client knows what exactly happened
1273 RemoteClient *client = getClient(peer_id);
1274 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1275 v3s16 blockpos2 = getNodeBlockPos(pointed.node_undersurface);
1276 if (!selected_item.getDefinition(m_itemdef
1277 ).node_placement_prediction.empty()) {
1278 client->SetBlockNotSent(blockpos);
1279 if (blockpos2 != blockpos)
1280 client->SetBlockNotSent(blockpos2);
1282 client->ResendBlockIfOnWire(blockpos);
1283 if (blockpos2 != blockpos)
1284 client->ResendBlockIfOnWire(blockpos2);
1288 } // action == INTERACT_PLACE
1290 case INTERACT_USE: {
1291 ItemStack selected_item;
1292 playersao->getWieldedItem(&selected_item, nullptr);
1294 actionstream << player->getName() << " uses " << selected_item.name
1295 << ", pointing at " << pointed.dump() << std::endl;
1297 if (m_script->item_OnUse(selected_item, playersao, pointed)) {
1298 // Apply returned ItemStack
1299 if (playersao->setWieldedItem(selected_item))
1300 SendInventory(playersao, true);
1307 case INTERACT_ACTIVATE: {
1308 ItemStack selected_item;
1309 playersao->getWieldedItem(&selected_item, nullptr);
1311 actionstream << player->getName() << " activates "
1312 << selected_item.name << std::endl;
1314 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1316 if (m_script->item_OnSecondaryUse(selected_item, playersao, pointed)) {
1317 if (playersao->setWieldedItem(selected_item))
1318 SendInventory(playersao, true);
1325 warningstream << "Server: Invalid action " << action << std::endl;
1330 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1334 for (u16 k = 0; k < num; k++) {
1339 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1340 m_playing_sounds.find(id);
1341 if (i == m_playing_sounds.end())
1344 ServerPlayingSound &psound = i->second;
1345 psound.clients.erase(pkt->getPeerId());
1346 if (psound.clients.empty())
1347 m_playing_sounds.erase(i++);
1351 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1354 std::string formname;
1357 *pkt >> p >> formname >> num;
1360 for (u16 k = 0; k < num; k++) {
1361 std::string fieldname;
1363 fields[fieldname] = pkt->readLongString();
1366 session_t peer_id = pkt->getPeerId();
1367 RemotePlayer *player = m_env->getPlayer(peer_id);
1369 if (player == NULL) {
1371 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1372 peer_id << " disconnecting peer!" << std::endl;
1373 DisconnectPeer(peer_id);
1377 PlayerSAO *playersao = player->getPlayerSAO();
1378 if (playersao == NULL) {
1380 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1381 peer_id << " disconnecting peer!" << std::endl;
1382 DisconnectPeer(peer_id);
1386 // If something goes wrong, this player is to blame
1387 RollbackScopeActor rollback_scope(m_rollback,
1388 std::string("player:")+player->getName());
1390 // Check the target node for rollback data; leave others unnoticed
1391 RollbackNode rn_old(&m_env->getMap(), p, this);
1393 m_script->node_on_receive_fields(p, formname, fields, playersao);
1395 // Report rollback data
1396 RollbackNode rn_new(&m_env->getMap(), p, this);
1397 if (rollback() && rn_new != rn_old) {
1398 RollbackAction action;
1399 action.setSetNode(p, rn_old, rn_new);
1400 rollback()->reportAction(action);
1404 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1406 std::string client_formspec_name;
1409 *pkt >> client_formspec_name >> num;
1412 for (u16 k = 0; k < num; k++) {
1413 std::string fieldname;
1415 fields[fieldname] = pkt->readLongString();
1418 session_t peer_id = pkt->getPeerId();
1419 RemotePlayer *player = m_env->getPlayer(peer_id);
1421 if (player == NULL) {
1423 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1424 peer_id << " disconnecting peer!" << std::endl;
1425 DisconnectPeer(peer_id);
1429 PlayerSAO *playersao = player->getPlayerSAO();
1430 if (playersao == NULL) {
1432 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1433 peer_id << " disconnecting peer!" << std::endl;
1434 DisconnectPeer(peer_id);
1438 if (client_formspec_name.empty()) { // pass through inventory submits
1439 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1443 // verify that we displayed the formspec to the user
1444 const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1445 if (peer_state_iterator != m_formspec_state_data.end()) {
1446 const std::string &server_formspec_name = peer_state_iterator->second;
1447 if (client_formspec_name == server_formspec_name) {
1448 auto it = fields.find("quit");
1449 if (it != fields.end() && it->second == "true")
1450 m_formspec_state_data.erase(peer_state_iterator);
1452 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1455 actionstream << "'" << player->getName()
1456 << "' submitted formspec ('" << client_formspec_name
1457 << "') but the name of the formspec doesn't match the"
1458 " expected name ('" << server_formspec_name << "')";
1461 actionstream << "'" << player->getName()
1462 << "' submitted formspec ('" << client_formspec_name
1463 << "') but server hasn't sent formspec to client";
1465 actionstream << ", possible exploitation attempt" << std::endl;
1468 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1470 session_t peer_id = pkt->getPeerId();
1471 RemoteClient *client = getClient(peer_id, CS_Invalid);
1472 ClientState cstate = client->getState();
1474 std::string playername = client->getName();
1477 std::string verification_key;
1479 std::string addr_s = getPeerAddress(peer_id).serializeString();
1482 *pkt >> salt >> verification_key >> is_empty;
1484 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1485 << ", with is_empty=" << (is_empty == 1) << std::endl;
1487 // Either this packet is sent because the user is new or to change the password
1488 if (cstate == CS_HelloSent) {
1489 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1490 actionstream << "Server: Client from " << addr_s
1491 << " tried to set password without being "
1492 << "authenticated, or the username being new." << std::endl;
1493 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1497 if (!isSingleplayer() &&
1498 g_settings->getBool("disallow_empty_password") &&
1500 actionstream << "Server: " << playername
1501 << " supplied empty password from " << addr_s << std::endl;
1502 DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1506 std::string initial_ver_key;
1508 initial_ver_key = encode_srp_verifier(verification_key, salt);
1509 m_script->createAuth(playername, initial_ver_key);
1510 m_script->on_authplayer(playername, addr_s, true);
1512 acceptAuth(peer_id, false);
1514 if (cstate < CS_SudoMode) {
1515 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1516 << addr_s << ": " << "Client has wrong state " << cstate << "."
1520 m_clients.event(peer_id, CSE_SudoLeave);
1521 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1522 bool success = m_script->setPassword(playername, pw_db_field);
1524 actionstream << playername << " changes password" << std::endl;
1525 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1526 L"Password change successful."));
1528 actionstream << playername <<
1529 " tries to change password but it fails" << std::endl;
1530 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1531 L"Password change failed or unavailable."));
1536 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1538 session_t peer_id = pkt->getPeerId();
1539 RemoteClient *client = getClient(peer_id, CS_Invalid);
1540 ClientState cstate = client->getState();
1542 bool wantSudo = (cstate == CS_Active);
1544 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1545 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1546 " from " << getPeerAddress(peer_id).serializeString() <<
1547 ". Ignoring." << std::endl;
1551 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1552 actionstream << "Server: got SRP _A packet, while auth is already "
1553 "going on with mech " << client->chosen_mech << " from " <<
1554 getPeerAddress(peer_id).serializeString() <<
1555 " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1557 DenySudoAccess(peer_id);
1561 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1565 std::string bytes_A;
1567 *pkt >> bytes_A >> based_on;
1569 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1570 << "based_on=" << int(based_on) << " and len_A="
1571 << bytes_A.length() << "." << std::endl;
1573 AuthMechanism chosen = (based_on == 0) ?
1574 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1577 if (!client->isSudoMechAllowed(chosen)) {
1578 actionstream << "Server: Player \"" << client->getName() <<
1579 "\" at " << getPeerAddress(peer_id).serializeString() <<
1580 " tried to change password using unallowed mech " << chosen <<
1582 DenySudoAccess(peer_id);
1586 if (!client->isMechAllowed(chosen)) {
1587 actionstream << "Server: Client tried to authenticate from " <<
1588 getPeerAddress(peer_id).serializeString() <<
1589 " using unallowed mech " << chosen << "." << std::endl;
1590 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1595 client->chosen_mech = chosen;
1598 std::string verifier;
1600 if (based_on == 0) {
1602 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1604 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1605 // Non-base64 errors should have been catched in the init handler
1606 actionstream << "Server: User " << client->getName() <<
1607 " tried to log in, but srp verifier field was invalid (most likely "
1608 "invalid base64)." << std::endl;
1609 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1616 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1617 client->getName().c_str(),
1618 (const unsigned char *) salt.c_str(), salt.size(),
1619 (const unsigned char *) verifier.c_str(), verifier.size(),
1620 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1622 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1625 actionstream << "Server: User " << client->getName()
1626 << " tried to log in, SRP-6a safety check violated in _A handler."
1629 DenySudoAccess(peer_id);
1633 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1637 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1638 resp_pkt << salt << std::string(bytes_B, len_B);
1642 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1644 session_t peer_id = pkt->getPeerId();
1645 RemoteClient *client = getClient(peer_id, CS_Invalid);
1646 ClientState cstate = client->getState();
1647 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1648 std::string playername = client->getName();
1650 bool wantSudo = (cstate == CS_Active);
1652 verbosestream << "Server: Received TOSERVER_SRP_BYTES_M." << std::endl;
1654 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1655 warningstream << "Server: got SRP_M packet in wrong state "
1656 << cstate << " from " << addr_s << ". Ignoring." << std::endl;
1660 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1661 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1662 warningstream << "Server: got SRP_M packet, while auth "
1663 "is going on with mech " << client->chosen_mech << " from "
1664 << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1666 DenySudoAccess(peer_id);
1670 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1674 std::string bytes_M;
1677 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1678 != bytes_M.size()) {
1679 actionstream << "Server: User " << playername << " at " << addr_s
1680 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1681 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1685 unsigned char *bytes_HAMK = 0;
1687 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1688 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1692 actionstream << "Server: User " << playername << " at " << addr_s
1693 << " tried to change their password, but supplied wrong"
1694 << " (SRP) password for authentication." << std::endl;
1695 DenySudoAccess(peer_id);
1699 actionstream << "Server: User " << playername << " at " << addr_s
1700 << " supplied wrong password (auth mechanism: SRP)." << std::endl;
1701 m_script->on_authplayer(playername, addr_s, false);
1702 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1706 if (client->create_player_on_auth_success) {
1707 m_script->createAuth(playername, client->enc_pwd);
1709 std::string checkpwd; // not used, but needed for passing something
1710 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1711 errorstream << "Server: " << playername <<
1712 " cannot be authenticated (auth handler does not work?)" <<
1714 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1717 client->create_player_on_auth_success = false;
1720 m_script->on_authplayer(playername, addr_s, true);
1721 acceptAuth(peer_id, wantSudo);
1728 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1730 std::string channel_name;
1731 *pkt >> channel_name;
1733 session_t peer_id = pkt->getPeerId();
1734 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1735 1 + 2 + channel_name.size(), peer_id);
1737 // Send signal to client to notify join succeed or not
1738 if (g_settings->getBool("enable_mod_channels") &&
1739 m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1740 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1741 infostream << "Peer " << peer_id << " joined channel " <<
1742 channel_name << std::endl;
1745 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1746 infostream << "Peer " << peer_id << " tried to join channel " <<
1747 channel_name << ", but was already registered." << std::endl;
1749 resp_pkt << channel_name;
1753 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1755 std::string channel_name;
1756 *pkt >> channel_name;
1758 session_t peer_id = pkt->getPeerId();
1759 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1760 1 + 2 + channel_name.size(), peer_id);
1762 // Send signal to client to notify join succeed or not
1763 if (g_settings->getBool("enable_mod_channels") &&
1764 m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1765 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1766 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1769 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1770 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1771 ", but was not registered." << std::endl;
1773 resp_pkt << channel_name;
1777 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1779 std::string channel_name, channel_msg;
1780 *pkt >> channel_name >> channel_msg;
1782 session_t peer_id = pkt->getPeerId();
1783 verbosestream << "Mod channel message received from peer " << peer_id <<
1784 " on channel " << channel_name << " message: " << channel_msg <<
1787 // If mod channels are not enabled, discard message
1788 if (!g_settings->getBool("enable_mod_channels")) {
1792 // If channel not registered, signal it and ignore message
1793 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1794 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1795 1 + 2 + channel_name.size(), peer_id);
1796 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1801 // @TODO: filter, rate limit
1803 broadcastModChannelMessage(channel_name, channel_msg, peer_id);