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);
61 Address address = getPeerAddress(peer_id);
62 addr_s = address.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 net_proto_version is set, this client has already been handled
77 if (client->getState() > CS_Created) {
78 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " <<
79 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
83 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s <<
84 " (peer_id=" << peer_id << ")" << std::endl;
86 // Do not allow multiple players in simple singleplayer mode.
87 // This isn't a perfect way to do it, but will suffice for now
88 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
89 infostream << "Server: Not allowing another client (" << addr_s <<
90 ") to connect in simple singleplayer mode" << std::endl;
91 DenyAccess(peer_id, SERVER_ACCESSDENIED_SINGLEPLAYER);
95 // First byte after command is maximum supported
96 // serialization version
99 u16 min_net_proto_version = 0;
100 u16 max_net_proto_version;
101 std::string playerName;
103 *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
104 >> max_net_proto_version >> playerName;
106 u8 our_max = SER_FMT_VER_HIGHEST_READ;
107 // Use the highest version supported by both
108 u8 depl_serial_v = std::min(client_max, our_max);
109 // If it's lower than the lowest supported, give up.
110 if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
111 depl_serial_v = SER_FMT_VER_INVALID;
113 if (depl_serial_v == SER_FMT_VER_INVALID) {
114 actionstream << "Server: A mismatched client tried to connect from " <<
115 addr_s << " ser_fmt_max=" << (int)client_max << std::endl;
116 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
120 client->setPendingSerializationVersion(depl_serial_v);
123 Read and check network protocol version
126 u16 net_proto_version = 0;
128 // Figure out a working version if it is possible at all
129 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
130 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
131 // If maximum is larger than our maximum, go with our maximum
132 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
133 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
134 // Else go with client's maximum
136 net_proto_version = max_net_proto_version;
139 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
140 << min_net_proto_version << ", max: " << max_net_proto_version
141 << ", chosen: " << net_proto_version << std::endl;
143 client->net_proto_version = net_proto_version;
145 if ((g_settings->getBool("strict_protocol_version_checking") &&
146 net_proto_version != LATEST_PROTOCOL_VERSION) ||
147 net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
148 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
149 actionstream << "Server: A mismatched client tried to connect from " <<
150 addr_s << " proto_max=" << (int)max_net_proto_version << std::endl;
151 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
158 const char* playername = playerName.c_str();
160 size_t pns = playerName.size();
161 if (pns == 0 || pns > PLAYERNAME_SIZE) {
162 actionstream << "Server: Player with " <<
163 ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty") <<
164 " name tried to connect from " << addr_s << std::endl;
165 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
169 if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
170 actionstream << "Server: Player with an invalid name tried to connect "
171 "from " << addr_s << std::endl;
172 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
176 m_clients.setPlayerName(peer_id, playername);
177 //TODO (later) case insensitivity
179 std::string legacyPlayerNameCasing = playerName;
181 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
182 actionstream << "Server: Player with the name \"singleplayer\" tried "
183 "to connect from " << addr_s << std::endl;
184 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
190 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
191 actionstream << "Server: Player with the name \"" << playerName <<
192 "\" tried to connect from " << addr_s <<
193 " but it was disallowed for the following reason: " << reason <<
195 DenyAccess(peer_id, SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
200 infostream << "Server: New connection: \"" << playerName << "\" from " <<
201 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
203 // Enforce user limit.
204 // Don't enforce for users that have some admin right or mod permits it.
205 if (m_clients.isUserLimitReached() &&
206 playername != g_settings->get("name") &&
207 !m_script->can_bypass_userlimit(playername, addr_s)) {
208 actionstream << "Server: " << playername << " tried to join from " <<
209 addr_s << ", but there are already max_users=" <<
210 g_settings->getU16("max_users") << " players." << std::endl;
211 DenyAccess(peer_id, SERVER_ACCESSDENIED_TOO_MANY_USERS);
216 Compose auth methods for answer
218 std::string encpwd; // encrypted Password field for the user
219 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
222 client->chosen_mech = AUTH_MECHANISM_NONE;
225 std::vector<std::string> pwd_components = str_split(encpwd, '#');
226 if (pwd_components.size() == 4) {
227 if (pwd_components[1] == "1") { // 1 means srp
228 auth_mechs |= AUTH_MECHANISM_SRP;
229 client->enc_pwd = encpwd;
231 actionstream << "User " << playername << " tried to log in, "
232 "but password field was invalid (unknown mechcode)." <<
234 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
237 } else if (base64_is_valid(encpwd)) {
238 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
239 client->enc_pwd = encpwd;
241 actionstream << "User " << playername << " tried to log in, but "
242 "password field was invalid (invalid base64)." << std::endl;
243 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
247 std::string default_password = g_settings->get("default_password");
248 if (default_password.length() == 0) {
249 auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
251 // Take care of default passwords.
252 client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
253 auth_mechs |= AUTH_MECHANISM_SRP;
254 // Allocate player in db, but only on successful login.
255 client->create_player_on_auth_success = true;
260 Answer with a TOCLIENT_HELLO
263 verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
264 << auth_mechs << std::endl;
266 NetworkPacket resp_pkt(TOCLIENT_HELLO,
267 1 + 4 + legacyPlayerNameCasing.size(), peer_id);
269 u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
270 resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
271 << auth_mechs << legacyPlayerNameCasing;
275 client->allowed_auth_mechs = auth_mechs;
276 client->setDeployedCompressionMode(depl_compress_mode);
278 m_clients.event(peer_id, CSE_Hello);
281 void Server::handleCommand_Init2(NetworkPacket* pkt)
283 session_t peer_id = pkt->getPeerId();
284 verbosestream << "Server: Got TOSERVER_INIT2 from " << peer_id << std::endl;
286 m_clients.event(peer_id, CSE_GotInit2);
287 u16 protocol_version = m_clients.getProtocolVersion(peer_id);
290 if (pkt->getSize() > 0)
294 Send some initialization data
297 infostream << "Server: Sending content to " << getPlayerName(peer_id) <<
300 // Send item definitions
301 SendItemDef(peer_id, m_itemdef, protocol_version);
303 // Send node definitions
304 SendNodeDef(peer_id, m_nodedef, protocol_version);
306 m_clients.event(peer_id, CSE_SetDefinitionsSent);
308 // Send media announcement
309 sendMediaAnnouncement(peer_id, lang);
311 RemoteClient *client = getClient(peer_id, CS_InitDone);
313 // Keep client language for server translations
314 client->setLangCode(lang);
316 // Send active objects
318 PlayerSAO *sao = getPlayerSAO(peer_id);
320 SendActiveObjectRemoveAdd(client, sao);
323 // Send detached inventories
324 sendDetachedInventories(peer_id, false);
326 // Send player movement settings
327 SendMovement(peer_id);
330 u16 time = m_env->getTimeOfDay();
331 float time_speed = g_settings->getFloat("time_speed");
332 SendTimeOfDay(peer_id, time, time_speed);
334 SendCSMRestrictionFlags(peer_id);
336 // Warnings about protocol version can be issued here
337 if (client->net_proto_version < LATEST_PROTOCOL_VERSION) {
338 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
339 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
340 L"WITH THIS SERVER!"));
344 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
346 std::vector<std::string> tosend;
351 session_t peer_id = pkt->getPeerId();
352 infostream << "Sending " << numfiles << " files to " <<
353 getPlayerName(peer_id) << std::endl;
354 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
356 for (u16 i = 0; i < numfiles; i++) {
361 tosend.push_back(name);
362 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
363 << name << std::endl;
366 sendRequestedMedia(peer_id, tosend);
369 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
371 session_t peer_id = pkt->getPeerId();
373 PlayerSAO* playersao = StageTwoClientInit(peer_id);
375 if (playersao == NULL) {
376 errorstream << "TOSERVER_CLIENT_READY stage 2 client init failed "
377 "peer_id=" << peer_id << std::endl;
378 DisconnectPeer(peer_id);
383 if (pkt->getSize() < 8) {
384 errorstream << "TOSERVER_CLIENT_READY client sent inconsistent data, "
385 "disconnecting peer_id: " << peer_id << std::endl;
386 DisconnectPeer(peer_id);
390 u8 major_ver, minor_ver, patch_ver, reserved;
391 std::string full_ver;
392 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
394 m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver,
397 if (pkt->getRemainingBytes() >= 2)
398 *pkt >> playersao->getPlayer()->formspec_version;
400 const std::vector<std::string> &players = m_clients.getPlayerNames();
401 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
402 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
403 for (const std::string &player: players) {
406 m_clients.send(peer_id, 0, &list_pkt, true);
408 NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
409 // (u16) 1 + std::string represents a pseudo vector serialization representation
410 notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
411 m_clients.sendToAll(¬ice_pkt);
412 m_clients.event(peer_id, CSE_SetClientReady);
415 m_script->getAuth(playersao->getPlayer()->getName(), nullptr, nullptr, &last_login);
416 m_script->on_joinplayer(playersao, last_login);
418 // Send shutdown timer if shutdown has been scheduled
419 if (m_shutdown_state.isTimerRunning()) {
420 SendChatMessage(peer_id, m_shutdown_state.getShutdownTimerMessage());
424 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
426 if (pkt->getSize() < 1)
440 RemoteClient *client = getClient(pkt->getPeerId());
442 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
443 throw con::InvalidIncomingDataException
444 ("GOTBLOCKS length is too short");
447 for (u16 i = 0; i < count; i++) {
454 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
457 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
461 s32 f32pitch, f32yaw;
469 f32 pitch = (f32)f32pitch / 100.0f;
470 f32 yaw = (f32)f32yaw / 100.0f;
473 // default behavior (in case an old client doesn't send these)
479 fov = (f32)f32fov / 80.0f;
480 *pkt >> wanted_range;
482 v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
483 v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
485 pitch = modulo360f(pitch);
486 yaw = wrapDegrees_0_360(yaw);
488 playersao->setBasePosition(position);
489 player->setSpeed(speed);
490 playersao->setLookPitch(pitch);
491 playersao->setPlayerYaw(yaw);
492 playersao->setFov(fov);
493 playersao->setWantedRange(wanted_range);
495 player->keyPressed = keyPressed;
496 player->control.up = (keyPressed & (0x1 << 0));
497 player->control.down = (keyPressed & (0x1 << 1));
498 player->control.left = (keyPressed & (0x1 << 2));
499 player->control.right = (keyPressed & (0x1 << 3));
500 player->control.jump = (keyPressed & (0x1 << 4));
501 player->control.aux1 = (keyPressed & (0x1 << 5));
502 player->control.sneak = (keyPressed & (0x1 << 6));
503 player->control.dig = (keyPressed & (0x1 << 7));
504 player->control.place = (keyPressed & (0x1 << 8));
505 player->control.zoom = (keyPressed & (0x1 << 9));
507 if (playersao->checkMovementCheat()) {
509 m_script->on_cheat(playersao, "moved_too_fast");
510 SendMovePlayer(pkt->getPeerId());
514 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
516 session_t peer_id = pkt->getPeerId();
517 RemotePlayer *player = m_env->getPlayer(peer_id);
518 if (player == NULL) {
520 "Server::ProcessData(): Canceling: No player for peer_id=" <<
521 peer_id << " disconnecting peer!" << std::endl;
522 DisconnectPeer(peer_id);
526 PlayerSAO *playersao = player->getPlayerSAO();
527 if (playersao == NULL) {
529 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
530 peer_id << " disconnecting peer!" << std::endl;
531 DisconnectPeer(peer_id);
535 // If player is dead we don't care of this packet
536 if (playersao->isDead()) {
537 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
538 << " is dead. Ignoring packet";
542 process_PlayerPos(player, playersao, pkt);
545 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
547 if (pkt->getSize() < 1)
561 RemoteClient *client = getClient(pkt->getPeerId());
563 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
564 throw con::InvalidIncomingDataException
565 ("DELETEDBLOCKS length is too short");
568 for (u16 i = 0; i < count; i++) {
571 client->SetBlockNotSent(p);
575 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
577 session_t peer_id = pkt->getPeerId();
578 RemotePlayer *player = m_env->getPlayer(peer_id);
580 if (player == NULL) {
582 "Server::ProcessData(): Canceling: No player for peer_id=" <<
583 peer_id << " disconnecting peer!" << std::endl;
584 DisconnectPeer(peer_id);
588 PlayerSAO *playersao = player->getPlayerSAO();
589 if (playersao == NULL) {
591 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
592 peer_id << " disconnecting peer!" << std::endl;
593 DisconnectPeer(peer_id);
597 // Strip command and create a stream
598 std::string datastring(pkt->getString(0), pkt->getSize());
599 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
601 std::istringstream is(datastring, std::ios_base::binary);
603 std::unique_ptr<InventoryAction> a(InventoryAction::deSerialize(is));
605 infostream << "TOSERVER_INVENTORY_ACTION: "
606 << "InventoryAction::deSerialize() returned NULL"
611 // If something goes wrong, this player is to blame
612 RollbackScopeActor rollback_scope(m_rollback,
613 std::string("player:")+player->getName());
616 Note: Always set inventory not sent, to repair cases
617 where the client made a bad prediction.
620 const bool player_has_interact = checkPriv(player->getName(), "interact");
622 auto check_inv_access = [player, player_has_interact] (
623 const InventoryLocation &loc) -> bool {
624 if (loc.type == InventoryLocation::CURRENT_PLAYER)
625 return false; // Only used internally on the client, never sent
626 if (loc.type == InventoryLocation::PLAYER) {
627 // Allow access to own inventory in all cases
628 return loc.name == player->getName();
631 if (!player_has_interact) {
632 infostream << "Cannot modify foreign inventory: "
633 << "No interact privilege" << std::endl;
640 Handle restrictions and special cases of the move action
642 if (a->getType() == IAction::Move) {
643 IMoveAction *ma = (IMoveAction*)a.get();
645 ma->from_inv.applyCurrentPlayer(player->getName());
646 ma->to_inv.applyCurrentPlayer(player->getName());
648 m_inventory_mgr->setInventoryModified(ma->from_inv);
649 if (ma->from_inv != ma->to_inv)
650 m_inventory_mgr->setInventoryModified(ma->to_inv);
652 if (!check_inv_access(ma->from_inv) ||
653 !check_inv_access(ma->to_inv))
656 InventoryLocation *remote = ma->from_inv.type == InventoryLocation::PLAYER ?
657 &ma->to_inv : &ma->from_inv;
659 // Check for out-of-range interaction
660 if (remote->type == InventoryLocation::NODEMETA) {
661 v3f node_pos = intToFloat(remote->p, BS);
662 v3f player_pos = player->getPlayerSAO()->getEyePosition();
663 f32 d = player_pos.getDistanceFrom(node_pos);
664 if (!checkInteractDistance(player, d, "inventory"))
669 Disable moving items out of craftpreview
671 if (ma->from_list == "craftpreview") {
672 infostream << "Ignoring IMoveAction from "
673 << (ma->from_inv.dump()) << ":" << ma->from_list
674 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
675 << " because src is " << ma->from_list << std::endl;
680 Disable moving items into craftresult and craftpreview
682 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
683 infostream << "Ignoring IMoveAction from "
684 << (ma->from_inv.dump()) << ":" << ma->from_list
685 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
686 << " because dst is " << ma->to_list << std::endl;
691 Handle restrictions and special cases of the drop action
693 else if (a->getType() == IAction::Drop) {
694 IDropAction *da = (IDropAction*)a.get();
696 da->from_inv.applyCurrentPlayer(player->getName());
698 m_inventory_mgr->setInventoryModified(da->from_inv);
701 Disable dropping items out of craftpreview
703 if (da->from_list == "craftpreview") {
704 infostream << "Ignoring IDropAction from "
705 << (da->from_inv.dump()) << ":" << da->from_list
706 << " because src is " << da->from_list << std::endl;
710 // Disallow dropping items if not allowed to interact
711 if (!player_has_interact || !check_inv_access(da->from_inv))
714 // Disallow dropping items if dead
715 if (playersao->isDead()) {
716 infostream << "Ignoring IDropAction from "
717 << (da->from_inv.dump()) << ":" << da->from_list
718 << " because player is dead." << std::endl;
723 Handle restrictions and special cases of the craft action
725 else if (a->getType() == IAction::Craft) {
726 ICraftAction *ca = (ICraftAction*)a.get();
728 ca->craft_inv.applyCurrentPlayer(player->getName());
730 m_inventory_mgr->setInventoryModified(ca->craft_inv);
732 // Disallow crafting if not allowed to interact
733 if (!player_has_interact) {
734 infostream << "Cannot craft: "
735 << "No interact privilege" << std::endl;
739 if (!check_inv_access(ca->craft_inv))
742 // Unknown action. Ignored.
747 a->apply(m_inventory_mgr.get(), playersao, this);
750 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
760 std::wstring message;
761 for (u16 i = 0; i < len; i++) {
765 message += (wchar_t)tmp_wchar;
768 session_t peer_id = pkt->getPeerId();
769 RemotePlayer *player = m_env->getPlayer(peer_id);
770 if (player == NULL) {
772 "Server::ProcessData(): Canceling: No player for peer_id=" <<
773 peer_id << " disconnecting peer!" << std::endl;
774 DisconnectPeer(peer_id);
778 // Get player name of this client
779 std::string name = player->getName();
780 std::wstring wname = narrow_to_wide(name);
782 std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
783 if (!answer_to_sender.empty()) {
784 // Send the answer to sender
785 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_NORMAL,
786 answer_to_sender, wname));
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);
830 SendPlayerHPOrDie(playersao, reason);
834 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
836 if (pkt->getSize() < 2)
839 session_t peer_id = pkt->getPeerId();
840 RemotePlayer *player = m_env->getPlayer(peer_id);
842 if (player == NULL) {
844 "Server::ProcessData(): Canceling: No player for peer_id=" <<
845 peer_id << " disconnecting peer!" << std::endl;
846 DisconnectPeer(peer_id);
850 PlayerSAO *playersao = player->getPlayerSAO();
851 if (playersao == NULL) {
853 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
854 peer_id << " disconnecting peer!" << std::endl;
855 DisconnectPeer(peer_id);
863 if (item >= player->getHotbarItemcount()) {
864 actionstream << "Player: " << player->getName()
865 << " tried to access item=" << item
866 << " out of hotbar_itemcount="
867 << player->getHotbarItemcount()
868 << "; ignoring." << std::endl;
872 playersao->getPlayer()->setWieldIndex(item);
875 void Server::handleCommand_Respawn(NetworkPacket* pkt)
877 session_t peer_id = pkt->getPeerId();
878 RemotePlayer *player = m_env->getPlayer(peer_id);
879 if (player == NULL) {
881 "Server::ProcessData(): Canceling: No player for peer_id=" <<
882 peer_id << " disconnecting peer!" << std::endl;
883 DisconnectPeer(peer_id);
887 PlayerSAO *playersao = player->getPlayerSAO();
890 if (!playersao->isDead())
893 RespawnPlayer(peer_id);
895 actionstream << player->getName() << " respawns at "
896 << PP(playersao->getBasePosition() / BS) << std::endl;
898 // ActiveObject is added to environment in AsyncRunStep after
899 // the previous addition has been successfully removed
902 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
904 ItemStack selected_item, hand_item;
905 player->getWieldedItem(&selected_item, &hand_item);
906 f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
907 hand_item.getDefinition(m_itemdef));
909 // Cube diagonal * 1.5 for maximal supported node extents:
910 // sqrt(3) * 1.5 ≅ 2.6
911 if (d > max_d + 2.6f * BS) {
912 actionstream << "Player " << player->getName()
913 << " tried to access " << what
915 << "d=" << d << ", max_d=" << max_d
916 << "; ignoring." << std::endl;
918 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
924 void Server::handleCommand_Interact(NetworkPacket *pkt)
930 [5] u32 length of the next item (plen)
931 [9] serialized PointedThing
932 [9 + plen] player position information
935 InteractAction action;
938 *pkt >> (u8 &)action;
941 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
942 PointedThing pointed;
943 pointed.deSerialize(tmp_is);
945 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
946 << item_i << ", pointed=" << pointed.dump() << std::endl;
948 session_t peer_id = pkt->getPeerId();
949 RemotePlayer *player = m_env->getPlayer(peer_id);
951 if (player == NULL) {
953 "Server::ProcessData(): Canceling: No player for peer_id=" <<
954 peer_id << " disconnecting peer!" << std::endl;
955 DisconnectPeer(peer_id);
959 PlayerSAO *playersao = player->getPlayerSAO();
960 if (playersao == NULL) {
962 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
963 peer_id << " disconnecting peer!" << std::endl;
964 DisconnectPeer(peer_id);
968 if (playersao->isDead()) {
969 actionstream << "Server: " << player->getName()
970 << " tried to interact while dead; ignoring." << std::endl;
971 if (pointed.type == POINTEDTHING_NODE) {
972 // Re-send block to revert change on client-side
973 RemoteClient *client = getClient(peer_id);
974 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
975 client->SetBlockNotSent(blockpos);
978 m_script->on_cheat(playersao, "interacted_while_dead");
982 process_PlayerPos(player, playersao, pkt);
984 v3f player_pos = playersao->getLastGoodPosition();
986 // Update wielded item
988 if (item_i >= player->getHotbarItemcount()) {
989 actionstream << "Player: " << player->getName()
990 << " tried to access item=" << item_i
991 << " out of hotbar_itemcount="
992 << player->getHotbarItemcount()
993 << "; ignoring." << std::endl;
997 playersao->getPlayer()->setWieldIndex(item_i);
999 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1000 ServerActiveObject *pointed_object = NULL;
1001 if (pointed.type == POINTEDTHING_OBJECT) {
1002 pointed_object = m_env->getActiveObject(pointed.object_id);
1003 if (pointed_object == NULL) {
1004 verbosestream << "TOSERVER_INTERACT: "
1005 "pointed object is NULL" << std::endl;
1012 Make sure the player is allowed to do it
1014 if (!checkPriv(player->getName(), "interact")) {
1015 actionstream << player->getName() << " attempted to interact with " <<
1016 pointed.dump() << " without 'interact' privilege" << std::endl;
1018 if (pointed.type != POINTEDTHING_NODE)
1021 // Re-send block to revert change on client-side
1022 RemoteClient *client = getClient(peer_id);
1023 // Digging completed -> under
1024 if (action == INTERACT_DIGGING_COMPLETED) {
1025 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1026 client->SetBlockNotSent(blockpos);
1028 // Placement -> above
1029 else if (action == INTERACT_PLACE) {
1030 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1031 client->SetBlockNotSent(blockpos);
1037 Check that target is reasonably close
1039 static thread_local const bool enable_anticheat =
1040 !g_settings->getBool("disable_anticheat");
1042 if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1043 action == INTERACT_PLACE || action == INTERACT_USE) &&
1044 enable_anticheat && !isSingleplayer()) {
1045 v3f target_pos = player_pos;
1046 if (pointed.type == POINTEDTHING_NODE) {
1047 target_pos = intToFloat(pointed.node_undersurface, BS);
1048 } else if (pointed.type == POINTEDTHING_OBJECT) {
1049 target_pos = pointed_object->getBasePosition();
1051 float d = playersao->getEyePosition().getDistanceFrom(target_pos);
1053 if (!checkInteractDistance(player, d, pointed.dump())) {
1054 if (pointed.type == POINTEDTHING_NODE) {
1055 // Re-send block to revert change on client-side
1056 RemoteClient *client = getClient(peer_id);
1057 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1058 client->SetBlockNotSent(blockpos);
1065 If something goes wrong, this player is to blame
1067 RollbackScopeActor rollback_scope(m_rollback,
1068 std::string("player:")+player->getName());
1071 // Start digging or punch object
1072 case INTERACT_START_DIGGING: {
1073 if (pointed.type == POINTEDTHING_NODE) {
1074 MapNode n(CONTENT_IGNORE);
1077 v3s16 p_under = pointed.node_undersurface;
1078 n = m_env->getMap().getNode(p_under, &pos_ok);
1080 infostream << "Server: Not punching: Node not found. "
1081 "Adding block to emerge queue." << std::endl;
1082 m_emerge->enqueueBlockEmerge(peer_id,
1083 getNodeBlockPos(pointed.node_abovesurface), false);
1086 if (n.getContent() != CONTENT_IGNORE)
1087 m_script->node_on_punch(p_under, n, playersao, pointed);
1090 playersao->noCheatDigStart(p_under);
1095 // Skip if the object can't be interacted with anymore
1096 if (pointed.type != POINTEDTHING_OBJECT || pointed_object->isGone())
1099 ItemStack selected_item, hand_item;
1100 ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
1101 ToolCapabilities toolcap =
1102 tool_item.getToolCapabilities(m_itemdef);
1103 v3f dir = (pointed_object->getBasePosition() -
1104 (playersao->getBasePosition() + playersao->getEyeOffset())
1106 float time_from_last_punch =
1107 playersao->resetTimeFromLastPunch();
1109 u16 src_original_hp = pointed_object->getHP();
1110 u16 dst_origin_hp = playersao->getHP();
1112 u16 wear = pointed_object->punch(dir, &toolcap, playersao,
1113 time_from_last_punch);
1115 // Callback may have changed item, so get it again
1116 playersao->getWieldedItem(&selected_item);
1117 bool changed = selected_item.addWear(wear, m_itemdef);
1119 playersao->setWieldedItem(selected_item);
1121 // If the object is a player and its HP changed
1122 if (src_original_hp != pointed_object->getHP() &&
1123 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1124 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1125 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1128 // If the puncher is a player and its HP changed
1129 if (dst_origin_hp != playersao->getHP())
1130 SendPlayerHPOrDie(playersao,
1131 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1134 } // action == INTERACT_START_DIGGING
1136 case INTERACT_STOP_DIGGING:
1140 case INTERACT_DIGGING_COMPLETED: {
1141 // Only digging of nodes
1142 if (pointed.type != POINTEDTHING_NODE)
1145 v3s16 p_under = pointed.node_undersurface;
1146 MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1148 infostream << "Server: Not finishing digging: Node not found. "
1149 "Adding block to emerge queue." << std::endl;
1150 m_emerge->enqueueBlockEmerge(peer_id,
1151 getNodeBlockPos(pointed.node_abovesurface), false);
1154 /* Cheat prevention */
1155 bool is_valid_dig = true;
1156 if (enable_anticheat && !isSingleplayer()) {
1157 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1158 float nocheat_t = playersao->getNoCheatDigTime();
1159 playersao->noCheatDigEnd();
1160 // If player didn't start digging this, ignore dig
1161 if (nocheat_p != p_under) {
1162 infostream << "Server: " << player->getName()
1163 << " started digging "
1164 << PP(nocheat_p) << " and completed digging "
1165 << PP(p_under) << "; not digging." << std::endl;
1166 is_valid_dig = false;
1168 m_script->on_cheat(playersao, "finished_unknown_dig");
1171 // Get player's wielded item
1172 // See also: Game::handleDigging
1173 ItemStack selected_item, hand_item;
1174 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1176 // Get diggability and expected digging time
1177 DigParams params = getDigParams(m_nodedef->get(n).groups,
1178 &selected_item.getToolCapabilities(m_itemdef));
1179 // If can't dig, try hand
1180 if (!params.diggable) {
1181 params = getDigParams(m_nodedef->get(n).groups,
1182 &hand_item.getToolCapabilities(m_itemdef));
1184 // If can't dig, ignore dig
1185 if (!params.diggable) {
1186 infostream << "Server: " << player->getName()
1187 << " completed digging " << PP(p_under)
1188 << ", which is not diggable with tool; not digging."
1190 is_valid_dig = false;
1192 m_script->on_cheat(playersao, "dug_unbreakable");
1194 // Check digging time
1195 // If already invalidated, we don't have to
1196 if (!is_valid_dig) {
1197 // Well not our problem then
1199 // Clean and long dig
1200 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1201 // All is good, but grab time from pool; don't care if
1202 // it's actually available
1203 playersao->getDigPool().grab(params.time);
1205 // Short or laggy dig
1206 // Try getting the time from pool
1207 else if (playersao->getDigPool().grab(params.time)) {
1212 infostream << "Server: " << player->getName()
1213 << " completed digging " << PP(p_under)
1214 << "too fast; not digging." << std::endl;
1215 is_valid_dig = false;
1217 m_script->on_cheat(playersao, "dug_too_fast");
1221 /* Actually dig node */
1223 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1224 m_script->node_on_dig(p_under, n, playersao);
1226 v3s16 blockpos = getNodeBlockPos(p_under);
1227 RemoteClient *client = getClient(peer_id);
1228 // Send unusual result (that is, node not being removed)
1229 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR)
1230 // Re-send block to revert change on client-side
1231 client->SetBlockNotSent(blockpos);
1233 client->ResendBlockIfOnWire(blockpos);
1236 } // action == INTERACT_DIGGING_COMPLETED
1238 // Place block or right-click object
1239 case INTERACT_PLACE: {
1240 ItemStack selected_item;
1241 playersao->getWieldedItem(&selected_item, nullptr);
1243 // Reset build time counter
1244 if (pointed.type == POINTEDTHING_NODE &&
1245 selected_item.getDefinition(m_itemdef).type == ITEM_NODE)
1246 getClient(peer_id)->m_time_from_building = 0.0;
1248 if (pointed.type == POINTEDTHING_OBJECT) {
1249 // Right click object
1251 // Skip if object can't be interacted with anymore
1252 if (pointed_object->isGone())
1255 actionstream << player->getName() << " right-clicks object "
1256 << pointed.object_id << ": "
1257 << pointed_object->getDescription() << std::endl;
1260 if (m_script->item_OnSecondaryUse(
1261 selected_item, playersao, pointed)) {
1262 if (playersao->setWieldedItem(selected_item)) {
1263 SendInventory(playersao, true);
1267 pointed_object->rightClick(playersao);
1268 } else if (m_script->item_OnPlace(selected_item, playersao, pointed)) {
1269 // Placement was handled in lua
1271 // Apply returned ItemStack
1272 if (playersao->setWieldedItem(selected_item))
1273 SendInventory(playersao, true);
1276 if (pointed.type != POINTEDTHING_NODE)
1279 // If item has node placement prediction, always send the
1280 // blocks to make sure the client knows what exactly happened
1281 RemoteClient *client = getClient(peer_id);
1282 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1283 v3s16 blockpos2 = getNodeBlockPos(pointed.node_undersurface);
1284 if (!selected_item.getDefinition(m_itemdef
1285 ).node_placement_prediction.empty()) {
1286 client->SetBlockNotSent(blockpos);
1287 if (blockpos2 != blockpos)
1288 client->SetBlockNotSent(blockpos2);
1290 client->ResendBlockIfOnWire(blockpos);
1291 if (blockpos2 != blockpos)
1292 client->ResendBlockIfOnWire(blockpos2);
1296 } // action == INTERACT_PLACE
1298 case INTERACT_USE: {
1299 ItemStack selected_item;
1300 playersao->getWieldedItem(&selected_item, nullptr);
1302 actionstream << player->getName() << " uses " << selected_item.name
1303 << ", pointing at " << pointed.dump() << std::endl;
1305 if (m_script->item_OnUse(selected_item, playersao, pointed)) {
1306 // Apply returned ItemStack
1307 if (playersao->setWieldedItem(selected_item))
1308 SendInventory(playersao, true);
1315 case INTERACT_ACTIVATE: {
1316 ItemStack selected_item;
1317 playersao->getWieldedItem(&selected_item, nullptr);
1319 actionstream << player->getName() << " activates "
1320 << selected_item.name << std::endl;
1322 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1324 if (m_script->item_OnSecondaryUse(selected_item, playersao, pointed)) {
1325 if (playersao->setWieldedItem(selected_item))
1326 SendInventory(playersao, true);
1333 warningstream << "Server: Invalid action " << action << std::endl;
1338 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1342 for (u16 k = 0; k < num; k++) {
1347 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1348 m_playing_sounds.find(id);
1349 if (i == m_playing_sounds.end())
1352 ServerPlayingSound &psound = i->second;
1353 psound.clients.erase(pkt->getPeerId());
1354 if (psound.clients.empty())
1355 m_playing_sounds.erase(i++);
1359 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1362 std::string formname;
1365 *pkt >> p >> formname >> num;
1368 for (u16 k = 0; k < num; k++) {
1369 std::string fieldname;
1371 fields[fieldname] = pkt->readLongString();
1374 session_t peer_id = pkt->getPeerId();
1375 RemotePlayer *player = m_env->getPlayer(peer_id);
1377 if (player == NULL) {
1379 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1380 peer_id << " disconnecting peer!" << std::endl;
1381 DisconnectPeer(peer_id);
1385 PlayerSAO *playersao = player->getPlayerSAO();
1386 if (playersao == NULL) {
1388 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1389 peer_id << " disconnecting peer!" << std::endl;
1390 DisconnectPeer(peer_id);
1394 // If something goes wrong, this player is to blame
1395 RollbackScopeActor rollback_scope(m_rollback,
1396 std::string("player:")+player->getName());
1398 // Check the target node for rollback data; leave others unnoticed
1399 RollbackNode rn_old(&m_env->getMap(), p, this);
1401 m_script->node_on_receive_fields(p, formname, fields, playersao);
1403 // Report rollback data
1404 RollbackNode rn_new(&m_env->getMap(), p, this);
1405 if (rollback() && rn_new != rn_old) {
1406 RollbackAction action;
1407 action.setSetNode(p, rn_old, rn_new);
1408 rollback()->reportAction(action);
1412 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1414 std::string client_formspec_name;
1417 *pkt >> client_formspec_name >> num;
1420 for (u16 k = 0; k < num; k++) {
1421 std::string fieldname;
1423 fields[fieldname] = pkt->readLongString();
1426 session_t peer_id = pkt->getPeerId();
1427 RemotePlayer *player = m_env->getPlayer(peer_id);
1429 if (player == NULL) {
1431 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1432 peer_id << " disconnecting peer!" << std::endl;
1433 DisconnectPeer(peer_id);
1437 PlayerSAO *playersao = player->getPlayerSAO();
1438 if (playersao == NULL) {
1440 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1441 peer_id << " disconnecting peer!" << std::endl;
1442 DisconnectPeer(peer_id);
1446 if (client_formspec_name.empty()) { // pass through inventory submits
1447 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1451 // verify that we displayed the formspec to the user
1452 const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1453 if (peer_state_iterator != m_formspec_state_data.end()) {
1454 const std::string &server_formspec_name = peer_state_iterator->second;
1455 if (client_formspec_name == server_formspec_name) {
1456 auto it = fields.find("quit");
1457 if (it != fields.end() && it->second == "true")
1458 m_formspec_state_data.erase(peer_state_iterator);
1460 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1463 actionstream << "'" << player->getName()
1464 << "' submitted formspec ('" << client_formspec_name
1465 << "') but the name of the formspec doesn't match the"
1466 " expected name ('" << server_formspec_name << "')";
1469 actionstream << "'" << player->getName()
1470 << "' submitted formspec ('" << client_formspec_name
1471 << "') but server hasn't sent formspec to client";
1473 actionstream << ", possible exploitation attempt" << std::endl;
1476 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1478 session_t peer_id = pkt->getPeerId();
1479 RemoteClient *client = getClient(peer_id, CS_Invalid);
1480 ClientState cstate = client->getState();
1482 std::string playername = client->getName();
1485 std::string verification_key;
1487 std::string addr_s = getPeerAddress(peer_id).serializeString();
1490 *pkt >> salt >> verification_key >> is_empty;
1492 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1493 << ", with is_empty=" << (is_empty == 1) << std::endl;
1495 // Either this packet is sent because the user is new or to change the password
1496 if (cstate == CS_HelloSent) {
1497 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1498 actionstream << "Server: Client from " << addr_s
1499 << " tried to set password without being "
1500 << "authenticated, or the username being new." << std::endl;
1501 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1505 if (!isSingleplayer() &&
1506 g_settings->getBool("disallow_empty_password") &&
1508 actionstream << "Server: " << playername
1509 << " supplied empty password from " << addr_s << std::endl;
1510 DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1514 std::string initial_ver_key;
1516 initial_ver_key = encode_srp_verifier(verification_key, salt);
1517 m_script->createAuth(playername, initial_ver_key);
1518 m_script->on_authplayer(playername, addr_s, true);
1520 acceptAuth(peer_id, false);
1522 if (cstate < CS_SudoMode) {
1523 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1524 << addr_s << ": " << "Client has wrong state " << cstate << "."
1528 m_clients.event(peer_id, CSE_SudoLeave);
1529 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1530 bool success = m_script->setPassword(playername, pw_db_field);
1532 actionstream << playername << " changes password" << std::endl;
1533 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1534 L"Password change successful."));
1536 actionstream << playername <<
1537 " tries to change password but it fails" << std::endl;
1538 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1539 L"Password change failed or unavailable."));
1544 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1546 session_t peer_id = pkt->getPeerId();
1547 RemoteClient *client = getClient(peer_id, CS_Invalid);
1548 ClientState cstate = client->getState();
1550 bool wantSudo = (cstate == CS_Active);
1552 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1553 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1554 " from " << getPeerAddress(peer_id).serializeString() <<
1555 ". Ignoring." << std::endl;
1559 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1560 actionstream << "Server: got SRP _A packet, while auth is already "
1561 "going on with mech " << client->chosen_mech << " from " <<
1562 getPeerAddress(peer_id).serializeString() <<
1563 " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1565 DenySudoAccess(peer_id);
1569 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1573 std::string bytes_A;
1575 *pkt >> bytes_A >> based_on;
1577 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1578 << "based_on=" << int(based_on) << " and len_A="
1579 << bytes_A.length() << "." << std::endl;
1581 AuthMechanism chosen = (based_on == 0) ?
1582 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1585 if (!client->isSudoMechAllowed(chosen)) {
1586 actionstream << "Server: Player \"" << client->getName() <<
1587 "\" at " << getPeerAddress(peer_id).serializeString() <<
1588 " tried to change password using unallowed mech " << chosen <<
1590 DenySudoAccess(peer_id);
1594 if (!client->isMechAllowed(chosen)) {
1595 actionstream << "Server: Client tried to authenticate from " <<
1596 getPeerAddress(peer_id).serializeString() <<
1597 " using unallowed mech " << chosen << "." << std::endl;
1598 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1603 client->chosen_mech = chosen;
1606 std::string verifier;
1608 if (based_on == 0) {
1610 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1612 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1613 // Non-base64 errors should have been catched in the init handler
1614 actionstream << "Server: User " << client->getName() <<
1615 " tried to log in, but srp verifier field was invalid (most likely "
1616 "invalid base64)." << std::endl;
1617 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1624 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1625 client->getName().c_str(),
1626 (const unsigned char *) salt.c_str(), salt.size(),
1627 (const unsigned char *) verifier.c_str(), verifier.size(),
1628 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1630 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1633 actionstream << "Server: User " << client->getName()
1634 << " tried to log in, SRP-6a safety check violated in _A handler."
1637 DenySudoAccess(peer_id);
1641 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1645 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1646 resp_pkt << salt << std::string(bytes_B, len_B);
1650 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1652 session_t peer_id = pkt->getPeerId();
1653 RemoteClient *client = getClient(peer_id, CS_Invalid);
1654 ClientState cstate = client->getState();
1655 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1656 std::string playername = client->getName();
1658 bool wantSudo = (cstate == CS_Active);
1660 verbosestream << "Server: Received TOSERVER_SRP_BYTES_M." << std::endl;
1662 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1663 warningstream << "Server: got SRP_M packet in wrong state "
1664 << cstate << " from " << addr_s << ". Ignoring." << std::endl;
1668 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1669 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1670 warningstream << "Server: got SRP_M packet, while auth "
1671 "is going on with mech " << client->chosen_mech << " from "
1672 << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1674 DenySudoAccess(peer_id);
1678 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1682 std::string bytes_M;
1685 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1686 != bytes_M.size()) {
1687 actionstream << "Server: User " << playername << " at " << addr_s
1688 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1689 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1693 unsigned char *bytes_HAMK = 0;
1695 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1696 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1700 actionstream << "Server: User " << playername << " at " << addr_s
1701 << " tried to change their password, but supplied wrong"
1702 << " (SRP) password for authentication." << std::endl;
1703 DenySudoAccess(peer_id);
1707 actionstream << "Server: User " << playername << " at " << addr_s
1708 << " supplied wrong password (auth mechanism: SRP)." << std::endl;
1709 m_script->on_authplayer(playername, addr_s, false);
1710 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1714 if (client->create_player_on_auth_success) {
1715 m_script->createAuth(playername, client->enc_pwd);
1717 std::string checkpwd; // not used, but needed for passing something
1718 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1719 errorstream << "Server: " << playername <<
1720 " cannot be authenticated (auth handler does not work?)" <<
1722 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1725 client->create_player_on_auth_success = false;
1728 m_script->on_authplayer(playername, addr_s, true);
1729 acceptAuth(peer_id, wantSudo);
1736 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1738 std::string channel_name;
1739 *pkt >> channel_name;
1741 session_t peer_id = pkt->getPeerId();
1742 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1743 1 + 2 + channel_name.size(), peer_id);
1745 // Send signal to client to notify join succeed or not
1746 if (g_settings->getBool("enable_mod_channels") &&
1747 m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1748 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1749 infostream << "Peer " << peer_id << " joined channel " <<
1750 channel_name << std::endl;
1753 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1754 infostream << "Peer " << peer_id << " tried to join channel " <<
1755 channel_name << ", but was already registered." << std::endl;
1757 resp_pkt << channel_name;
1761 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1763 std::string channel_name;
1764 *pkt >> channel_name;
1766 session_t peer_id = pkt->getPeerId();
1767 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1768 1 + 2 + channel_name.size(), peer_id);
1770 // Send signal to client to notify join succeed or not
1771 if (g_settings->getBool("enable_mod_channels") &&
1772 m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1773 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1774 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1777 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1778 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1779 ", but was not registered." << std::endl;
1781 resp_pkt << channel_name;
1785 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1787 std::string channel_name, channel_msg;
1788 *pkt >> channel_name >> channel_msg;
1790 session_t peer_id = pkt->getPeerId();
1791 verbosestream << "Mod channel message received from peer " << peer_id <<
1792 " on channel " << channel_name << " message: " << channel_msg <<
1795 // If mod channels are not enabled, discard message
1796 if (!g_settings->getBool("enable_mod_channels")) {
1800 // If channel not registered, signal it and ignore message
1801 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1802 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1803 1 + 2 + channel_name.size(), peer_id);
1804 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1809 // @TODO: filter, rate limit
1811 broadcastModChannelMessage(channel_name, channel_msg, peer_id);