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"
28 #include "rollback_interface.h"
29 #include "scripting_game.h"
33 #include "network/networkprotocol.h"
34 #include "network/serveropcodes.h"
35 #include "util/auth.h"
36 #include "util/base64.h"
37 #include "util/pointedthing.h"
38 #include "util/serialize.h"
41 void Server::handleCommand_Deprecated(NetworkPacket* pkt)
43 infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
44 << " not supported anymore" << std::endl;
47 void Server::handleCommand_Init(NetworkPacket* pkt)
50 if(pkt->getSize() < 1)
53 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
57 Address address = getPeerAddress(pkt->getPeerId());
58 addr_s = address.serializeString();
60 catch (con::PeerNotFoundException &e) {
62 * no peer for this packet found
63 * most common reason is peer timeout, e.g. peer didn't
64 * respond for some time, your server was overloaded or
67 infostream << "Server::ProcessData(): Canceling: peer "
68 << pkt->getPeerId() << " not found" << std::endl;
72 // If net_proto_version is set, this client has already been handled
73 if (client->getState() > CS_Created) {
74 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
75 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
79 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
80 << pkt->getPeerId() << ")" << std::endl;
82 // Do not allow multiple players in simple singleplayer mode.
83 // This isn't a perfect way to do it, but will suffice for now
84 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
85 infostream << "Server: Not allowing another client (" << addr_s
86 << ") to connect in simple singleplayer mode" << std::endl;
87 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SINGLEPLAYER);
91 // First byte after command is maximum supported
92 // serialization version
95 u16 min_net_proto_version = 0;
96 u16 max_net_proto_version;
97 std::string playerName;
99 *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
100 >> max_net_proto_version >> playerName;
102 u8 our_max = SER_FMT_VER_HIGHEST_READ;
103 // Use the highest version supported by both
104 u8 depl_serial_v = std::min(client_max, our_max);
105 // If it's lower than the lowest supported, give up.
106 if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
107 depl_serial_v = SER_FMT_VER_INVALID;
109 if (depl_serial_v == SER_FMT_VER_INVALID) {
110 actionstream << "Server: A mismatched client tried to connect from "
111 << addr_s << std::endl;
112 infostream<<"Server: Cannot negotiate serialization version with "
113 << addr_s << std::endl;
114 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
118 client->setPendingSerializationVersion(depl_serial_v);
121 Read and check network protocol version
124 u16 net_proto_version = 0;
126 // Figure out a working version if it is possible at all
127 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
128 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
129 // If maximum is larger than our maximum, go with our maximum
130 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
131 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
132 // Else go with client's maximum
134 net_proto_version = max_net_proto_version;
137 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
138 << min_net_proto_version << ", max: " << max_net_proto_version
139 << ", chosen: " << net_proto_version << std::endl;
141 client->net_proto_version = net_proto_version;
143 // On this handler at least protocol version 25 is required
144 if (net_proto_version < 25 ||
145 net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
146 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
147 actionstream << "Server: A mismatched client tried to connect from "
148 << addr_s << std::endl;
149 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
153 if (g_settings->getBool("strict_protocol_version_checking")) {
154 if (net_proto_version != LATEST_PROTOCOL_VERSION) {
155 actionstream << "Server: A mismatched (strict) client tried to "
156 << "connect from " << addr_s << std::endl;
157 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
165 const char* playername = playerName.c_str();
167 size_t pns = playerName.size();
168 if (pns == 0 || pns > PLAYERNAME_SIZE) {
169 actionstream << "Server: Player with "
170 << ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty")
171 << " name tried to connect from " << addr_s << std::endl;
172 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
176 if (string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS) == false) {
177 actionstream << "Server: Player with an invalid name "
178 << "tried to connect from " << addr_s << std::endl;
179 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
183 m_clients.setPlayerName(pkt->getPeerId(), playername);
184 //TODO (later) case insensitivity
186 std::string legacyPlayerNameCasing = playerName;
188 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
189 actionstream << "Server: Player with the name \"singleplayer\" "
190 << "tried to connect from " << addr_s << std::endl;
191 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
197 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
198 actionstream << "Server: Player with the name \"" << playerName << "\" "
199 << "tried to connect from " << addr_s << " "
200 << "but it was disallowed for the following reason: "
201 << reason << std::endl;
202 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING,
208 infostream << "Server: New connection: \"" << playerName << "\" from "
209 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
211 // Enforce user limit.
212 // Don't enforce for users that have some admin right
213 if (m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
214 !checkPriv(playername, "server") &&
215 !checkPriv(playername, "ban") &&
216 !checkPriv(playername, "privs") &&
217 !checkPriv(playername, "password") &&
218 playername != g_settings->get("name")) {
219 actionstream << "Server: " << playername << " tried to join from "
220 << addr_s << ", but there" << " are already max_users="
221 << g_settings->getU16("max_users") << " players." << std::endl;
222 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_TOO_MANY_USERS);
227 Compose auth methods for answer
229 std::string encpwd; // encrypted Password field for the user
230 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
233 client->chosen_mech = AUTH_MECHANISM_NONE;
236 std::vector<std::string> pwd_components = str_split(encpwd, '#');
237 if (pwd_components.size() == 4) {
238 if (pwd_components[1] == "1") { // 1 means srp
239 auth_mechs |= AUTH_MECHANISM_SRP;
240 client->enc_pwd = encpwd;
242 actionstream << "User " << playername
243 << " tried to log in, but password field"
244 << " was invalid (unknown mechcode)." << std::endl;
245 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
248 } else if (base64_is_valid(encpwd)) {
249 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
250 client->enc_pwd = encpwd;
252 actionstream << "User " << playername
253 << " tried to log in, but password field"
254 << " was invalid (invalid base64)." << std::endl;
255 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
259 std::string default_password = g_settings->get("default_password");
260 if (default_password.length() == 0) {
261 auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
263 // Take care of default passwords.
264 client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
265 auth_mechs |= AUTH_MECHANISM_SRP;
266 // Allocate player in db, but only on successful login.
267 client->create_player_on_auth_success = true;
272 Answer with a TOCLIENT_HELLO
275 verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
276 << auth_mechs << std::endl;
278 NetworkPacket resp_pkt(TOCLIENT_HELLO, 1 + 4
279 + legacyPlayerNameCasing.size(), pkt->getPeerId());
281 u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
282 resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
283 << auth_mechs << legacyPlayerNameCasing;
287 client->allowed_auth_mechs = auth_mechs;
288 client->setDeployedCompressionMode(depl_compress_mode);
290 m_clients.event(pkt->getPeerId(), CSE_Hello);
293 void Server::handleCommand_Init_Legacy(NetworkPacket* pkt)
295 // [0] u8 SER_FMT_VER_HIGHEST_READ
296 // [1] u8[20] player_name
297 // [21] u8[28] password <--- can be sent without this, from old versions
299 if (pkt->getSize() < 1+PLAYERNAME_SIZE)
302 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
306 Address address = getPeerAddress(pkt->getPeerId());
307 addr_s = address.serializeString();
309 catch (con::PeerNotFoundException &e) {
311 * no peer for this packet found
312 * most common reason is peer timeout, e.g. peer didn't
313 * respond for some time, your server was overloaded or
316 infostream << "Server::ProcessData(): Canceling: peer "
317 << pkt->getPeerId() << " not found" << std::endl;
321 // If net_proto_version is set, this client has already been handled
322 if (client->getState() > CS_Created) {
323 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
324 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
328 verbosestream << "Server: Got TOSERVER_INIT_LEGACY from " << addr_s << " (peer_id="
329 << pkt->getPeerId() << ")" << std::endl;
331 // Do not allow multiple players in simple singleplayer mode.
332 // This isn't a perfect way to do it, but will suffice for now
333 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
334 infostream << "Server: Not allowing another client (" << addr_s
335 << ") to connect in simple singleplayer mode" << std::endl;
336 DenyAccess_Legacy(pkt->getPeerId(), L"Running in simple singleplayer mode.");
340 // First byte after command is maximum supported
341 // serialization version
346 u8 our_max = SER_FMT_VER_HIGHEST_READ;
347 // Use the highest version supported by both
348 int deployed = std::min(client_max, our_max);
349 // If it's lower than the lowest supported, give up.
350 if (deployed < SER_FMT_VER_LOWEST_READ)
351 deployed = SER_FMT_VER_INVALID;
353 if (deployed == SER_FMT_VER_INVALID) {
354 actionstream << "Server: A mismatched client tried to connect from "
355 << addr_s << std::endl;
356 infostream<<"Server: Cannot negotiate serialization version with "
357 << addr_s << std::endl;
358 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
359 L"Your client's version is not supported.\n"
360 L"Server version is ")
361 + utf8_to_wide(g_version_string) + L"."
366 client->setPendingSerializationVersion(deployed);
369 Read and check network protocol version
372 u16 min_net_proto_version = 0;
373 if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2)
374 min_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE);
376 // Use same version as minimum and maximum if maximum version field
377 // doesn't exist (backwards compatibility)
378 u16 max_net_proto_version = min_net_proto_version;
379 if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2)
380 max_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2);
382 // Start with client's maximum version
383 u16 net_proto_version = max_net_proto_version;
385 // Figure out a working version if it is possible at all
386 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
387 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
388 // If maximum is larger than our maximum, go with our maximum
389 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
390 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
391 // Else go with client's maximum
393 net_proto_version = max_net_proto_version;
396 // The client will send up to date init packet, ignore this one
397 if (net_proto_version >= 25)
400 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
401 << min_net_proto_version << ", max: " << max_net_proto_version
402 << ", chosen: " << net_proto_version << std::endl;
404 client->net_proto_version = net_proto_version;
406 if (net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
407 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
408 actionstream << "Server: A mismatched client tried to connect from "
409 << addr_s << std::endl;
410 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
411 L"Your client's version is not supported.\n"
412 L"Server version is ")
413 + utf8_to_wide(g_version_string) + L",\n"
414 + L"server's PROTOCOL_VERSION is "
415 + utf8_to_wide(itos(SERVER_PROTOCOL_VERSION_MIN))
417 + utf8_to_wide(itos(SERVER_PROTOCOL_VERSION_MAX))
418 + L", client's PROTOCOL_VERSION is "
419 + utf8_to_wide(itos(min_net_proto_version))
421 + utf8_to_wide(itos(max_net_proto_version))
426 if (g_settings->getBool("strict_protocol_version_checking")) {
427 if (net_proto_version != LATEST_PROTOCOL_VERSION) {
428 actionstream << "Server: A mismatched (strict) client tried to "
429 << "connect from " << addr_s << std::endl;
430 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
431 L"Your client's version is not supported.\n"
432 L"Server version is ")
433 + utf8_to_wide(g_version_string) + L",\n"
434 + L"server's PROTOCOL_VERSION (strict) is "
435 + utf8_to_wide(itos(LATEST_PROTOCOL_VERSION))
436 + L", client's PROTOCOL_VERSION is "
437 + utf8_to_wide(itos(min_net_proto_version))
439 + utf8_to_wide(itos(max_net_proto_version))
448 char playername[PLAYERNAME_SIZE];
449 unsigned int playername_length = 0;
450 for (; playername_length < PLAYERNAME_SIZE; playername_length++ ) {
451 playername[playername_length] = pkt->getChar(1+playername_length);
452 if (pkt->getChar(1+playername_length) == 0)
456 if (playername_length == PLAYERNAME_SIZE) {
457 actionstream << "Server: Player with name exceeding max length "
458 << "tried to connect from " << addr_s << std::endl;
459 DenyAccess_Legacy(pkt->getPeerId(), L"Name too long");
464 if (playername[0]=='\0') {
465 actionstream << "Server: Player with an empty name "
466 << "tried to connect from " << addr_s << std::endl;
467 DenyAccess_Legacy(pkt->getPeerId(), L"Empty name");
471 if (string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false) {
472 actionstream << "Server: Player with an invalid name "
473 << "tried to connect from " << addr_s << std::endl;
474 DenyAccess_Legacy(pkt->getPeerId(), L"Name contains unallowed characters");
478 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
479 actionstream << "Server: Player with the name \"singleplayer\" "
480 << "tried to connect from " << addr_s << std::endl;
481 DenyAccess_Legacy(pkt->getPeerId(), L"Name is not allowed");
487 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
488 actionstream << "Server: Player with the name \"" << playername << "\" "
489 << "tried to connect from " << addr_s << " "
490 << "but it was disallowed for the following reason: "
491 << reason << std::endl;
492 DenyAccess_Legacy(pkt->getPeerId(), utf8_to_wide(reason.c_str()));
497 infostream<<"Server: New connection: \""<<playername<<"\" from "
498 <<addr_s<<" (peer_id="<<pkt->getPeerId()<<")"<<std::endl;
501 char given_password[PASSWORD_SIZE];
502 if (pkt->getSize() < 1 + PLAYERNAME_SIZE + PASSWORD_SIZE) {
503 // old version - assume blank password
504 given_password[0] = 0;
507 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
508 given_password[i] = pkt->getChar(21 + i);
510 given_password[PASSWORD_SIZE - 1] = 0;
513 if (!base64_is_valid(given_password)) {
514 actionstream << "Server: " << playername
515 << " supplied invalid password hash" << std::endl;
516 DenyAccess_Legacy(pkt->getPeerId(), L"Invalid password hash");
520 // Enforce user limit.
521 // Don't enforce for users that have some admin right
522 if (m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
523 !checkPriv(playername, "server") &&
524 !checkPriv(playername, "ban") &&
525 !checkPriv(playername, "privs") &&
526 !checkPriv(playername, "password") &&
527 playername != g_settings->get("name")) {
528 actionstream << "Server: " << playername << " tried to join, but there"
529 << " are already max_users="
530 << g_settings->getU16("max_users") << " players." << std::endl;
531 DenyAccess_Legacy(pkt->getPeerId(), L"Too many users.");
535 std::string checkpwd; // Password hash to check against
536 bool has_auth = m_script->getAuth(playername, &checkpwd, NULL);
538 // If no authentication info exists for user, create it
540 if (!isSingleplayer() &&
541 g_settings->getBool("disallow_empty_password") &&
542 std::string(given_password) == "") {
543 actionstream << "Server: " << playername
544 << " supplied empty password" << std::endl;
545 DenyAccess_Legacy(pkt->getPeerId(), L"Empty passwords are "
546 L"disallowed. Set a password and try again.");
549 std::string raw_default_password =
550 g_settings->get("default_password");
551 std::string initial_password =
552 translate_password(playername, raw_default_password);
554 // If default_password is empty, allow any initial password
555 if (raw_default_password.length() == 0)
556 initial_password = given_password;
558 m_script->createAuth(playername, initial_password);
561 has_auth = m_script->getAuth(playername, &checkpwd, NULL);
564 actionstream << "Server: " << playername << " cannot be authenticated"
565 << " (auth handler does not work?)" << std::endl;
566 DenyAccess_Legacy(pkt->getPeerId(), L"Not allowed to login");
570 if (given_password != checkpwd) {
571 actionstream << "Server: User " << playername
573 << " supplied wrong password (auth mechanism: legacy)."
575 DenyAccess_Legacy(pkt->getPeerId(), L"Wrong password");
579 RemotePlayer *player =
580 static_cast<RemotePlayer*>(m_env->getPlayer(playername));
582 if (player && player->peer_id != 0) {
583 actionstream << "Server: " << playername << ": Failed to emerge player"
584 << " (player allocated to an another client)" << std::endl;
585 DenyAccess_Legacy(pkt->getPeerId(), L"Another client is connected with this "
586 L"name. If your client closed unexpectedly, try again in "
590 m_clients.setPlayerName(pkt->getPeerId(), playername);
593 Answer with a TOCLIENT_INIT
596 NetworkPacket resp_pkt(TOCLIENT_INIT_LEGACY, 1 + 6 + 8 + 4,
599 resp_pkt << (u8) deployed << (v3s16) floatToInt(v3f(0,0,0), BS)
600 << (u64) m_env->getServerMap().getSeed()
601 << g_settings->getFloat("dedicated_server_step");
604 m_clients.event(pkt->getPeerId(), CSE_InitLegacy);
607 void Server::handleCommand_Init2(NetworkPacket* pkt)
609 verbosestream << "Server: Got TOSERVER_INIT2 from "
610 << pkt->getPeerId() << std::endl;
612 m_clients.event(pkt->getPeerId(), CSE_GotInit2);
613 u16 protocol_version = m_clients.getProtocolVersion(pkt->getPeerId());
616 ///// begin compatibility code
617 PlayerSAO* playersao = NULL;
618 if (protocol_version <= 22) {
619 playersao = StageTwoClientInit(pkt->getPeerId());
621 if (playersao == NULL) {
623 << "TOSERVER_INIT2 stage 2 client init failed for peer "
624 << pkt->getPeerId() << std::endl;
628 ///// end compatibility code
631 Send some initialization data
634 infostream << "Server: Sending content to "
635 << getPlayerName(pkt->getPeerId()) << std::endl;
637 // Send player movement settings
638 SendMovement(pkt->getPeerId());
640 // Send item definitions
641 SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
643 // Send node definitions
644 SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
646 m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
648 // Send media announcement
649 sendMediaAnnouncement(pkt->getPeerId());
651 // Send detached inventories
652 sendDetachedInventories(pkt->getPeerId());
655 u16 time = m_env->getTimeOfDay();
656 float time_speed = g_settings->getFloat("time_speed");
657 SendTimeOfDay(pkt->getPeerId(), time, time_speed);
659 ///// begin compatibility code
660 if (protocol_version <= 22) {
661 m_clients.event(pkt->getPeerId(), CSE_SetClientReady);
662 m_script->on_joinplayer(playersao);
664 ///// end compatibility code
666 // Warnings about protocol version can be issued here
667 if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
668 SendChatMessage(pkt->getPeerId(), L"# Server: WARNING: YOUR CLIENT'S "
669 L"VERSION MAY NOT BE FULLY COMPATIBLE WITH THIS SERVER!");
673 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
675 std::vector<std::string> tosend;
680 infostream << "Sending " << numfiles << " files to "
681 << getPlayerName(pkt->getPeerId()) << std::endl;
682 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
684 for (u16 i = 0; i < numfiles; i++) {
689 tosend.push_back(name);
690 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
691 << name << std::endl;
694 sendRequestedMedia(pkt->getPeerId(), tosend);
697 void Server::handleCommand_ReceivedMedia(NetworkPacket* pkt)
701 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
703 u16 peer_id = pkt->getPeerId();
704 u16 peer_proto_ver = getClient(peer_id, CS_InitDone)->net_proto_version;
706 // clients <= protocol version 22 did not send ready message,
707 // they're already initialized
708 if (peer_proto_ver <= 22) {
709 infostream << "Client sent message not expected by a "
710 << "client using protocol version <= 22,"
711 << "disconnecting peer_id: " << peer_id << std::endl;
712 m_con.DisconnectPeer(peer_id);
716 PlayerSAO* playersao = StageTwoClientInit(peer_id);
718 if (playersao == NULL) {
720 << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
721 << peer_id << std::endl;
722 m_con.DisconnectPeer(peer_id);
727 if (pkt->getSize() < 8) {
729 << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
730 << peer_id << std::endl;
731 m_con.DisconnectPeer(peer_id);
735 u8 major_ver, minor_ver, patch_ver, reserved;
736 std::string full_ver;
737 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
739 m_clients.setClientVersion(
740 peer_id, major_ver, minor_ver, patch_ver,
743 m_clients.event(peer_id, CSE_SetClientReady);
744 m_script->on_joinplayer(playersao);
747 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
749 if (pkt->getSize() < 1)
763 RemoteClient *client = getClient(pkt->getPeerId());
765 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
766 throw con::InvalidIncomingDataException
767 ("GOTBLOCKS length is too short");
770 for (u16 i = 0; i < count; i++) {
777 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
779 if (pkt->getSize() < 12 + 12 + 4 + 4)
783 s32 f32pitch, f32yaw;
790 f32 pitch = (f32)f32pitch / 100.0;
791 f32 yaw = (f32)f32yaw / 100.0;
794 if (pkt->getSize() >= 12 + 12 + 4 + 4 + 4)
797 v3f position((f32)ps.X / 100.0, (f32)ps.Y / 100.0, (f32)ps.Z / 100.0);
798 v3f speed((f32)ss.X / 100.0, (f32)ss.Y / 100.0, (f32)ss.Z / 100.0);
800 pitch = modulo360f(pitch);
801 yaw = modulo360f(yaw);
803 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
804 if (player == NULL) {
805 errorstream << "Server::ProcessData(): Canceling: "
806 "No player for peer_id=" << pkt->getPeerId()
807 << " disconnecting peer!" << std::endl;
808 m_con.DisconnectPeer(pkt->getPeerId());
812 PlayerSAO *playersao = player->getPlayerSAO();
813 if (playersao == NULL) {
814 errorstream << "Server::ProcessData(): Canceling: "
815 "No player object for peer_id=" << pkt->getPeerId()
816 << " disconnecting peer!" << std::endl;
817 m_con.DisconnectPeer(pkt->getPeerId());
821 // If player is dead we don't care of this packet
822 if (playersao->isDead()) {
823 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
824 << " is dead. Ignoring packet";
828 playersao->setBasePosition(position);
829 player->setSpeed(speed);
830 playersao->setPitch(pitch);
831 playersao->setYaw(yaw);
832 player->keyPressed = keyPressed;
833 player->control.up = (keyPressed & 1);
834 player->control.down = (keyPressed & 2);
835 player->control.left = (keyPressed & 4);
836 player->control.right = (keyPressed & 8);
837 player->control.jump = (keyPressed & 16);
838 player->control.aux1 = (keyPressed & 32);
839 player->control.sneak = (keyPressed & 64);
840 player->control.LMB = (keyPressed & 128);
841 player->control.RMB = (keyPressed & 256);
843 if (playersao->checkMovementCheat()) {
845 m_script->on_cheat(playersao, "moved_too_fast");
846 SendMovePlayer(pkt->getPeerId());
850 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
852 if (pkt->getSize() < 1)
866 RemoteClient *client = getClient(pkt->getPeerId());
868 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
869 throw con::InvalidIncomingDataException
870 ("DELETEDBLOCKS length is too short");
873 for (u16 i = 0; i < count; i++) {
876 client->SetBlockNotSent(p);
880 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
882 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
884 if (player == NULL) {
885 errorstream << "Server::ProcessData(): Canceling: "
886 "No player for peer_id=" << pkt->getPeerId()
887 << " disconnecting peer!" << std::endl;
888 m_con.DisconnectPeer(pkt->getPeerId());
892 PlayerSAO *playersao = player->getPlayerSAO();
893 if (playersao == NULL) {
894 errorstream << "Server::ProcessData(): Canceling: "
895 "No player object for peer_id=" << pkt->getPeerId()
896 << " disconnecting peer!" << std::endl;
897 m_con.DisconnectPeer(pkt->getPeerId());
901 // Strip command and create a stream
902 std::string datastring(pkt->getString(0), pkt->getSize());
903 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
905 std::istringstream is(datastring, std::ios_base::binary);
907 InventoryAction *a = InventoryAction::deSerialize(is);
909 infostream << "TOSERVER_INVENTORY_ACTION: "
910 << "InventoryAction::deSerialize() returned NULL"
915 // If something goes wrong, this player is to blame
916 RollbackScopeActor rollback_scope(m_rollback,
917 std::string("player:")+player->getName());
920 Note: Always set inventory not sent, to repair cases
921 where the client made a bad prediction.
925 Handle restrictions and special cases of the move action
927 if (a->getType() == IACTION_MOVE) {
928 IMoveAction *ma = (IMoveAction*)a;
930 ma->from_inv.applyCurrentPlayer(player->getName());
931 ma->to_inv.applyCurrentPlayer(player->getName());
933 setInventoryModified(ma->from_inv, false);
934 setInventoryModified(ma->to_inv, false);
936 bool from_inv_is_current_player =
937 (ma->from_inv.type == InventoryLocation::PLAYER) &&
938 (ma->from_inv.name == player->getName());
940 bool to_inv_is_current_player =
941 (ma->to_inv.type == InventoryLocation::PLAYER) &&
942 (ma->to_inv.name == player->getName());
945 Disable moving items out of craftpreview
947 if (ma->from_list == "craftpreview") {
948 infostream << "Ignoring IMoveAction from "
949 << (ma->from_inv.dump()) << ":" << ma->from_list
950 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
951 << " because src is " << ma->from_list << std::endl;
957 Disable moving items into craftresult and craftpreview
959 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
960 infostream << "Ignoring IMoveAction from "
961 << (ma->from_inv.dump()) << ":" << ma->from_list
962 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
963 << " because dst is " << ma->to_list << std::endl;
968 // Disallow moving items in elsewhere than player's inventory
969 // if not allowed to interact
970 if (!checkPriv(player->getName(), "interact") &&
971 (!from_inv_is_current_player ||
972 !to_inv_is_current_player)) {
973 infostream << "Cannot move outside of player's inventory: "
974 << "No interact privilege" << std::endl;
980 Handle restrictions and special cases of the drop action
982 else if (a->getType() == IACTION_DROP) {
983 IDropAction *da = (IDropAction*)a;
985 da->from_inv.applyCurrentPlayer(player->getName());
987 setInventoryModified(da->from_inv, false);
990 Disable dropping items out of craftpreview
992 if (da->from_list == "craftpreview") {
993 infostream << "Ignoring IDropAction from "
994 << (da->from_inv.dump()) << ":" << da->from_list
995 << " because src is " << da->from_list << std::endl;
1000 // Disallow dropping items if not allowed to interact
1001 if (!checkPriv(player->getName(), "interact")) {
1007 Handle restrictions and special cases of the craft action
1009 else if (a->getType() == IACTION_CRAFT) {
1010 ICraftAction *ca = (ICraftAction*)a;
1012 ca->craft_inv.applyCurrentPlayer(player->getName());
1014 setInventoryModified(ca->craft_inv, false);
1016 //bool craft_inv_is_current_player =
1017 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
1018 // (ca->craft_inv.name == player->getName());
1020 // Disallow crafting if not allowed to interact
1021 if (!checkPriv(player->getName(), "interact")) {
1022 infostream << "Cannot craft: "
1023 << "No interact privilege" << std::endl;
1030 a->apply(this, playersao, this);
1034 SendInventory(playersao);
1037 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
1047 std::wstring message;
1048 for (u16 i = 0; i < len; i++) {
1052 message += (wchar_t)tmp_wchar;
1055 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1056 if (player == NULL) {
1057 errorstream << "Server::ProcessData(): Canceling: "
1058 "No player for peer_id=" << pkt->getPeerId()
1059 << " disconnecting peer!" << std::endl;
1060 m_con.DisconnectPeer(pkt->getPeerId());
1064 // Get player name of this client
1065 std::string name = player->getName();
1066 std::wstring wname = narrow_to_wide(name);
1068 std::wstring answer_to_sender = handleChat(name, wname, message,
1069 true, dynamic_cast<RemotePlayer *>(player));
1070 if (!answer_to_sender.empty()) {
1071 // Send the answer to sender
1072 SendChatMessage(pkt->getPeerId(), answer_to_sender);
1076 void Server::handleCommand_Damage(NetworkPacket* pkt)
1082 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1084 if (player == NULL) {
1085 errorstream << "Server::ProcessData(): Canceling: "
1086 "No player for peer_id=" << pkt->getPeerId()
1087 << " disconnecting peer!" << std::endl;
1088 m_con.DisconnectPeer(pkt->getPeerId());
1092 PlayerSAO *playersao = player->getPlayerSAO();
1093 if (playersao == NULL) {
1094 errorstream << "Server::ProcessData(): Canceling: "
1095 "No player object for peer_id=" << pkt->getPeerId()
1096 << " disconnecting peer!" << std::endl;
1097 m_con.DisconnectPeer(pkt->getPeerId());
1101 if (g_settings->getBool("enable_damage")) {
1102 actionstream << player->getName() << " damaged by "
1103 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
1106 playersao->setHP(playersao->getHP() - damage);
1107 SendPlayerHPOrDie(playersao);
1111 void Server::handleCommand_Breath(NetworkPacket* pkt)
1117 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1119 if (player == NULL) {
1120 errorstream << "Server::ProcessData(): Canceling: "
1121 "No player for peer_id=" << pkt->getPeerId()
1122 << " disconnecting peer!" << std::endl;
1123 m_con.DisconnectPeer(pkt->getPeerId());
1128 PlayerSAO *playersao = player->getPlayerSAO();
1129 if (playersao == NULL) {
1130 errorstream << "Server::ProcessData(): Canceling: "
1131 "No player object for peer_id=" << pkt->getPeerId()
1132 << " disconnecting peer!" << std::endl;
1133 m_con.DisconnectPeer(pkt->getPeerId());
1138 * If player is dead, we don't need to update the breath
1141 if (playersao->isDead()) {
1142 verbosestream << "TOSERVER_BREATH: " << player->getName()
1143 << " is dead. Ignoring packet";
1147 playersao->setBreath(breath);
1148 SendPlayerBreath(pkt->getPeerId());
1151 void Server::handleCommand_Password(NetworkPacket* pkt)
1153 if (pkt->getSize() != PASSWORD_SIZE * 2)
1159 // Deny for clients using the new protocol
1160 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
1161 if (client->net_proto_version >= 25) {
1162 infostream << "Server::handleCommand_Password(): Denying change: "
1163 << " Client protocol version for peer_id=" << pkt->getPeerId()
1164 << " too new!" << std::endl;
1168 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1169 char c = pkt->getChar(i);
1175 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1176 char c = pkt->getChar(PASSWORD_SIZE + i);
1182 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1183 if (player == NULL) {
1184 errorstream << "Server::ProcessData(): Canceling: "
1185 "No player for peer_id=" << pkt->getPeerId()
1186 << " disconnecting peer!" << std::endl;
1187 m_con.DisconnectPeer(pkt->getPeerId());
1191 if (!base64_is_valid(newpwd)) {
1192 infostream<<"Server: " << player->getName() <<
1193 " supplied invalid password hash" << std::endl;
1194 // Wrong old password supplied!!
1195 SendChatMessage(pkt->getPeerId(), L"Invalid new password hash supplied. Password NOT changed.");
1199 infostream << "Server: Client requests a password change from "
1200 << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
1202 std::string playername = player->getName();
1204 std::string checkpwd;
1205 m_script->getAuth(playername, &checkpwd, NULL);
1207 if (oldpwd != checkpwd) {
1208 infostream << "Server: invalid old password" << std::endl;
1209 // Wrong old password supplied!!
1210 SendChatMessage(pkt->getPeerId(), L"Invalid old password supplied. Password NOT changed.");
1214 bool success = m_script->setPassword(playername, newpwd);
1216 actionstream << player->getName() << " changes password" << std::endl;
1217 SendChatMessage(pkt->getPeerId(), L"Password change successful.");
1219 actionstream << player->getName() << " tries to change password but "
1220 << "it fails" << std::endl;
1221 SendChatMessage(pkt->getPeerId(), L"Password change failed or unavailable.");
1225 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
1227 if (pkt->getSize() < 2)
1230 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1232 if (player == NULL) {
1233 errorstream << "Server::ProcessData(): Canceling: "
1234 "No player for peer_id=" << pkt->getPeerId()
1235 << " disconnecting peer!" << std::endl;
1236 m_con.DisconnectPeer(pkt->getPeerId());
1240 PlayerSAO *playersao = player->getPlayerSAO();
1241 if (playersao == NULL) {
1242 errorstream << "Server::ProcessData(): Canceling: "
1243 "No player object for peer_id=" << pkt->getPeerId()
1244 << " disconnecting peer!" << std::endl;
1245 m_con.DisconnectPeer(pkt->getPeerId());
1253 playersao->setWieldIndex(item);
1256 void Server::handleCommand_Respawn(NetworkPacket* pkt)
1258 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1259 if (player == NULL) {
1260 errorstream << "Server::ProcessData(): Canceling: "
1261 "No player for peer_id=" << pkt->getPeerId()
1262 << " disconnecting peer!" << std::endl;
1263 m_con.DisconnectPeer(pkt->getPeerId());
1267 PlayerSAO *playersao = player->getPlayerSAO();
1270 if (!playersao->isDead())
1273 RespawnPlayer(pkt->getPeerId());
1275 actionstream << player->getName() << " respawns at "
1276 << PP(playersao->getBasePosition() / BS) << std::endl;
1278 // ActiveObject is added to environment in AsyncRunStep after
1279 // the previous addition has been successfully removed
1282 void Server::handleCommand_Interact(NetworkPacket* pkt)
1284 std::string datastring(pkt->getString(0), pkt->getSize());
1285 std::istringstream is(datastring, std::ios_base::binary);
1291 [5] u32 length of the next item
1292 [9] serialized PointedThing
1294 0: start digging (from undersurface) or use
1295 1: stop digging (all parameters ignored)
1296 2: digging completed
1297 3: place block or item (to abovesurface)
1300 u8 action = readU8(is);
1301 u16 item_i = readU16(is);
1302 std::istringstream tmp_is(deSerializeLongString(is), std::ios::binary);
1303 PointedThing pointed;
1304 pointed.deSerialize(tmp_is);
1306 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
1307 << item_i << ", pointed=" << pointed.dump() << std::endl;
1309 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1311 if (player == NULL) {
1312 errorstream << "Server::ProcessData(): Canceling: "
1313 "No player for peer_id=" << pkt->getPeerId()
1314 << " disconnecting peer!" << std::endl;
1315 m_con.DisconnectPeer(pkt->getPeerId());
1319 PlayerSAO *playersao = player->getPlayerSAO();
1320 if (playersao == NULL) {
1321 errorstream << "Server::ProcessData(): Canceling: "
1322 "No player object for peer_id=" << pkt->getPeerId()
1323 << " disconnecting peer!" << std::endl;
1324 m_con.DisconnectPeer(pkt->getPeerId());
1328 if (playersao->isDead()) {
1329 verbosestream << "TOSERVER_INTERACT: " << player->getName()
1330 << " is dead. Ignoring packet";
1334 v3f player_pos = playersao->getLastGoodPosition();
1336 // Update wielded item
1337 playersao->setWieldIndex(item_i);
1339 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1340 v3s16 p_under = pointed.node_undersurface;
1341 v3s16 p_above = pointed.node_abovesurface;
1343 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1344 ServerActiveObject *pointed_object = NULL;
1345 if (pointed.type == POINTEDTHING_OBJECT) {
1346 pointed_object = m_env->getActiveObject(pointed.object_id);
1347 if (pointed_object == NULL) {
1348 verbosestream << "TOSERVER_INTERACT: "
1349 "pointed object is NULL" << std::endl;
1355 v3f pointed_pos_under = player_pos;
1356 v3f pointed_pos_above = player_pos;
1357 if (pointed.type == POINTEDTHING_NODE) {
1358 pointed_pos_under = intToFloat(p_under, BS);
1359 pointed_pos_above = intToFloat(p_above, BS);
1361 else if (pointed.type == POINTEDTHING_OBJECT) {
1362 pointed_pos_under = pointed_object->getBasePosition();
1363 pointed_pos_above = pointed_pos_under;
1367 Check that target is reasonably close
1368 (only when digging or placing things)
1370 static const bool enable_anticheat = !g_settings->getBool("disable_anticheat");
1371 if ((action == 0 || action == 2 || action == 3) &&
1372 (enable_anticheat && !isSingleplayer())) {
1373 float d = player_pos.getDistanceFrom(pointed_pos_under);
1374 float max_d = BS * 14; // Just some large enough value
1376 actionstream << "Player " << player->getName()
1377 << " tried to access " << pointed.dump()
1378 << " from too far: "
1379 << "d=" << d <<", max_d=" << max_d
1380 << ". ignoring." << std::endl;
1381 // Re-send block to revert change on client-side
1382 RemoteClient *client = getClient(pkt->getPeerId());
1383 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1384 client->SetBlockNotSent(blockpos);
1386 m_script->on_cheat(playersao, "interacted_too_far");
1393 Make sure the player is allowed to do it
1395 if (!checkPriv(player->getName(), "interact")) {
1396 actionstream<<player->getName()<<" attempted to interact with "
1397 <<pointed.dump()<<" without 'interact' privilege"
1399 // Re-send block to revert change on client-side
1400 RemoteClient *client = getClient(pkt->getPeerId());
1401 // Digging completed -> under
1403 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1404 client->SetBlockNotSent(blockpos);
1406 // Placement -> above
1408 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1409 client->SetBlockNotSent(blockpos);
1415 If something goes wrong, this player is to blame
1417 RollbackScopeActor rollback_scope(m_rollback,
1418 std::string("player:")+player->getName());
1421 0: start digging or punch object
1424 if (pointed.type == POINTEDTHING_NODE) {
1426 NOTE: This can be used in the future to check if
1427 somebody is cheating, by checking the timing.
1430 MapNode n(CONTENT_IGNORE);
1433 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1435 infostream << "Server: Not punching: Node not found."
1436 << " Adding block to emerge queue."
1438 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1439 getNodeBlockPos(p_above), false);
1442 if (n.getContent() != CONTENT_IGNORE)
1443 m_script->node_on_punch(p_under, n, playersao, pointed);
1446 playersao->noCheatDigStart(p_under);
1448 else if (pointed.type == POINTEDTHING_OBJECT) {
1449 // Skip if object has been removed
1450 if (pointed_object->m_removed)
1453 actionstream<<player->getName()<<" punches object "
1454 <<pointed.object_id<<": "
1455 <<pointed_object->getDescription()<<std::endl;
1457 ItemStack punchitem = playersao->getWieldedItem();
1458 ToolCapabilities toolcap =
1459 punchitem.getToolCapabilities(m_itemdef);
1460 v3f dir = (pointed_object->getBasePosition() -
1461 (playersao->getBasePosition() + playersao->getEyeOffset())
1463 float time_from_last_punch =
1464 playersao->resetTimeFromLastPunch();
1466 s16 src_original_hp = pointed_object->getHP();
1467 s16 dst_origin_hp = playersao->getHP();
1469 pointed_object->punch(dir, &toolcap, playersao,
1470 time_from_last_punch);
1472 // If the object is a player and its HP changed
1473 if (src_original_hp != pointed_object->getHP() &&
1474 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1475 SendPlayerHPOrDie((PlayerSAO *)pointed_object);
1478 // If the puncher is a player and its HP changed
1479 if (dst_origin_hp != playersao->getHP())
1480 SendPlayerHPOrDie(playersao);
1488 else if (action == 1) {
1492 2: Digging completed
1494 else if (action == 2) {
1495 // Only digging of nodes
1496 if (pointed.type == POINTEDTHING_NODE) {
1498 MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1500 infostream << "Server: Not finishing digging: Node not found."
1501 << " Adding block to emerge queue."
1503 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1504 getNodeBlockPos(p_above), false);
1507 /* Cheat prevention */
1508 bool is_valid_dig = true;
1509 if (enable_anticheat && !isSingleplayer()) {
1510 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1511 float nocheat_t = playersao->getNoCheatDigTime();
1512 playersao->noCheatDigEnd();
1513 // If player didn't start digging this, ignore dig
1514 if (nocheat_p != p_under) {
1515 infostream << "Server: NoCheat: " << player->getName()
1516 << " started digging "
1517 << PP(nocheat_p) << " and completed digging "
1518 << PP(p_under) << "; not digging." << std::endl;
1519 is_valid_dig = false;
1521 m_script->on_cheat(playersao, "finished_unknown_dig");
1523 // Get player's wielded item
1524 ItemStack playeritem;
1525 InventoryList *mlist = playersao->getInventory()->getList("main");
1527 playeritem = mlist->getItem(playersao->getWieldIndex());
1528 ToolCapabilities playeritem_toolcap =
1529 playeritem.getToolCapabilities(m_itemdef);
1530 // Get diggability and expected digging time
1531 DigParams params = getDigParams(m_nodedef->get(n).groups,
1532 &playeritem_toolcap);
1533 // If can't dig, try hand
1534 if (!params.diggable) {
1535 const ItemDefinition &hand = m_itemdef->get("");
1536 const ToolCapabilities *tp = hand.tool_capabilities;
1538 params = getDigParams(m_nodedef->get(n).groups, tp);
1540 // If can't dig, ignore dig
1541 if (!params.diggable) {
1542 infostream << "Server: NoCheat: " << player->getName()
1543 << " completed digging " << PP(p_under)
1544 << ", which is not diggable with tool. not digging."
1546 is_valid_dig = false;
1548 m_script->on_cheat(playersao, "dug_unbreakable");
1550 // Check digging time
1551 // If already invalidated, we don't have to
1552 if (!is_valid_dig) {
1553 // Well not our problem then
1555 // Clean and long dig
1556 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1557 // All is good, but grab time from pool; don't care if
1558 // it's actually available
1559 playersao->getDigPool().grab(params.time);
1561 // Short or laggy dig
1562 // Try getting the time from pool
1563 else if (playersao->getDigPool().grab(params.time)) {
1568 infostream << "Server: NoCheat: " << player->getName()
1569 << " completed digging " << PP(p_under)
1570 << "too fast; not digging." << std::endl;
1571 is_valid_dig = false;
1573 m_script->on_cheat(playersao, "dug_too_fast");
1577 /* Actually dig node */
1579 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1580 m_script->node_on_dig(p_under, n, playersao);
1582 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1583 RemoteClient *client = getClient(pkt->getPeerId());
1584 // Send unusual result (that is, node not being removed)
1585 if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1586 // Re-send block to revert change on client-side
1587 client->SetBlockNotSent(blockpos);
1590 client->ResendBlockIfOnWire(blockpos);
1596 3: place block or right-click object
1598 else if (action == 3) {
1599 ItemStack item = playersao->getWieldedItem();
1601 // Reset build time counter
1602 if (pointed.type == POINTEDTHING_NODE &&
1603 item.getDefinition(m_itemdef).type == ITEM_NODE)
1604 getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1606 if (pointed.type == POINTEDTHING_OBJECT) {
1607 // Right click object
1609 // Skip if object has been removed
1610 if (pointed_object->m_removed)
1613 actionstream << player->getName() << " right-clicks object "
1614 << pointed.object_id << ": "
1615 << pointed_object->getDescription() << std::endl;
1618 pointed_object->rightClick(playersao);
1620 else if (m_script->item_OnPlace(
1621 item, playersao, pointed)) {
1622 // Placement was handled in lua
1624 // Apply returned ItemStack
1625 if (playersao->setWieldedItem(item)) {
1626 SendInventory(playersao);
1630 // If item has node placement prediction, always send the
1631 // blocks to make sure the client knows what exactly happened
1632 RemoteClient *client = getClient(pkt->getPeerId());
1633 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1634 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1635 if (item.getDefinition(m_itemdef).node_placement_prediction != "") {
1636 client->SetBlockNotSent(blockpos);
1637 if (blockpos2 != blockpos) {
1638 client->SetBlockNotSent(blockpos2);
1642 client->ResendBlockIfOnWire(blockpos);
1643 if (blockpos2 != blockpos) {
1644 client->ResendBlockIfOnWire(blockpos2);
1652 else if (action == 4) {
1653 ItemStack item = playersao->getWieldedItem();
1655 actionstream << player->getName() << " uses " << item.name
1656 << ", pointing at " << pointed.dump() << std::endl;
1658 if (m_script->item_OnUse(
1659 item, playersao, pointed)) {
1660 // Apply returned ItemStack
1661 if (playersao->setWieldedItem(item)) {
1662 SendInventory(playersao);
1671 else if (action == 5) {
1672 ItemStack item = playersao->getWieldedItem();
1674 actionstream << player->getName() << " activates "
1675 << item.name << std::endl;
1677 if (m_script->item_OnSecondaryUse(
1679 if( playersao->setWieldedItem(item)) {
1680 SendInventory(playersao);
1687 Catch invalid actions
1690 warningstream << "Server: Invalid action "
1691 << action << std::endl;
1695 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1699 for (u16 k = 0; k < num; k++) {
1704 UNORDERED_MAP<s32, ServerPlayingSound>::iterator i = m_playing_sounds.find(id);
1705 if (i == m_playing_sounds.end())
1708 ServerPlayingSound &psound = i->second;
1709 psound.clients.erase(pkt->getPeerId());
1710 if (psound.clients.empty())
1711 m_playing_sounds.erase(i++);
1715 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1718 std::string formname;
1721 *pkt >> p >> formname >> num;
1724 for (u16 k = 0; k < num; k++) {
1725 std::string fieldname;
1727 fields[fieldname] = pkt->readLongString();
1730 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1732 if (player == NULL) {
1733 errorstream << "Server::ProcessData(): Canceling: "
1734 "No player for peer_id=" << pkt->getPeerId()
1735 << " disconnecting peer!" << std::endl;
1736 m_con.DisconnectPeer(pkt->getPeerId());
1740 PlayerSAO *playersao = player->getPlayerSAO();
1741 if (playersao == NULL) {
1742 errorstream << "Server::ProcessData(): Canceling: "
1743 "No player object for peer_id=" << pkt->getPeerId()
1744 << " disconnecting peer!" << std::endl;
1745 m_con.DisconnectPeer(pkt->getPeerId());
1749 // If something goes wrong, this player is to blame
1750 RollbackScopeActor rollback_scope(m_rollback,
1751 std::string("player:")+player->getName());
1753 // Check the target node for rollback data; leave others unnoticed
1754 RollbackNode rn_old(&m_env->getMap(), p, this);
1756 m_script->node_on_receive_fields(p, formname, fields, playersao);
1758 // Report rollback data
1759 RollbackNode rn_new(&m_env->getMap(), p, this);
1760 if (rollback() && rn_new != rn_old) {
1761 RollbackAction action;
1762 action.setSetNode(p, rn_old, rn_new);
1763 rollback()->reportAction(action);
1767 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1769 std::string formname;
1772 *pkt >> formname >> num;
1775 for (u16 k = 0; k < num; k++) {
1776 std::string fieldname;
1778 fields[fieldname] = pkt->readLongString();
1781 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1783 if (player == NULL) {
1784 errorstream << "Server::ProcessData(): Canceling: "
1785 "No player for peer_id=" << pkt->getPeerId()
1786 << " disconnecting peer!" << std::endl;
1787 m_con.DisconnectPeer(pkt->getPeerId());
1791 PlayerSAO *playersao = player->getPlayerSAO();
1792 if (playersao == NULL) {
1793 errorstream << "Server::ProcessData(): Canceling: "
1794 "No player object for peer_id=" << pkt->getPeerId()
1795 << " disconnecting peer!" << std::endl;
1796 m_con.DisconnectPeer(pkt->getPeerId());
1800 m_script->on_playerReceiveFields(playersao, formname, fields);
1803 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1805 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1806 ClientState cstate = client->getState();
1808 std::string playername = client->getName();
1811 std::string verification_key;
1813 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1816 *pkt >> salt >> verification_key >> is_empty;
1818 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1819 << ", with is_empty=" << (is_empty == 1) << std::endl;
1821 // Either this packet is sent because the user is new or to change the password
1822 if (cstate == CS_HelloSent) {
1823 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1824 actionstream << "Server: Client from " << addr_s
1825 << " tried to set password without being "
1826 << "authenticated, or the username being new." << std::endl;
1827 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1831 if (!isSingleplayer() &&
1832 g_settings->getBool("disallow_empty_password") &&
1834 actionstream << "Server: " << playername
1835 << " supplied empty password from " << addr_s << std::endl;
1836 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1840 std::string initial_ver_key;
1842 initial_ver_key = encode_srp_verifier(verification_key, salt);
1843 m_script->createAuth(playername, initial_ver_key);
1845 acceptAuth(pkt->getPeerId(), false);
1847 if (cstate < CS_SudoMode) {
1848 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1849 << addr_s << ": " << "Client has wrong state " << cstate << "."
1853 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1854 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1855 bool success = m_script->setPassword(playername, pw_db_field);
1857 actionstream << playername << " changes password" << std::endl;
1858 SendChatMessage(pkt->getPeerId(), L"Password change successful.");
1860 actionstream << playername << " tries to change password but "
1861 << "it fails" << std::endl;
1862 SendChatMessage(pkt->getPeerId(), L"Password change failed or unavailable.");
1867 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1869 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1870 ClientState cstate = client->getState();
1872 bool wantSudo = (cstate == CS_Active);
1874 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1875 actionstream << "Server: got SRP _A packet in wrong state "
1876 << cstate << " from "
1877 << getPeerAddress(pkt->getPeerId()).serializeString()
1878 << ". Ignoring." << std::endl;
1882 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1883 actionstream << "Server: got SRP _A packet, while auth"
1884 << "is already going on with mech " << client->chosen_mech
1885 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1886 << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1888 DenySudoAccess(pkt->getPeerId());
1891 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1896 std::string bytes_A;
1898 *pkt >> bytes_A >> based_on;
1900 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1901 << "based_on=" << int(based_on) << " and len_A="
1902 << bytes_A.length() << "." << std::endl;
1904 AuthMechanism chosen = (based_on == 0) ?
1905 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1908 if (!client->isSudoMechAllowed(chosen)) {
1909 actionstream << "Server: Player \"" << client->getName()
1910 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1911 << " tried to change password using unallowed mech "
1912 << chosen << "." << std::endl;
1913 DenySudoAccess(pkt->getPeerId());
1917 if (!client->isMechAllowed(chosen)) {
1918 actionstream << "Server: Client tried to authenticate from "
1919 << getPeerAddress(pkt->getPeerId()).serializeString()
1920 << " using unallowed mech " << chosen << "." << std::endl;
1921 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1926 client->chosen_mech = chosen;
1929 std::string verifier;
1931 if (based_on == 0) {
1933 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1935 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1936 // Non-base64 errors should have been catched in the init handler
1937 actionstream << "Server: User " << client->getName()
1938 << " tried to log in, but srp verifier field"
1939 << " was invalid (most likely invalid base64)." << std::endl;
1940 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1947 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1948 client->getName().c_str(),
1949 (const unsigned char *) salt.c_str(), salt.size(),
1950 (const unsigned char *) verifier.c_str(), verifier.size(),
1951 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1953 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1956 actionstream << "Server: User " << client->getName()
1957 << " tried to log in, SRP-6a safety check violated in _A handler."
1960 DenySudoAccess(pkt->getPeerId());
1963 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1968 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1969 resp_pkt << salt << std::string(bytes_B, len_B);
1973 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1975 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1976 ClientState cstate = client->getState();
1978 bool wantSudo = (cstate == CS_Active);
1980 verbosestream << "Server: Recieved TOCLIENT_SRP_BYTES_M." << std::endl;
1982 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1983 actionstream << "Server: got SRP _M packet in wrong state "
1984 << cstate << " from "
1985 << getPeerAddress(pkt->getPeerId()).serializeString()
1986 << ". Ignoring." << std::endl;
1990 if ((client->chosen_mech != AUTH_MECHANISM_SRP)
1991 && (client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD)) {
1992 actionstream << "Server: got SRP _M packet, while auth"
1993 << "is going on with mech " << client->chosen_mech
1994 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1995 << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1997 DenySudoAccess(pkt->getPeerId());
2000 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2005 std::string bytes_M;
2008 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
2009 != bytes_M.size()) {
2010 actionstream << "Server: User " << client->getName()
2011 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2012 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
2013 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2017 unsigned char *bytes_HAMK = 0;
2019 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
2020 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
2024 actionstream << "Server: User " << client->getName()
2025 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2026 << " tried to change their password, but supplied wrong"
2027 << " (SRP) password for authentication." << std::endl;
2028 DenySudoAccess(pkt->getPeerId());
2031 actionstream << "Server: User " << client->getName()
2032 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2033 << " supplied wrong password (auth mechanism: SRP)."
2035 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
2040 if (client->create_player_on_auth_success) {
2041 std::string playername = client->getName();
2042 m_script->createAuth(playername, client->enc_pwd);
2044 std::string checkpwd; // not used, but needed for passing something
2045 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
2046 actionstream << "Server: " << playername << " cannot be authenticated"
2047 << " (auth handler does not work?)" << std::endl;
2048 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
2051 client->create_player_on_auth_success = false;
2054 acceptAuth(pkt->getPeerId(), wantSudo);