3 Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "chatmessage.h"
23 #include "content_sao.h"
27 #include "remoteplayer.h"
28 #include "rollback_interface.h"
29 #include "scripting_server.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.isUserLimitReached() &&
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.isUserLimitReached() &&
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());
617 Send some initialization data
620 infostream << "Server: Sending content to "
621 << getPlayerName(pkt->getPeerId()) << std::endl;
623 // Send player movement settings
624 SendMovement(pkt->getPeerId());
626 // Send item definitions
627 SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
629 // Send node definitions
630 SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
632 m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
634 // Send media announcement
635 sendMediaAnnouncement(pkt->getPeerId());
637 // Send detached inventories
638 sendDetachedInventories(pkt->getPeerId());
641 u16 time = m_env->getTimeOfDay();
642 float time_speed = g_settings->getFloat("time_speed");
643 SendTimeOfDay(pkt->getPeerId(), time, time_speed);
645 SendCSMFlavourLimits(pkt->getPeerId());
647 // Warnings about protocol version can be issued here
648 if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
649 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
650 L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
651 L"WITH THIS SERVER!"));
656 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
658 std::vector<std::string> tosend;
663 infostream << "Sending " << numfiles << " files to "
664 << getPlayerName(pkt->getPeerId()) << std::endl;
665 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
667 for (u16 i = 0; i < numfiles; i++) {
672 tosend.push_back(name);
673 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
674 << name << std::endl;
677 sendRequestedMedia(pkt->getPeerId(), tosend);
680 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
682 u16 peer_id = pkt->getPeerId();
684 PlayerSAO* playersao = StageTwoClientInit(peer_id);
686 if (playersao == NULL) {
688 << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
689 << peer_id << std::endl;
690 m_con.DisconnectPeer(peer_id);
695 if (pkt->getSize() < 8) {
697 << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
698 << peer_id << std::endl;
699 m_con.DisconnectPeer(peer_id);
703 u8 major_ver, minor_ver, patch_ver, reserved;
704 std::string full_ver;
705 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
707 m_clients.setClientVersion(
708 peer_id, major_ver, minor_ver, patch_ver,
711 const std::vector<std::string> &players = m_clients.getPlayerNames();
712 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
713 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
714 for (const std::string &player: players) {
717 m_clients.send(peer_id, 0, &list_pkt, true);
719 NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
720 // (u16) 1 + std::string represents a pseudo vector serialization representation
721 notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
722 m_clients.sendToAll(¬ice_pkt);
724 m_clients.event(peer_id, CSE_SetClientReady);
725 m_script->on_joinplayer(playersao);
726 // Send shutdown timer if shutdown has been scheduled
727 if (m_shutdown_timer > 0.0f) {
728 std::wstringstream ws;
729 ws << L"*** Server shutting down in "
730 << duration_to_string(myround(m_shutdown_timer)).c_str() << ".";
731 SendChatMessage(pkt->getPeerId(), ws.str());
735 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
737 if (pkt->getSize() < 1)
751 RemoteClient *client = getClient(pkt->getPeerId());
753 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
754 throw con::InvalidIncomingDataException
755 ("GOTBLOCKS length is too short");
758 for (u16 i = 0; i < count; i++) {
765 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
768 if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4)
772 s32 f32pitch, f32yaw;
780 f32 pitch = (f32)f32pitch / 100.0;
781 f32 yaw = (f32)f32yaw / 100.0;
784 // default behavior (in case an old client doesn't send these)
788 if (pkt->getRemainingBytes() >= 4)
790 if (pkt->getRemainingBytes() >= 1) {
792 fov = (f32)f32fov / 80.0;
794 if (pkt->getRemainingBytes() >= 1)
795 *pkt >> wanted_range;
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 = wrapDegrees_0_360(yaw);
803 playersao->setBasePosition(position);
804 player->setSpeed(speed);
805 playersao->setPitch(pitch);
806 playersao->setYaw(yaw);
807 playersao->setFov(fov);
808 playersao->setWantedRange(wanted_range);
809 player->keyPressed = keyPressed;
810 player->control.up = (keyPressed & 1);
811 player->control.down = (keyPressed & 2);
812 player->control.left = (keyPressed & 4);
813 player->control.right = (keyPressed & 8);
814 player->control.jump = (keyPressed & 16);
815 player->control.aux1 = (keyPressed & 32);
816 player->control.sneak = (keyPressed & 64);
817 player->control.LMB = (keyPressed & 128);
818 player->control.RMB = (keyPressed & 256);
820 if (playersao->checkMovementCheat()) {
822 m_script->on_cheat(playersao, "moved_too_fast");
823 SendMovePlayer(pkt->getPeerId());
827 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
829 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
830 if (player == NULL) {
831 errorstream << "Server::ProcessData(): Canceling: "
832 "No player for peer_id=" << pkt->getPeerId()
833 << " disconnecting peer!" << std::endl;
834 m_con.DisconnectPeer(pkt->getPeerId());
838 PlayerSAO *playersao = player->getPlayerSAO();
839 if (playersao == NULL) {
840 errorstream << "Server::ProcessData(): Canceling: "
841 "No player object for peer_id=" << pkt->getPeerId()
842 << " disconnecting peer!" << std::endl;
843 m_con.DisconnectPeer(pkt->getPeerId());
847 // If player is dead we don't care of this packet
848 if (playersao->isDead()) {
849 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
850 << " is dead. Ignoring packet";
854 process_PlayerPos(player, playersao, pkt);
857 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
859 if (pkt->getSize() < 1)
873 RemoteClient *client = getClient(pkt->getPeerId());
875 if ((s16)pkt->getSize() < 1 + (int)count * 6) {
876 throw con::InvalidIncomingDataException
877 ("DELETEDBLOCKS length is too short");
880 for (u16 i = 0; i < count; i++) {
883 client->SetBlockNotSent(p);
887 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
889 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
891 if (player == NULL) {
892 errorstream << "Server::ProcessData(): Canceling: "
893 "No player for peer_id=" << pkt->getPeerId()
894 << " disconnecting peer!" << std::endl;
895 m_con.DisconnectPeer(pkt->getPeerId());
899 PlayerSAO *playersao = player->getPlayerSAO();
900 if (playersao == NULL) {
901 errorstream << "Server::ProcessData(): Canceling: "
902 "No player object for peer_id=" << pkt->getPeerId()
903 << " disconnecting peer!" << std::endl;
904 m_con.DisconnectPeer(pkt->getPeerId());
908 // Strip command and create a stream
909 std::string datastring(pkt->getString(0), pkt->getSize());
910 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
912 std::istringstream is(datastring, std::ios_base::binary);
914 InventoryAction *a = InventoryAction::deSerialize(is);
916 infostream << "TOSERVER_INVENTORY_ACTION: "
917 << "InventoryAction::deSerialize() returned NULL"
922 // If something goes wrong, this player is to blame
923 RollbackScopeActor rollback_scope(m_rollback,
924 std::string("player:")+player->getName());
927 Note: Always set inventory not sent, to repair cases
928 where the client made a bad prediction.
932 Handle restrictions and special cases of the move action
934 if (a->getType() == IAction::Move) {
935 IMoveAction *ma = (IMoveAction*)a;
937 ma->from_inv.applyCurrentPlayer(player->getName());
938 ma->to_inv.applyCurrentPlayer(player->getName());
940 setInventoryModified(ma->from_inv, false);
941 setInventoryModified(ma->to_inv, false);
943 bool from_inv_is_current_player =
944 (ma->from_inv.type == InventoryLocation::PLAYER) &&
945 (ma->from_inv.name == player->getName());
947 bool to_inv_is_current_player =
948 (ma->to_inv.type == InventoryLocation::PLAYER) &&
949 (ma->to_inv.name == player->getName());
952 Disable moving items out of craftpreview
954 if (ma->from_list == "craftpreview") {
955 infostream << "Ignoring IMoveAction from "
956 << (ma->from_inv.dump()) << ":" << ma->from_list
957 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
958 << " because src is " << ma->from_list << std::endl;
964 Disable moving items into craftresult and craftpreview
966 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
967 infostream << "Ignoring IMoveAction from "
968 << (ma->from_inv.dump()) << ":" << ma->from_list
969 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
970 << " because dst is " << ma->to_list << std::endl;
975 // Disallow moving items in elsewhere than player's inventory
976 // if not allowed to interact
977 if (!checkPriv(player->getName(), "interact") &&
978 (!from_inv_is_current_player ||
979 !to_inv_is_current_player)) {
980 infostream << "Cannot move outside of player's inventory: "
981 << "No interact privilege" << std::endl;
987 Handle restrictions and special cases of the drop action
989 else if (a->getType() == IAction::Drop) {
990 IDropAction *da = (IDropAction*)a;
992 da->from_inv.applyCurrentPlayer(player->getName());
994 setInventoryModified(da->from_inv, false);
997 Disable dropping items out of craftpreview
999 if (da->from_list == "craftpreview") {
1000 infostream << "Ignoring IDropAction from "
1001 << (da->from_inv.dump()) << ":" << da->from_list
1002 << " because src is " << da->from_list << std::endl;
1007 // Disallow dropping items if not allowed to interact
1008 if (!checkPriv(player->getName(), "interact")) {
1013 // Disallow dropping items if dead
1014 if (playersao->isDead()) {
1015 infostream << "Ignoring IDropAction from "
1016 << (da->from_inv.dump()) << ":" << da->from_list
1017 << " because player is dead." << std::endl;
1023 Handle restrictions and special cases of the craft action
1025 else if (a->getType() == IAction::Craft) {
1026 ICraftAction *ca = (ICraftAction*)a;
1028 ca->craft_inv.applyCurrentPlayer(player->getName());
1030 setInventoryModified(ca->craft_inv, false);
1032 //bool craft_inv_is_current_player =
1033 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
1034 // (ca->craft_inv.name == player->getName());
1036 // Disallow crafting if not allowed to interact
1037 if (!checkPriv(player->getName(), "interact")) {
1038 infostream << "Cannot craft: "
1039 << "No interact privilege" << std::endl;
1046 a->apply(this, playersao, this);
1050 SendInventory(playersao);
1053 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
1063 std::wstring message;
1064 for (u16 i = 0; i < len; i++) {
1068 message += (wchar_t)tmp_wchar;
1071 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1072 if (player == NULL) {
1073 errorstream << "Server::ProcessData(): Canceling: "
1074 "No player for peer_id=" << pkt->getPeerId()
1075 << " disconnecting peer!" << std::endl;
1076 m_con.DisconnectPeer(pkt->getPeerId());
1080 // Get player name of this client
1081 std::string name = player->getName();
1082 std::wstring wname = narrow_to_wide(name);
1084 std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
1085 if (!answer_to_sender.empty()) {
1086 // Send the answer to sender
1087 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
1088 answer_to_sender, wname));
1092 void Server::handleCommand_Damage(NetworkPacket* pkt)
1098 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1100 if (player == NULL) {
1101 errorstream << "Server::ProcessData(): Canceling: "
1102 "No player for peer_id=" << pkt->getPeerId()
1103 << " disconnecting peer!" << std::endl;
1104 m_con.DisconnectPeer(pkt->getPeerId());
1108 PlayerSAO *playersao = player->getPlayerSAO();
1109 if (playersao == NULL) {
1110 errorstream << "Server::ProcessData(): Canceling: "
1111 "No player object for peer_id=" << pkt->getPeerId()
1112 << " disconnecting peer!" << std::endl;
1113 m_con.DisconnectPeer(pkt->getPeerId());
1117 if (g_settings->getBool("enable_damage")) {
1118 if (playersao->isDead()) {
1119 verbosestream << "Server::ProcessData(): Info: "
1120 "Ignoring damage as player " << player->getName()
1121 << " is already dead." << std::endl;
1125 actionstream << player->getName() << " damaged by "
1126 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
1129 playersao->setHP(playersao->getHP() - damage);
1130 SendPlayerHPOrDie(playersao);
1134 void Server::handleCommand_Password(NetworkPacket* pkt)
1136 if (pkt->getSize() != PASSWORD_SIZE * 2)
1142 // Deny for clients using the new protocol
1143 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
1144 if (client->net_proto_version >= 25) {
1145 infostream << "Server::handleCommand_Password(): Denying change: "
1146 << " Client protocol version for peer_id=" << pkt->getPeerId()
1147 << " too new!" << std::endl;
1151 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1152 char c = pkt->getChar(i);
1158 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1159 char c = pkt->getChar(PASSWORD_SIZE + i);
1165 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1166 if (player == NULL) {
1167 errorstream << "Server::ProcessData(): Canceling: "
1168 "No player for peer_id=" << pkt->getPeerId()
1169 << " disconnecting peer!" << std::endl;
1170 m_con.DisconnectPeer(pkt->getPeerId());
1174 if (!base64_is_valid(newpwd)) {
1175 infostream<<"Server: " << player->getName() <<
1176 " supplied invalid password hash" << std::endl;
1177 // Wrong old password supplied!!
1178 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1179 L"Invalid new password hash supplied. Password NOT changed."));
1183 infostream << "Server: Client requests a password change from "
1184 << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
1186 std::string playername = player->getName();
1188 std::string checkpwd;
1189 m_script->getAuth(playername, &checkpwd, NULL);
1191 if (oldpwd != checkpwd) {
1192 infostream << "Server: invalid old password" << std::endl;
1193 // Wrong old password supplied!!
1194 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1195 L"Invalid old password supplied. Password NOT changed."));
1199 bool success = m_script->setPassword(playername, newpwd);
1201 actionstream << player->getName() << " changes password" << std::endl;
1202 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1203 L"Password change successful."));
1205 actionstream << player->getName() << " tries to change password but "
1206 << "it fails" << std::endl;
1207 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1208 L"Password change failed or unavailable."));
1212 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
1214 if (pkt->getSize() < 2)
1217 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1219 if (player == NULL) {
1220 errorstream << "Server::ProcessData(): Canceling: "
1221 "No player for peer_id=" << pkt->getPeerId()
1222 << " disconnecting peer!" << std::endl;
1223 m_con.DisconnectPeer(pkt->getPeerId());
1227 PlayerSAO *playersao = player->getPlayerSAO();
1228 if (playersao == NULL) {
1229 errorstream << "Server::ProcessData(): Canceling: "
1230 "No player object for peer_id=" << pkt->getPeerId()
1231 << " disconnecting peer!" << std::endl;
1232 m_con.DisconnectPeer(pkt->getPeerId());
1240 playersao->setWieldIndex(item);
1243 void Server::handleCommand_Respawn(NetworkPacket* pkt)
1245 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1246 if (player == NULL) {
1247 errorstream << "Server::ProcessData(): Canceling: "
1248 "No player for peer_id=" << pkt->getPeerId()
1249 << " disconnecting peer!" << std::endl;
1250 m_con.DisconnectPeer(pkt->getPeerId());
1254 PlayerSAO *playersao = player->getPlayerSAO();
1257 if (!playersao->isDead())
1260 RespawnPlayer(pkt->getPeerId());
1262 actionstream << player->getName() << " respawns at "
1263 << PP(playersao->getBasePosition() / BS) << std::endl;
1265 // ActiveObject is added to environment in AsyncRunStep after
1266 // the previous addition has been successfully removed
1269 void Server::handleCommand_Interact(NetworkPacket* pkt)
1275 [5] u32 length of the next item (plen)
1276 [9] serialized PointedThing
1277 [9 + plen] player position information
1279 0: start digging (from undersurface) or use
1280 1: stop digging (all parameters ignored)
1281 2: digging completed
1282 3: place block or item (to abovesurface)
1284 5: rightclick air ("activate")
1290 std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
1291 PointedThing pointed;
1292 pointed.deSerialize(tmp_is);
1294 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
1295 << item_i << ", pointed=" << pointed.dump() << std::endl;
1297 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1299 if (player == NULL) {
1300 errorstream << "Server::ProcessData(): Canceling: "
1301 "No player for peer_id=" << pkt->getPeerId()
1302 << " disconnecting peer!" << std::endl;
1303 m_con.DisconnectPeer(pkt->getPeerId());
1307 PlayerSAO *playersao = player->getPlayerSAO();
1308 if (playersao == NULL) {
1309 errorstream << "Server::ProcessData(): Canceling: "
1310 "No player object for peer_id=" << pkt->getPeerId()
1311 << " disconnecting peer!" << std::endl;
1312 m_con.DisconnectPeer(pkt->getPeerId());
1316 if (playersao->isDead()) {
1317 actionstream << "Server: NoCheat: " << player->getName()
1318 << " tried to interact while dead; ignoring." << std::endl;
1319 if (pointed.type == POINTEDTHING_NODE) {
1320 // Re-send block to revert change on client-side
1321 RemoteClient *client = getClient(pkt->getPeerId());
1322 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1323 client->SetBlockNotSent(blockpos);
1326 m_script->on_cheat(playersao, "interacted_while_dead");
1330 process_PlayerPos(player, playersao, pkt);
1332 v3f player_pos = playersao->getLastGoodPosition();
1334 // Update wielded item
1335 playersao->setWieldIndex(item_i);
1337 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1338 v3s16 p_under = pointed.node_undersurface;
1339 v3s16 p_above = pointed.node_abovesurface;
1341 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1342 ServerActiveObject *pointed_object = NULL;
1343 if (pointed.type == POINTEDTHING_OBJECT) {
1344 pointed_object = m_env->getActiveObject(pointed.object_id);
1345 if (pointed_object == NULL) {
1346 verbosestream << "TOSERVER_INTERACT: "
1347 "pointed object is NULL" << std::endl;
1353 v3f pointed_pos_under = player_pos;
1354 v3f pointed_pos_above = player_pos;
1355 if (pointed.type == POINTEDTHING_NODE) {
1356 pointed_pos_under = intToFloat(p_under, BS);
1357 pointed_pos_above = intToFloat(p_above, BS);
1359 else if (pointed.type == POINTEDTHING_OBJECT) {
1360 pointed_pos_under = pointed_object->getBasePosition();
1361 pointed_pos_above = pointed_pos_under;
1365 Make sure the player is allowed to do it
1367 if (!checkPriv(player->getName(), "interact")) {
1368 actionstream<<player->getName()<<" attempted to interact with "
1369 <<pointed.dump()<<" without 'interact' privilege"
1371 // Re-send block to revert change on client-side
1372 RemoteClient *client = getClient(pkt->getPeerId());
1373 // Digging completed -> under
1375 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1376 client->SetBlockNotSent(blockpos);
1378 // Placement -> above
1380 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1381 client->SetBlockNotSent(blockpos);
1387 Check that target is reasonably close
1388 (only when digging or placing things)
1390 static thread_local const bool enable_anticheat =
1391 !g_settings->getBool("disable_anticheat");
1393 if ((action == 0 || action == 2 || action == 3 || action == 4) &&
1394 (enable_anticheat && !isSingleplayer())) {
1395 float d = player_pos.getDistanceFrom(pointed_pos_under);
1396 const ItemDefinition &playeritem_def =
1397 playersao->getWieldedItem().getDefinition(m_itemdef);
1398 float max_d = BS * playeritem_def.range;
1399 InventoryList *hlist = playersao->getInventory()->getList("hand");
1400 const ItemDefinition &hand_def =
1401 hlist ? (hlist->getItem(0).getDefinition(m_itemdef)) : (m_itemdef->get(""));
1402 float max_d_hand = BS * hand_def.range;
1403 if (max_d < 0 && max_d_hand >= 0)
1407 // cube diagonal: sqrt(3) = 1.73
1408 if (d > max_d * 1.73) {
1409 actionstream << "Player " << player->getName()
1410 << " tried to access " << pointed.dump()
1411 << " from too far: "
1412 << "d=" << d <<", max_d=" << max_d
1413 << ". ignoring." << std::endl;
1414 // Re-send block to revert change on client-side
1415 RemoteClient *client = getClient(pkt->getPeerId());
1416 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1417 client->SetBlockNotSent(blockpos);
1419 m_script->on_cheat(playersao, "interacted_too_far");
1426 If something goes wrong, this player is to blame
1428 RollbackScopeActor rollback_scope(m_rollback,
1429 std::string("player:")+player->getName());
1432 0: start digging or punch object
1435 if (pointed.type == POINTEDTHING_NODE) {
1436 MapNode n(CONTENT_IGNORE);
1439 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1441 infostream << "Server: Not punching: Node not found."
1442 << " Adding block to emerge queue."
1444 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1445 getNodeBlockPos(p_above), false);
1448 if (n.getContent() != CONTENT_IGNORE)
1449 m_script->node_on_punch(p_under, n, playersao, pointed);
1452 playersao->noCheatDigStart(p_under);
1454 else if (pointed.type == POINTEDTHING_OBJECT) {
1455 // Skip if object has been removed
1456 if (pointed_object->m_removed)
1459 actionstream<<player->getName()<<" punches object "
1460 <<pointed.object_id<<": "
1461 <<pointed_object->getDescription()<<std::endl;
1463 ItemStack punchitem = playersao->getWieldedItemOrHand();
1464 ToolCapabilities toolcap =
1465 punchitem.getToolCapabilities(m_itemdef);
1466 v3f dir = (pointed_object->getBasePosition() -
1467 (playersao->getBasePosition() + playersao->getEyeOffset())
1469 float time_from_last_punch =
1470 playersao->resetTimeFromLastPunch();
1472 s16 src_original_hp = pointed_object->getHP();
1473 s16 dst_origin_hp = playersao->getHP();
1475 pointed_object->punch(dir, &toolcap, playersao,
1476 time_from_last_punch);
1478 // If the object is a player and its HP changed
1479 if (src_original_hp != pointed_object->getHP() &&
1480 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1481 SendPlayerHPOrDie((PlayerSAO *)pointed_object);
1484 // If the puncher is a player and its HP changed
1485 if (dst_origin_hp != playersao->getHP())
1486 SendPlayerHPOrDie(playersao);
1494 else if (action == 1) {
1498 2: Digging completed
1500 else if (action == 2) {
1501 // Only digging of nodes
1502 if (pointed.type == POINTEDTHING_NODE) {
1504 MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1506 infostream << "Server: Not finishing digging: Node not found."
1507 << " Adding block to emerge queue."
1509 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1510 getNodeBlockPos(p_above), false);
1513 /* Cheat prevention */
1514 bool is_valid_dig = true;
1515 if (enable_anticheat && !isSingleplayer()) {
1516 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1517 float nocheat_t = playersao->getNoCheatDigTime();
1518 playersao->noCheatDigEnd();
1519 // If player didn't start digging this, ignore dig
1520 if (nocheat_p != p_under) {
1521 infostream << "Server: NoCheat: " << player->getName()
1522 << " started digging "
1523 << PP(nocheat_p) << " and completed digging "
1524 << PP(p_under) << "; not digging." << std::endl;
1525 is_valid_dig = false;
1527 m_script->on_cheat(playersao, "finished_unknown_dig");
1529 // Get player's wielded item
1530 ItemStack playeritem = playersao->getWieldedItemOrHand();
1531 ToolCapabilities playeritem_toolcap =
1532 playeritem.getToolCapabilities(m_itemdef);
1533 // Get diggability and expected digging time
1534 DigParams params = getDigParams(m_nodedef->get(n).groups,
1535 &playeritem_toolcap);
1536 // If can't dig, try hand
1537 if (!params.diggable) {
1538 InventoryList *hlist = playersao->getInventory()->getList("hand");
1539 const ItemDefinition &hand =
1540 hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
1541 const ToolCapabilities *tp = hand.tool_capabilities;
1543 params = getDigParams(m_nodedef->get(n).groups, tp);
1545 // If can't dig, ignore dig
1546 if (!params.diggable) {
1547 infostream << "Server: NoCheat: " << player->getName()
1548 << " completed digging " << PP(p_under)
1549 << ", which is not diggable with tool. not digging."
1551 is_valid_dig = false;
1553 m_script->on_cheat(playersao, "dug_unbreakable");
1555 // Check digging time
1556 // If already invalidated, we don't have to
1557 if (!is_valid_dig) {
1558 // Well not our problem then
1560 // Clean and long dig
1561 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1562 // All is good, but grab time from pool; don't care if
1563 // it's actually available
1564 playersao->getDigPool().grab(params.time);
1566 // Short or laggy dig
1567 // Try getting the time from pool
1568 else if (playersao->getDigPool().grab(params.time)) {
1573 infostream << "Server: NoCheat: " << player->getName()
1574 << " completed digging " << PP(p_under)
1575 << "too fast; not digging." << std::endl;
1576 is_valid_dig = false;
1578 m_script->on_cheat(playersao, "dug_too_fast");
1582 /* Actually dig node */
1584 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1585 m_script->node_on_dig(p_under, n, playersao);
1587 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1588 RemoteClient *client = getClient(pkt->getPeerId());
1589 // Send unusual result (that is, node not being removed)
1590 if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1591 // Re-send block to revert change on client-side
1592 client->SetBlockNotSent(blockpos);
1595 client->ResendBlockIfOnWire(blockpos);
1601 3: place block or right-click object
1603 else if (action == 3) {
1604 ItemStack item = playersao->getWieldedItem();
1606 // Reset build time counter
1607 if (pointed.type == POINTEDTHING_NODE &&
1608 item.getDefinition(m_itemdef).type == ITEM_NODE)
1609 getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1611 if (pointed.type == POINTEDTHING_OBJECT) {
1612 // Right click object
1614 // Skip if object has been removed
1615 if (pointed_object->m_removed)
1618 actionstream << player->getName() << " right-clicks object "
1619 << pointed.object_id << ": "
1620 << pointed_object->getDescription() << std::endl;
1623 pointed_object->rightClick(playersao);
1625 else if (m_script->item_OnPlace(
1626 item, playersao, pointed)) {
1627 // Placement was handled in lua
1629 // Apply returned ItemStack
1630 if (playersao->setWieldedItem(item)) {
1631 SendInventory(playersao);
1635 // If item has node placement prediction, always send the
1636 // blocks to make sure the client knows what exactly happened
1637 RemoteClient *client = getClient(pkt->getPeerId());
1638 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1639 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1640 if (item.getDefinition(m_itemdef).node_placement_prediction != "") {
1641 client->SetBlockNotSent(blockpos);
1642 if (blockpos2 != blockpos) {
1643 client->SetBlockNotSent(blockpos2);
1647 client->ResendBlockIfOnWire(blockpos);
1648 if (blockpos2 != blockpos) {
1649 client->ResendBlockIfOnWire(blockpos2);
1657 else if (action == 4) {
1658 ItemStack item = playersao->getWieldedItem();
1660 actionstream << player->getName() << " uses " << item.name
1661 << ", pointing at " << pointed.dump() << std::endl;
1663 if (m_script->item_OnUse(
1664 item, playersao, pointed)) {
1665 // Apply returned ItemStack
1666 if (playersao->setWieldedItem(item)) {
1667 SendInventory(playersao);
1676 else if (action == 5) {
1677 ItemStack item = playersao->getWieldedItem();
1679 actionstream << player->getName() << " activates "
1680 << item.name << std::endl;
1682 if (m_script->item_OnSecondaryUse(
1684 if( playersao->setWieldedItem(item)) {
1685 SendInventory(playersao);
1692 Catch invalid actions
1695 warningstream << "Server: Invalid action "
1696 << action << std::endl;
1700 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1704 for (u16 k = 0; k < num; k++) {
1709 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1710 m_playing_sounds.find(id);
1711 if (i == m_playing_sounds.end())
1714 ServerPlayingSound &psound = i->second;
1715 psound.clients.erase(pkt->getPeerId());
1716 if (psound.clients.empty())
1717 m_playing_sounds.erase(i++);
1721 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1724 std::string formname;
1727 *pkt >> p >> formname >> num;
1730 for (u16 k = 0; k < num; k++) {
1731 std::string fieldname;
1733 fields[fieldname] = pkt->readLongString();
1736 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1738 if (player == NULL) {
1739 errorstream << "Server::ProcessData(): Canceling: "
1740 "No player for peer_id=" << pkt->getPeerId()
1741 << " disconnecting peer!" << std::endl;
1742 m_con.DisconnectPeer(pkt->getPeerId());
1746 PlayerSAO *playersao = player->getPlayerSAO();
1747 if (playersao == NULL) {
1748 errorstream << "Server::ProcessData(): Canceling: "
1749 "No player object for peer_id=" << pkt->getPeerId()
1750 << " disconnecting peer!" << std::endl;
1751 m_con.DisconnectPeer(pkt->getPeerId());
1755 // If something goes wrong, this player is to blame
1756 RollbackScopeActor rollback_scope(m_rollback,
1757 std::string("player:")+player->getName());
1759 // Check the target node for rollback data; leave others unnoticed
1760 RollbackNode rn_old(&m_env->getMap(), p, this);
1762 m_script->node_on_receive_fields(p, formname, fields, playersao);
1764 // Report rollback data
1765 RollbackNode rn_new(&m_env->getMap(), p, this);
1766 if (rollback() && rn_new != rn_old) {
1767 RollbackAction action;
1768 action.setSetNode(p, rn_old, rn_new);
1769 rollback()->reportAction(action);
1773 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1775 std::string formname;
1778 *pkt >> formname >> num;
1781 for (u16 k = 0; k < num; k++) {
1782 std::string fieldname;
1784 fields[fieldname] = pkt->readLongString();
1787 RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1789 if (player == NULL) {
1790 errorstream << "Server::ProcessData(): Canceling: "
1791 "No player for peer_id=" << pkt->getPeerId()
1792 << " disconnecting peer!" << std::endl;
1793 m_con.DisconnectPeer(pkt->getPeerId());
1797 PlayerSAO *playersao = player->getPlayerSAO();
1798 if (playersao == NULL) {
1799 errorstream << "Server::ProcessData(): Canceling: "
1800 "No player object for peer_id=" << pkt->getPeerId()
1801 << " disconnecting peer!" << std::endl;
1802 m_con.DisconnectPeer(pkt->getPeerId());
1806 m_script->on_playerReceiveFields(playersao, formname, fields);
1809 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1811 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1812 ClientState cstate = client->getState();
1814 std::string playername = client->getName();
1817 std::string verification_key;
1819 std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1822 *pkt >> salt >> verification_key >> is_empty;
1824 verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1825 << ", with is_empty=" << (is_empty == 1) << std::endl;
1827 // Either this packet is sent because the user is new or to change the password
1828 if (cstate == CS_HelloSent) {
1829 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1830 actionstream << "Server: Client from " << addr_s
1831 << " tried to set password without being "
1832 << "authenticated, or the username being new." << std::endl;
1833 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1837 if (!isSingleplayer() &&
1838 g_settings->getBool("disallow_empty_password") &&
1840 actionstream << "Server: " << playername
1841 << " supplied empty password from " << addr_s << std::endl;
1842 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1846 std::string initial_ver_key;
1848 initial_ver_key = encode_srp_verifier(verification_key, salt);
1849 m_script->createAuth(playername, initial_ver_key);
1851 acceptAuth(pkt->getPeerId(), false);
1853 if (cstate < CS_SudoMode) {
1854 infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1855 << addr_s << ": " << "Client has wrong state " << cstate << "."
1859 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1860 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1861 bool success = m_script->setPassword(playername, pw_db_field);
1863 actionstream << playername << " changes password" << std::endl;
1864 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1865 L"Password change successful."));
1867 actionstream << playername << " tries to change password but "
1868 << "it fails" << std::endl;
1869 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1870 L"Password change failed or unavailable."));
1875 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1877 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1878 ClientState cstate = client->getState();
1880 bool wantSudo = (cstate == CS_Active);
1882 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1883 actionstream << "Server: got SRP _A packet in wrong state "
1884 << cstate << " from "
1885 << getPeerAddress(pkt->getPeerId()).serializeString()
1886 << ". Ignoring." << std::endl;
1890 if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1891 actionstream << "Server: got SRP _A packet, while auth"
1892 << "is already going on with mech " << client->chosen_mech
1893 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1894 << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1896 DenySudoAccess(pkt->getPeerId());
1899 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1904 std::string bytes_A;
1906 *pkt >> bytes_A >> based_on;
1908 infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1909 << "based_on=" << int(based_on) << " and len_A="
1910 << bytes_A.length() << "." << std::endl;
1912 AuthMechanism chosen = (based_on == 0) ?
1913 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1916 if (!client->isSudoMechAllowed(chosen)) {
1917 actionstream << "Server: Player \"" << client->getName()
1918 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1919 << " tried to change password using unallowed mech "
1920 << chosen << "." << std::endl;
1921 DenySudoAccess(pkt->getPeerId());
1925 if (!client->isMechAllowed(chosen)) {
1926 actionstream << "Server: Client tried to authenticate from "
1927 << getPeerAddress(pkt->getPeerId()).serializeString()
1928 << " using unallowed mech " << chosen << "." << std::endl;
1929 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1934 client->chosen_mech = chosen;
1937 std::string verifier;
1939 if (based_on == 0) {
1941 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1943 } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1944 // Non-base64 errors should have been catched in the init handler
1945 actionstream << "Server: User " << client->getName()
1946 << " tried to log in, but srp verifier field"
1947 << " was invalid (most likely invalid base64)." << std::endl;
1948 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1955 client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1956 client->getName().c_str(),
1957 (const unsigned char *) salt.c_str(), salt.size(),
1958 (const unsigned char *) verifier.c_str(), verifier.size(),
1959 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1961 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1964 actionstream << "Server: User " << client->getName()
1965 << " tried to log in, SRP-6a safety check violated in _A handler."
1968 DenySudoAccess(pkt->getPeerId());
1971 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1976 NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1977 resp_pkt << salt << std::string(bytes_B, len_B);
1981 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1983 RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1984 ClientState cstate = client->getState();
1986 bool wantSudo = (cstate == CS_Active);
1988 verbosestream << "Server: Recieved TOCLIENT_SRP_BYTES_M." << std::endl;
1990 if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1991 actionstream << "Server: got SRP _M packet in wrong state "
1992 << cstate << " from "
1993 << getPeerAddress(pkt->getPeerId()).serializeString()
1994 << ". Ignoring." << std::endl;
1998 if ((client->chosen_mech != AUTH_MECHANISM_SRP)
1999 && (client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD)) {
2000 actionstream << "Server: got SRP _M packet, while auth"
2001 << "is going on with mech " << client->chosen_mech
2002 << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
2003 << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
2005 DenySudoAccess(pkt->getPeerId());
2008 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2013 std::string bytes_M;
2016 if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
2017 != bytes_M.size()) {
2018 actionstream << "Server: User " << client->getName()
2019 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2020 << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
2021 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2025 unsigned char *bytes_HAMK = 0;
2027 srp_verifier_verify_session((SRPVerifier *) client->auth_data,
2028 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
2032 actionstream << "Server: User " << client->getName()
2033 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2034 << " tried to change their password, but supplied wrong"
2035 << " (SRP) password for authentication." << std::endl;
2036 DenySudoAccess(pkt->getPeerId());
2039 actionstream << "Server: User " << client->getName()
2040 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2041 << " supplied wrong password (auth mechanism: SRP)."
2043 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
2048 if (client->create_player_on_auth_success) {
2049 std::string playername = client->getName();
2050 m_script->createAuth(playername, client->enc_pwd);
2052 std::string checkpwd; // not used, but needed for passing something
2053 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
2054 actionstream << "Server: " << playername << " cannot be authenticated"
2055 << " (auth handler does not work?)" << std::endl;
2056 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
2059 client->create_player_on_auth_success = false;
2062 acceptAuth(pkt->getPeerId(), wantSudo);