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 >> compression_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 deployed = std::min(client_max, our_max);
105 // If it's lower than the lowest supported, give up.
106 if (deployed < SER_FMT_VER_LOWEST)
107 deployed = SER_FMT_VER_INVALID;
109 if (deployed == 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(deployed);
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 if (playerName.size() > PLAYERNAME_SIZE) {
168 actionstream << "Server: Player with an too long name "
169 << "tried to connect from " << addr_s << std::endl;
170 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
174 if (string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS) == false) {
175 actionstream << "Server: Player with an invalid name "
176 << "tried to connect from " << addr_s << std::endl;
177 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
181 m_clients.setPlayerName(pkt->getPeerId(), playername);
182 //TODO (later) case insensitivity
184 std::string legacyPlayerNameCasing = playerName;
186 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
187 actionstream << "Server: Player with the name \"singleplayer\" "
188 << "tried to connect from " << addr_s << std::endl;
189 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
195 if(m_script->on_prejoinplayer(playername, addr_s, reason)) {
196 actionstream << "Server: Player with the name \"" << playerName << "\" "
197 << "tried to connect from " << addr_s << " "
198 << "but it was disallowed for the following reason: "
199 << reason << std::endl;
200 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING,
206 infostream << "Server: New connection: \"" << playerName << "\" from "
207 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
209 // Enforce user limit.
210 // Don't enforce for users that have some admin right
211 if (m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
212 !checkPriv(playername, "server") &&
213 !checkPriv(playername, "ban") &&
214 !checkPriv(playername, "privs") &&
215 !checkPriv(playername, "password") &&
216 playername != g_settings->get("name")) {
217 actionstream << "Server: " << playername << " tried to join from "
218 << addr_s << ", but there" << " are already max_users="
219 << g_settings->getU16("max_users") << " players." << std::endl;
220 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_TOO_MANY_USERS);
225 Compose auth methods for answer
227 std::string encpwd; // encrypted Password field for the user
228 bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
231 client->chosen_mech = AUTH_MECHANISM_NONE;
234 std::vector<std::string> pwd_components = str_split(encpwd, '#');
235 if (pwd_components.size() == 4) {
236 if (pwd_components[1] == "1") { // 1 means srp
237 auth_mechs |= AUTH_MECHANISM_SRP;
238 client->enc_pwd = encpwd;
240 actionstream << "User " << playername
241 << " tried to log in, but password field"
242 << " was invalid (unknown mechcode)." << std::endl;
243 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
246 } else if (base64_is_valid(encpwd)) {
247 auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
248 client->enc_pwd = encpwd;
250 actionstream << "User " << playername
251 << " tried to log in, but password field"
252 << " was invalid (invalid base64)." << std::endl;
253 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
257 std::string default_password = g_settings->get("default_password");
258 if (default_password.length() == 0) {
259 auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
261 // Take care of default passwords.
262 client->enc_pwd = getSRPVerifier(playerName, default_password);
263 auth_mechs |= AUTH_MECHANISM_SRP;
268 Answer with a TOCLIENT_HELLO
271 verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
272 << auth_mechs << std::endl;
274 NetworkPacket resp_pkt(TOCLIENT_HELLO, 1 + 4
275 + legacyPlayerNameCasing.size(), pkt->getPeerId());
277 resp_pkt << deployed << auth_mechs << legacyPlayerNameCasing;
281 client->allowed_auth_mechs = auth_mechs;
282 client->setSupportedCompressionModes(compression_modes);
284 m_clients.event(pkt->getPeerId(), CSE_Hello);
287 void Server::handleCommand_Init_Legacy(NetworkPacket* pkt)
289 // [0] u8 SER_FMT_VER_HIGHEST_READ
290 // [1] u8[20] player_name
291 // [21] u8[28] password <--- can be sent without this, from old versions
293 if (pkt->getSize() < 1+PLAYERNAME_SIZE)
296 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
300 Address address = getPeerAddress(pkt->getPeerId());
301 addr_s = address.serializeString();
303 catch (con::PeerNotFoundException &e) {
305 * no peer for this packet found
306 * most common reason is peer timeout, e.g. peer didn't
307 * respond for some time, your server was overloaded or
310 infostream << "Server::ProcessData(): Canceling: peer "
311 << pkt->getPeerId() << " not found" << std::endl;
315 // If net_proto_version is set, this client has already been handled
316 if (client->getState() > CS_Created) {
317 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
318 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
322 verbosestream << "Server: Got TOSERVER_INIT_LEGACY from " << addr_s << " (peer_id="
323 << pkt->getPeerId() << ")" << std::endl;
325 // Do not allow multiple players in simple singleplayer mode.
326 // This isn't a perfect way to do it, but will suffice for now
327 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
328 infostream << "Server: Not allowing another client (" << addr_s
329 << ") to connect in simple singleplayer mode" << std::endl;
330 DenyAccess_Legacy(pkt->getPeerId(), L"Running in simple singleplayer mode.");
334 // First byte after command is maximum supported
335 // serialization version
340 u8 our_max = SER_FMT_VER_HIGHEST_READ;
341 // Use the highest version supported by both
342 int deployed = std::min(client_max, our_max);
343 // If it's lower than the lowest supported, give up.
344 if (deployed < SER_FMT_VER_LOWEST)
345 deployed = SER_FMT_VER_INVALID;
347 if (deployed == SER_FMT_VER_INVALID) {
348 actionstream << "Server: A mismatched client tried to connect from "
349 << addr_s << std::endl;
350 infostream<<"Server: Cannot negotiate serialization version with "
351 << addr_s << std::endl;
352 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
353 L"Your client's version is not supported.\n"
354 L"Server version is ")
355 + narrow_to_wide(g_version_string) + L"."
360 client->setPendingSerializationVersion(deployed);
363 Read and check network protocol version
366 u16 min_net_proto_version = 0;
367 if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2)
368 min_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE);
370 // Use same version as minimum and maximum if maximum version field
371 // doesn't exist (backwards compatibility)
372 u16 max_net_proto_version = min_net_proto_version;
373 if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2)
374 max_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2);
376 // Start with client's maximum version
377 u16 net_proto_version = max_net_proto_version;
379 // Figure out a working version if it is possible at all
380 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
381 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
382 // If maximum is larger than our maximum, go with our maximum
383 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
384 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
385 // Else go with client's maximum
387 net_proto_version = max_net_proto_version;
390 // The client will send up to date init packet, ignore this one
391 if (net_proto_version >= 25)
394 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
395 << min_net_proto_version << ", max: " << max_net_proto_version
396 << ", chosen: " << net_proto_version << std::endl;
398 client->net_proto_version = net_proto_version;
400 if (net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
401 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
402 actionstream << "Server: A mismatched client tried to connect from "
403 << addr_s << std::endl;
404 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
405 L"Your client's version is not supported.\n"
406 L"Server version is ")
407 + narrow_to_wide(g_version_string) + L",\n"
408 + L"server's PROTOCOL_VERSION is "
409 + narrow_to_wide(itos(SERVER_PROTOCOL_VERSION_MIN))
411 + narrow_to_wide(itos(SERVER_PROTOCOL_VERSION_MAX))
412 + L", client's PROTOCOL_VERSION is "
413 + narrow_to_wide(itos(min_net_proto_version))
415 + narrow_to_wide(itos(max_net_proto_version))
420 if (g_settings->getBool("strict_protocol_version_checking")) {
421 if (net_proto_version != LATEST_PROTOCOL_VERSION) {
422 actionstream << "Server: A mismatched (strict) client tried to "
423 << "connect from " << addr_s << std::endl;
424 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
425 L"Your client's version is not supported.\n"
426 L"Server version is ")
427 + narrow_to_wide(g_version_string) + L",\n"
428 + L"server's PROTOCOL_VERSION (strict) is "
429 + narrow_to_wide(itos(LATEST_PROTOCOL_VERSION))
430 + L", client's PROTOCOL_VERSION is "
431 + narrow_to_wide(itos(min_net_proto_version))
433 + narrow_to_wide(itos(max_net_proto_version))
442 char playername[PLAYERNAME_SIZE];
443 unsigned int playername_length = 0;
444 for (; playername_length < PLAYERNAME_SIZE; playername_length++ ) {
445 playername[playername_length] = pkt->getChar(1+playername_length);
446 if (pkt->getChar(1+playername_length) == 0)
450 if (playername_length == PLAYERNAME_SIZE) {
451 actionstream << "Server: Player with name exceeding max length "
452 << "tried to connect from " << addr_s << std::endl;
453 DenyAccess_Legacy(pkt->getPeerId(), L"Name too long");
458 if (playername[0]=='\0') {
459 actionstream << "Server: Player with an empty name "
460 << "tried to connect from " << addr_s << std::endl;
461 DenyAccess_Legacy(pkt->getPeerId(), L"Empty name");
465 if (string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false) {
466 actionstream << "Server: Player with an invalid name "
467 << "tried to connect from " << addr_s << std::endl;
468 DenyAccess_Legacy(pkt->getPeerId(), L"Name contains unallowed characters");
472 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
473 actionstream << "Server: Player with the name \"singleplayer\" "
474 << "tried to connect from " << addr_s << std::endl;
475 DenyAccess_Legacy(pkt->getPeerId(), L"Name is not allowed");
481 if (m_script->on_prejoinplayer(playername, addr_s, reason)) {
482 actionstream << "Server: Player with the name \"" << playername << "\" "
483 << "tried to connect from " << addr_s << " "
484 << "but it was disallowed for the following reason: "
485 << reason << std::endl;
486 DenyAccess_Legacy(pkt->getPeerId(), narrow_to_wide(reason.c_str()));
491 infostream<<"Server: New connection: \""<<playername<<"\" from "
492 <<addr_s<<" (peer_id="<<pkt->getPeerId()<<")"<<std::endl;
495 char given_password[PASSWORD_SIZE];
496 if (pkt->getSize() < 1 + PLAYERNAME_SIZE + PASSWORD_SIZE) {
497 // old version - assume blank password
498 given_password[0] = 0;
501 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
502 given_password[i] = pkt->getChar(21 + i);
504 given_password[PASSWORD_SIZE - 1] = 0;
507 if (!base64_is_valid(given_password)) {
508 actionstream << "Server: " << playername
509 << " supplied invalid password hash" << std::endl;
510 DenyAccess_Legacy(pkt->getPeerId(), L"Invalid password hash");
514 // Enforce user limit.
515 // Don't enforce for users that have some admin right
516 if (m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
517 !checkPriv(playername, "server") &&
518 !checkPriv(playername, "ban") &&
519 !checkPriv(playername, "privs") &&
520 !checkPriv(playername, "password") &&
521 playername != g_settings->get("name")) {
522 actionstream << "Server: " << playername << " tried to join, but there"
523 << " are already max_users="
524 << g_settings->getU16("max_users") << " players." << std::endl;
525 DenyAccess_Legacy(pkt->getPeerId(), L"Too many users.");
529 std::string checkpwd; // Password hash to check against
530 bool has_auth = m_script->getAuth(playername, &checkpwd, NULL);
532 // If no authentication info exists for user, create it
534 if (!isSingleplayer() &&
535 g_settings->getBool("disallow_empty_password") &&
536 std::string(given_password) == "") {
537 actionstream << "Server: " << playername
538 << " supplied empty password" << std::endl;
539 DenyAccess_Legacy(pkt->getPeerId(), L"Empty passwords are "
540 L"disallowed. Set a password and try again.");
543 std::string raw_default_password =
544 g_settings->get("default_password");
545 std::string initial_password =
546 translatePassword(playername, raw_default_password);
548 // If default_password is empty, allow any initial password
549 if (raw_default_password.length() == 0)
550 initial_password = given_password;
552 m_script->createAuth(playername, initial_password);
555 has_auth = m_script->getAuth(playername, &checkpwd, NULL);
558 actionstream << "Server: " << playername << " cannot be authenticated"
559 << " (auth handler does not work?)" << std::endl;
560 DenyAccess_Legacy(pkt->getPeerId(), L"Not allowed to login");
564 if (given_password != checkpwd) {
565 actionstream << "Server: " << playername << " supplied wrong password"
567 DenyAccess_Legacy(pkt->getPeerId(), L"Wrong password");
571 RemotePlayer *player =
572 static_cast<RemotePlayer*>(m_env->getPlayer(playername));
574 if (player && player->peer_id != 0) {
575 errorstream << "Server: " << playername << ": Failed to emerge player"
576 << " (player allocated to an another client)" << std::endl;
577 DenyAccess_Legacy(pkt->getPeerId(), L"Another client is connected with this "
578 L"name. If your client closed unexpectedly, try again in "
582 m_clients.setPlayerName(pkt->getPeerId(), playername);
585 Answer with a TOCLIENT_INIT
588 NetworkPacket resp_pkt(TOCLIENT_INIT_LEGACY, 1 + 6 + 8 + 4,
591 resp_pkt << (u8) deployed << (v3s16) floatToInt(v3f(0,0,0), BS)
592 << (u64) m_env->getServerMap().getSeed()
593 << g_settings->getFloat("dedicated_server_step");
596 m_clients.event(pkt->getPeerId(), CSE_InitLegacy);
599 void Server::handleCommand_Init2(NetworkPacket* pkt)
601 verbosestream << "Server: Got TOSERVER_INIT2 from "
602 << pkt->getPeerId() << std::endl;
604 m_clients.event(pkt->getPeerId(), CSE_GotInit2);
605 u16 protocol_version = m_clients.getProtocolVersion(pkt->getPeerId());
608 ///// begin compatibility code
609 PlayerSAO* playersao = NULL;
610 if (protocol_version <= 22) {
611 playersao = StageTwoClientInit(pkt->getPeerId());
613 if (playersao == NULL) {
615 << "TOSERVER_INIT2 stage 2 client init failed for peer "
616 << pkt->getPeerId() << std::endl;
620 ///// end compatibility code
623 Send some initialization data
626 infostream << "Server: Sending content to "
627 << getPlayerName(pkt->getPeerId()) << std::endl;
629 // Send player movement settings
630 SendMovement(pkt->getPeerId());
632 // Send item definitions
633 SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
635 // Send node definitions
636 SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
638 m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
640 // Send media announcement
641 sendMediaAnnouncement(pkt->getPeerId());
643 // Send detached inventories
644 sendDetachedInventories(pkt->getPeerId());
647 u16 time = m_env->getTimeOfDay();
648 float time_speed = g_settings->getFloat("time_speed");
649 SendTimeOfDay(pkt->getPeerId(), time, time_speed);
651 ///// begin compatibility code
652 if (protocol_version <= 22) {
653 m_clients.event(pkt->getPeerId(), CSE_SetClientReady);
654 m_script->on_joinplayer(playersao);
656 ///// end compatibility code
658 // Warnings about protocol version can be issued here
659 if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
660 SendChatMessage(pkt->getPeerId(), L"# Server: WARNING: YOUR CLIENT'S "
661 L"VERSION MAY NOT BE FULLY COMPATIBLE WITH THIS SERVER!");
665 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
667 std::vector<std::string> tosend;
672 infostream << "Sending " << numfiles << " files to "
673 << getPlayerName(pkt->getPeerId()) << std::endl;
674 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
676 for (u16 i = 0; i < numfiles; i++) {
681 tosend.push_back(name);
682 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
683 << name << std::endl;
686 sendRequestedMedia(pkt->getPeerId(), tosend);
689 void Server::handleCommand_ReceivedMedia(NetworkPacket* pkt)
693 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
695 u16 peer_id = pkt->getPeerId();
696 u16 peer_proto_ver = getClient(peer_id, CS_InitDone)->net_proto_version;
698 // clients <= protocol version 22 did not send ready message,
699 // they're already initialized
700 if (peer_proto_ver <= 22) {
701 infostream << "Client sent message not expected by a "
702 << "client using protocol version <= 22,"
703 << "disconnecting peer_id: " << peer_id << std::endl;
704 m_con.DisconnectPeer(peer_id);
708 PlayerSAO* playersao = StageTwoClientInit(peer_id);
710 if (playersao == NULL) {
712 << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
713 << peer_id << std::endl;
714 m_con.DisconnectPeer(peer_id);
719 if (pkt->getSize() < 8) {
721 << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
722 << peer_id << std::endl;
723 m_con.DisconnectPeer(peer_id);
727 u8 major_ver, minor_ver, patch_ver, reserved;
728 std::string full_ver;
729 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
731 m_clients.setClientVersion(
732 peer_id, major_ver, minor_ver, patch_ver,
735 m_clients.event(peer_id, CSE_SetClientReady);
736 m_script->on_joinplayer(playersao);
739 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
741 if (pkt->getSize() < 1)
755 RemoteClient *client = getClient(pkt->getPeerId());
757 for (u16 i = 0; i < count; i++) {
758 if ((s16)pkt->getSize() < 1 + (i + 1) * 6)
759 throw con::InvalidIncomingDataException
760 ("GOTBLOCKS length is too short");
769 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
771 if (pkt->getSize() < 12 + 12 + 4 + 4)
775 s32 f32pitch, f32yaw;
782 f32 pitch = (f32)f32pitch / 100.0;
783 f32 yaw = (f32)f32yaw / 100.0;
786 if (pkt->getSize() >= 12 + 12 + 4 + 4 + 4)
789 v3f position((f32)ps.X / 100.0, (f32)ps.Y / 100.0, (f32)ps.Z / 100.0);
790 v3f speed((f32)ss.X / 100.0, (f32)ss.Y / 100.0, (f32)ss.Z / 100.0);
792 pitch = modulo360f(pitch);
793 yaw = modulo360f(yaw);
795 Player *player = m_env->getPlayer(pkt->getPeerId());
796 if (player == NULL) {
797 errorstream << "Server::ProcessData(): Canceling: "
798 "No player for peer_id=" << pkt->getPeerId()
799 << " disconnecting peer!" << std::endl;
800 m_con.DisconnectPeer(pkt->getPeerId());
804 // If player is dead we don't care of this packet
805 if (player->isDead()) {
806 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
807 << " is dead. Ignoring packet";
811 PlayerSAO *playersao = player->getPlayerSAO();
812 if (playersao == NULL) {
813 errorstream << "Server::ProcessData(): Canceling: "
814 "No player object for peer_id=" << pkt->getPeerId()
815 << " disconnecting peer!" << std::endl;
816 m_con.DisconnectPeer(pkt->getPeerId());
820 player->setPosition(position);
821 player->setSpeed(speed);
822 player->setPitch(pitch);
824 player->keyPressed = keyPressed;
825 player->control.up = (keyPressed & 1);
826 player->control.down = (keyPressed & 2);
827 player->control.left = (keyPressed & 4);
828 player->control.right = (keyPressed & 8);
829 player->control.jump = (keyPressed & 16);
830 player->control.aux1 = (keyPressed & 32);
831 player->control.sneak = (keyPressed & 64);
832 player->control.LMB = (keyPressed & 128);
833 player->control.RMB = (keyPressed & 256);
835 if (playersao->checkMovementCheat()) {
837 m_script->on_cheat(playersao, "moved_too_fast");
838 SendMovePlayer(pkt->getPeerId());
842 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
844 if (pkt->getSize() < 1)
858 RemoteClient *client = getClient(pkt->getPeerId());
860 for (u16 i = 0; i < count; i++) {
861 if ((s16)pkt->getSize() < 1 + (i + 1) * 6)
862 throw con::InvalidIncomingDataException
863 ("DELETEDBLOCKS length is too short");
867 client->SetBlockNotSent(p);
871 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
873 Player *player = m_env->getPlayer(pkt->getPeerId());
874 if (player == NULL) {
875 errorstream << "Server::ProcessData(): Canceling: "
876 "No player for peer_id=" << pkt->getPeerId()
877 << " disconnecting peer!" << std::endl;
878 m_con.DisconnectPeer(pkt->getPeerId());
882 PlayerSAO *playersao = player->getPlayerSAO();
883 if (playersao == NULL) {
884 errorstream << "Server::ProcessData(): Canceling: "
885 "No player object for peer_id=" << pkt->getPeerId()
886 << " disconnecting peer!" << std::endl;
887 m_con.DisconnectPeer(pkt->getPeerId());
891 // Strip command and create a stream
892 std::string datastring(pkt->getString(0), pkt->getSize());
893 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
895 std::istringstream is(datastring, std::ios_base::binary);
897 InventoryAction *a = InventoryAction::deSerialize(is);
899 infostream << "TOSERVER_INVENTORY_ACTION: "
900 << "InventoryAction::deSerialize() returned NULL"
905 // If something goes wrong, this player is to blame
906 RollbackScopeActor rollback_scope(m_rollback,
907 std::string("player:")+player->getName());
910 Note: Always set inventory not sent, to repair cases
911 where the client made a bad prediction.
915 Handle restrictions and special cases of the move action
917 if (a->getType() == IACTION_MOVE) {
918 IMoveAction *ma = (IMoveAction*)a;
920 ma->from_inv.applyCurrentPlayer(player->getName());
921 ma->to_inv.applyCurrentPlayer(player->getName());
923 setInventoryModified(ma->from_inv, false);
924 setInventoryModified(ma->to_inv, false);
926 bool from_inv_is_current_player =
927 (ma->from_inv.type == InventoryLocation::PLAYER) &&
928 (ma->from_inv.name == player->getName());
930 bool to_inv_is_current_player =
931 (ma->to_inv.type == InventoryLocation::PLAYER) &&
932 (ma->to_inv.name == player->getName());
935 Disable moving items out of craftpreview
937 if (ma->from_list == "craftpreview") {
938 infostream << "Ignoring IMoveAction from "
939 << (ma->from_inv.dump()) << ":" << ma->from_list
940 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
941 << " because src is " << ma->from_list << std::endl;
947 Disable moving items into craftresult and craftpreview
949 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
950 infostream << "Ignoring IMoveAction from "
951 << (ma->from_inv.dump()) << ":" << ma->from_list
952 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
953 << " because dst is " << ma->to_list << std::endl;
958 // Disallow moving items in elsewhere than player's inventory
959 // if not allowed to interact
960 if (!checkPriv(player->getName(), "interact") &&
961 (!from_inv_is_current_player ||
962 !to_inv_is_current_player)) {
963 infostream << "Cannot move outside of player's inventory: "
964 << "No interact privilege" << std::endl;
970 Handle restrictions and special cases of the drop action
972 else if (a->getType() == IACTION_DROP) {
973 IDropAction *da = (IDropAction*)a;
975 da->from_inv.applyCurrentPlayer(player->getName());
977 setInventoryModified(da->from_inv, false);
980 Disable dropping items out of craftpreview
982 if (da->from_list == "craftpreview") {
983 infostream << "Ignoring IDropAction from "
984 << (da->from_inv.dump()) << ":" << da->from_list
985 << " because src is " << da->from_list << std::endl;
990 // Disallow dropping items if not allowed to interact
991 if (!checkPriv(player->getName(), "interact")) {
997 Handle restrictions and special cases of the craft action
999 else if (a->getType() == IACTION_CRAFT) {
1000 ICraftAction *ca = (ICraftAction*)a;
1002 ca->craft_inv.applyCurrentPlayer(player->getName());
1004 setInventoryModified(ca->craft_inv, false);
1006 //bool craft_inv_is_current_player =
1007 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
1008 // (ca->craft_inv.name == player->getName());
1010 // Disallow crafting if not allowed to interact
1011 if (!checkPriv(player->getName(), "interact")) {
1012 infostream << "Cannot craft: "
1013 << "No interact privilege" << std::endl;
1020 a->apply(this, playersao, this);
1024 SendInventory(playersao);
1027 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
1037 std::wstring message;
1038 for (u16 i = 0; i < len; i++) {
1042 message += (wchar_t)tmp_wchar;
1045 Player *player = m_env->getPlayer(pkt->getPeerId());
1046 if (player == NULL) {
1047 errorstream << "Server::ProcessData(): Canceling: "
1048 "No player for peer_id=" << pkt->getPeerId()
1049 << " disconnecting peer!" << std::endl;
1050 m_con.DisconnectPeer(pkt->getPeerId());
1054 // If something goes wrong, this player is to blame
1055 RollbackScopeActor rollback_scope(m_rollback,
1056 std::string("player:")+player->getName());
1058 // Get player name of this client
1059 std::wstring name = narrow_to_wide(player->getName());
1062 bool ate = m_script->on_chat_message(player->getName(),
1063 wide_to_narrow(message));
1064 // If script ate the message, don't proceed
1068 // Line to send to players
1070 // Whether to send to the player that sent the line
1071 bool send_to_sender_only = false;
1073 // Commands are implemented in Lua, so only catch invalid
1074 // commands that were not "eaten" and send an error back
1075 if (message[0] == L'/') {
1076 message = message.substr(1);
1077 send_to_sender_only = true;
1078 if (message.length() == 0)
1079 line += L"-!- Empty command";
1081 line += L"-!- Invalid command: " + str_split(message, L' ')[0];
1084 if (checkPriv(player->getName(), "shout")) {
1090 line += L"-!- You don't have permission to shout.";
1091 send_to_sender_only = true;
1098 Send the message to sender
1100 if (send_to_sender_only) {
1101 SendChatMessage(pkt->getPeerId(), line);
1104 Send the message to others
1107 actionstream << "CHAT: " << wide_to_narrow(line)<<std::endl;
1109 std::vector<u16> clients = m_clients.getClientIDs();
1111 for (std::vector<u16>::iterator i = clients.begin();
1112 i != clients.end(); ++i) {
1113 if (*i != pkt->getPeerId())
1114 SendChatMessage(*i, line);
1120 void Server::handleCommand_Damage(NetworkPacket* pkt)
1126 Player *player = m_env->getPlayer(pkt->getPeerId());
1127 if (player == NULL) {
1128 errorstream << "Server::ProcessData(): Canceling: "
1129 "No player for peer_id=" << pkt->getPeerId()
1130 << " disconnecting peer!" << std::endl;
1131 m_con.DisconnectPeer(pkt->getPeerId());
1135 PlayerSAO *playersao = player->getPlayerSAO();
1136 if (playersao == NULL) {
1137 errorstream << "Server::ProcessData(): Canceling: "
1138 "No player object for peer_id=" << pkt->getPeerId()
1139 << " disconnecting peer!" << std::endl;
1140 m_con.DisconnectPeer(pkt->getPeerId());
1144 if (g_settings->getBool("enable_damage")) {
1145 actionstream << player->getName() << " damaged by "
1146 << (int)damage << " hp at " << PP(player->getPosition() / BS)
1149 playersao->setHP(playersao->getHP() - damage);
1150 SendPlayerHPOrDie(playersao->getPeerID(), playersao->getHP() == 0);
1154 void Server::handleCommand_Breath(NetworkPacket* pkt)
1160 Player *player = m_env->getPlayer(pkt->getPeerId());
1161 if (player == NULL) {
1162 errorstream << "Server::ProcessData(): Canceling: "
1163 "No player for peer_id=" << pkt->getPeerId()
1164 << " disconnecting peer!" << std::endl;
1165 m_con.DisconnectPeer(pkt->getPeerId());
1170 * If player is dead, we don't need to update the breath
1173 if (player->isDead()) {
1174 verbosestream << "TOSERVER_BREATH: " << player->getName()
1175 << " is dead. Ignoring packet";
1180 PlayerSAO *playersao = player->getPlayerSAO();
1181 if (playersao == NULL) {
1182 errorstream << "Server::ProcessData(): Canceling: "
1183 "No player object for peer_id=" << pkt->getPeerId()
1184 << " disconnecting peer!" << std::endl;
1185 m_con.DisconnectPeer(pkt->getPeerId());
1189 playersao->setBreath(breath);
1190 SendPlayerBreath(pkt->getPeerId());
1193 void Server::handleCommand_Password(NetworkPacket* pkt)
1195 if (pkt->getSize() != PASSWORD_SIZE * 2)
1201 // Deny for clients using the new protocol
1202 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
1203 if (client->net_proto_version >= 25) {
1204 infostream << "Server::handleCommand_Password(): Denying change: "
1205 << " Client protocol version for peer_id=" << pkt->getPeerId()
1206 << " too new!" << std::endl;
1210 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1211 char c = pkt->getChar(i);
1217 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1218 char c = pkt->getChar(PASSWORD_SIZE + i);
1224 Player *player = m_env->getPlayer(pkt->getPeerId());
1225 if (player == NULL) {
1226 errorstream << "Server::ProcessData(): Canceling: "
1227 "No player for peer_id=" << pkt->getPeerId()
1228 << " disconnecting peer!" << std::endl;
1229 m_con.DisconnectPeer(pkt->getPeerId());
1233 if (!base64_is_valid(newpwd)) {
1234 infostream<<"Server: " << player->getName() <<
1235 " supplied invalid password hash" << std::endl;
1236 // Wrong old password supplied!!
1237 SendChatMessage(pkt->getPeerId(), L"Invalid new password hash supplied. Password NOT changed.");
1241 infostream << "Server: Client requests a password change from "
1242 << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
1244 std::string playername = player->getName();
1246 std::string checkpwd;
1247 m_script->getAuth(playername, &checkpwd, NULL);
1249 if (oldpwd != checkpwd) {
1250 infostream << "Server: invalid old password" << std::endl;
1251 // Wrong old password supplied!!
1252 SendChatMessage(pkt->getPeerId(), L"Invalid old password supplied. Password NOT changed.");
1256 bool success = m_script->setPassword(playername, newpwd);
1258 actionstream << player->getName() << " changes password" << std::endl;
1259 SendChatMessage(pkt->getPeerId(), L"Password change successful.");
1261 actionstream << player->getName() << " tries to change password but "
1262 << "it fails" << std::endl;
1263 SendChatMessage(pkt->getPeerId(), L"Password change failed or unavailable.");
1267 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
1269 if (pkt->getSize() < 2)
1272 Player *player = m_env->getPlayer(pkt->getPeerId());
1273 if (player == NULL) {
1274 errorstream << "Server::ProcessData(): Canceling: "
1275 "No player for peer_id=" << pkt->getPeerId()
1276 << " disconnecting peer!" << std::endl;
1277 m_con.DisconnectPeer(pkt->getPeerId());
1281 PlayerSAO *playersao = player->getPlayerSAO();
1282 if (playersao == NULL) {
1283 errorstream << "Server::ProcessData(): Canceling: "
1284 "No player object for peer_id=" << pkt->getPeerId()
1285 << " disconnecting peer!" << std::endl;
1286 m_con.DisconnectPeer(pkt->getPeerId());
1294 playersao->setWieldIndex(item);
1297 void Server::handleCommand_Respawn(NetworkPacket* pkt)
1299 Player *player = m_env->getPlayer(pkt->getPeerId());
1300 if (player == NULL) {
1301 errorstream << "Server::ProcessData(): Canceling: "
1302 "No player for peer_id=" << pkt->getPeerId()
1303 << " disconnecting peer!" << std::endl;
1304 m_con.DisconnectPeer(pkt->getPeerId());
1308 if (!player->isDead())
1311 RespawnPlayer(pkt->getPeerId());
1313 actionstream << player->getName() << " respawns at "
1314 << PP(player->getPosition()/BS) << std::endl;
1316 // ActiveObject is added to environment in AsyncRunStep after
1317 // the previous addition has been successfully removed
1320 void Server::handleCommand_Interact(NetworkPacket* pkt)
1322 std::string datastring(pkt->getString(0), pkt->getSize());
1323 std::istringstream is(datastring, std::ios_base::binary);
1329 [5] u32 length of the next item
1330 [9] serialized PointedThing
1332 0: start digging (from undersurface) or use
1333 1: stop digging (all parameters ignored)
1334 2: digging completed
1335 3: place block or item (to abovesurface)
1338 u8 action = readU8(is);
1339 u16 item_i = readU16(is);
1340 std::istringstream tmp_is(deSerializeLongString(is), std::ios::binary);
1341 PointedThing pointed;
1342 pointed.deSerialize(tmp_is);
1344 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
1345 << item_i << ", pointed=" << pointed.dump() << std::endl;
1347 Player *player = m_env->getPlayer(pkt->getPeerId());
1348 if (player == NULL) {
1349 errorstream << "Server::ProcessData(): Canceling: "
1350 "No player for peer_id=" << pkt->getPeerId()
1351 << " disconnecting peer!" << std::endl;
1352 m_con.DisconnectPeer(pkt->getPeerId());
1356 PlayerSAO *playersao = player->getPlayerSAO();
1357 if (playersao == NULL) {
1358 errorstream << "Server::ProcessData(): Canceling: "
1359 "No player object for peer_id=" << pkt->getPeerId()
1360 << " disconnecting peer!" << std::endl;
1361 m_con.DisconnectPeer(pkt->getPeerId());
1365 if (player->isDead()) {
1366 verbosestream << "TOSERVER_INTERACT: " << player->getName()
1367 << " is dead. Ignoring packet";
1371 v3f player_pos = playersao->getLastGoodPosition();
1373 // Update wielded item
1374 playersao->setWieldIndex(item_i);
1376 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1377 v3s16 p_under = pointed.node_undersurface;
1378 v3s16 p_above = pointed.node_abovesurface;
1380 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1381 ServerActiveObject *pointed_object = NULL;
1382 if (pointed.type == POINTEDTHING_OBJECT) {
1383 pointed_object = m_env->getActiveObject(pointed.object_id);
1384 if (pointed_object == NULL) {
1385 verbosestream << "TOSERVER_INTERACT: "
1386 "pointed object is NULL" << std::endl;
1392 v3f pointed_pos_under = player_pos;
1393 v3f pointed_pos_above = player_pos;
1394 if (pointed.type == POINTEDTHING_NODE) {
1395 pointed_pos_under = intToFloat(p_under, BS);
1396 pointed_pos_above = intToFloat(p_above, BS);
1398 else if (pointed.type == POINTEDTHING_OBJECT) {
1399 pointed_pos_under = pointed_object->getBasePosition();
1400 pointed_pos_above = pointed_pos_under;
1404 Check that target is reasonably close
1405 (only when digging or placing things)
1407 if (action == 0 || action == 2 || action == 3) {
1408 float d = player_pos.getDistanceFrom(pointed_pos_under);
1409 float max_d = BS * 14; // Just some large enough value
1411 actionstream << "Player " << player->getName()
1412 << " tried to access " << pointed.dump()
1413 << " from too far: "
1414 << "d=" << d <<", max_d=" << max_d
1415 << ". ignoring." << std::endl;
1416 // Re-send block to revert change on client-side
1417 RemoteClient *client = getClient(pkt->getPeerId());
1418 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1419 client->SetBlockNotSent(blockpos);
1421 m_script->on_cheat(playersao, "interacted_too_far");
1428 Make sure the player is allowed to do it
1430 if (!checkPriv(player->getName(), "interact")) {
1431 actionstream<<player->getName()<<" attempted to interact with "
1432 <<pointed.dump()<<" without 'interact' privilege"
1434 // Re-send block to revert change on client-side
1435 RemoteClient *client = getClient(pkt->getPeerId());
1436 // Digging completed -> under
1438 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1439 client->SetBlockNotSent(blockpos);
1441 // Placement -> above
1443 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1444 client->SetBlockNotSent(blockpos);
1450 If something goes wrong, this player is to blame
1452 RollbackScopeActor rollback_scope(m_rollback,
1453 std::string("player:")+player->getName());
1456 0: start digging or punch object
1459 if (pointed.type == POINTEDTHING_NODE) {
1461 NOTE: This can be used in the future to check if
1462 somebody is cheating, by checking the timing.
1464 MapNode n(CONTENT_IGNORE);
1466 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1468 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1471 infostream << "Server: Not punching: Node not found."
1472 << " Adding block to emerge queue."
1474 m_emerge->enqueueBlockEmerge(pkt->getPeerId(), getNodeBlockPos(p_above), false);
1477 if (n.getContent() != CONTENT_IGNORE)
1478 m_script->node_on_punch(p_under, n, playersao, pointed);
1480 playersao->noCheatDigStart(p_under);
1482 else if (pointed.type == POINTEDTHING_OBJECT) {
1483 // Skip if object has been removed
1484 if (pointed_object->m_removed)
1487 actionstream<<player->getName()<<" punches object "
1488 <<pointed.object_id<<": "
1489 <<pointed_object->getDescription()<<std::endl;
1491 ItemStack punchitem = playersao->getWieldedItem();
1492 ToolCapabilities toolcap =
1493 punchitem.getToolCapabilities(m_itemdef);
1494 v3f dir = (pointed_object->getBasePosition() -
1495 (player->getPosition() + player->getEyeOffset())
1497 float time_from_last_punch =
1498 playersao->resetTimeFromLastPunch();
1500 s16 src_original_hp = pointed_object->getHP();
1501 s16 dst_origin_hp = playersao->getHP();
1503 pointed_object->punch(dir, &toolcap, playersao,
1504 time_from_last_punch);
1506 // If the object is a player and its HP changed
1507 if (src_original_hp != pointed_object->getHP() &&
1508 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1509 SendPlayerHPOrDie(((PlayerSAO*)pointed_object)->getPeerID(),
1510 pointed_object->getHP() == 0);
1513 // If the puncher is a player and its HP changed
1514 if (dst_origin_hp != playersao->getHP()) {
1515 SendPlayerHPOrDie(playersao->getPeerID(), playersao->getHP() == 0);
1524 else if (action == 1) {
1528 2: Digging completed
1530 else if (action == 2) {
1531 // Only digging of nodes
1532 if (pointed.type == POINTEDTHING_NODE) {
1534 MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1536 infostream << "Server: Not finishing digging: Node not found."
1537 << " Adding block to emerge queue."
1539 m_emerge->enqueueBlockEmerge(pkt->getPeerId(), getNodeBlockPos(p_above), false);
1542 /* Cheat prevention */
1543 bool is_valid_dig = true;
1544 if (!isSingleplayer() && !g_settings->getBool("disable_anticheat")) {
1545 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1546 float nocheat_t = playersao->getNoCheatDigTime();
1547 playersao->noCheatDigEnd();
1548 // If player didn't start digging this, ignore dig
1549 if (nocheat_p != p_under) {
1550 infostream << "Server: NoCheat: " << player->getName()
1551 << " started digging "
1552 << PP(nocheat_p) << " and completed digging "
1553 << PP(p_under) << "; not digging." << std::endl;
1554 is_valid_dig = false;
1556 m_script->on_cheat(playersao, "finished_unknown_dig");
1558 // Get player's wielded item
1559 ItemStack playeritem;
1560 InventoryList *mlist = playersao->getInventory()->getList("main");
1562 playeritem = mlist->getItem(playersao->getWieldIndex());
1563 ToolCapabilities playeritem_toolcap =
1564 playeritem.getToolCapabilities(m_itemdef);
1565 // Get diggability and expected digging time
1566 DigParams params = getDigParams(m_nodedef->get(n).groups,
1567 &playeritem_toolcap);
1568 // If can't dig, try hand
1569 if (!params.diggable) {
1570 const ItemDefinition &hand = m_itemdef->get("");
1571 const ToolCapabilities *tp = hand.tool_capabilities;
1573 params = getDigParams(m_nodedef->get(n).groups, tp);
1575 // If can't dig, ignore dig
1576 if (!params.diggable) {
1577 infostream << "Server: NoCheat: " << player->getName()
1578 << " completed digging " << PP(p_under)
1579 << ", which is not diggable with tool. not digging."
1581 is_valid_dig = false;
1583 m_script->on_cheat(playersao, "dug_unbreakable");
1585 // Check digging time
1586 // If already invalidated, we don't have to
1587 if (!is_valid_dig) {
1588 // Well not our problem then
1590 // Clean and long dig
1591 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1592 // All is good, but grab time from pool; don't care if
1593 // it's actually available
1594 playersao->getDigPool().grab(params.time);
1596 // Short or laggy dig
1597 // Try getting the time from pool
1598 else if (playersao->getDigPool().grab(params.time)) {
1603 infostream << "Server: NoCheat: " << player->getName()
1604 << " completed digging " << PP(p_under)
1605 << "too fast; not digging." << std::endl;
1606 is_valid_dig = false;
1608 m_script->on_cheat(playersao, "dug_too_fast");
1612 /* Actually dig node */
1614 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1615 m_script->node_on_dig(p_under, n, playersao);
1617 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1618 RemoteClient *client = getClient(pkt->getPeerId());
1619 // Send unusual result (that is, node not being removed)
1620 if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1621 // Re-send block to revert change on client-side
1622 client->SetBlockNotSent(blockpos);
1625 client->ResendBlockIfOnWire(blockpos);
1631 3: place block or right-click object
1633 else if (action == 3) {
1634 ItemStack item = playersao->getWieldedItem();
1636 // Reset build time counter
1637 if (pointed.type == POINTEDTHING_NODE &&
1638 item.getDefinition(m_itemdef).type == ITEM_NODE)
1639 getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1641 if (pointed.type == POINTEDTHING_OBJECT) {
1642 // Right click object
1644 // Skip if object has been removed
1645 if (pointed_object->m_removed)
1648 actionstream << player->getName() << " right-clicks object "
1649 << pointed.object_id << ": "
1650 << pointed_object->getDescription() << std::endl;
1653 pointed_object->rightClick(playersao);
1655 else if (m_script->item_OnPlace(
1656 item, playersao, pointed)) {
1657 // Placement was handled in lua
1659 // Apply returned ItemStack
1660 if (playersao->setWieldedItem(item)) {
1661 SendInventory(playersao);
1665 // If item has node placement prediction, always send the
1666 // blocks to make sure the client knows what exactly happened
1667 RemoteClient *client = getClient(pkt->getPeerId());
1668 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1669 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1670 if (item.getDefinition(m_itemdef).node_placement_prediction != "") {
1671 client->SetBlockNotSent(blockpos);
1672 if (blockpos2 != blockpos) {
1673 client->SetBlockNotSent(blockpos2);
1677 client->ResendBlockIfOnWire(blockpos);
1678 if (blockpos2 != blockpos) {
1679 client->ResendBlockIfOnWire(blockpos2);
1687 else if (action == 4) {
1688 ItemStack item = playersao->getWieldedItem();
1690 actionstream << player->getName() << " uses " << item.name
1691 << ", pointing at " << pointed.dump() << std::endl;
1693 if (m_script->item_OnUse(
1694 item, playersao, pointed)) {
1695 // Apply returned ItemStack
1696 if (playersao->setWieldedItem(item)) {
1697 SendInventory(playersao);
1705 Catch invalid actions
1708 infostream << "WARNING: Server: Invalid action "
1709 << action << std::endl;
1713 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1717 for (u16 k = 0; k < num; k++) {
1722 std::map<s32, ServerPlayingSound>::iterator i =
1723 m_playing_sounds.find(id);
1725 if (i == m_playing_sounds.end())
1728 ServerPlayingSound &psound = i->second;
1729 psound.clients.erase(pkt->getPeerId());
1730 if (psound.clients.empty())
1731 m_playing_sounds.erase(i++);
1735 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1738 std::string formname;
1741 *pkt >> p >> formname >> num;
1743 std::map<std::string, std::string> fields;
1744 for (u16 k = 0; k < num; k++) {
1745 std::string fieldname;
1747 fields[fieldname] = pkt->readLongString();
1750 Player *player = m_env->getPlayer(pkt->getPeerId());
1751 if (player == NULL) {
1752 errorstream << "Server::ProcessData(): Canceling: "
1753 "No player for peer_id=" << pkt->getPeerId()
1754 << " disconnecting peer!" << std::endl;
1755 m_con.DisconnectPeer(pkt->getPeerId());
1759 PlayerSAO *playersao = player->getPlayerSAO();
1760 if (playersao == NULL) {
1761 errorstream << "Server::ProcessData(): Canceling: "
1762 "No player object for peer_id=" << pkt->getPeerId()
1763 << " disconnecting peer!" << std::endl;
1764 m_con.DisconnectPeer(pkt->getPeerId());
1768 // If something goes wrong, this player is to blame
1769 RollbackScopeActor rollback_scope(m_rollback,
1770 std::string("player:")+player->getName());
1772 // Check the target node for rollback data; leave others unnoticed
1773 RollbackNode rn_old(&m_env->getMap(), p, this);
1775 m_script->node_on_receive_fields(p, formname, fields, playersao);
1777 // Report rollback data
1778 RollbackNode rn_new(&m_env->getMap(), p, this);
1779 if (rollback() && rn_new != rn_old) {
1780 RollbackAction action;
1781 action.setSetNode(p, rn_old, rn_new);
1782 rollback()->reportAction(action);
1786 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1788 std::string formname;
1791 *pkt >> formname >> num;
1793 std::map<std::string, std::string> fields;
1794 for (u16 k = 0; k < num; k++) {
1795 std::string fieldname;
1797 fields[fieldname] = pkt->readLongString();
1800 Player *player = m_env->getPlayer(pkt->getPeerId());
1801 if (player == NULL) {
1802 errorstream << "Server::ProcessData(): Canceling: "
1803 "No player for peer_id=" << pkt->getPeerId()
1804 << " disconnecting peer!" << std::endl;
1805 m_con.DisconnectPeer(pkt->getPeerId());
1809 PlayerSAO *playersao = player->getPlayerSAO();
1810 if (playersao == NULL) {
1811 errorstream << "Server::ProcessData(): Canceling: "
1812 "No player object for peer_id=" << pkt->getPeerId()
1813 << " disconnecting peer!" << std::endl;
1814 m_con.DisconnectPeer(pkt->getPeerId());
1818 m_script->on_playerReceiveFields(playersao, formname, fields);
1821 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1823 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1824 ClientState cstate = client->getState();
1826 std::string playername = client->getName();
1829 std::string verification_key;
1831 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1834 *pkt >> salt >> verification_key >> is_empty;
1836 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1837 << ", with is_empty= " << is_empty << std::endl;
1839 // Either this packet is sent because the user is new or to change the password
1840 if (cstate == CS_HelloSent) {
1841 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1842 actionstream << "Server: Client from " << addr_s
1843 << " tried to set password without being "
1844 << "authenticated, or the username being new." << std::endl;
1845 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1849 if (!isSingleplayer() &&
1850 g_settings->getBool("disallow_empty_password") &&
1852 actionstream << "Server: " << playername
1853 << " supplied empty password from " << addr_s << std::endl;
1854 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1858 std::string initial_ver_key;
1859 std::string raw_default_password = g_settings->get("default_password");
1860 // If default_password is empty, allow any initial password
1861 if (raw_default_password.length() == 0) {
1862 initial_ver_key = encodeSRPVerifier(verification_key, salt);
1864 initial_ver_key = getSRPVerifier(playername, raw_default_password);
1867 m_script->createAuth(playername, initial_ver_key);
1869 acceptAuth(pkt->getPeerId(), false);
1871 if (cstate < CS_SudoMode) {
1872 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1873 << addr_s << ": " << "Client has wrong state " << cstate << "."
1877 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1878 std::string pw_db_field = encodeSRPVerifier(verification_key, salt);
1879 bool success = m_script->setPassword(playername, pw_db_field);
1881 actionstream << playername << " changes password" << std::endl;
1882 SendChatMessage(pkt->getPeerId(), L"Password change successful.");
1884 actionstream << playername << " tries to change password but "
1885 << "it fails" << std::endl;
1886 SendChatMessage(pkt->getPeerId(), L"Password change failed or unavailable.");
1891 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1893 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1894 ClientState cstate = client->getState();
1896 bool wantSudo = (cstate == CS_Active);
1898 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1899 actionstream << "Server: got SRP _A packet in wrong state "
1900 << cstate << " from "
1901 << getPeerAddress(pkt->getPeerId()).serializeString()
1902 << ". Ignoring." << std::endl;
1906 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1907 actionstream << "Server: got SRP _A packet, while auth"
1908 << "is already going on with mech " << client->chosen_mech
1909 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1910 << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1912 DenySudoAccess(pkt->getPeerId());
1915 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1920 std::string bytes_A;
1922 *pkt >> bytes_A >> based_on;
1924 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1925 << "based_on=" << int(based_on) << " and len_A="
1926 << bytes_A.length() << "." << std::endl;
1928 AuthMechanism chosen = (based_on == 0) ?
1929 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1932 if (!client->isSudoMechAllowed(chosen)) {
1933 actionstream << "Server: Player \"" << client->getName()
1934 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1935 << " tried to change password using unallowed mech "
1936 << chosen << "." << std::endl;
1937 DenySudoAccess(pkt->getPeerId());
1941 if (!client->isMechAllowed(chosen)) {
1942 actionstream << "Server: Client tried to authenticate from "
1943 << getPeerAddress(pkt->getPeerId()).serializeString()
1944 << " using unallowed mech " << chosen << "." << std::endl;
1945 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1950 client->chosen_mech = chosen;
1952 std::string bytes_s;
1953 std::string bytes_v;
1955 if (based_on == 0) {
1956 char *p_bytes_s = 0;
1958 char *p_bytes_v = 0;
1960 getSRPVerifier(client->getName(), client->enc_pwd,
1962 &p_bytes_v, &len_v);
1963 bytes_s = std::string(p_bytes_s, len_s);
1964 bytes_v = std::string(p_bytes_v, len_v);
1967 } else if (!decodeSRPVerifier(client->enc_pwd, &bytes_s, &bytes_v)) {
1968 // Non-base64 errors should have been catched in the init handler
1969 actionstream << "Server: User " << client->getName()
1970 << " tried to log in, but srp verifier field"
1971 << " was invalid (most likely invalid base64)." << std::endl;
1972 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1979 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1980 client->getName().c_str(),
1981 (const unsigned char *) bytes_s.c_str(), bytes_s.size(),
1982 (const unsigned char *) bytes_v.c_str(), bytes_v.size(),
1983 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1985 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1988 actionstream << "Server: User " << client->getName()
1989 << " tried to log in, SRP-6a safety check violated in _A handler."
1992 DenySudoAccess(pkt->getPeerId());
1995 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2000 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
2001 resp_pkt << bytes_s << std::string(bytes_B, len_B);
2005 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
2007 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
2008 ClientState cstate = client->getState();
2010 bool wantSudo = (cstate == CS_Active);
2012 verbosestream << "Server: Recieved TOCLIENT_SRP_BYTES_M." << std::endl;
2014 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
2015 actionstream << "Server: got SRP _M packet in wrong state "
2016 << cstate << " from "
2017 << getPeerAddress(pkt->getPeerId()).serializeString()
2018 << ". Ignoring." << std::endl;
2022 if ((client->chosen_mech != AUTH_MECHANISM_SRP)
2023 && (client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD)) {
2024 actionstream << "Server: got SRP _M packet, while auth"
2025 << "is going on with mech " << client->chosen_mech
2026 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
2027 << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
2029 DenySudoAccess(pkt->getPeerId());
2032 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2037 std::string bytes_M;
2040 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
2041 != bytes_M.size()) {
2042 actionstream << "Server: User " << client->getName()
2043 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2044 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
2045 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2049 unsigned char *bytes_HAMK = 0;
2051 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
2052 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
2056 actionstream << "Server: User " << client->getName()
2057 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2058 << " tried to change their password, but supplied wrong"
2059 << " (SRP) password for authentication." << std::endl;
2060 DenySudoAccess(pkt->getPeerId());
2063 actionstream << "Server: User " << client->getName()
2064 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2065 << " supplied wrong (SRP) password from address "
2066 << getPeerAddress(pkt->getPeerId()).serializeString()
2067 << "." << std::endl;
2068 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
2073 acceptAuth(pkt->getPeerId(), wantSudo);