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.
23 #include "content_abm.h"
24 #include "content_sao.h"
29 #include "rollback_interface.h"
30 #include "serverscripting.h"
34 #include "network/networkprotocol.h"
35 #include "network/serveropcodes.h"
36 #include "util/auth.h"
37 #include "util/base64.h"
38 #include "util/pointedthing.h"
39 #include "util/serialize.h"
42 void Server::handleCommand_Deprecated(NetworkPacket* pkt)
44 infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
45 << " not supported anymore" << std::endl;
48 void Server::handleCommand_Init(NetworkPacket* pkt)
51 if(pkt->getSize() < 1)
54 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
58 Address address = getPeerAddress(pkt->getPeerId());
59 addr_s = address.serializeString();
61 catch (con::PeerNotFoundException &e) {
63 * no peer for this packet found
64 * most common reason is peer timeout, e.g. peer didn't
65 * respond for some time, your server was overloaded or
68 infostream << "Server::ProcessData(): Canceling: peer "
69 << pkt->getPeerId() << " not found" << std::endl;
73 // If net_proto_version is set, this client has already been handled
74 if (client->getState() > CS_Created) {
75 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
76 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
80 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
81 << pkt->getPeerId() << ")" << std::endl;
83 // Do not allow multiple players in simple singleplayer mode.
84 // This isn't a perfect way to do it, but will suffice for now
85 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
86 infostream << "Server: Not allowing another client (" << addr_s
87 << ") to connect in simple singleplayer mode" << std::endl;
88 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SINGLEPLAYER);
92 // First byte after command is maximum supported
93 // serialization version
96 u16 min_net_proto_version = 0;
97 u16 max_net_proto_version;
98 std::string playerName;
100 *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
101 >> max_net_proto_version >> playerName;
103 u8 our_max = SER_FMT_VER_HIGHEST_READ;
104 // Use the highest version supported by both
105 u8 depl_serial_v = std::min(client_max, our_max);
106 // If it's lower than the lowest supported, give up.
107 if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
108 depl_serial_v = SER_FMT_VER_INVALID;
110 if (depl_serial_v == SER_FMT_VER_INVALID) {
111 actionstream << "Server: A mismatched client tried to connect from "
112 << addr_s << std::endl;
113 infostream<<"Server: Cannot negotiate serialization version with "
114 << addr_s << std::endl;
115 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
119 client->setPendingSerializationVersion(depl_serial_v);
122 Read and check network protocol version
125 u16 net_proto_version = 0;
127 // Figure out a working version if it is possible at all
128 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
129 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
130 // If maximum is larger than our maximum, go with our maximum
131 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
132 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
133 // Else go with client's maximum
135 net_proto_version = max_net_proto_version;
138 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
139 << min_net_proto_version << ", max: " << max_net_proto_version
140 << ", chosen: " << net_proto_version << std::endl;
142 client->net_proto_version = net_proto_version;
144 // On this handler at least protocol version 25 is required
145 if (net_proto_version < 25 ||
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);
154 if (g_settings->getBool("strict_protocol_version_checking")) {
155 if (net_proto_version != LATEST_PROTOCOL_VERSION) {
156 actionstream << "Server: A mismatched (strict) client tried to "
157 << "connect from " << addr_s << std::endl;
158 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
166 const char* playername = playerName.c_str();
168 size_t pns = playerName.size();
169 if (pns == 0 || pns > PLAYERNAME_SIZE) {
170 actionstream << "Server: Player with "
171 << ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty")
172 << " name tried to connect from " << addr_s << std::endl;
173 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
177 if (string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS) == false) {
178 actionstream << "Server: Player with an invalid name "
179 << "tried to connect from " << addr_s << std::endl;
180 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
184 m_clients.setPlayerName(pkt->getPeerId(), playername);
185 //TODO (later) case insensitivity
187 std::string legacyPlayerNameCasing = playerName;
189 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
190 actionstream << "Server: Player with the name \"singleplayer\" "
191 << "tried to connect from " << addr_s << std::endl;
192 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
198 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
199 actionstream << "Server: Player with the name \"" << playerName << "\" "
200 << "tried to connect from " << addr_s << " "
201 << "but it was disallowed for the following reason: "
202 << reason << std::endl;
203 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING,
209 infostream << "Server: New connection: \"" << playerName << "\" from "
210 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
212 // Enforce user limit.
213 // Don't enforce for users that have some admin right
214 if (m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
215 !checkPriv(playername, "server") &&
216 !checkPriv(playername, "ban") &&
217 !checkPriv(playername, "privs") &&
218 !checkPriv(playername, "password") &&
219 playername != g_settings->get("name")) {
220 actionstream << "Server: " << playername << " tried to join from "
221 << addr_s << ", but there" << " are already max_users="
222 << g_settings->getU16("max_users") << " players." << std::endl;
223 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_TOO_MANY_USERS);
228 Compose auth methods for answer
230 std::string encpwd; // encrypted Password field for the user
231 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
234 client->chosen_mech = AUTH_MECHANISM_NONE;
237 std::vector<std::string> pwd_components = str_split(encpwd, '#');
238 if (pwd_components.size() == 4) {
239 if (pwd_components[1] == "1") { // 1 means srp
240 auth_mechs |= AUTH_MECHANISM_SRP;
241 client->enc_pwd = encpwd;
243 actionstream << "User " << playername
244 << " tried to log in, but password field"
245 << " was invalid (unknown mechcode)." << std::endl;
246 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
249 } else if (base64_is_valid(encpwd)) {
250 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
251 client->enc_pwd = encpwd;
253 actionstream << "User " << playername
254 << " tried to log in, but password field"
255 << " was invalid (invalid base64)." << std::endl;
256 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
260 std::string default_password = g_settings->get("default_password");
261 if (default_password.length() == 0) {
262 auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
264 // Take care of default passwords.
265 client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
266 auth_mechs |= AUTH_MECHANISM_SRP;
267 // Allocate player in db, but only on successful login.
268 client->create_player_on_auth_success = true;
273 Answer with a TOCLIENT_HELLO
276 verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
277 << auth_mechs << std::endl;
279 NetworkPacket resp_pkt(TOCLIENT_HELLO, 1 + 4
280 + legacyPlayerNameCasing.size(), pkt->getPeerId());
282 u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
283 resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
284 << auth_mechs << legacyPlayerNameCasing;
288 client->allowed_auth_mechs = auth_mechs;
289 client->setDeployedCompressionMode(depl_compress_mode);
291 m_clients.event(pkt->getPeerId(), CSE_Hello);
294 void Server::handleCommand_Init_Legacy(NetworkPacket* pkt)
296 // [0] u8 SER_FMT_VER_HIGHEST_READ
297 // [1] u8[20] player_name
298 // [21] u8[28] password <--- can be sent without this, from old versions
300 if (pkt->getSize() < 1+PLAYERNAME_SIZE)
303 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
307 Address address = getPeerAddress(pkt->getPeerId());
308 addr_s = address.serializeString();
310 catch (con::PeerNotFoundException &e) {
312 * no peer for this packet found
313 * most common reason is peer timeout, e.g. peer didn't
314 * respond for some time, your server was overloaded or
317 infostream << "Server::ProcessData(): Canceling: peer "
318 << pkt->getPeerId() << " not found" << std::endl;
322 // If net_proto_version is set, this client has already been handled
323 if (client->getState() > CS_Created) {
324 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
325 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
329 verbosestream << "Server: Got TOSERVER_INIT_LEGACY from " << addr_s << " (peer_id="
330 << pkt->getPeerId() << ")" << std::endl;
332 // Do not allow multiple players in simple singleplayer mode.
333 // This isn't a perfect way to do it, but will suffice for now
334 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
335 infostream << "Server: Not allowing another client (" << addr_s
336 << ") to connect in simple singleplayer mode" << std::endl;
337 DenyAccess_Legacy(pkt->getPeerId(), L"Running in simple singleplayer mode.");
341 // First byte after command is maximum supported
342 // serialization version
347 u8 our_max = SER_FMT_VER_HIGHEST_READ;
348 // Use the highest version supported by both
349 int deployed = std::min(client_max, our_max);
350 // If it's lower than the lowest supported, give up.
351 if (deployed < SER_FMT_VER_LOWEST_READ)
352 deployed = SER_FMT_VER_INVALID;
354 if (deployed == SER_FMT_VER_INVALID) {
355 actionstream << "Server: A mismatched client tried to connect from "
356 << addr_s << std::endl;
357 infostream<<"Server: Cannot negotiate serialization version with "
358 << addr_s << std::endl;
359 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
360 L"Your client's version is not supported.\n"
361 L"Server version is ")
362 + utf8_to_wide(g_version_string) + L"."
367 client->setPendingSerializationVersion(deployed);
370 Read and check network protocol version
373 u16 min_net_proto_version = 0;
374 if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2)
375 min_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE);
377 // Use same version as minimum and maximum if maximum version field
378 // doesn't exist (backwards compatibility)
379 u16 max_net_proto_version = min_net_proto_version;
380 if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2)
381 max_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2);
383 // Start with client's maximum version
384 u16 net_proto_version = max_net_proto_version;
386 // Figure out a working version if it is possible at all
387 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
388 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
389 // If maximum is larger than our maximum, go with our maximum
390 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
391 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
392 // Else go with client's maximum
394 net_proto_version = max_net_proto_version;
397 // The client will send up to date init packet, ignore this one
398 if (net_proto_version >= 25)
401 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
402 << min_net_proto_version << ", max: " << max_net_proto_version
403 << ", chosen: " << net_proto_version << std::endl;
405 client->net_proto_version = net_proto_version;
407 if (net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
408 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
409 actionstream << "Server: A mismatched client tried to connect from "
410 << addr_s << std::endl;
411 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
412 L"Your client's version is not supported.\n"
413 L"Server version is ")
414 + utf8_to_wide(g_version_string) + L",\n"
415 + L"server's PROTOCOL_VERSION is "
416 + utf8_to_wide(itos(SERVER_PROTOCOL_VERSION_MIN))
418 + utf8_to_wide(itos(SERVER_PROTOCOL_VERSION_MAX))
419 + L", client's PROTOCOL_VERSION is "
420 + utf8_to_wide(itos(min_net_proto_version))
422 + utf8_to_wide(itos(max_net_proto_version))
427 if (g_settings->getBool("strict_protocol_version_checking")) {
428 if (net_proto_version != LATEST_PROTOCOL_VERSION) {
429 actionstream << "Server: A mismatched (strict) client tried to "
430 << "connect from " << addr_s << std::endl;
431 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
432 L"Your client's version is not supported.\n"
433 L"Server version is ")
434 + utf8_to_wide(g_version_string) + L",\n"
435 + L"server's PROTOCOL_VERSION (strict) is "
436 + utf8_to_wide(itos(LATEST_PROTOCOL_VERSION))
437 + L", client's PROTOCOL_VERSION is "
438 + utf8_to_wide(itos(min_net_proto_version))
440 + utf8_to_wide(itos(max_net_proto_version))
449 char playername[PLAYERNAME_SIZE];
450 unsigned int playername_length = 0;
451 for (; playername_length < PLAYERNAME_SIZE; playername_length++ ) {
452 playername[playername_length] = pkt->getChar(1+playername_length);
453 if (pkt->getChar(1+playername_length) == 0)
457 if (playername_length == PLAYERNAME_SIZE) {
458 actionstream << "Server: Player with name exceeding max length "
459 << "tried to connect from " << addr_s << std::endl;
460 DenyAccess_Legacy(pkt->getPeerId(), L"Name too long");
465 if (playername[0]=='\0') {
466 actionstream << "Server: Player with an empty name "
467 << "tried to connect from " << addr_s << std::endl;
468 DenyAccess_Legacy(pkt->getPeerId(), L"Empty name");
472 if (string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false) {
473 actionstream << "Server: Player with an invalid name "
474 << "tried to connect from " << addr_s << std::endl;
475 DenyAccess_Legacy(pkt->getPeerId(), L"Name contains unallowed characters");
479 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
480 actionstream << "Server: Player with the name \"singleplayer\" "
481 << "tried to connect from " << addr_s << std::endl;
482 DenyAccess_Legacy(pkt->getPeerId(), L"Name is not allowed");
488 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
489 actionstream << "Server: Player with the name \"" << playername << "\" "
490 << "tried to connect from " << addr_s << " "
491 << "but it was disallowed for the following reason: "
492 << reason << std::endl;
493 DenyAccess_Legacy(pkt->getPeerId(), utf8_to_wide(reason.c_str()));
498 infostream<<"Server: New connection: \""<<playername<<"\" from "
499 <<addr_s<<" (peer_id="<<pkt->getPeerId()<<")"<<std::endl;
502 char given_password[PASSWORD_SIZE];
503 if (pkt->getSize() < 1 + PLAYERNAME_SIZE + PASSWORD_SIZE) {
504 // old version - assume blank password
505 given_password[0] = 0;
508 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
509 given_password[i] = pkt->getChar(21 + i);
511 given_password[PASSWORD_SIZE - 1] = 0;
514 if (!base64_is_valid(given_password)) {
515 actionstream << "Server: " << playername
516 << " supplied invalid password hash" << std::endl;
517 DenyAccess_Legacy(pkt->getPeerId(), L"Invalid password hash");
521 // Enforce user limit.
522 // Don't enforce for users that have some admin right
523 if (m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
524 !checkPriv(playername, "server") &&
525 !checkPriv(playername, "ban") &&
526 !checkPriv(playername, "privs") &&
527 !checkPriv(playername, "password") &&
528 playername != g_settings->get("name")) {
529 actionstream << "Server: " << playername << " tried to join, but there"
530 << " are already max_users="
531 << g_settings->getU16("max_users") << " players." << std::endl;
532 DenyAccess_Legacy(pkt->getPeerId(), L"Too many users.");
536 std::string checkpwd; // Password hash to check against
537 bool has_auth = m_script->getAuth(playername, &checkpwd, NULL);
539 // If no authentication info exists for user, create it
541 if (!isSingleplayer() &&
542 g_settings->getBool("disallow_empty_password") &&
543 std::string(given_password) == "") {
544 actionstream << "Server: " << playername
545 << " supplied empty password" << std::endl;
546 DenyAccess_Legacy(pkt->getPeerId(), L"Empty passwords are "
547 L"disallowed. Set a password and try again.");
550 std::string raw_default_password =
551 g_settings->get("default_password");
552 std::string initial_password =
553 translate_password(playername, raw_default_password);
555 // If default_password is empty, allow any initial password
556 if (raw_default_password.length() == 0)
557 initial_password = given_password;
559 m_script->createAuth(playername, initial_password);
562 has_auth = m_script->getAuth(playername, &checkpwd, NULL);
565 actionstream << "Server: " << playername << " cannot be authenticated"
566 << " (auth handler does not work?)" << std::endl;
567 DenyAccess_Legacy(pkt->getPeerId(), L"Not allowed to login");
571 if (given_password != checkpwd) {
572 actionstream << "Server: User " << playername
574 << " supplied wrong password (auth mechanism: legacy)."
576 DenyAccess_Legacy(pkt->getPeerId(), L"Wrong password");
580 RemotePlayer *player =
581 static_cast<RemotePlayer*>(m_env->getPlayer(playername));
583 if (player && player->peer_id != 0) {
584 actionstream << "Server: " << playername << ": Failed to emerge player"
585 << " (player allocated to an another client)" << std::endl;
586 DenyAccess_Legacy(pkt->getPeerId(), L"Another client is connected with this "
587 L"name. If your client closed unexpectedly, try again in "
591 m_clients.setPlayerName(pkt->getPeerId(), playername);
594 Answer with a TOCLIENT_INIT
597 NetworkPacket resp_pkt(TOCLIENT_INIT_LEGACY, 1 + 6 + 8 + 4,
600 resp_pkt << (u8) deployed << (v3s16) floatToInt(v3f(0,0,0), BS)
601 << (u64) m_env->getServerMap().getSeed()
602 << g_settings->getFloat("dedicated_server_step");
605 m_clients.event(pkt->getPeerId(), CSE_InitLegacy);
608 void Server::handleCommand_Init2(NetworkPacket* pkt)
610 verbosestream << "Server: Got TOSERVER_INIT2 from "
611 << pkt->getPeerId() << std::endl;
613 m_clients.event(pkt->getPeerId(), CSE_GotInit2);
614 u16 protocol_version = m_clients.getProtocolVersion(pkt->getPeerId());
618 Send some initialization data
621 infostream << "Server: Sending content to "
622 << getPlayerName(pkt->getPeerId()) << std::endl;
624 // Send player movement settings
625 SendMovement(pkt->getPeerId());
627 // Send item definitions
628 SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
630 // Send node definitions
631 SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
633 m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
635 // Send media announcement
636 sendMediaAnnouncement(pkt->getPeerId());
638 // Send detached inventories
639 sendDetachedInventories(pkt->getPeerId());
642 u16 time = m_env->getTimeOfDay();
643 float time_speed = g_settings->getFloat("time_speed");
644 SendTimeOfDay(pkt->getPeerId(), time, time_speed);
646 // Warnings about protocol version can be issued here
647 if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
648 SendChatMessage(pkt->getPeerId(), L"# Server: WARNING: YOUR CLIENT'S "
649 L"VERSION MAY NOT BE FULLY COMPATIBLE WITH THIS SERVER!");
653 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
655 std::vector<std::string> tosend;
660 infostream << "Sending " << numfiles << " files to "
661 << getPlayerName(pkt->getPeerId()) << std::endl;
662 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
664 for (u16 i = 0; i < numfiles; i++) {
669 tosend.push_back(name);
670 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
671 << name << std::endl;
674 sendRequestedMedia(pkt->getPeerId(), tosend);
677 void Server::handleCommand_ReceivedMedia(NetworkPacket* pkt)
681 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
683 u16 peer_id = pkt->getPeerId();
684 u16 peer_proto_ver = getClient(peer_id, CS_InitDone)->net_proto_version;
686 // clients <= protocol version 22 did not send ready message,
687 // they're already initialized
688 if (peer_proto_ver <= 22) {
689 infostream << "Client sent message not expected by a "
690 << "client using protocol version <= 22,"
691 << "disconnecting peer_id: " << peer_id << std::endl;
692 m_con.DisconnectPeer(peer_id);
696 PlayerSAO* playersao = StageTwoClientInit(peer_id);
698 if (playersao == NULL) {
700 << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
701 << peer_id << std::endl;
702 m_con.DisconnectPeer(peer_id);
707 if (pkt->getSize() < 8) {
709 << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
710 << peer_id << std::endl;
711 m_con.DisconnectPeer(peer_id);
715 u8 major_ver, minor_ver, patch_ver, reserved;
716 std::string full_ver;
717 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
719 m_clients.setClientVersion(
720 peer_id, major_ver, minor_ver, patch_ver,
723 m_clients.event(peer_id, CSE_SetClientReady);
724 m_script->on_joinplayer(playersao);
725 // Send shutdown timer if shutdown has been scheduled
726 if (m_shutdown_timer > 0.0f) {
727 std::wstringstream ws;
728 ws << L"*** Server shutting down in "
729 << duration_to_string(round(m_shutdown_timer)).c_str() << ".";
730 SendChatMessage(pkt->getPeerId(), ws.str());
734 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
736 if (pkt->getSize() < 1)
750 RemoteClient *client = getClient(pkt->getPeerId());
752 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
753 throw con::InvalidIncomingDataException
754 ("GOTBLOCKS length is too short");
757 for (u16 i = 0; i < count; i++) {
764 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
767 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4)
771 s32 f32pitch, f32yaw;
779 f32 pitch = (f32)f32pitch / 100.0;
780 f32 yaw = (f32)f32yaw / 100.0;
783 // default behavior (in case an old client doesn't send these)
787 if (pkt->getRemainingBytes() >= 4)
789 if (pkt->getRemainingBytes() >= 1) {
791 fov = (f32)f32fov / 80.0;
793 if (pkt->getRemainingBytes() >= 1)
794 *pkt >> wanted_range;
796 v3f position((f32)ps.X / 100.0, (f32)ps.Y / 100.0, (f32)ps.Z / 100.0);
797 v3f speed((f32)ss.X / 100.0, (f32)ss.Y / 100.0, (f32)ss.Z / 100.0);
799 pitch = modulo360f(pitch);
800 yaw = wrapDegrees_0_360(yaw);
802 playersao->setBasePosition(position);
803 player->setSpeed(speed);
804 playersao->setPitch(pitch);
805 playersao->setYaw(yaw);
806 playersao->setFov(fov);
807 playersao->setWantedRange(wanted_range);
808 player->keyPressed = keyPressed;
809 player->control.up = (keyPressed & 1);
810 player->control.down = (keyPressed & 2);
811 player->control.left = (keyPressed & 4);
812 player->control.right = (keyPressed & 8);
813 player->control.jump = (keyPressed & 16);
814 player->control.aux1 = (keyPressed & 32);
815 player->control.sneak = (keyPressed & 64);
816 player->control.LMB = (keyPressed & 128);
817 player->control.RMB = (keyPressed & 256);
819 if (playersao->checkMovementCheat()) {
821 m_script->on_cheat(playersao, "moved_too_fast");
822 SendMovePlayer(pkt->getPeerId());
826 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
828 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
829 if (player == NULL) {
830 errorstream << "Server::ProcessData(): Canceling: "
831 "No player for peer_id=" << pkt->getPeerId()
832 << " disconnecting peer!" << std::endl;
833 m_con.DisconnectPeer(pkt->getPeerId());
837 PlayerSAO *playersao = player->getPlayerSAO();
838 if (playersao == NULL) {
839 errorstream << "Server::ProcessData(): Canceling: "
840 "No player object for peer_id=" << pkt->getPeerId()
841 << " disconnecting peer!" << std::endl;
842 m_con.DisconnectPeer(pkt->getPeerId());
846 // If player is dead we don't care of this packet
847 if (playersao->isDead()) {
848 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
849 << " is dead. Ignoring packet";
853 process_PlayerPos(player, playersao, pkt);
856 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
858 if (pkt->getSize() < 1)
872 RemoteClient *client = getClient(pkt->getPeerId());
874 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
875 throw con::InvalidIncomingDataException
876 ("DELETEDBLOCKS length is too short");
879 for (u16 i = 0; i < count; i++) {
882 client->SetBlockNotSent(p);
886 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
888 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
890 if (player == NULL) {
891 errorstream << "Server::ProcessData(): Canceling: "
892 "No player for peer_id=" << pkt->getPeerId()
893 << " disconnecting peer!" << std::endl;
894 m_con.DisconnectPeer(pkt->getPeerId());
898 PlayerSAO *playersao = player->getPlayerSAO();
899 if (playersao == NULL) {
900 errorstream << "Server::ProcessData(): Canceling: "
901 "No player object for peer_id=" << pkt->getPeerId()
902 << " disconnecting peer!" << std::endl;
903 m_con.DisconnectPeer(pkt->getPeerId());
907 // Strip command and create a stream
908 std::string datastring(pkt->getString(0), pkt->getSize());
909 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
911 std::istringstream is(datastring, std::ios_base::binary);
913 InventoryAction *a = InventoryAction::deSerialize(is);
915 infostream << "TOSERVER_INVENTORY_ACTION: "
916 << "InventoryAction::deSerialize() returned NULL"
921 // If something goes wrong, this player is to blame
922 RollbackScopeActor rollback_scope(m_rollback,
923 std::string("player:")+player->getName());
926 Note: Always set inventory not sent, to repair cases
927 where the client made a bad prediction.
931 Handle restrictions and special cases of the move action
933 if (a->getType() == IACTION_MOVE) {
934 IMoveAction *ma = (IMoveAction*)a;
936 ma->from_inv.applyCurrentPlayer(player->getName());
937 ma->to_inv.applyCurrentPlayer(player->getName());
939 setInventoryModified(ma->from_inv, false);
940 setInventoryModified(ma->to_inv, false);
942 bool from_inv_is_current_player =
943 (ma->from_inv.type == InventoryLocation::PLAYER) &&
944 (ma->from_inv.name == player->getName());
946 bool to_inv_is_current_player =
947 (ma->to_inv.type == InventoryLocation::PLAYER) &&
948 (ma->to_inv.name == player->getName());
951 Disable moving items out of craftpreview
953 if (ma->from_list == "craftpreview") {
954 infostream << "Ignoring IMoveAction from "
955 << (ma->from_inv.dump()) << ":" << ma->from_list
956 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
957 << " because src is " << ma->from_list << std::endl;
963 Disable moving items into craftresult and craftpreview
965 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
966 infostream << "Ignoring IMoveAction from "
967 << (ma->from_inv.dump()) << ":" << ma->from_list
968 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
969 << " because dst is " << ma->to_list << std::endl;
974 // Disallow moving items in elsewhere than player's inventory
975 // if not allowed to interact
976 if (!checkPriv(player->getName(), "interact") &&
977 (!from_inv_is_current_player ||
978 !to_inv_is_current_player)) {
979 infostream << "Cannot move outside of player's inventory: "
980 << "No interact privilege" << std::endl;
986 Handle restrictions and special cases of the drop action
988 else if (a->getType() == IACTION_DROP) {
989 IDropAction *da = (IDropAction*)a;
991 da->from_inv.applyCurrentPlayer(player->getName());
993 setInventoryModified(da->from_inv, false);
996 Disable dropping items out of craftpreview
998 if (da->from_list == "craftpreview") {
999 infostream << "Ignoring IDropAction from "
1000 << (da->from_inv.dump()) << ":" << da->from_list
1001 << " because src is " << da->from_list << std::endl;
1006 // Disallow dropping items if not allowed to interact
1007 if (!checkPriv(player->getName(), "interact")) {
1012 // Disallow dropping items if dead
1013 if (playersao->isDead()) {
1014 infostream << "Ignoring IDropAction from "
1015 << (da->from_inv.dump()) << ":" << da->from_list
1016 << " because player is dead." << std::endl;
1022 Handle restrictions and special cases of the craft action
1024 else if (a->getType() == IACTION_CRAFT) {
1025 ICraftAction *ca = (ICraftAction*)a;
1027 ca->craft_inv.applyCurrentPlayer(player->getName());
1029 setInventoryModified(ca->craft_inv, false);
1031 //bool craft_inv_is_current_player =
1032 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
1033 // (ca->craft_inv.name == player->getName());
1035 // Disallow crafting if not allowed to interact
1036 if (!checkPriv(player->getName(), "interact")) {
1037 infostream << "Cannot craft: "
1038 << "No interact privilege" << std::endl;
1045 a->apply(this, playersao, this);
1049 SendInventory(playersao);
1052 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
1062 std::wstring message;
1063 for (u16 i = 0; i < len; i++) {
1067 message += (wchar_t)tmp_wchar;
1070 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1071 if (player == NULL) {
1072 errorstream << "Server::ProcessData(): Canceling: "
1073 "No player for peer_id=" << pkt->getPeerId()
1074 << " disconnecting peer!" << std::endl;
1075 m_con.DisconnectPeer(pkt->getPeerId());
1079 // Get player name of this client
1080 std::string name = player->getName();
1081 std::wstring wname = narrow_to_wide(name);
1083 std::wstring answer_to_sender = handleChat(name, wname, message,
1084 true, dynamic_cast<RemotePlayer *>(player));
1085 if (!answer_to_sender.empty()) {
1086 // Send the answer to sender
1087 SendChatMessage(pkt->getPeerId(), answer_to_sender);
1091 void Server::handleCommand_Damage(NetworkPacket* pkt)
1097 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1099 if (player == NULL) {
1100 errorstream << "Server::ProcessData(): Canceling: "
1101 "No player for peer_id=" << pkt->getPeerId()
1102 << " disconnecting peer!" << std::endl;
1103 m_con.DisconnectPeer(pkt->getPeerId());
1107 PlayerSAO *playersao = player->getPlayerSAO();
1108 if (playersao == NULL) {
1109 errorstream << "Server::ProcessData(): Canceling: "
1110 "No player object for peer_id=" << pkt->getPeerId()
1111 << " disconnecting peer!" << std::endl;
1112 m_con.DisconnectPeer(pkt->getPeerId());
1116 if (g_settings->getBool("enable_damage")) {
1117 if (playersao->isDead()) {
1118 verbosestream << "Server::ProcessData(): Info: "
1119 "Ignoring damage as player " << player->getName()
1120 << " is already dead." << std::endl;
1124 actionstream << player->getName() << " damaged by "
1125 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
1128 playersao->setHP(playersao->getHP() - damage);
1129 SendPlayerHPOrDie(playersao);
1133 void Server::handleCommand_Password(NetworkPacket* pkt)
1135 if (pkt->getSize() != PASSWORD_SIZE * 2)
1141 // Deny for clients using the new protocol
1142 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
1143 if (client->net_proto_version >= 25) {
1144 infostream << "Server::handleCommand_Password(): Denying change: "
1145 << " Client protocol version for peer_id=" << pkt->getPeerId()
1146 << " too new!" << std::endl;
1150 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1151 char c = pkt->getChar(i);
1157 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1158 char c = pkt->getChar(PASSWORD_SIZE + i);
1164 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1165 if (player == NULL) {
1166 errorstream << "Server::ProcessData(): Canceling: "
1167 "No player for peer_id=" << pkt->getPeerId()
1168 << " disconnecting peer!" << std::endl;
1169 m_con.DisconnectPeer(pkt->getPeerId());
1173 if (!base64_is_valid(newpwd)) {
1174 infostream<<"Server: " << player->getName() <<
1175 " supplied invalid password hash" << std::endl;
1176 // Wrong old password supplied!!
1177 SendChatMessage(pkt->getPeerId(), L"Invalid new password hash supplied. Password NOT changed.");
1181 infostream << "Server: Client requests a password change from "
1182 << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
1184 std::string playername = player->getName();
1186 std::string checkpwd;
1187 m_script->getAuth(playername, &checkpwd, NULL);
1189 if (oldpwd != checkpwd) {
1190 infostream << "Server: invalid old password" << std::endl;
1191 // Wrong old password supplied!!
1192 SendChatMessage(pkt->getPeerId(), L"Invalid old password supplied. Password NOT changed.");
1196 bool success = m_script->setPassword(playername, newpwd);
1198 actionstream << player->getName() << " changes password" << std::endl;
1199 SendChatMessage(pkt->getPeerId(), L"Password change successful.");
1201 actionstream << player->getName() << " tries to change password but "
1202 << "it fails" << std::endl;
1203 SendChatMessage(pkt->getPeerId(), L"Password change failed or unavailable.");
1207 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
1209 if (pkt->getSize() < 2)
1212 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1214 if (player == NULL) {
1215 errorstream << "Server::ProcessData(): Canceling: "
1216 "No player for peer_id=" << pkt->getPeerId()
1217 << " disconnecting peer!" << std::endl;
1218 m_con.DisconnectPeer(pkt->getPeerId());
1222 PlayerSAO *playersao = player->getPlayerSAO();
1223 if (playersao == NULL) {
1224 errorstream << "Server::ProcessData(): Canceling: "
1225 "No player object for peer_id=" << pkt->getPeerId()
1226 << " disconnecting peer!" << std::endl;
1227 m_con.DisconnectPeer(pkt->getPeerId());
1235 playersao->setWieldIndex(item);
1238 void Server::handleCommand_Respawn(NetworkPacket* pkt)
1240 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1241 if (player == NULL) {
1242 errorstream << "Server::ProcessData(): Canceling: "
1243 "No player for peer_id=" << pkt->getPeerId()
1244 << " disconnecting peer!" << std::endl;
1245 m_con.DisconnectPeer(pkt->getPeerId());
1249 PlayerSAO *playersao = player->getPlayerSAO();
1252 if (!playersao->isDead())
1255 RespawnPlayer(pkt->getPeerId());
1257 actionstream << player->getName() << " respawns at "
1258 << PP(playersao->getBasePosition() / BS) << std::endl;
1260 // ActiveObject is added to environment in AsyncRunStep after
1261 // the previous addition has been successfully removed
1264 void Server::handleCommand_Interact(NetworkPacket* pkt)
1270 [5] u32 length of the next item (plen)
1271 [9] serialized PointedThing
1272 [9 + plen] player position information
1274 0: start digging (from undersurface) or use
1275 1: stop digging (all parameters ignored)
1276 2: digging completed
1277 3: place block or item (to abovesurface)
1279 5: rightclick air ("activate")
1285 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
1286 PointedThing pointed;
1287 pointed.deSerialize(tmp_is);
1289 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
1290 << item_i << ", pointed=" << pointed.dump() << std::endl;
1292 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1294 if (player == NULL) {
1295 errorstream << "Server::ProcessData(): Canceling: "
1296 "No player for peer_id=" << pkt->getPeerId()
1297 << " disconnecting peer!" << std::endl;
1298 m_con.DisconnectPeer(pkt->getPeerId());
1302 PlayerSAO *playersao = player->getPlayerSAO();
1303 if (playersao == NULL) {
1304 errorstream << "Server::ProcessData(): Canceling: "
1305 "No player object for peer_id=" << pkt->getPeerId()
1306 << " disconnecting peer!" << std::endl;
1307 m_con.DisconnectPeer(pkt->getPeerId());
1311 if (playersao->isDead()) {
1312 actionstream << "Server: NoCheat: " << player->getName()
1313 << " tried to interact while dead; ignoring." << std::endl;
1314 if (pointed.type == POINTEDTHING_NODE) {
1315 // Re-send block to revert change on client-side
1316 RemoteClient *client = getClient(pkt->getPeerId());
1317 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1318 client->SetBlockNotSent(blockpos);
1321 m_script->on_cheat(playersao, "interacted_while_dead");
1325 process_PlayerPos(player, playersao, pkt);
1327 v3f player_pos = playersao->getLastGoodPosition();
1329 // Update wielded item
1330 playersao->setWieldIndex(item_i);
1332 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1333 v3s16 p_under = pointed.node_undersurface;
1334 v3s16 p_above = pointed.node_abovesurface;
1336 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1337 ServerActiveObject *pointed_object = NULL;
1338 if (pointed.type == POINTEDTHING_OBJECT) {
1339 pointed_object = m_env->getActiveObject(pointed.object_id);
1340 if (pointed_object == NULL) {
1341 verbosestream << "TOSERVER_INTERACT: "
1342 "pointed object is NULL" << std::endl;
1348 v3f pointed_pos_under = player_pos;
1349 v3f pointed_pos_above = player_pos;
1350 if (pointed.type == POINTEDTHING_NODE) {
1351 pointed_pos_under = intToFloat(p_under, BS);
1352 pointed_pos_above = intToFloat(p_above, BS);
1354 else if (pointed.type == POINTEDTHING_OBJECT) {
1355 pointed_pos_under = pointed_object->getBasePosition();
1356 pointed_pos_above = pointed_pos_under;
1360 Make sure the player is allowed to do it
1362 if (!checkPriv(player->getName(), "interact")) {
1363 actionstream<<player->getName()<<" attempted to interact with "
1364 <<pointed.dump()<<" without 'interact' privilege"
1366 // Re-send block to revert change on client-side
1367 RemoteClient *client = getClient(pkt->getPeerId());
1368 // Digging completed -> under
1370 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1371 client->SetBlockNotSent(blockpos);
1373 // Placement -> above
1375 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1376 client->SetBlockNotSent(blockpos);
1382 Check that target is reasonably close
1383 (only when digging or placing things)
1385 static const bool enable_anticheat = !g_settings->getBool("disable_anticheat");
1386 if ((action == 0 || action == 2 || action == 3 || action == 4) &&
1387 (enable_anticheat && !isSingleplayer())) {
1388 float d = player_pos.getDistanceFrom(pointed_pos_under);
1389 const ItemDefinition &playeritem_def =
1390 playersao->getWieldedItem().getDefinition(m_itemdef);
1391 float max_d = BS * playeritem_def.range;
1392 InventoryList *hlist = playersao->getInventory()->getList("hand");
1393 const ItemDefinition &hand_def =
1394 hlist ? (hlist->getItem(0).getDefinition(m_itemdef)) : (m_itemdef->get(""));
1395 float max_d_hand = BS * hand_def.range;
1396 if (max_d < 0 && max_d_hand >= 0)
1400 // cube diagonal: sqrt(3) = 1.73
1401 if (d > max_d * 1.73) {
1402 actionstream << "Player " << player->getName()
1403 << " tried to access " << pointed.dump()
1404 << " from too far: "
1405 << "d=" << d <<", max_d=" << max_d
1406 << ". ignoring." << std::endl;
1407 // Re-send block to revert change on client-side
1408 RemoteClient *client = getClient(pkt->getPeerId());
1409 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1410 client->SetBlockNotSent(blockpos);
1412 m_script->on_cheat(playersao, "interacted_too_far");
1419 If something goes wrong, this player is to blame
1421 RollbackScopeActor rollback_scope(m_rollback,
1422 std::string("player:")+player->getName());
1425 0: start digging or punch object
1428 if (pointed.type == POINTEDTHING_NODE) {
1429 MapNode n(CONTENT_IGNORE);
1432 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1434 infostream << "Server: Not punching: Node not found."
1435 << " Adding block to emerge queue."
1437 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1438 getNodeBlockPos(p_above), false);
1441 if (n.getContent() != CONTENT_IGNORE)
1442 m_script->node_on_punch(p_under, n, playersao, pointed);
1445 playersao->noCheatDigStart(p_under);
1447 else if (pointed.type == POINTEDTHING_OBJECT) {
1448 // Skip if object has been removed
1449 if (pointed_object->m_removed)
1452 actionstream<<player->getName()<<" punches object "
1453 <<pointed.object_id<<": "
1454 <<pointed_object->getDescription()<<std::endl;
1456 ItemStack punchitem = playersao->getWieldedItemOrHand();
1457 ToolCapabilities toolcap =
1458 punchitem.getToolCapabilities(m_itemdef);
1459 v3f dir = (pointed_object->getBasePosition() -
1460 (playersao->getBasePosition() + playersao->getEyeOffset())
1462 float time_from_last_punch =
1463 playersao->resetTimeFromLastPunch();
1465 s16 src_original_hp = pointed_object->getHP();
1466 s16 dst_origin_hp = playersao->getHP();
1468 pointed_object->punch(dir, &toolcap, playersao,
1469 time_from_last_punch);
1471 // If the object is a player and its HP changed
1472 if (src_original_hp != pointed_object->getHP() &&
1473 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1474 SendPlayerHPOrDie((PlayerSAO *)pointed_object);
1477 // If the puncher is a player and its HP changed
1478 if (dst_origin_hp != playersao->getHP())
1479 SendPlayerHPOrDie(playersao);
1487 else if (action == 1) {
1491 2: Digging completed
1493 else if (action == 2) {
1494 // Only digging of nodes
1495 if (pointed.type == POINTEDTHING_NODE) {
1497 MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1499 infostream << "Server: Not finishing digging: Node not found."
1500 << " Adding block to emerge queue."
1502 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1503 getNodeBlockPos(p_above), false);
1506 /* Cheat prevention */
1507 bool is_valid_dig = true;
1508 if (enable_anticheat && !isSingleplayer()) {
1509 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1510 float nocheat_t = playersao->getNoCheatDigTime();
1511 playersao->noCheatDigEnd();
1512 // If player didn't start digging this, ignore dig
1513 if (nocheat_p != p_under) {
1514 infostream << "Server: NoCheat: " << player->getName()
1515 << " started digging "
1516 << PP(nocheat_p) << " and completed digging "
1517 << PP(p_under) << "; not digging." << std::endl;
1518 is_valid_dig = false;
1520 m_script->on_cheat(playersao, "finished_unknown_dig");
1522 // Get player's wielded item
1523 ItemStack playeritem = playersao->getWieldedItemOrHand();
1524 ToolCapabilities playeritem_toolcap =
1525 playeritem.getToolCapabilities(m_itemdef);
1526 // Get diggability and expected digging time
1527 DigParams params = getDigParams(m_nodedef->get(n).groups,
1528 &playeritem_toolcap);
1529 // If can't dig, try hand
1530 if (!params.diggable) {
1531 InventoryList *hlist = playersao->getInventory()->getList("hand");
1532 const ItemDefinition &hand =
1533 hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
1534 const ToolCapabilities *tp = hand.tool_capabilities;
1536 params = getDigParams(m_nodedef->get(n).groups, tp);
1538 // If can't dig, ignore dig
1539 if (!params.diggable) {
1540 infostream << "Server: NoCheat: " << player->getName()
1541 << " completed digging " << PP(p_under)
1542 << ", which is not diggable with tool. not digging."
1544 is_valid_dig = false;
1546 m_script->on_cheat(playersao, "dug_unbreakable");
1548 // Check digging time
1549 // If already invalidated, we don't have to
1550 if (!is_valid_dig) {
1551 // Well not our problem then
1553 // Clean and long dig
1554 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1555 // All is good, but grab time from pool; don't care if
1556 // it's actually available
1557 playersao->getDigPool().grab(params.time);
1559 // Short or laggy dig
1560 // Try getting the time from pool
1561 else if (playersao->getDigPool().grab(params.time)) {
1566 infostream << "Server: NoCheat: " << player->getName()
1567 << " completed digging " << PP(p_under)
1568 << "too fast; not digging." << std::endl;
1569 is_valid_dig = false;
1571 m_script->on_cheat(playersao, "dug_too_fast");
1575 /* Actually dig node */
1577 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1578 m_script->node_on_dig(p_under, n, playersao);
1580 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1581 RemoteClient *client = getClient(pkt->getPeerId());
1582 // Send unusual result (that is, node not being removed)
1583 if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1584 // Re-send block to revert change on client-side
1585 client->SetBlockNotSent(blockpos);
1588 client->ResendBlockIfOnWire(blockpos);
1594 3: place block or right-click object
1596 else if (action == 3) {
1597 ItemStack item = playersao->getWieldedItem();
1599 // Reset build time counter
1600 if (pointed.type == POINTEDTHING_NODE &&
1601 item.getDefinition(m_itemdef).type == ITEM_NODE)
1602 getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1604 if (pointed.type == POINTEDTHING_OBJECT) {
1605 // Right click object
1607 // Skip if object has been removed
1608 if (pointed_object->m_removed)
1611 actionstream << player->getName() << " right-clicks object "
1612 << pointed.object_id << ": "
1613 << pointed_object->getDescription() << std::endl;
1616 pointed_object->rightClick(playersao);
1618 else if (m_script->item_OnPlace(
1619 item, playersao, pointed)) {
1620 // Placement was handled in lua
1622 // Apply returned ItemStack
1623 if (playersao->setWieldedItem(item)) {
1624 SendInventory(playersao);
1628 // If item has node placement prediction, always send the
1629 // blocks to make sure the client knows what exactly happened
1630 RemoteClient *client = getClient(pkt->getPeerId());
1631 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1632 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1633 if (item.getDefinition(m_itemdef).node_placement_prediction != "") {
1634 client->SetBlockNotSent(blockpos);
1635 if (blockpos2 != blockpos) {
1636 client->SetBlockNotSent(blockpos2);
1640 client->ResendBlockIfOnWire(blockpos);
1641 if (blockpos2 != blockpos) {
1642 client->ResendBlockIfOnWire(blockpos2);
1650 else if (action == 4) {
1651 ItemStack item = playersao->getWieldedItem();
1653 actionstream << player->getName() << " uses " << item.name
1654 << ", pointing at " << pointed.dump() << std::endl;
1656 if (m_script->item_OnUse(
1657 item, playersao, pointed)) {
1658 // Apply returned ItemStack
1659 if (playersao->setWieldedItem(item)) {
1660 SendInventory(playersao);
1669 else if (action == 5) {
1670 ItemStack item = playersao->getWieldedItem();
1672 actionstream << player->getName() << " activates "
1673 << item.name << std::endl;
1675 if (m_script->item_OnSecondaryUse(
1677 if( playersao->setWieldedItem(item)) {
1678 SendInventory(playersao);
1685 Catch invalid actions
1688 warningstream << "Server: Invalid action "
1689 << action << std::endl;
1693 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1697 for (u16 k = 0; k < num; k++) {
1702 UNORDERED_MAP<s32, ServerPlayingSound>::iterator i = m_playing_sounds.find(id);
1703 if (i == m_playing_sounds.end())
1706 ServerPlayingSound &psound = i->second;
1707 psound.clients.erase(pkt->getPeerId());
1708 if (psound.clients.empty())
1709 m_playing_sounds.erase(i++);
1713 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1716 std::string formname;
1719 *pkt >> p >> formname >> num;
1722 for (u16 k = 0; k < num; k++) {
1723 std::string fieldname;
1725 fields[fieldname] = pkt->readLongString();
1728 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1730 if (player == NULL) {
1731 errorstream << "Server::ProcessData(): Canceling: "
1732 "No player for peer_id=" << pkt->getPeerId()
1733 << " disconnecting peer!" << std::endl;
1734 m_con.DisconnectPeer(pkt->getPeerId());
1738 PlayerSAO *playersao = player->getPlayerSAO();
1739 if (playersao == NULL) {
1740 errorstream << "Server::ProcessData(): Canceling: "
1741 "No player object for peer_id=" << pkt->getPeerId()
1742 << " disconnecting peer!" << std::endl;
1743 m_con.DisconnectPeer(pkt->getPeerId());
1747 // If something goes wrong, this player is to blame
1748 RollbackScopeActor rollback_scope(m_rollback,
1749 std::string("player:")+player->getName());
1751 // Check the target node for rollback data; leave others unnoticed
1752 RollbackNode rn_old(&m_env->getMap(), p, this);
1754 m_script->node_on_receive_fields(p, formname, fields, playersao);
1756 // Report rollback data
1757 RollbackNode rn_new(&m_env->getMap(), p, this);
1758 if (rollback() && rn_new != rn_old) {
1759 RollbackAction action;
1760 action.setSetNode(p, rn_old, rn_new);
1761 rollback()->reportAction(action);
1765 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1767 std::string formname;
1770 *pkt >> formname >> num;
1773 for (u16 k = 0; k < num; k++) {
1774 std::string fieldname;
1776 fields[fieldname] = pkt->readLongString();
1779 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1781 if (player == NULL) {
1782 errorstream << "Server::ProcessData(): Canceling: "
1783 "No player for peer_id=" << pkt->getPeerId()
1784 << " disconnecting peer!" << std::endl;
1785 m_con.DisconnectPeer(pkt->getPeerId());
1789 PlayerSAO *playersao = player->getPlayerSAO();
1790 if (playersao == NULL) {
1791 errorstream << "Server::ProcessData(): Canceling: "
1792 "No player object for peer_id=" << pkt->getPeerId()
1793 << " disconnecting peer!" << std::endl;
1794 m_con.DisconnectPeer(pkt->getPeerId());
1798 m_script->on_playerReceiveFields(playersao, formname, fields);
1801 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1803 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1804 ClientState cstate = client->getState();
1806 std::string playername = client->getName();
1809 std::string verification_key;
1811 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1814 *pkt >> salt >> verification_key >> is_empty;
1816 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1817 << ", with is_empty=" << (is_empty == 1) << std::endl;
1819 // Either this packet is sent because the user is new or to change the password
1820 if (cstate == CS_HelloSent) {
1821 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1822 actionstream << "Server: Client from " << addr_s
1823 << " tried to set password without being "
1824 << "authenticated, or the username being new." << std::endl;
1825 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1829 if (!isSingleplayer() &&
1830 g_settings->getBool("disallow_empty_password") &&
1832 actionstream << "Server: " << playername
1833 << " supplied empty password from " << addr_s << std::endl;
1834 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1838 std::string initial_ver_key;
1840 initial_ver_key = encode_srp_verifier(verification_key, salt);
1841 m_script->createAuth(playername, initial_ver_key);
1843 acceptAuth(pkt->getPeerId(), false);
1845 if (cstate < CS_SudoMode) {
1846 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1847 << addr_s << ": " << "Client has wrong state " << cstate << "."
1851 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1852 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1853 bool success = m_script->setPassword(playername, pw_db_field);
1855 actionstream << playername << " changes password" << std::endl;
1856 SendChatMessage(pkt->getPeerId(), L"Password change successful.");
1858 actionstream << playername << " tries to change password but "
1859 << "it fails" << std::endl;
1860 SendChatMessage(pkt->getPeerId(), L"Password change failed or unavailable.");
1865 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1867 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1868 ClientState cstate = client->getState();
1870 bool wantSudo = (cstate == CS_Active);
1872 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1873 actionstream << "Server: got SRP _A packet in wrong state "
1874 << cstate << " from "
1875 << getPeerAddress(pkt->getPeerId()).serializeString()
1876 << ". Ignoring." << std::endl;
1880 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1881 actionstream << "Server: got SRP _A packet, while auth"
1882 << "is already going on with mech " << client->chosen_mech
1883 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1884 << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1886 DenySudoAccess(pkt->getPeerId());
1889 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1894 std::string bytes_A;
1896 *pkt >> bytes_A >> based_on;
1898 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1899 << "based_on=" << int(based_on) << " and len_A="
1900 << bytes_A.length() << "." << std::endl;
1902 AuthMechanism chosen = (based_on == 0) ?
1903 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1906 if (!client->isSudoMechAllowed(chosen)) {
1907 actionstream << "Server: Player \"" << client->getName()
1908 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1909 << " tried to change password using unallowed mech "
1910 << chosen << "." << std::endl;
1911 DenySudoAccess(pkt->getPeerId());
1915 if (!client->isMechAllowed(chosen)) {
1916 actionstream << "Server: Client tried to authenticate from "
1917 << getPeerAddress(pkt->getPeerId()).serializeString()
1918 << " using unallowed mech " << chosen << "." << std::endl;
1919 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1924 client->chosen_mech = chosen;
1927 std::string verifier;
1929 if (based_on == 0) {
1931 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1933 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1934 // Non-base64 errors should have been catched in the init handler
1935 actionstream << "Server: User " << client->getName()
1936 << " tried to log in, but srp verifier field"
1937 << " was invalid (most likely invalid base64)." << std::endl;
1938 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1945 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1946 client->getName().c_str(),
1947 (const unsigned char *) salt.c_str(), salt.size(),
1948 (const unsigned char *) verifier.c_str(), verifier.size(),
1949 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1951 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1954 actionstream << "Server: User " << client->getName()
1955 << " tried to log in, SRP-6a safety check violated in _A handler."
1958 DenySudoAccess(pkt->getPeerId());
1961 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1966 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1967 resp_pkt << salt << std::string(bytes_B, len_B);
1971 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1973 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1974 ClientState cstate = client->getState();
1976 bool wantSudo = (cstate == CS_Active);
1978 verbosestream << "Server: Recieved TOCLIENT_SRP_BYTES_M." << std::endl;
1980 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1981 actionstream << "Server: got SRP _M packet in wrong state "
1982 << cstate << " from "
1983 << getPeerAddress(pkt->getPeerId()).serializeString()
1984 << ". Ignoring." << std::endl;
1988 if ((client->chosen_mech != AUTH_MECHANISM_SRP)
1989 && (client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD)) {
1990 actionstream << "Server: got SRP _M packet, while auth"
1991 << "is going on with mech " << client->chosen_mech
1992 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1993 << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1995 DenySudoAccess(pkt->getPeerId());
1998 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2003 std::string bytes_M;
2006 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
2007 != bytes_M.size()) {
2008 actionstream << "Server: User " << client->getName()
2009 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2010 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
2011 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2015 unsigned char *bytes_HAMK = 0;
2017 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
2018 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
2022 actionstream << "Server: User " << client->getName()
2023 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2024 << " tried to change their password, but supplied wrong"
2025 << " (SRP) password for authentication." << std::endl;
2026 DenySudoAccess(pkt->getPeerId());
2029 actionstream << "Server: User " << client->getName()
2030 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2031 << " supplied wrong password (auth mechanism: SRP)."
2033 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
2038 if (client->create_player_on_auth_success) {
2039 std::string playername = client->getName();
2040 m_script->createAuth(playername, client->enc_pwd);
2042 std::string checkpwd; // not used, but needed for passing something
2043 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
2044 actionstream << "Server: " << playername << " cannot be authenticated"
2045 << " (auth handler does not work?)" << std::endl;
2046 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
2049 client->create_player_on_auth_success = false;
2052 acceptAuth(pkt->getPeerId(), wantSudo);