3 Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "chatmessage.h"
23 #include "content_sao.h"
26 #include "modchannels.h"
28 #include "remoteplayer.h"
29 #include "rollback_interface.h"
30 #include "scripting_server.h"
34 #include "network/connection.h"
35 #include "network/networkprotocol.h"
36 #include "network/serveropcodes.h"
37 #include "util/auth.h"
38 #include "util/base64.h"
39 #include "util/pointedthing.h"
40 #include "util/serialize.h"
43 void Server::handleCommand_Deprecated(NetworkPacket* pkt)
45 infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
46 << " not supported anymore" << std::endl;
49 void Server::handleCommand_Init(NetworkPacket* pkt)
52 if(pkt->getSize() < 1)
55 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
59 Address address = getPeerAddress(pkt->getPeerId());
60 addr_s = address.serializeString();
62 catch (con::PeerNotFoundException &e) {
64 * no peer for this packet found
65 * most common reason is peer timeout, e.g. peer didn't
66 * respond for some time, your server was overloaded or
69 infostream << "Server::ProcessData(): Canceling: peer "
70 << pkt->getPeerId() << " not found" << std::endl;
74 // If net_proto_version is set, this client has already been handled
75 if (client->getState() > CS_Created) {
76 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
77 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
81 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
82 << pkt->getPeerId() << ")" << std::endl;
84 // Do not allow multiple players in simple singleplayer mode.
85 // This isn't a perfect way to do it, but will suffice for now
86 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
87 infostream << "Server: Not allowing another client (" << addr_s
88 << ") to connect in simple singleplayer mode" << std::endl;
89 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SINGLEPLAYER);
93 // First byte after command is maximum supported
94 // serialization version
97 u16 min_net_proto_version = 0;
98 u16 max_net_proto_version;
99 std::string playerName;
101 *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
102 >> max_net_proto_version >> playerName;
104 u8 our_max = SER_FMT_VER_HIGHEST_READ;
105 // Use the highest version supported by both
106 u8 depl_serial_v = std::min(client_max, our_max);
107 // If it's lower than the lowest supported, give up.
108 if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
109 depl_serial_v = SER_FMT_VER_INVALID;
111 if (depl_serial_v == SER_FMT_VER_INVALID) {
112 actionstream << "Server: A mismatched client tried to connect from "
113 << addr_s << std::endl;
114 infostream<<"Server: Cannot negotiate serialization version with "
115 << addr_s << std::endl;
116 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
120 client->setPendingSerializationVersion(depl_serial_v);
123 Read and check network protocol version
126 u16 net_proto_version = 0;
128 // Figure out a working version if it is possible at all
129 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
130 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
131 // If maximum is larger than our maximum, go with our maximum
132 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
133 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
134 // Else go with client's maximum
136 net_proto_version = max_net_proto_version;
139 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
140 << min_net_proto_version << ", max: " << max_net_proto_version
141 << ", chosen: " << net_proto_version << std::endl;
143 client->net_proto_version = net_proto_version;
145 if (g_settings->getBool("strict_protocol_version_checking") ||
146 net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
147 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
148 actionstream << "Server: A mismatched client tried to connect from "
149 << addr_s << std::endl;
150 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
157 const char* playername = playerName.c_str();
159 size_t pns = playerName.size();
160 if (pns == 0 || pns > PLAYERNAME_SIZE) {
161 actionstream << "Server: Player with "
162 << ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty")
163 << " name tried to connect from " << addr_s << std::endl;
164 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
168 if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
169 actionstream << "Server: Player with an invalid name "
170 << "tried to connect from " << addr_s << std::endl;
171 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
175 m_clients.setPlayerName(pkt->getPeerId(), playername);
176 //TODO (later) case insensitivity
178 std::string legacyPlayerNameCasing = playerName;
180 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
181 actionstream << "Server: Player with the name \"singleplayer\" "
182 << "tried to connect from " << addr_s << std::endl;
183 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
189 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
190 actionstream << "Server: Player with the name \"" << playerName << "\" "
191 << "tried to connect from " << addr_s << " "
192 << "but it was disallowed for the following reason: "
193 << reason << std::endl;
194 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
199 infostream << "Server: New connection: \"" << playerName << "\" from "
200 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
202 // Enforce user limit.
203 // Don't enforce for users that have some admin right or mod permits it.
204 if (m_clients.isUserLimitReached() &&
205 playername != g_settings->get("name") &&
206 !m_script->can_bypass_userlimit(playername, addr_s)) {
207 actionstream << "Server: " << playername << " tried to join from "
208 << addr_s << ", but there" << " are already max_users="
209 << g_settings->getU16("max_users") << " players." << std::endl;
210 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_TOO_MANY_USERS);
215 Compose auth methods for answer
217 std::string encpwd; // encrypted Password field for the user
218 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
221 client->chosen_mech = AUTH_MECHANISM_NONE;
224 std::vector<std::string> pwd_components = str_split(encpwd, '#');
225 if (pwd_components.size() == 4) {
226 if (pwd_components[1] == "1") { // 1 means srp
227 auth_mechs |= AUTH_MECHANISM_SRP;
228 client->enc_pwd = encpwd;
230 actionstream << "User " << playername
231 << " tried to log in, but password field"
232 << " was invalid (unknown mechcode)." << std::endl;
233 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
236 } else if (base64_is_valid(encpwd)) {
237 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
238 client->enc_pwd = encpwd;
240 actionstream << "User " << playername
241 << " tried to log in, but password field"
242 << " was invalid (invalid base64)." << std::endl;
243 DenyAccess(pkt->getPeerId(), 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, 1 + 4
267 + legacyPlayerNameCasing.size(), pkt->getPeerId());
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(pkt->getPeerId(), CSE_Hello);
281 void Server::handleCommand_Init2(NetworkPacket* pkt)
283 verbosestream << "Server: Got TOSERVER_INIT2 from "
284 << pkt->getPeerId() << std::endl;
286 m_clients.event(pkt->getPeerId(), CSE_GotInit2);
287 u16 protocol_version = m_clients.getProtocolVersion(pkt->getPeerId());
290 if (pkt->getSize() > 0)
294 Send some initialization data
297 infostream << "Server: Sending content to "
298 << getPlayerName(pkt->getPeerId()) << std::endl;
300 // Send player movement settings
301 SendMovement(pkt->getPeerId());
303 // Send item definitions
304 SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
306 // Send node definitions
307 SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
309 m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
311 // Send media announcement
312 sendMediaAnnouncement(pkt->getPeerId(), lang);
314 // Send detached inventories
315 sendDetachedInventories(pkt->getPeerId());
318 u16 time = m_env->getTimeOfDay();
319 float time_speed = g_settings->getFloat("time_speed");
320 SendTimeOfDay(pkt->getPeerId(), time, time_speed);
322 SendCSMFlavourLimits(pkt->getPeerId());
324 // Warnings about protocol version can be issued here
325 if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
326 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
327 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
328 L"WITH THIS SERVER!"));
333 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
335 std::vector<std::string> tosend;
340 infostream << "Sending " << numfiles << " files to "
341 << getPlayerName(pkt->getPeerId()) << std::endl;
342 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
344 for (u16 i = 0; i < numfiles; i++) {
349 tosend.push_back(name);
350 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
351 << name << std::endl;
354 sendRequestedMedia(pkt->getPeerId(), tosend);
357 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
359 session_t peer_id = pkt->getPeerId();
361 PlayerSAO* playersao = StageTwoClientInit(peer_id);
363 if (playersao == NULL) {
365 << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
366 << peer_id << std::endl;
367 DisconnectPeer(peer_id);
372 if (pkt->getSize() < 8) {
374 << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
375 << peer_id << std::endl;
376 DisconnectPeer(peer_id);
380 u8 major_ver, minor_ver, patch_ver, reserved;
381 std::string full_ver;
382 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
384 m_clients.setClientVersion(
385 peer_id, major_ver, minor_ver, patch_ver,
388 const std::vector<std::string> &players = m_clients.getPlayerNames();
389 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
390 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
391 for (const std::string &player: players) {
394 m_clients.send(peer_id, 0, &list_pkt, true);
396 NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
397 // (u16) 1 + std::string represents a pseudo vector serialization representation
398 notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
399 m_clients.sendToAll(¬ice_pkt);
401 m_clients.event(peer_id, CSE_SetClientReady);
402 m_script->on_joinplayer(playersao);
403 // Send shutdown timer if shutdown has been scheduled
404 if (m_shutdown_timer > 0.0f) {
405 std::wstringstream ws;
406 ws << L"*** Server shutting down in "
407 << duration_to_string(myround(m_shutdown_timer)).c_str() << ".";
408 SendChatMessage(pkt->getPeerId(), ws.str());
412 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
414 if (pkt->getSize() < 1)
428 RemoteClient *client = getClient(pkt->getPeerId());
430 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
431 throw con::InvalidIncomingDataException
432 ("GOTBLOCKS length is too short");
435 for (u16 i = 0; i < count; i++) {
442 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
445 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
449 s32 f32pitch, f32yaw;
457 f32 pitch = (f32)f32pitch / 100.0f;
458 f32 yaw = (f32)f32yaw / 100.0f;
461 // default behavior (in case an old client doesn't send these)
467 fov = (f32)f32fov / 80.0f;
468 *pkt >> wanted_range;
470 v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
471 v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
473 pitch = modulo360f(pitch);
474 yaw = wrapDegrees_0_360(yaw);
476 playersao->setBasePosition(position);
477 player->setSpeed(speed);
478 playersao->setPitch(pitch);
479 playersao->setYaw(yaw);
480 playersao->setFov(fov);
481 playersao->setWantedRange(wanted_range);
482 player->keyPressed = keyPressed;
483 player->control.up = (keyPressed & 1);
484 player->control.down = (keyPressed & 2);
485 player->control.left = (keyPressed & 4);
486 player->control.right = (keyPressed & 8);
487 player->control.jump = (keyPressed & 16);
488 player->control.aux1 = (keyPressed & 32);
489 player->control.sneak = (keyPressed & 64);
490 player->control.LMB = (keyPressed & 128);
491 player->control.RMB = (keyPressed & 256);
493 if (playersao->checkMovementCheat()) {
495 m_script->on_cheat(playersao, "moved_too_fast");
496 SendMovePlayer(pkt->getPeerId());
500 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
502 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
503 if (player == NULL) {
504 errorstream << "Server::ProcessData(): Canceling: "
505 "No player for peer_id=" << pkt->getPeerId()
506 << " disconnecting peer!" << std::endl;
507 DisconnectPeer(pkt->getPeerId());
511 PlayerSAO *playersao = player->getPlayerSAO();
512 if (playersao == NULL) {
513 errorstream << "Server::ProcessData(): Canceling: "
514 "No player object for peer_id=" << pkt->getPeerId()
515 << " disconnecting peer!" << std::endl;
516 DisconnectPeer(pkt->getPeerId());
520 // If player is dead we don't care of this packet
521 if (playersao->isDead()) {
522 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
523 << " is dead. Ignoring packet";
527 process_PlayerPos(player, playersao, pkt);
530 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
532 if (pkt->getSize() < 1)
546 RemoteClient *client = getClient(pkt->getPeerId());
548 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
549 throw con::InvalidIncomingDataException
550 ("DELETEDBLOCKS length is too short");
553 for (u16 i = 0; i < count; i++) {
556 client->SetBlockNotSent(p);
560 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
562 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
564 if (player == NULL) {
565 errorstream << "Server::ProcessData(): Canceling: "
566 "No player for peer_id=" << pkt->getPeerId()
567 << " disconnecting peer!" << std::endl;
568 DisconnectPeer(pkt->getPeerId());
572 PlayerSAO *playersao = player->getPlayerSAO();
573 if (playersao == NULL) {
574 errorstream << "Server::ProcessData(): Canceling: "
575 "No player object for peer_id=" << pkt->getPeerId()
576 << " disconnecting peer!" << std::endl;
577 DisconnectPeer(pkt->getPeerId());
581 // Strip command and create a stream
582 std::string datastring(pkt->getString(0), pkt->getSize());
583 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
585 std::istringstream is(datastring, std::ios_base::binary);
587 InventoryAction *a = InventoryAction::deSerialize(is);
589 infostream << "TOSERVER_INVENTORY_ACTION: "
590 << "InventoryAction::deSerialize() returned NULL"
595 // If something goes wrong, this player is to blame
596 RollbackScopeActor rollback_scope(m_rollback,
597 std::string("player:")+player->getName());
600 Note: Always set inventory not sent, to repair cases
601 where the client made a bad prediction.
605 Handle restrictions and special cases of the move action
607 if (a->getType() == IAction::Move) {
608 IMoveAction *ma = (IMoveAction*)a;
610 ma->from_inv.applyCurrentPlayer(player->getName());
611 ma->to_inv.applyCurrentPlayer(player->getName());
613 setInventoryModified(ma->from_inv, false);
614 setInventoryModified(ma->to_inv, false);
616 bool from_inv_is_current_player =
617 (ma->from_inv.type == InventoryLocation::PLAYER) &&
618 (ma->from_inv.name == player->getName());
620 bool to_inv_is_current_player =
621 (ma->to_inv.type == InventoryLocation::PLAYER) &&
622 (ma->to_inv.name == player->getName());
625 Disable moving items out of craftpreview
627 if (ma->from_list == "craftpreview") {
628 infostream << "Ignoring IMoveAction from "
629 << (ma->from_inv.dump()) << ":" << ma->from_list
630 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
631 << " because src is " << ma->from_list << std::endl;
637 Disable moving items into craftresult and craftpreview
639 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
640 infostream << "Ignoring IMoveAction from "
641 << (ma->from_inv.dump()) << ":" << ma->from_list
642 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
643 << " because dst is " << ma->to_list << std::endl;
648 // Disallow moving items in elsewhere than player's inventory
649 // if not allowed to interact
650 if (!checkPriv(player->getName(), "interact") &&
651 (!from_inv_is_current_player ||
652 !to_inv_is_current_player)) {
653 infostream << "Cannot move outside of player's inventory: "
654 << "No interact privilege" << std::endl;
660 Handle restrictions and special cases of the drop action
662 else if (a->getType() == IAction::Drop) {
663 IDropAction *da = (IDropAction*)a;
665 da->from_inv.applyCurrentPlayer(player->getName());
667 setInventoryModified(da->from_inv, false);
670 Disable dropping items out of craftpreview
672 if (da->from_list == "craftpreview") {
673 infostream << "Ignoring IDropAction from "
674 << (da->from_inv.dump()) << ":" << da->from_list
675 << " because src is " << da->from_list << std::endl;
680 // Disallow dropping items if not allowed to interact
681 if (!checkPriv(player->getName(), "interact")) {
686 // Disallow dropping items if dead
687 if (playersao->isDead()) {
688 infostream << "Ignoring IDropAction from "
689 << (da->from_inv.dump()) << ":" << da->from_list
690 << " because player is dead." << std::endl;
696 Handle restrictions and special cases of the craft action
698 else if (a->getType() == IAction::Craft) {
699 ICraftAction *ca = (ICraftAction*)a;
701 ca->craft_inv.applyCurrentPlayer(player->getName());
703 setInventoryModified(ca->craft_inv, false);
705 //bool craft_inv_is_current_player =
706 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
707 // (ca->craft_inv.name == player->getName());
709 // Disallow crafting if not allowed to interact
710 if (!checkPriv(player->getName(), "interact")) {
711 infostream << "Cannot craft: "
712 << "No interact privilege" << std::endl;
719 a->apply(this, playersao, this);
723 SendInventory(playersao);
726 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
736 std::wstring message;
737 for (u16 i = 0; i < len; i++) {
741 message += (wchar_t)tmp_wchar;
744 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
745 if (player == NULL) {
746 errorstream << "Server::ProcessData(): Canceling: "
747 "No player for peer_id=" << pkt->getPeerId()
748 << " disconnecting peer!" << std::endl;
749 DisconnectPeer(pkt->getPeerId());
753 // Get player name of this client
754 std::string name = player->getName();
755 std::wstring wname = narrow_to_wide(name);
757 std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
758 if (!answer_to_sender.empty()) {
759 // Send the answer to sender
760 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
761 answer_to_sender, wname));
765 void Server::handleCommand_Damage(NetworkPacket* pkt)
771 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
773 if (player == NULL) {
774 errorstream << "Server::ProcessData(): Canceling: "
775 "No player for peer_id=" << pkt->getPeerId()
776 << " disconnecting peer!" << std::endl;
777 DisconnectPeer(pkt->getPeerId());
781 PlayerSAO *playersao = player->getPlayerSAO();
782 if (playersao == NULL) {
783 errorstream << "Server::ProcessData(): Canceling: "
784 "No player object for peer_id=" << pkt->getPeerId()
785 << " disconnecting peer!" << std::endl;
786 DisconnectPeer(pkt->getPeerId());
790 if (g_settings->getBool("enable_damage")) {
791 if (playersao->isDead()) {
792 verbosestream << "Server::ProcessData(): Info: "
793 "Ignoring damage as player " << player->getName()
794 << " is already dead." << std::endl;
798 actionstream << player->getName() << " damaged by "
799 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
802 playersao->setHP(playersao->getHP() - damage);
803 SendPlayerHPOrDie(playersao);
807 void Server::handleCommand_Password(NetworkPacket* pkt)
809 if (pkt->getSize() != PASSWORD_SIZE * 2)
815 // Deny for clients using the new protocol
816 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
817 if (client->net_proto_version >= 25) {
818 infostream << "Server::handleCommand_Password(): Denying change: "
819 << " Client protocol version for peer_id=" << pkt->getPeerId()
820 << " too new!" << std::endl;
824 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
825 char c = pkt->getChar(i);
831 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
832 char c = pkt->getChar(PASSWORD_SIZE + i);
838 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
839 if (player == NULL) {
840 errorstream << "Server::ProcessData(): Canceling: "
841 "No player for peer_id=" << pkt->getPeerId()
842 << " disconnecting peer!" << std::endl;
843 DisconnectPeer(pkt->getPeerId());
847 if (!base64_is_valid(newpwd)) {
848 infostream<<"Server: " << player->getName() <<
849 " supplied invalid password hash" << std::endl;
850 // Wrong old password supplied!!
851 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
852 L"Invalid new password hash supplied. Password NOT changed."));
856 infostream << "Server: Client requests a password change from "
857 << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
859 std::string playername = player->getName();
861 std::string checkpwd;
862 m_script->getAuth(playername, &checkpwd, NULL);
864 if (oldpwd != checkpwd) {
865 infostream << "Server: invalid old password" << std::endl;
866 // Wrong old password supplied!!
867 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
868 L"Invalid old password supplied. Password NOT changed."));
872 bool success = m_script->setPassword(playername, newpwd);
874 actionstream << player->getName() << " changes password" << std::endl;
875 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
876 L"Password change successful."));
878 actionstream << player->getName() << " tries to change password but "
879 << "it fails" << std::endl;
880 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
881 L"Password change failed or unavailable."));
885 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
887 if (pkt->getSize() < 2)
890 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
892 if (player == NULL) {
893 errorstream << "Server::ProcessData(): Canceling: "
894 "No player for peer_id=" << pkt->getPeerId()
895 << " disconnecting peer!" << std::endl;
896 DisconnectPeer(pkt->getPeerId());
900 PlayerSAO *playersao = player->getPlayerSAO();
901 if (playersao == NULL) {
902 errorstream << "Server::ProcessData(): Canceling: "
903 "No player object for peer_id=" << pkt->getPeerId()
904 << " disconnecting peer!" << std::endl;
905 DisconnectPeer(pkt->getPeerId());
913 playersao->setWieldIndex(item);
916 void Server::handleCommand_Respawn(NetworkPacket* pkt)
918 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
919 if (player == NULL) {
920 errorstream << "Server::ProcessData(): Canceling: "
921 "No player for peer_id=" << pkt->getPeerId()
922 << " disconnecting peer!" << std::endl;
923 DisconnectPeer(pkt->getPeerId());
927 PlayerSAO *playersao = player->getPlayerSAO();
930 if (!playersao->isDead())
933 RespawnPlayer(pkt->getPeerId());
935 actionstream << player->getName() << " respawns at "
936 << PP(playersao->getBasePosition() / BS) << std::endl;
938 // ActiveObject is added to environment in AsyncRunStep after
939 // the previous addition has been successfully removed
942 void Server::handleCommand_Interact(NetworkPacket* pkt)
948 [5] u32 length of the next item (plen)
949 [9] serialized PointedThing
950 [9 + plen] player position information
952 0: start digging (from undersurface) or use
953 1: stop digging (all parameters ignored)
955 3: place block or item (to abovesurface)
957 5: rightclick air ("activate")
963 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
964 PointedThing pointed;
965 pointed.deSerialize(tmp_is);
967 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
968 << item_i << ", pointed=" << pointed.dump() << std::endl;
970 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
972 if (player == NULL) {
973 errorstream << "Server::ProcessData(): Canceling: "
974 "No player for peer_id=" << pkt->getPeerId()
975 << " disconnecting peer!" << std::endl;
976 DisconnectPeer(pkt->getPeerId());
980 PlayerSAO *playersao = player->getPlayerSAO();
981 if (playersao == NULL) {
982 errorstream << "Server::ProcessData(): Canceling: "
983 "No player object for peer_id=" << pkt->getPeerId()
984 << " disconnecting peer!" << std::endl;
985 DisconnectPeer(pkt->getPeerId());
989 if (playersao->isDead()) {
990 actionstream << "Server: NoCheat: " << player->getName()
991 << " tried to interact while dead; ignoring." << std::endl;
992 if (pointed.type == POINTEDTHING_NODE) {
993 // Re-send block to revert change on client-side
994 RemoteClient *client = getClient(pkt->getPeerId());
995 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
996 client->SetBlockNotSent(blockpos);
999 m_script->on_cheat(playersao, "interacted_while_dead");
1003 process_PlayerPos(player, playersao, pkt);
1005 v3f player_pos = playersao->getLastGoodPosition();
1007 // Update wielded item
1008 playersao->setWieldIndex(item_i);
1010 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1011 v3s16 p_under = pointed.node_undersurface;
1012 v3s16 p_above = pointed.node_abovesurface;
1014 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1015 ServerActiveObject *pointed_object = NULL;
1016 if (pointed.type == POINTEDTHING_OBJECT) {
1017 pointed_object = m_env->getActiveObject(pointed.object_id);
1018 if (pointed_object == NULL) {
1019 verbosestream << "TOSERVER_INTERACT: "
1020 "pointed object is NULL" << std::endl;
1026 v3f pointed_pos_under = player_pos;
1027 v3f pointed_pos_above = player_pos;
1028 if (pointed.type == POINTEDTHING_NODE) {
1029 pointed_pos_under = intToFloat(p_under, BS);
1030 pointed_pos_above = intToFloat(p_above, BS);
1032 else if (pointed.type == POINTEDTHING_OBJECT) {
1033 pointed_pos_under = pointed_object->getBasePosition();
1034 pointed_pos_above = pointed_pos_under;
1038 Make sure the player is allowed to do it
1040 if (!checkPriv(player->getName(), "interact")) {
1041 actionstream<<player->getName()<<" attempted to interact with "
1042 <<pointed.dump()<<" without 'interact' privilege"
1044 // Re-send block to revert change on client-side
1045 RemoteClient *client = getClient(pkt->getPeerId());
1046 // Digging completed -> under
1048 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1049 client->SetBlockNotSent(blockpos);
1051 // Placement -> above
1053 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1054 client->SetBlockNotSent(blockpos);
1060 Check that target is reasonably close
1061 (only when digging or placing things)
1063 static thread_local const bool enable_anticheat =
1064 !g_settings->getBool("disable_anticheat");
1066 if ((action == 0 || action == 2 || action == 3 || action == 4) &&
1067 (enable_anticheat && !isSingleplayer())) {
1068 float d = player_pos.getDistanceFrom(pointed_pos_under);
1069 const ItemDefinition &playeritem_def =
1070 playersao->getWieldedItem().getDefinition(m_itemdef);
1071 float max_d = BS * playeritem_def.range;
1072 InventoryList *hlist = playersao->getInventory()->getList("hand");
1073 const ItemDefinition &hand_def =
1074 hlist ? (hlist->getItem(0).getDefinition(m_itemdef)) : (m_itemdef->get(""));
1075 float max_d_hand = BS * hand_def.range;
1076 if (max_d < 0 && max_d_hand >= 0)
1080 // cube diagonal: sqrt(3) = 1.73
1081 if (d > max_d * 1.73) {
1082 actionstream << "Player " << player->getName()
1083 << " tried to access " << pointed.dump()
1084 << " from too far: "
1085 << "d=" << d <<", max_d=" << max_d
1086 << ". ignoring." << std::endl;
1087 // Re-send block to revert change on client-side
1088 RemoteClient *client = getClient(pkt->getPeerId());
1089 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1090 client->SetBlockNotSent(blockpos);
1092 m_script->on_cheat(playersao, "interacted_too_far");
1099 If something goes wrong, this player is to blame
1101 RollbackScopeActor rollback_scope(m_rollback,
1102 std::string("player:")+player->getName());
1105 0: start digging or punch object
1108 if (pointed.type == POINTEDTHING_NODE) {
1109 MapNode n(CONTENT_IGNORE);
1112 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1114 infostream << "Server: Not punching: Node not found."
1115 << " Adding block to emerge queue."
1117 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1118 getNodeBlockPos(p_above), false);
1121 if (n.getContent() != CONTENT_IGNORE)
1122 m_script->node_on_punch(p_under, n, playersao, pointed);
1125 playersao->noCheatDigStart(p_under);
1127 else if (pointed.type == POINTEDTHING_OBJECT) {
1128 // Skip if object can't be interacted with anymore
1129 if (pointed_object->isGone())
1132 actionstream<<player->getName()<<" punches object "
1133 <<pointed.object_id<<": "
1134 <<pointed_object->getDescription()<<std::endl;
1136 ItemStack punchitem = playersao->getWieldedItemOrHand();
1137 ToolCapabilities toolcap =
1138 punchitem.getToolCapabilities(m_itemdef);
1139 v3f dir = (pointed_object->getBasePosition() -
1140 (playersao->getBasePosition() + playersao->getEyeOffset())
1142 float time_from_last_punch =
1143 playersao->resetTimeFromLastPunch();
1145 s16 src_original_hp = pointed_object->getHP();
1146 s16 dst_origin_hp = playersao->getHP();
1148 pointed_object->punch(dir, &toolcap, playersao,
1149 time_from_last_punch);
1151 // If the object is a player and its HP changed
1152 if (src_original_hp != pointed_object->getHP() &&
1153 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1154 SendPlayerHPOrDie((PlayerSAO *)pointed_object);
1157 // If the puncher is a player and its HP changed
1158 if (dst_origin_hp != playersao->getHP())
1159 SendPlayerHPOrDie(playersao);
1167 else if (action == 1) {
1171 2: Digging completed
1173 else if (action == 2) {
1174 // Only digging of nodes
1175 if (pointed.type == POINTEDTHING_NODE) {
1177 MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1179 infostream << "Server: Not finishing digging: Node not found."
1180 << " Adding block to emerge queue."
1182 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1183 getNodeBlockPos(p_above), false);
1186 /* Cheat prevention */
1187 bool is_valid_dig = true;
1188 if (enable_anticheat && !isSingleplayer()) {
1189 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1190 float nocheat_t = playersao->getNoCheatDigTime();
1191 playersao->noCheatDigEnd();
1192 // If player didn't start digging this, ignore dig
1193 if (nocheat_p != p_under) {
1194 infostream << "Server: NoCheat: " << player->getName()
1195 << " started digging "
1196 << PP(nocheat_p) << " and completed digging "
1197 << PP(p_under) << "; not digging." << std::endl;
1198 is_valid_dig = false;
1200 m_script->on_cheat(playersao, "finished_unknown_dig");
1202 // Get player's wielded item
1203 ItemStack playeritem = playersao->getWieldedItemOrHand();
1204 ToolCapabilities playeritem_toolcap =
1205 playeritem.getToolCapabilities(m_itemdef);
1206 // Get diggability and expected digging time
1207 DigParams params = getDigParams(m_nodedef->get(n).groups,
1208 &playeritem_toolcap);
1209 // If can't dig, try hand
1210 if (!params.diggable) {
1211 InventoryList *hlist = playersao->getInventory()->getList("hand");
1212 const ItemDefinition &hand =
1213 hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
1214 const ToolCapabilities *tp = hand.tool_capabilities;
1216 params = getDigParams(m_nodedef->get(n).groups, tp);
1218 // If can't dig, ignore dig
1219 if (!params.diggable) {
1220 infostream << "Server: NoCheat: " << player->getName()
1221 << " completed digging " << PP(p_under)
1222 << ", which is not diggable with tool. not digging."
1224 is_valid_dig = false;
1226 m_script->on_cheat(playersao, "dug_unbreakable");
1228 // Check digging time
1229 // If already invalidated, we don't have to
1230 if (!is_valid_dig) {
1231 // Well not our problem then
1233 // Clean and long dig
1234 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1235 // All is good, but grab time from pool; don't care if
1236 // it's actually available
1237 playersao->getDigPool().grab(params.time);
1239 // Short or laggy dig
1240 // Try getting the time from pool
1241 else if (playersao->getDigPool().grab(params.time)) {
1246 infostream << "Server: NoCheat: " << player->getName()
1247 << " completed digging " << PP(p_under)
1248 << "too fast; not digging." << std::endl;
1249 is_valid_dig = false;
1251 m_script->on_cheat(playersao, "dug_too_fast");
1255 /* Actually dig node */
1257 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1258 m_script->node_on_dig(p_under, n, playersao);
1260 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1261 RemoteClient *client = getClient(pkt->getPeerId());
1262 // Send unusual result (that is, node not being removed)
1263 if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1264 // Re-send block to revert change on client-side
1265 client->SetBlockNotSent(blockpos);
1268 client->ResendBlockIfOnWire(blockpos);
1274 3: place block or right-click object
1276 else if (action == 3) {
1277 ItemStack item = playersao->getWieldedItem();
1279 // Reset build time counter
1280 if (pointed.type == POINTEDTHING_NODE &&
1281 item.getDefinition(m_itemdef).type == ITEM_NODE)
1282 getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1284 if (pointed.type == POINTEDTHING_OBJECT) {
1285 // Right click object
1287 // Skip if object can't be interacted with anymore
1288 if (pointed_object->isGone())
1291 actionstream << player->getName() << " right-clicks object "
1292 << pointed.object_id << ": "
1293 << pointed_object->getDescription() << std::endl;
1296 pointed_object->rightClick(playersao);
1298 else if (m_script->item_OnPlace(
1299 item, playersao, pointed)) {
1300 // Placement was handled in lua
1302 // Apply returned ItemStack
1303 if (playersao->setWieldedItem(item)) {
1304 SendInventory(playersao);
1308 // If item has node placement prediction, always send the
1309 // blocks to make sure the client knows what exactly happened
1310 RemoteClient *client = getClient(pkt->getPeerId());
1311 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1312 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1313 if (!item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
1314 client->SetBlockNotSent(blockpos);
1315 if (blockpos2 != blockpos) {
1316 client->SetBlockNotSent(blockpos2);
1320 client->ResendBlockIfOnWire(blockpos);
1321 if (blockpos2 != blockpos) {
1322 client->ResendBlockIfOnWire(blockpos2);
1330 else if (action == 4) {
1331 ItemStack item = playersao->getWieldedItem();
1333 actionstream << player->getName() << " uses " << item.name
1334 << ", pointing at " << pointed.dump() << std::endl;
1336 if (m_script->item_OnUse(
1337 item, playersao, pointed)) {
1338 // Apply returned ItemStack
1339 if (playersao->setWieldedItem(item)) {
1340 SendInventory(playersao);
1349 else if (action == 5) {
1350 ItemStack item = playersao->getWieldedItem();
1352 actionstream << player->getName() << " activates "
1353 << item.name << std::endl;
1355 if (m_script->item_OnSecondaryUse(
1357 if( playersao->setWieldedItem(item)) {
1358 SendInventory(playersao);
1365 Catch invalid actions
1368 warningstream << "Server: Invalid action "
1369 << action << std::endl;
1373 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1377 for (u16 k = 0; k < num; k++) {
1382 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1383 m_playing_sounds.find(id);
1384 if (i == m_playing_sounds.end())
1387 ServerPlayingSound &psound = i->second;
1388 psound.clients.erase(pkt->getPeerId());
1389 if (psound.clients.empty())
1390 m_playing_sounds.erase(i++);
1394 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1397 std::string formname;
1400 *pkt >> p >> formname >> num;
1403 for (u16 k = 0; k < num; k++) {
1404 std::string fieldname;
1406 fields[fieldname] = pkt->readLongString();
1409 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1411 if (player == NULL) {
1412 errorstream << "Server::ProcessData(): Canceling: "
1413 "No player for peer_id=" << pkt->getPeerId()
1414 << " disconnecting peer!" << std::endl;
1415 DisconnectPeer(pkt->getPeerId());
1419 PlayerSAO *playersao = player->getPlayerSAO();
1420 if (playersao == NULL) {
1421 errorstream << "Server::ProcessData(): Canceling: "
1422 "No player object for peer_id=" << pkt->getPeerId()
1423 << " disconnecting peer!" << std::endl;
1424 DisconnectPeer(pkt->getPeerId());
1428 // If something goes wrong, this player is to blame
1429 RollbackScopeActor rollback_scope(m_rollback,
1430 std::string("player:")+player->getName());
1432 // Check the target node for rollback data; leave others unnoticed
1433 RollbackNode rn_old(&m_env->getMap(), p, this);
1435 m_script->node_on_receive_fields(p, formname, fields, playersao);
1437 // Report rollback data
1438 RollbackNode rn_new(&m_env->getMap(), p, this);
1439 if (rollback() && rn_new != rn_old) {
1440 RollbackAction action;
1441 action.setSetNode(p, rn_old, rn_new);
1442 rollback()->reportAction(action);
1446 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1448 std::string formname;
1451 *pkt >> formname >> num;
1454 for (u16 k = 0; k < num; k++) {
1455 std::string fieldname;
1457 fields[fieldname] = pkt->readLongString();
1460 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1462 if (player == NULL) {
1463 errorstream << "Server::ProcessData(): Canceling: "
1464 "No player for peer_id=" << pkt->getPeerId()
1465 << " disconnecting peer!" << std::endl;
1466 DisconnectPeer(pkt->getPeerId());
1470 PlayerSAO *playersao = player->getPlayerSAO();
1471 if (playersao == NULL) {
1472 errorstream << "Server::ProcessData(): Canceling: "
1473 "No player object for peer_id=" << pkt->getPeerId()
1474 << " disconnecting peer!" << std::endl;
1475 DisconnectPeer(pkt->getPeerId());
1479 m_script->on_playerReceiveFields(playersao, formname, fields);
1482 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1484 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1485 ClientState cstate = client->getState();
1487 std::string playername = client->getName();
1490 std::string verification_key;
1492 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1495 *pkt >> salt >> verification_key >> is_empty;
1497 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1498 << ", with is_empty=" << (is_empty == 1) << std::endl;
1500 // Either this packet is sent because the user is new or to change the password
1501 if (cstate == CS_HelloSent) {
1502 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1503 actionstream << "Server: Client from " << addr_s
1504 << " tried to set password without being "
1505 << "authenticated, or the username being new." << std::endl;
1506 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1510 if (!isSingleplayer() &&
1511 g_settings->getBool("disallow_empty_password") &&
1513 actionstream << "Server: " << playername
1514 << " supplied empty password from " << addr_s << std::endl;
1515 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1519 std::string initial_ver_key;
1521 initial_ver_key = encode_srp_verifier(verification_key, salt);
1522 m_script->createAuth(playername, initial_ver_key);
1524 acceptAuth(pkt->getPeerId(), false);
1526 if (cstate < CS_SudoMode) {
1527 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1528 << addr_s << ": " << "Client has wrong state " << cstate << "."
1532 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1533 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1534 bool success = m_script->setPassword(playername, pw_db_field);
1536 actionstream << playername << " changes password" << std::endl;
1537 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1538 L"Password change successful."));
1540 actionstream << playername << " tries to change password but "
1541 << "it fails" << std::endl;
1542 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1543 L"Password change failed or unavailable."));
1548 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1550 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1551 ClientState cstate = client->getState();
1553 bool wantSudo = (cstate == CS_Active);
1555 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1556 actionstream << "Server: got SRP _A packet in wrong state "
1557 << cstate << " from "
1558 << getPeerAddress(pkt->getPeerId()).serializeString()
1559 << ". Ignoring." << std::endl;
1563 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1564 actionstream << "Server: got SRP _A packet, while auth"
1565 << "is already going on with mech " << client->chosen_mech
1566 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1567 << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1569 DenySudoAccess(pkt->getPeerId());
1573 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1577 std::string bytes_A;
1579 *pkt >> bytes_A >> based_on;
1581 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1582 << "based_on=" << int(based_on) << " and len_A="
1583 << bytes_A.length() << "." << std::endl;
1585 AuthMechanism chosen = (based_on == 0) ?
1586 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1589 if (!client->isSudoMechAllowed(chosen)) {
1590 actionstream << "Server: Player \"" << client->getName()
1591 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1592 << " tried to change password using unallowed mech "
1593 << chosen << "." << std::endl;
1594 DenySudoAccess(pkt->getPeerId());
1598 if (!client->isMechAllowed(chosen)) {
1599 actionstream << "Server: Client tried to authenticate from "
1600 << getPeerAddress(pkt->getPeerId()).serializeString()
1601 << " using unallowed mech " << chosen << "." << std::endl;
1602 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1607 client->chosen_mech = chosen;
1610 std::string verifier;
1612 if (based_on == 0) {
1614 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1616 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1617 // Non-base64 errors should have been catched in the init handler
1618 actionstream << "Server: User " << client->getName()
1619 << " tried to log in, but srp verifier field"
1620 << " was invalid (most likely invalid base64)." << std::endl;
1621 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1628 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1629 client->getName().c_str(),
1630 (const unsigned char *) salt.c_str(), salt.size(),
1631 (const unsigned char *) verifier.c_str(), verifier.size(),
1632 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1634 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1637 actionstream << "Server: User " << client->getName()
1638 << " tried to log in, SRP-6a safety check violated in _A handler."
1641 DenySudoAccess(pkt->getPeerId());
1645 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1649 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1650 resp_pkt << salt << std::string(bytes_B, len_B);
1654 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1656 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1657 ClientState cstate = client->getState();
1659 bool wantSudo = (cstate == CS_Active);
1661 verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
1663 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1664 actionstream << "Server: got SRP _M packet in wrong state "
1665 << cstate << " from "
1666 << getPeerAddress(pkt->getPeerId()).serializeString()
1667 << ". Ignoring." << std::endl;
1671 if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1672 client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1673 actionstream << "Server: got SRP _M packet, while auth"
1674 << "is going on with mech " << client->chosen_mech
1675 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1676 << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1678 DenySudoAccess(pkt->getPeerId());
1682 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1686 std::string bytes_M;
1689 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1690 != bytes_M.size()) {
1691 actionstream << "Server: User " << client->getName()
1692 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1693 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1694 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1698 unsigned char *bytes_HAMK = 0;
1700 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1701 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1705 actionstream << "Server: User " << client->getName()
1706 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1707 << " tried to change their password, but supplied wrong"
1708 << " (SRP) password for authentication." << std::endl;
1709 DenySudoAccess(pkt->getPeerId());
1713 actionstream << "Server: User " << client->getName()
1714 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1715 << " supplied wrong password (auth mechanism: SRP)."
1717 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
1721 if (client->create_player_on_auth_success) {
1722 std::string playername = client->getName();
1723 m_script->createAuth(playername, client->enc_pwd);
1725 std::string checkpwd; // not used, but needed for passing something
1726 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1727 actionstream << "Server: " << playername << " cannot be authenticated"
1728 << " (auth handler does not work?)" << std::endl;
1729 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1732 client->create_player_on_auth_success = false;
1735 acceptAuth(pkt->getPeerId(), wantSudo);
1742 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1744 std::string channel_name;
1745 *pkt >> channel_name;
1747 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1750 // Send signal to client to notify join succeed or not
1751 if (g_settings->getBool("enable_mod_channels") &&
1752 m_modchannel_mgr->joinChannel(channel_name, pkt->getPeerId())) {
1753 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1754 infostream << "Peer " << pkt->getPeerId() << " joined channel " << channel_name
1758 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1759 infostream << "Peer " << pkt->getPeerId() << " tried to join channel "
1760 << channel_name << ", but was already registered." << std::endl;
1762 resp_pkt << channel_name;
1766 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1768 std::string channel_name;
1769 *pkt >> channel_name;
1771 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1774 // Send signal to client to notify join succeed or not
1775 if (g_settings->getBool("enable_mod_channels") &&
1776 m_modchannel_mgr->leaveChannel(channel_name, pkt->getPeerId())) {
1777 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1778 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1781 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1782 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1783 << ", but was not registered." << std::endl;
1785 resp_pkt << channel_name;
1789 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1791 std::string channel_name, channel_msg;
1792 *pkt >> channel_name >> channel_msg;
1794 verbosestream << "Mod channel message received from peer " << pkt->getPeerId()
1795 << " on channel " << channel_name << " message: " << channel_msg << std::endl;
1797 // If mod channels are not enabled, discard message
1798 if (!g_settings->getBool("enable_mod_channels")) {
1802 // If channel not registered, signal it and ignore message
1803 if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1804 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1806 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1811 // @TODO: filter, rate limit
1813 broadcastModChannelMessage(channel_name, channel_msg, pkt->getPeerId());