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 playersao->setBasePosition(position);
492 player->setSpeed(speed);
493 playersao->setLookPitch(pitch);
494 playersao->setPlayerYaw(yaw);
495 playersao->setFov(fov);
496 playersao->setWantedRange(wanted_range);
498 player->keyPressed = keyPressed;
499 player->control.up = (keyPressed & (0x1 << 0));
500 player->control.down = (keyPressed & (0x1 << 1));
501 player->control.left = (keyPressed & (0x1 << 2));
502 player->control.right = (keyPressed & (0x1 << 3));
503 player->control.jump = (keyPressed & (0x1 << 4));
504 player->control.aux1 = (keyPressed & (0x1 << 5));
505 player->control.sneak = (keyPressed & (0x1 << 6));
506 player->control.dig = (keyPressed & (0x1 << 7));
507 player->control.place = (keyPressed & (0x1 << 8));
508 player->control.zoom = (keyPressed & (0x1 << 9));
510 if (playersao->checkMovementCheat()) {
512 m_script->on_cheat(playersao, "moved_too_fast");
513 SendMovePlayer(pkt->getPeerId());
517 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
519 session_t peer_id = pkt->getPeerId();
520 RemotePlayer *player = m_env->getPlayer(peer_id);
521 if (player == NULL) {
523 "Server::ProcessData(): Canceling: No player for peer_id=" <<
524 peer_id << " disconnecting peer!" << std::endl;
525 DisconnectPeer(peer_id);
529 PlayerSAO *playersao = player->getPlayerSAO();
530 if (playersao == NULL) {
532 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
533 peer_id << " disconnecting peer!" << std::endl;
534 DisconnectPeer(peer_id);
538 // If player is dead we don't care of this packet
539 if (playersao->isDead()) {
540 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
541 << " is dead. Ignoring packet";
545 process_PlayerPos(player, playersao, pkt);
548 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
550 if (pkt->getSize() < 1)
564 RemoteClient *client = getClient(pkt->getPeerId());
566 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
567 throw con::InvalidIncomingDataException
568 ("DELETEDBLOCKS length is too short");
571 for (u16 i = 0; i < count; i++) {
574 client->SetBlockNotSent(p);
578 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
580 session_t peer_id = pkt->getPeerId();
581 RemotePlayer *player = m_env->getPlayer(peer_id);
583 if (player == NULL) {
585 "Server::ProcessData(): Canceling: No player for peer_id=" <<
586 peer_id << " disconnecting peer!" << std::endl;
587 DisconnectPeer(peer_id);
591 PlayerSAO *playersao = player->getPlayerSAO();
592 if (playersao == NULL) {
594 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
595 peer_id << " disconnecting peer!" << std::endl;
596 DisconnectPeer(peer_id);
600 // Strip command and create a stream
601 std::string datastring(pkt->getString(0), pkt->getSize());
602 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
604 std::istringstream is(datastring, std::ios_base::binary);
606 std::unique_ptr<InventoryAction> a(InventoryAction::deSerialize(is));
608 infostream << "TOSERVER_INVENTORY_ACTION: "
609 << "InventoryAction::deSerialize() returned NULL"
614 // If something goes wrong, this player is to blame
615 RollbackScopeActor rollback_scope(m_rollback,
616 std::string("player:")+player->getName());
619 Note: Always set inventory not sent, to repair cases
620 where the client made a bad prediction.
623 const bool player_has_interact = checkPriv(player->getName(), "interact");
625 auto check_inv_access = [player, player_has_interact] (
626 const InventoryLocation &loc) -> bool {
627 if (loc.type == InventoryLocation::CURRENT_PLAYER)
628 return false; // Only used internally on the client, never sent
629 if (loc.type == InventoryLocation::PLAYER) {
630 // Allow access to own inventory in all cases
631 return loc.name == player->getName();
634 if (!player_has_interact) {
635 infostream << "Cannot modify foreign inventory: "
636 << "No interact privilege" << std::endl;
643 Handle restrictions and special cases of the move action
645 if (a->getType() == IAction::Move) {
646 IMoveAction *ma = (IMoveAction*)a.get();
648 ma->from_inv.applyCurrentPlayer(player->getName());
649 ma->to_inv.applyCurrentPlayer(player->getName());
651 m_inventory_mgr->setInventoryModified(ma->from_inv);
652 if (ma->from_inv != ma->to_inv)
653 m_inventory_mgr->setInventoryModified(ma->to_inv);
655 if (!check_inv_access(ma->from_inv) ||
656 !check_inv_access(ma->to_inv))
659 InventoryLocation *remote = ma->from_inv.type == InventoryLocation::PLAYER ?
660 &ma->to_inv : &ma->from_inv;
662 // Check for out-of-range interaction
663 if (remote->type == InventoryLocation::NODEMETA) {
664 v3f node_pos = intToFloat(remote->p, BS);
665 v3f player_pos = player->getPlayerSAO()->getEyePosition();
666 f32 d = player_pos.getDistanceFrom(node_pos);
667 if (!checkInteractDistance(player, d, "inventory"))
672 Disable moving items out of craftpreview
674 if (ma->from_list == "craftpreview") {
675 infostream << "Ignoring IMoveAction from "
676 << (ma->from_inv.dump()) << ":" << ma->from_list
677 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
678 << " because src is " << ma->from_list << std::endl;
683 Disable moving items into craftresult and craftpreview
685 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
686 infostream << "Ignoring IMoveAction from "
687 << (ma->from_inv.dump()) << ":" << ma->from_list
688 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
689 << " because dst is " << ma->to_list << std::endl;
694 Handle restrictions and special cases of the drop action
696 else if (a->getType() == IAction::Drop) {
697 IDropAction *da = (IDropAction*)a.get();
699 da->from_inv.applyCurrentPlayer(player->getName());
701 m_inventory_mgr->setInventoryModified(da->from_inv);
704 Disable dropping items out of craftpreview
706 if (da->from_list == "craftpreview") {
707 infostream << "Ignoring IDropAction from "
708 << (da->from_inv.dump()) << ":" << da->from_list
709 << " because src is " << da->from_list << std::endl;
713 // Disallow dropping items if not allowed to interact
714 if (!player_has_interact || !check_inv_access(da->from_inv))
717 // Disallow dropping items if dead
718 if (playersao->isDead()) {
719 infostream << "Ignoring IDropAction from "
720 << (da->from_inv.dump()) << ":" << da->from_list
721 << " because player is dead." << std::endl;
726 Handle restrictions and special cases of the craft action
728 else if (a->getType() == IAction::Craft) {
729 ICraftAction *ca = (ICraftAction*)a.get();
731 ca->craft_inv.applyCurrentPlayer(player->getName());
733 m_inventory_mgr->setInventoryModified(ca->craft_inv);
735 // Disallow crafting if not allowed to interact
736 if (!player_has_interact) {
737 infostream << "Cannot craft: "
738 << "No interact privilege" << std::endl;
742 if (!check_inv_access(ca->craft_inv))
745 // Unknown action. Ignored.
750 a->apply(m_inventory_mgr.get(), playersao, this);
753 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
755 std::wstring message;
758 session_t peer_id = pkt->getPeerId();
759 RemotePlayer *player = m_env->getPlayer(peer_id);
760 if (player == NULL) {
762 "Server::ProcessData(): Canceling: No player for peer_id=" <<
763 peer_id << " disconnecting peer!" << std::endl;
764 DisconnectPeer(peer_id);
768 std::string name = player->getName();
770 std::wstring answer_to_sender = handleChat(name, message, true, player);
771 if (!answer_to_sender.empty()) {
772 // Send the answer to sender
773 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
778 void Server::handleCommand_Damage(NetworkPacket* pkt)
784 session_t peer_id = pkt->getPeerId();
785 RemotePlayer *player = m_env->getPlayer(peer_id);
787 if (player == NULL) {
789 "Server::ProcessData(): Canceling: No player for peer_id=" <<
790 peer_id << " disconnecting peer!" << std::endl;
791 DisconnectPeer(peer_id);
795 PlayerSAO *playersao = player->getPlayerSAO();
796 if (playersao == NULL) {
798 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
799 peer_id << " disconnecting peer!" << std::endl;
800 DisconnectPeer(peer_id);
804 if (!playersao->isImmortal()) {
805 if (playersao->isDead()) {
806 verbosestream << "Server::ProcessData(): Info: "
807 "Ignoring damage as player " << player->getName()
808 << " is already dead." << std::endl;
812 actionstream << player->getName() << " damaged by "
813 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
816 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
817 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
818 SendPlayerHPOrDie(playersao, reason);
822 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
824 if (pkt->getSize() < 2)
827 session_t peer_id = pkt->getPeerId();
828 RemotePlayer *player = m_env->getPlayer(peer_id);
830 if (player == NULL) {
832 "Server::ProcessData(): Canceling: No player for peer_id=" <<
833 peer_id << " disconnecting peer!" << std::endl;
834 DisconnectPeer(peer_id);
838 PlayerSAO *playersao = player->getPlayerSAO();
839 if (playersao == NULL) {
841 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
842 peer_id << " disconnecting peer!" << std::endl;
843 DisconnectPeer(peer_id);
851 if (item >= player->getHotbarItemcount()) {
852 actionstream << "Player: " << player->getName()
853 << " tried to access item=" << item
854 << " out of hotbar_itemcount="
855 << player->getHotbarItemcount()
856 << "; ignoring." << std::endl;
860 playersao->getPlayer()->setWieldIndex(item);
863 void Server::handleCommand_Respawn(NetworkPacket* pkt)
865 session_t peer_id = pkt->getPeerId();
866 RemotePlayer *player = m_env->getPlayer(peer_id);
867 if (player == NULL) {
869 "Server::ProcessData(): Canceling: No player for peer_id=" <<
870 peer_id << " disconnecting peer!" << std::endl;
871 DisconnectPeer(peer_id);
875 PlayerSAO *playersao = player->getPlayerSAO();
878 if (!playersao->isDead())
881 RespawnPlayer(peer_id);
883 actionstream << player->getName() << " respawns at "
884 << PP(playersao->getBasePosition() / BS) << std::endl;
886 // ActiveObject is added to environment in AsyncRunStep after
887 // the previous addition has been successfully removed
890 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
892 ItemStack selected_item, hand_item;
893 player->getWieldedItem(&selected_item, &hand_item);
894 f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
895 hand_item.getDefinition(m_itemdef));
897 // Cube diagonal * 1.5 for maximal supported node extents:
898 // sqrt(3) * 1.5 ≅ 2.6
899 if (d > max_d + 2.6f * BS) {
900 actionstream << "Player " << player->getName()
901 << " tried to access " << what
903 << "d=" << d << ", max_d=" << max_d
904 << "; ignoring." << std::endl;
906 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
912 void Server::handleCommand_Interact(NetworkPacket *pkt)
918 [5] u32 length of the next item (plen)
919 [9] serialized PointedThing
920 [9 + plen] player position information
923 InteractAction action;
926 *pkt >> (u8 &)action;
929 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
930 PointedThing pointed;
931 pointed.deSerialize(tmp_is);
933 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
934 << item_i << ", pointed=" << pointed.dump() << std::endl;
936 session_t peer_id = pkt->getPeerId();
937 RemotePlayer *player = m_env->getPlayer(peer_id);
939 if (player == NULL) {
941 "Server::ProcessData(): Canceling: No player for peer_id=" <<
942 peer_id << " disconnecting peer!" << std::endl;
943 DisconnectPeer(peer_id);
947 PlayerSAO *playersao = player->getPlayerSAO();
948 if (playersao == NULL) {
950 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
951 peer_id << " disconnecting peer!" << std::endl;
952 DisconnectPeer(peer_id);
956 if (playersao->isDead()) {
957 actionstream << "Server: " << player->getName()
958 << " tried to interact while dead; ignoring." << std::endl;
959 if (pointed.type == POINTEDTHING_NODE) {
960 // Re-send block to revert change on client-side
961 RemoteClient *client = getClient(peer_id);
962 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
963 client->SetBlockNotSent(blockpos);
966 m_script->on_cheat(playersao, "interacted_while_dead");
970 process_PlayerPos(player, playersao, pkt);
972 v3f player_pos = playersao->getLastGoodPosition();
974 // Update wielded item
976 if (item_i >= player->getHotbarItemcount()) {
977 actionstream << "Player: " << player->getName()
978 << " tried to access item=" << item_i
979 << " out of hotbar_itemcount="
980 << player->getHotbarItemcount()
981 << "; ignoring." << std::endl;
985 playersao->getPlayer()->setWieldIndex(item_i);
987 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
988 ServerActiveObject *pointed_object = NULL;
989 if (pointed.type == POINTEDTHING_OBJECT) {
990 pointed_object = m_env->getActiveObject(pointed.object_id);
991 if (pointed_object == NULL) {
992 verbosestream << "TOSERVER_INTERACT: "
993 "pointed object is NULL" << std::endl;
1000 Make sure the player is allowed to do it
1002 if (!checkPriv(player->getName(), "interact")) {
1003 actionstream << player->getName() << " attempted to interact with " <<
1004 pointed.dump() << " without 'interact' privilege" << std::endl;
1006 if (pointed.type != POINTEDTHING_NODE)
1009 // Re-send block to revert change on client-side
1010 RemoteClient *client = getClient(peer_id);
1011 // Digging completed -> under
1012 if (action == INTERACT_DIGGING_COMPLETED) {
1013 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1014 client->SetBlockNotSent(blockpos);
1016 // Placement -> above
1017 else if (action == INTERACT_PLACE) {
1018 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1019 client->SetBlockNotSent(blockpos);
1025 Check that target is reasonably close
1027 static thread_local const bool enable_anticheat =
1028 !g_settings->getBool("disable_anticheat");
1030 if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1031 action == INTERACT_PLACE || action == INTERACT_USE) &&
1032 enable_anticheat && !isSingleplayer()) {
1033 v3f target_pos = player_pos;
1034 if (pointed.type == POINTEDTHING_NODE) {
1035 target_pos = intToFloat(pointed.node_undersurface, BS);
1036 } else if (pointed.type == POINTEDTHING_OBJECT) {
1037 target_pos = pointed_object->getBasePosition();
1039 float d = playersao->getEyePosition().getDistanceFrom(target_pos);
1041 if (!checkInteractDistance(player, d, pointed.dump())) {
1042 if (pointed.type == POINTEDTHING_NODE) {
1043 // Re-send block to revert change on client-side
1044 RemoteClient *client = getClient(peer_id);
1045 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1046 client->SetBlockNotSent(blockpos);
1053 If something goes wrong, this player is to blame
1055 RollbackScopeActor rollback_scope(m_rollback,
1056 std::string("player:")+player->getName());
1059 // Start digging or punch object
1060 case INTERACT_START_DIGGING: {
1061 if (pointed.type == POINTEDTHING_NODE) {
1062 MapNode n(CONTENT_IGNORE);
1065 v3s16 p_under = pointed.node_undersurface;
1066 n = m_env->getMap().getNode(p_under, &pos_ok);
1068 infostream << "Server: Not punching: Node not found. "
1069 "Adding block to emerge queue." << std::endl;
1070 m_emerge->enqueueBlockEmerge(peer_id,
1071 getNodeBlockPos(pointed.node_abovesurface), false);
1074 if (n.getContent() != CONTENT_IGNORE)
1075 m_script->node_on_punch(p_under, n, playersao, pointed);
1078 playersao->noCheatDigStart(p_under);
1083 // Skip if the object can't be interacted with anymore
1084 if (pointed.type != POINTEDTHING_OBJECT || pointed_object->isGone())
1087 ItemStack selected_item, hand_item;
1088 ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
1089 ToolCapabilities toolcap =
1090 tool_item.getToolCapabilities(m_itemdef);
1091 v3f dir = (pointed_object->getBasePosition() -
1092 (playersao->getBasePosition() + playersao->getEyeOffset())
1094 float time_from_last_punch =
1095 playersao->resetTimeFromLastPunch();
1097 u16 src_original_hp = pointed_object->getHP();
1098 u16 dst_origin_hp = playersao->getHP();
1100 u16 wear = pointed_object->punch(dir, &toolcap, playersao,
1101 time_from_last_punch);
1103 // Callback may have changed item, so get it again
1104 playersao->getWieldedItem(&selected_item);
1105 bool changed = selected_item.addWear(wear, m_itemdef);
1107 playersao->setWieldedItem(selected_item);
1109 // If the object is a player and its HP changed
1110 if (src_original_hp != pointed_object->getHP() &&
1111 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1112 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1113 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1116 // If the puncher is a player and its HP changed
1117 if (dst_origin_hp != playersao->getHP())
1118 SendPlayerHPOrDie(playersao,
1119 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1122 } // action == INTERACT_START_DIGGING
1124 case INTERACT_STOP_DIGGING:
1128 case INTERACT_DIGGING_COMPLETED: {
1129 // Only digging of nodes
1130 if (pointed.type != POINTEDTHING_NODE)
1133 v3s16 p_under = pointed.node_undersurface;
1134 MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1136 infostream << "Server: Not finishing digging: Node not found. "
1137 "Adding block to emerge queue." << std::endl;
1138 m_emerge->enqueueBlockEmerge(peer_id,
1139 getNodeBlockPos(pointed.node_abovesurface), false);
1142 /* Cheat prevention */
1143 bool is_valid_dig = true;
1144 if (enable_anticheat && !isSingleplayer()) {
1145 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1146 float nocheat_t = playersao->getNoCheatDigTime();
1147 playersao->noCheatDigEnd();
1148 // If player didn't start digging this, ignore dig
1149 if (nocheat_p != p_under) {
1150 infostream << "Server: " << player->getName()
1151 << " started digging "
1152 << PP(nocheat_p) << " and completed digging "
1153 << PP(p_under) << "; not digging." << std::endl;
1154 is_valid_dig = false;
1156 m_script->on_cheat(playersao, "finished_unknown_dig");
1159 // Get player's wielded item
1160 // See also: Game::handleDigging
1161 ItemStack selected_item, hand_item;
1162 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1164 // Get diggability and expected digging time
1165 DigParams params = getDigParams(m_nodedef->get(n).groups,
1166 &selected_item.getToolCapabilities(m_itemdef));
1167 // If can't dig, try hand
1168 if (!params.diggable) {
1169 params = getDigParams(m_nodedef->get(n).groups,
1170 &hand_item.getToolCapabilities(m_itemdef));
1172 // If can't dig, ignore dig
1173 if (!params.diggable) {
1174 infostream << "Server: " << player->getName()
1175 << " completed digging " << PP(p_under)
1176 << ", which is not diggable with tool; not digging."
1178 is_valid_dig = false;
1180 m_script->on_cheat(playersao, "dug_unbreakable");
1182 // Check digging time
1183 // If already invalidated, we don't have to
1184 if (!is_valid_dig) {
1185 // Well not our problem then
1187 // Clean and long dig
1188 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1189 // All is good, but grab time from pool; don't care if
1190 // it's actually available
1191 playersao->getDigPool().grab(params.time);
1193 // Short or laggy dig
1194 // Try getting the time from pool
1195 else if (playersao->getDigPool().grab(params.time)) {
1200 infostream << "Server: " << player->getName()
1201 << " completed digging " << PP(p_under)
1202 << "too fast; not digging." << std::endl;
1203 is_valid_dig = false;
1205 m_script->on_cheat(playersao, "dug_too_fast");
1209 /* Actually dig node */
1211 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1212 m_script->node_on_dig(p_under, n, playersao);
1214 v3s16 blockpos = getNodeBlockPos(p_under);
1215 RemoteClient *client = getClient(peer_id);
1216 // Send unusual result (that is, node not being removed)
1217 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR)
1218 // Re-send block to revert change on client-side
1219 client->SetBlockNotSent(blockpos);
1221 client->ResendBlockIfOnWire(blockpos);
1224 } // action == INTERACT_DIGGING_COMPLETED
1226 // Place block or right-click object
1227 case INTERACT_PLACE: {
1228 ItemStack selected_item;
1229 playersao->getWieldedItem(&selected_item, nullptr);
1231 // Reset build time counter
1232 if (pointed.type == POINTEDTHING_NODE &&
1233 selected_item.getDefinition(m_itemdef).type == ITEM_NODE)
1234 getClient(peer_id)->m_time_from_building = 0.0;
1236 if (pointed.type == POINTEDTHING_OBJECT) {
1237 // Right click object
1239 // Skip if object can't be interacted with anymore
1240 if (pointed_object->isGone())
1243 actionstream << player->getName() << " right-clicks object "
1244 << pointed.object_id << ": "
1245 << pointed_object->getDescription() << std::endl;
1248 if (m_script->item_OnSecondaryUse(
1249 selected_item, playersao, pointed)) {
1250 if (playersao->setWieldedItem(selected_item)) {
1251 SendInventory(playersao, true);
1255 pointed_object->rightClick(playersao);
1256 } else if (m_script->item_OnPlace(selected_item, playersao, pointed)) {
1257 // Placement was handled in lua
1259 // Apply returned ItemStack
1260 if (playersao->setWieldedItem(selected_item))
1261 SendInventory(playersao, true);
1264 if (pointed.type != POINTEDTHING_NODE)
1267 // If item has node placement prediction, always send the
1268 // blocks to make sure the client knows what exactly happened
1269 RemoteClient *client = getClient(peer_id);
1270 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1271 v3s16 blockpos2 = getNodeBlockPos(pointed.node_undersurface);
1272 if (!selected_item.getDefinition(m_itemdef
1273 ).node_placement_prediction.empty()) {
1274 client->SetBlockNotSent(blockpos);
1275 if (blockpos2 != blockpos)
1276 client->SetBlockNotSent(blockpos2);
1278 client->ResendBlockIfOnWire(blockpos);
1279 if (blockpos2 != blockpos)
1280 client->ResendBlockIfOnWire(blockpos2);
1284 } // action == INTERACT_PLACE
1286 case INTERACT_USE: {
1287 ItemStack selected_item;
1288 playersao->getWieldedItem(&selected_item, nullptr);
1290 actionstream << player->getName() << " uses " << selected_item.name
1291 << ", pointing at " << pointed.dump() << std::endl;
1293 if (m_script->item_OnUse(selected_item, playersao, pointed)) {
1294 // Apply returned ItemStack
1295 if (playersao->setWieldedItem(selected_item))
1296 SendInventory(playersao, true);
1303 case INTERACT_ACTIVATE: {
1304 ItemStack selected_item;
1305 playersao->getWieldedItem(&selected_item, nullptr);
1307 actionstream << player->getName() << " activates "
1308 << selected_item.name << std::endl;
1310 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1312 if (m_script->item_OnSecondaryUse(selected_item, playersao, pointed)) {
1313 if (playersao->setWieldedItem(selected_item))
1314 SendInventory(playersao, true);
1321 warningstream << "Server: Invalid action " << action << std::endl;
1326 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1330 for (u16 k = 0; k < num; k++) {
1335 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1336 m_playing_sounds.find(id);
1337 if (i == m_playing_sounds.end())
1340 ServerPlayingSound &psound = i->second;
1341 psound.clients.erase(pkt->getPeerId());
1342 if (psound.clients.empty())
1343 m_playing_sounds.erase(i++);
1347 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1350 std::string formname;
1353 *pkt >> p >> formname >> num;
1356 for (u16 k = 0; k < num; k++) {
1357 std::string fieldname;
1359 fields[fieldname] = pkt->readLongString();
1362 session_t peer_id = pkt->getPeerId();
1363 RemotePlayer *player = m_env->getPlayer(peer_id);
1365 if (player == NULL) {
1367 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1368 peer_id << " disconnecting peer!" << std::endl;
1369 DisconnectPeer(peer_id);
1373 PlayerSAO *playersao = player->getPlayerSAO();
1374 if (playersao == NULL) {
1376 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1377 peer_id << " disconnecting peer!" << std::endl;
1378 DisconnectPeer(peer_id);
1382 // If something goes wrong, this player is to blame
1383 RollbackScopeActor rollback_scope(m_rollback,
1384 std::string("player:")+player->getName());
1386 // Check the target node for rollback data; leave others unnoticed
1387 RollbackNode rn_old(&m_env->getMap(), p, this);
1389 m_script->node_on_receive_fields(p, formname, fields, playersao);
1391 // Report rollback data
1392 RollbackNode rn_new(&m_env->getMap(), p, this);
1393 if (rollback() && rn_new != rn_old) {
1394 RollbackAction action;
1395 action.setSetNode(p, rn_old, rn_new);
1396 rollback()->reportAction(action);
1400 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1402 std::string client_formspec_name;
1405 *pkt >> client_formspec_name >> num;
1408 for (u16 k = 0; k < num; k++) {
1409 std::string fieldname;
1411 fields[fieldname] = pkt->readLongString();
1414 session_t peer_id = pkt->getPeerId();
1415 RemotePlayer *player = m_env->getPlayer(peer_id);
1417 if (player == NULL) {
1419 "Server::ProcessData(): Canceling: No player for peer_id=" <<
1420 peer_id << " disconnecting peer!" << std::endl;
1421 DisconnectPeer(peer_id);
1425 PlayerSAO *playersao = player->getPlayerSAO();
1426 if (playersao == NULL) {
1428 "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1429 peer_id << " disconnecting peer!" << std::endl;
1430 DisconnectPeer(peer_id);
1434 if (client_formspec_name.empty()) { // pass through inventory submits
1435 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1439 // verify that we displayed the formspec to the user
1440 const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1441 if (peer_state_iterator != m_formspec_state_data.end()) {
1442 const std::string &server_formspec_name = peer_state_iterator->second;
1443 if (client_formspec_name == server_formspec_name) {
1444 auto it = fields.find("quit");
1445 if (it != fields.end() && it->second == "true")
1446 m_formspec_state_data.erase(peer_state_iterator);
1448 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1451 actionstream << "'" << player->getName()
1452 << "' submitted formspec ('" << client_formspec_name
1453 << "') but the name of the formspec doesn't match the"
1454 " expected name ('" << server_formspec_name << "')";
1457 actionstream << "'" << player->getName()
1458 << "' submitted formspec ('" << client_formspec_name
1459 << "') but server hasn't sent formspec to client";
1461 actionstream << ", possible exploitation attempt" << std::endl;
1464 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1466 session_t peer_id = pkt->getPeerId();
1467 RemoteClient *client = getClient(peer_id, CS_Invalid);
1468 ClientState cstate = client->getState();
1470 std::string playername = client->getName();
1473 std::string verification_key;
1475 std::string addr_s = getPeerAddress(peer_id).serializeString();
1478 *pkt >> salt >> verification_key >> is_empty;
1480 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1481 << ", with is_empty=" << (is_empty == 1) << std::endl;
1483 // Either this packet is sent because the user is new or to change the password
1484 if (cstate == CS_HelloSent) {
1485 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1486 actionstream << "Server: Client from " << addr_s
1487 << " tried to set password without being "
1488 << "authenticated, or the username being new." << std::endl;
1489 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1493 if (!isSingleplayer() &&
1494 g_settings->getBool("disallow_empty_password") &&
1496 actionstream << "Server: " << playername
1497 << " supplied empty password from " << addr_s << std::endl;
1498 DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1502 std::string initial_ver_key;
1504 initial_ver_key = encode_srp_verifier(verification_key, salt);
1505 m_script->createAuth(playername, initial_ver_key);
1506 m_script->on_authplayer(playername, addr_s, true);
1508 acceptAuth(peer_id, false);
1510 if (cstate < CS_SudoMode) {
1511 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1512 << addr_s << ": " << "Client has wrong state " << cstate << "."
1516 m_clients.event(peer_id, CSE_SudoLeave);
1517 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1518 bool success = m_script->setPassword(playername, pw_db_field);
1520 actionstream << playername << " changes password" << std::endl;
1521 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1522 L"Password change successful."));
1524 actionstream << playername <<
1525 " tries to change password but it fails" << std::endl;
1526 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1527 L"Password change failed or unavailable."));
1532 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1534 session_t peer_id = pkt->getPeerId();
1535 RemoteClient *client = getClient(peer_id, CS_Invalid);
1536 ClientState cstate = client->getState();
1538 bool wantSudo = (cstate == CS_Active);
1540 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1541 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1542 " from " << getPeerAddress(peer_id).serializeString() <<
1543 ". Ignoring." << std::endl;
1547 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1548 actionstream << "Server: got SRP _A packet, while auth is already "
1549 "going on with mech " << client->chosen_mech << " from " <<
1550 getPeerAddress(peer_id).serializeString() <<
1551 " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1553 DenySudoAccess(peer_id);
1557 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1561 std::string bytes_A;
1563 *pkt >> bytes_A >> based_on;
1565 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1566 << "based_on=" << int(based_on) << " and len_A="
1567 << bytes_A.length() << "." << std::endl;
1569 AuthMechanism chosen = (based_on == 0) ?
1570 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1573 if (!client->isSudoMechAllowed(chosen)) {
1574 actionstream << "Server: Player \"" << client->getName() <<
1575 "\" at " << getPeerAddress(peer_id).serializeString() <<
1576 " tried to change password using unallowed mech " << chosen <<
1578 DenySudoAccess(peer_id);
1582 if (!client->isMechAllowed(chosen)) {
1583 actionstream << "Server: Client tried to authenticate from " <<
1584 getPeerAddress(peer_id).serializeString() <<
1585 " using unallowed mech " << chosen << "." << std::endl;
1586 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1591 client->chosen_mech = chosen;
1594 std::string verifier;
1596 if (based_on == 0) {
1598 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1600 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1601 // Non-base64 errors should have been catched in the init handler
1602 actionstream << "Server: User " << client->getName() <<
1603 " tried to log in, but srp verifier field was invalid (most likely "
1604 "invalid base64)." << std::endl;
1605 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1612 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1613 client->getName().c_str(),
1614 (const unsigned char *) salt.c_str(), salt.size(),
1615 (const unsigned char *) verifier.c_str(), verifier.size(),
1616 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1618 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1621 actionstream << "Server: User " << client->getName()
1622 << " tried to log in, SRP-6a safety check violated in _A handler."
1625 DenySudoAccess(peer_id);
1629 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1633 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1634 resp_pkt << salt << std::string(bytes_B, len_B);
1638 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1640 session_t peer_id = pkt->getPeerId();
1641 RemoteClient *client = getClient(peer_id, CS_Invalid);
1642 ClientState cstate = client->getState();
1643 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1644 std::string playername = client->getName();
1646 bool wantSudo = (cstate == CS_Active);
1648 verbosestream << "Server: Received TOSERVER_SRP_BYTES_M." << std::endl;
1650 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1651 warningstream << "Server: got SRP_M packet in wrong state "
1652 << cstate << " from " << addr_s << ". Ignoring." << std::endl;
1656 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1657 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1658 warningstream << "Server: got SRP_M packet, while auth "
1659 "is going on with mech " << client->chosen_mech << " from "
1660 << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1662 DenySudoAccess(peer_id);
1666 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1670 std::string bytes_M;
1673 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1674 != bytes_M.size()) {
1675 actionstream << "Server: User " << playername << " at " << addr_s
1676 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1677 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1681 unsigned char *bytes_HAMK = 0;
1683 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1684 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1688 actionstream << "Server: User " << playername << " at " << addr_s
1689 << " tried to change their password, but supplied wrong"
1690 << " (SRP) password for authentication." << std::endl;
1691 DenySudoAccess(peer_id);
1695 actionstream << "Server: User " << playername << " at " << addr_s
1696 << " supplied wrong password (auth mechanism: SRP)." << std::endl;
1697 m_script->on_authplayer(playername, addr_s, false);
1698 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1702 if (client->create_player_on_auth_success) {
1703 m_script->createAuth(playername, client->enc_pwd);
1705 std::string checkpwd; // not used, but needed for passing something
1706 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1707 errorstream << "Server: " << playername <<
1708 " cannot be authenticated (auth handler does not work?)" <<
1710 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1713 client->create_player_on_auth_success = false;
1716 m_script->on_authplayer(playername, addr_s, true);
1717 acceptAuth(peer_id, wantSudo);
1724 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1726 std::string channel_name;
1727 *pkt >> channel_name;
1729 session_t peer_id = pkt->getPeerId();
1730 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1731 1 + 2 + channel_name.size(), peer_id);
1733 // Send signal to client to notify join succeed or not
1734 if (g_settings->getBool("enable_mod_channels") &&
1735 m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1736 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1737 infostream << "Peer " << peer_id << " joined channel " <<
1738 channel_name << std::endl;
1741 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1742 infostream << "Peer " << peer_id << " tried to join channel " <<
1743 channel_name << ", but was already registered." << std::endl;
1745 resp_pkt << channel_name;
1749 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1751 std::string channel_name;
1752 *pkt >> channel_name;
1754 session_t peer_id = pkt->getPeerId();
1755 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1756 1 + 2 + channel_name.size(), peer_id);
1758 // Send signal to client to notify join succeed or not
1759 if (g_settings->getBool("enable_mod_channels") &&
1760 m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1761 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1762 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1765 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1766 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1767 ", but was not registered." << std::endl;
1769 resp_pkt << channel_name;
1773 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1775 std::string channel_name, channel_msg;
1776 *pkt >> channel_name >> channel_msg;
1778 session_t peer_id = pkt->getPeerId();
1779 verbosestream << "Mod channel message received from peer " << peer_id <<
1780 " on channel " << channel_name << " message: " << channel_msg <<
1783 // If mod channels are not enabled, discard message
1784 if (!g_settings->getBool("enable_mod_channels")) {
1788 // If channel not registered, signal it and ignore message
1789 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1790 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1791 1 + 2 + channel_name.size(), peer_id);
1792 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1797 // @TODO: filter, rate limit
1799 broadcastModChannelMessage(channel_name, channel_msg, peer_id);