3 Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "content_abm.h"
24 #include "content_sao.h"
29 #include "rollback_interface.h"
30 #include "scripting_game.h"
34 #include "network/networkprotocol.h"
35 #include "network/serveropcodes.h"
36 #include "util/base64.h"
37 #include "util/pointedthing.h"
38 #include "util/serialize.h"
40 void Server::handleCommand_Deprecated(NetworkPacket* pkt)
42 infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
43 << " not supported anymore" << std::endl;
46 void Server::handleCommand_Init(NetworkPacket* pkt)
49 if(pkt->getSize() < 1)
52 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
56 Address address = getPeerAddress(pkt->getPeerId());
57 addr_s = address.serializeString();
59 catch (con::PeerNotFoundException &e) {
61 * no peer for this packet found
62 * most common reason is peer timeout, e.g. peer didn't
63 * respond for some time, your server was overloaded or
66 infostream << "Server::ProcessData(): Canceling: peer "
67 << pkt->getPeerId() << " not found" << std::endl;
71 // If net_proto_version is set, this client has already been handled
72 if (client->getState() > CS_Created) {
73 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
74 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
78 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
79 << pkt->getPeerId() << ")" << std::endl;
81 // Do not allow multiple players in simple singleplayer mode.
82 // This isn't a perfect way to do it, but will suffice for now
83 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
84 infostream << "Server: Not allowing another client (" << addr_s
85 << ") to connect in simple singleplayer mode" << std::endl;
86 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SINGLEPLAYER);
90 // First byte after command is maximum supported
91 // serialization version
94 u16 min_net_proto_version = 0;
95 u16 max_net_proto_version;
97 *pkt >> client_max >> compression_modes >> min_net_proto_version
98 >> max_net_proto_version;
100 u8 our_max = SER_FMT_VER_HIGHEST_READ;
101 // Use the highest version supported by both
102 int deployed = std::min(client_max, our_max);
103 // If it's lower than the lowest supported, give up.
104 if (deployed < SER_FMT_VER_LOWEST)
105 deployed = SER_FMT_VER_INVALID;
107 if (deployed == SER_FMT_VER_INVALID) {
108 actionstream << "Server: A mismatched client tried to connect from "
109 << addr_s << std::endl;
110 infostream<<"Server: Cannot negotiate serialization version with "
111 << addr_s << std::endl;
112 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
116 client->setPendingSerializationVersion(deployed);
119 Read and check network protocol version
122 u16 net_proto_version = 0;
124 // Figure out a working version if it is possible at all
125 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
126 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
127 // If maximum is larger than our maximum, go with our maximum
128 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
129 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
130 // Else go with client's maximum
132 net_proto_version = max_net_proto_version;
135 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
136 << min_net_proto_version << ", max: " << max_net_proto_version
137 << ", chosen: " << net_proto_version << std::endl;
139 client->net_proto_version = net_proto_version;
141 // On this handler protocol version 25 is required
142 if (net_proto_version < 25 ||
143 net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
144 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
145 actionstream << "Server: A mismatched client tried to connect from "
146 << addr_s << std::endl;
147 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
151 if (g_settings->getBool("strict_protocol_version_checking")) {
152 if (net_proto_version != LATEST_PROTOCOL_VERSION) {
153 actionstream << "Server: A mismatched (strict) client tried to "
154 << "connect from " << addr_s << std::endl;
155 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
160 // @TODO: check if we support same modes, but not required now
162 client->setSupportedCompressionModes(compression_modes);
164 m_clients.event(pkt->getPeerId(), CSE_Init);
167 void Server::handleCommand_Auth(NetworkPacket* pkt)
171 Address address = getPeerAddress(pkt->getPeerId());
172 addr_s = address.serializeString();
174 catch (con::PeerNotFoundException &e) {
176 * no peer for this packet found
177 * most common reason is peer timeout, e.g. peer didn't
178 * respond for some time, your server was overloaded or
181 infostream << "Server::ProcessData(): Canceling: peer "
182 << pkt->getPeerId() << " not found" << std::endl;
186 std::string playerName, playerPassword;
188 *pkt >> playerName >> playerPassword;
190 const char* playername = playerName.c_str();
192 if (playerName.size() > PLAYERNAME_SIZE) {
193 actionstream << "Server: Player with an too long name "
194 << "tried to connect from " << addr_s << std::endl;
195 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
199 if (string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS) == false) {
200 actionstream << "Server: Player with an invalid name "
201 << "tried to connect from " << addr_s << std::endl;
202 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
206 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
207 actionstream << "Server: Player with the name \"singleplayer\" "
208 << "tried to connect from " << addr_s << std::endl;
209 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
215 if(m_script->on_prejoinplayer(playername, addr_s, reason)) {
216 actionstream << "Server: Player with the name \"" << playerName << "\" "
217 << "tried to connect from " << addr_s << " "
218 << "but it was disallowed for the following reason: "
219 << reason << std::endl;
220 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING,
221 narrow_to_wide(reason.c_str()));
226 if (playerPassword.size() > PASSWORD_SIZE) {
227 actionstream << "Server: Player with an too long password "
228 << "tried to connect from " << addr_s << std::endl;
229 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
233 infostream << "Server: New connection: \"" << playerName << "\" from "
234 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
236 if(!base64_is_valid(playerPassword)){
237 actionstream << "Server: " << playerName
238 << " supplied invalid password hash" << std::endl;
239 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
243 // Enforce user limit.
244 // Don't enforce for users that have some admin right
245 if (m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
246 !checkPriv(playername, "server") &&
247 !checkPriv(playername, "ban") &&
248 !checkPriv(playername, "privs") &&
249 !checkPriv(playername, "password") &&
250 playername != g_settings->get("name")) {
251 actionstream << "Server: " << playername << " tried to join, but there"
252 << " are already max_users="
253 << g_settings->getU16("max_users") << " players." << std::endl;
254 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_TOO_MANY_USERS);
258 std::string checkpwd; // Password hash to check against
259 bool has_auth = m_script->getAuth(playername, &checkpwd, NULL);
261 // If no authentication info exists for user, create it
263 if (!isSingleplayer() &&
264 g_settings->getBool("disallow_empty_password") &&
265 playerPassword.empty()) {
266 actionstream << "Server: " << playerName
267 << " supplied empty password" << std::endl;
268 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
271 std::wstring raw_default_password =
272 narrow_to_wide(g_settings->get("default_password"));
273 std::string initial_password =
274 translatePassword(playername, raw_default_password);
276 // If default_password is empty, allow any initial password
277 if (raw_default_password.length() == 0)
278 initial_password = playerPassword.c_str();
280 m_script->createAuth(playername, initial_password);
283 has_auth = m_script->getAuth(playername, &checkpwd, NULL);
286 actionstream << "Server: " << playerName << " cannot be authenticated"
287 << " (auth handler does not work?)" << std::endl;
288 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
292 if(playerPassword.c_str() != checkpwd) {
293 actionstream << "Server: " << playerName << " supplied wrong password"
295 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
299 RemotePlayer *player =
300 static_cast<RemotePlayer*>(m_env->getPlayer(playername));
302 if (player && player->peer_id != 0) {
303 errorstream << "Server: " << playername << ": Failed to emerge player"
304 << " (player allocated to an another client)" << std::endl;
305 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_ALREADY_CONNECTED);
308 m_clients.setPlayerName(pkt->getPeerId(), playername);
311 Answer with a TOCLIENT_INIT
314 NetworkPacket resp_pkt(TOCLIENT_AUTH_ACCEPT, 1 + 6 + 8 + 4, pkt->getPeerId());
316 resp_pkt << v3f(0,0,0) << (u64) m_env->getServerMap().getSeed()
317 << g_settings->getFloat("dedicated_server_step");
320 m_clients.event(pkt->getPeerId(), CSE_Init);
323 void Server::handleCommand_Init_Legacy(NetworkPacket* pkt)
325 // [0] u8 SER_FMT_VER_HIGHEST_READ
326 // [1] u8[20] player_name
327 // [21] u8[28] password <--- can be sent without this, from old versions
329 if (pkt->getSize() < 1+PLAYERNAME_SIZE)
332 RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
336 Address address = getPeerAddress(pkt->getPeerId());
337 addr_s = address.serializeString();
339 catch (con::PeerNotFoundException &e) {
341 * no peer for this packet found
342 * most common reason is peer timeout, e.g. peer didn't
343 * respond for some time, your server was overloaded or
346 infostream << "Server::ProcessData(): Canceling: peer "
347 << pkt->getPeerId() << " not found" << std::endl;
351 // If net_proto_version is set, this client has already been handled
352 if (client->getState() > CS_Created) {
353 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
354 << addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
358 verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
359 << pkt->getPeerId() << ")" << std::endl;
361 // Do not allow multiple players in simple singleplayer mode.
362 // This isn't a perfect way to do it, but will suffice for now
363 if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
364 infostream << "Server: Not allowing another client (" << addr_s
365 << ") to connect in simple singleplayer mode" << std::endl;
366 DenyAccess_Legacy(pkt->getPeerId(), L"Running in simple singleplayer mode.");
370 // First byte after command is maximum supported
371 // serialization version
376 u8 our_max = SER_FMT_VER_HIGHEST_READ;
377 // Use the highest version supported by both
378 int deployed = std::min(client_max, our_max);
379 // If it's lower than the lowest supported, give up.
380 if (deployed < SER_FMT_VER_LOWEST)
381 deployed = SER_FMT_VER_INVALID;
383 if (deployed == SER_FMT_VER_INVALID) {
384 actionstream << "Server: A mismatched client tried to connect from "
385 << addr_s << std::endl;
386 infostream<<"Server: Cannot negotiate serialization version with "
387 << addr_s << std::endl;
388 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
389 L"Your client's version is not supported.\n"
390 L"Server version is ")
391 + narrow_to_wide(g_version_string) + L"."
396 client->setPendingSerializationVersion(deployed);
399 Read and check network protocol version
402 u16 min_net_proto_version = 0;
403 if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2)
404 min_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE);
406 // Use same version as minimum and maximum if maximum version field
407 // doesn't exist (backwards compatibility)
408 u16 max_net_proto_version = min_net_proto_version;
409 if (pkt->getSize() >= 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2)
410 max_net_proto_version = pkt->getU16(1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2);
412 // Start with client's maximum version
413 u16 net_proto_version = max_net_proto_version;
415 // Figure out a working version if it is possible at all
416 if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
417 min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
418 // If maximum is larger than our maximum, go with our maximum
419 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
420 net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
421 // Else go with client's maximum
423 net_proto_version = max_net_proto_version;
426 verbosestream << "Server: " << addr_s << ": Protocol version: min: "
427 << min_net_proto_version << ", max: " << max_net_proto_version
428 << ", chosen: " << net_proto_version << std::endl;
430 client->net_proto_version = net_proto_version;
432 if (net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
433 net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
434 actionstream << "Server: A mismatched client tried to connect from "
435 << addr_s << std::endl;
436 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
437 L"Your client's version is not supported.\n"
438 L"Server version is ")
439 + narrow_to_wide(g_version_string) + L",\n"
440 + L"server's PROTOCOL_VERSION is "
441 + narrow_to_wide(itos(SERVER_PROTOCOL_VERSION_MIN))
443 + narrow_to_wide(itos(SERVER_PROTOCOL_VERSION_MAX))
444 + L", client's PROTOCOL_VERSION is "
445 + narrow_to_wide(itos(min_net_proto_version))
447 + narrow_to_wide(itos(max_net_proto_version))
452 if (g_settings->getBool("strict_protocol_version_checking")) {
453 if (net_proto_version != LATEST_PROTOCOL_VERSION) {
454 actionstream << "Server: A mismatched (strict) client tried to "
455 << "connect from " << addr_s << std::endl;
456 DenyAccess_Legacy(pkt->getPeerId(), std::wstring(
457 L"Your client's version is not supported.\n"
458 L"Server version is ")
459 + narrow_to_wide(g_version_string) + L",\n"
460 + L"server's PROTOCOL_VERSION (strict) is "
461 + narrow_to_wide(itos(LATEST_PROTOCOL_VERSION))
462 + L", client's PROTOCOL_VERSION is "
463 + narrow_to_wide(itos(min_net_proto_version))
465 + narrow_to_wide(itos(max_net_proto_version))
474 char playername[PLAYERNAME_SIZE];
475 unsigned int playername_length = 0;
476 for (; playername_length < PLAYERNAME_SIZE; playername_length++ ) {
477 playername[playername_length] = pkt->getChar(1+playername_length);
478 if (pkt->getChar(1+playername_length) == 0)
482 if (playername_length == PLAYERNAME_SIZE) {
483 actionstream << "Server: Player with name exceeding max length "
484 << "tried to connect from " << addr_s << std::endl;
485 DenyAccess_Legacy(pkt->getPeerId(), L"Name too long");
490 if (playername[0]=='\0') {
491 actionstream << "Server: Player with an empty name "
492 << "tried to connect from " << addr_s << std::endl;
493 DenyAccess_Legacy(pkt->getPeerId(), L"Empty name");
497 if (string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false) {
498 actionstream << "Server: Player with an invalid name "
499 << "tried to connect from " << addr_s << std::endl;
500 DenyAccess_Legacy(pkt->getPeerId(), L"Name contains unallowed characters");
504 if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
505 actionstream << "Server: Player with the name \"singleplayer\" "
506 << "tried to connect from " << addr_s << std::endl;
507 DenyAccess_Legacy(pkt->getPeerId(), L"Name is not allowed");
513 if (m_script->on_prejoinplayer(playername, addr_s, reason)) {
514 actionstream << "Server: Player with the name \"" << playername << "\" "
515 << "tried to connect from " << addr_s << " "
516 << "but it was disallowed for the following reason: "
517 << reason << std::endl;
518 DenyAccess_Legacy(pkt->getPeerId(), narrow_to_wide(reason.c_str()));
523 infostream<<"Server: New connection: \""<<playername<<"\" from "
524 <<addr_s<<" (peer_id="<<pkt->getPeerId()<<")"<<std::endl;
527 char given_password[PASSWORD_SIZE];
528 if (pkt->getSize() < 1 + PLAYERNAME_SIZE + PASSWORD_SIZE) {
529 // old version - assume blank password
530 given_password[0] = 0;
533 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
534 given_password[i] = pkt->getChar(21 + i);
536 given_password[PASSWORD_SIZE - 1] = 0;
539 if (!base64_is_valid(given_password)) {
540 actionstream << "Server: " << playername
541 << " supplied invalid password hash" << std::endl;
542 DenyAccess_Legacy(pkt->getPeerId(), L"Invalid password hash");
546 // Enforce user limit.
547 // Don't enforce for users that have some admin right
548 if (m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
549 !checkPriv(playername, "server") &&
550 !checkPriv(playername, "ban") &&
551 !checkPriv(playername, "privs") &&
552 !checkPriv(playername, "password") &&
553 playername != g_settings->get("name")) {
554 actionstream << "Server: " << playername << " tried to join, but there"
555 << " are already max_users="
556 << g_settings->getU16("max_users") << " players." << std::endl;
557 DenyAccess_Legacy(pkt->getPeerId(), L"Too many users.");
561 std::string checkpwd; // Password hash to check against
562 bool has_auth = m_script->getAuth(playername, &checkpwd, NULL);
564 // If no authentication info exists for user, create it
566 if (!isSingleplayer() &&
567 g_settings->getBool("disallow_empty_password") &&
568 std::string(given_password) == "") {
569 actionstream << "Server: " << playername
570 << " supplied empty password" << std::endl;
571 DenyAccess_Legacy(pkt->getPeerId(), L"Empty passwords are "
572 L"disallowed. Set a password and try again.");
575 std::wstring raw_default_password =
576 narrow_to_wide(g_settings->get("default_password"));
577 std::string initial_password =
578 translatePassword(playername, raw_default_password);
580 // If default_password is empty, allow any initial password
581 if (raw_default_password.length() == 0)
582 initial_password = given_password;
584 m_script->createAuth(playername, initial_password);
587 has_auth = m_script->getAuth(playername, &checkpwd, NULL);
590 actionstream << "Server: " << playername << " cannot be authenticated"
591 << " (auth handler does not work?)" << std::endl;
592 DenyAccess_Legacy(pkt->getPeerId(), L"Not allowed to login");
596 if (given_password != checkpwd) {
597 actionstream << "Server: " << playername << " supplied wrong password"
599 DenyAccess_Legacy(pkt->getPeerId(), L"Wrong password");
603 RemotePlayer *player =
604 static_cast<RemotePlayer*>(m_env->getPlayer(playername));
606 if (player && player->peer_id != 0) {
607 errorstream << "Server: " << playername << ": Failed to emerge player"
608 << " (player allocated to an another client)" << std::endl;
609 DenyAccess_Legacy(pkt->getPeerId(), L"Another client is connected with this "
610 L"name. If your client closed unexpectedly, try again in "
614 m_clients.setPlayerName(pkt->getPeerId(), playername);
617 Answer with a TOCLIENT_INIT
620 NetworkPacket resp_pkt(TOCLIENT_INIT_LEGACY, 1 + 6 + 8 + 4,
623 resp_pkt << (u8) deployed << (v3s16) floatToInt(v3f(0,0,0), BS)
624 << (u64) m_env->getServerMap().getSeed()
625 << g_settings->getFloat("dedicated_server_step");
628 m_clients.event(pkt->getPeerId(), CSE_Init);
631 void Server::handleCommand_Init2(NetworkPacket* pkt)
633 verbosestream << "Server: Got TOSERVER_INIT2 from "
634 << pkt->getPeerId() << std::endl;
636 m_clients.event(pkt->getPeerId(), CSE_GotInit2);
637 u16 protocol_version = m_clients.getProtocolVersion(pkt->getPeerId());
640 ///// begin compatibility code
641 PlayerSAO* playersao = NULL;
642 if (protocol_version <= 22) {
643 playersao = StageTwoClientInit(pkt->getPeerId());
645 if (playersao == NULL) {
647 << "TOSERVER_INIT2 stage 2 client init failed for peer "
648 << pkt->getPeerId() << std::endl;
652 ///// end compatibility code
655 Send some initialization data
658 infostream << "Server: Sending content to "
659 << getPlayerName(pkt->getPeerId()) << std::endl;
661 // Send player movement settings
662 SendMovement(pkt->getPeerId());
664 // Send item definitions
665 SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
667 // Send node definitions
668 SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
670 m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
672 // Send media announcement
673 sendMediaAnnouncement(pkt->getPeerId());
675 // Send detached inventories
676 sendDetachedInventories(pkt->getPeerId());
679 u16 time = m_env->getTimeOfDay();
680 float time_speed = g_settings->getFloat("time_speed");
681 SendTimeOfDay(pkt->getPeerId(), time, time_speed);
683 ///// begin compatibility code
684 if (protocol_version <= 22) {
685 m_clients.event(pkt->getPeerId(), CSE_SetClientReady);
686 m_script->on_joinplayer(playersao);
688 ///// end compatibility code
690 // Warnings about protocol version can be issued here
691 if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
692 SendChatMessage(pkt->getPeerId(), L"# Server: WARNING: YOUR CLIENT'S "
693 L"VERSION MAY NOT BE FULLY COMPATIBLE WITH THIS SERVER!");
697 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
699 std::vector<std::string> tosend;
704 infostream << "Sending " << numfiles << " files to "
705 << getPlayerName(pkt->getPeerId()) << std::endl;
706 verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
708 for (u16 i = 0; i < numfiles; i++) {
713 tosend.push_back(name);
714 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
715 << name << std::endl;
718 sendRequestedMedia(pkt->getPeerId(), tosend);
721 void Server::handleCommand_ReceivedMedia(NetworkPacket* pkt)
725 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
727 u16 peer_id = pkt->getPeerId();
728 u16 peer_proto_ver = getClient(peer_id, CS_InitDone)->net_proto_version;
730 // clients <= protocol version 22 did not send ready message,
731 // they're already initialized
732 if (peer_proto_ver <= 22) {
733 infostream << "Client sent message not expected by a "
734 << "client using protocol version <= 22,"
735 << "disconnecting peer_id: " << peer_id << std::endl;
736 m_con.DisconnectPeer(peer_id);
740 PlayerSAO* playersao = StageTwoClientInit(peer_id);
742 if (playersao == NULL) {
744 << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
745 << peer_id << std::endl;
746 m_con.DisconnectPeer(peer_id);
751 if (pkt->getSize() < 8) {
753 << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
754 << peer_id << std::endl;
755 m_con.DisconnectPeer(peer_id);
759 u8 major_ver, minor_ver, patch_ver, reserved;
760 std::string full_ver;
761 *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
763 m_clients.setClientVersion(
764 peer_id, major_ver, minor_ver, patch_ver,
767 m_clients.event(peer_id, CSE_SetClientReady);
768 m_script->on_joinplayer(playersao);
771 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
773 if (pkt->getSize() < 1)
787 RemoteClient *client = getClient(pkt->getPeerId());
789 for (u16 i = 0; i < count; i++) {
790 if ((s16)pkt->getSize() < 1 + (i + 1) * 6)
791 throw con::InvalidIncomingDataException
792 ("GOTBLOCKS length is too short");
801 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
803 if (pkt->getSize() < 12 + 12 + 4 + 4)
807 s32 f32pitch, f32yaw;
814 f32 pitch = (f32)f32pitch / 100.0;
815 f32 yaw = (f32)f32yaw / 100.0;
818 if (pkt->getSize() >= 12 + 12 + 4 + 4 + 4)
821 v3f position((f32)ps.X / 100.0, (f32)ps.Y / 100.0, (f32)ps.Z / 100.0);
822 v3f speed((f32)ss.X / 100.0, (f32)ss.Y / 100.0, (f32)ss.Z / 100.0);
824 pitch = modulo360f(pitch);
825 yaw = modulo360f(yaw);
827 Player *player = m_env->getPlayer(pkt->getPeerId());
828 if (player == NULL) {
829 errorstream << "Server::ProcessData(): Canceling: "
830 "No player for peer_id=" << pkt->getPeerId()
831 << " disconnecting peer!" << std::endl;
832 m_con.DisconnectPeer(pkt->getPeerId());
836 // If player is dead we don't care of this packet
837 if (player->isDead()) {
838 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
839 << " is dead. Ignoring packet";
843 PlayerSAO *playersao = player->getPlayerSAO();
844 if (playersao == NULL) {
845 errorstream << "Server::ProcessData(): Canceling: "
846 "No player object for peer_id=" << pkt->getPeerId()
847 << " disconnecting peer!" << std::endl;
848 m_con.DisconnectPeer(pkt->getPeerId());
852 player->setPosition(position);
853 player->setSpeed(speed);
854 player->setPitch(pitch);
856 player->keyPressed = keyPressed;
857 player->control.up = (keyPressed & 1);
858 player->control.down = (keyPressed & 2);
859 player->control.left = (keyPressed & 4);
860 player->control.right = (keyPressed & 8);
861 player->control.jump = (keyPressed & 16);
862 player->control.aux1 = (keyPressed & 32);
863 player->control.sneak = (keyPressed & 64);
864 player->control.LMB = (keyPressed & 128);
865 player->control.RMB = (keyPressed & 256);
867 if (playersao->checkMovementCheat()) {
869 m_script->on_cheat(playersao, "moved_too_fast");
870 SendMovePlayer(pkt->getPeerId());
874 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
876 if (pkt->getSize() < 1)
890 RemoteClient *client = getClient(pkt->getPeerId());
892 for (u16 i = 0; i < count; i++) {
893 if ((s16)pkt->getSize() < 1 + (i + 1) * 6)
894 throw con::InvalidIncomingDataException
895 ("DELETEDBLOCKS length is too short");
899 client->SetBlockNotSent(p);
903 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
905 Player *player = m_env->getPlayer(pkt->getPeerId());
906 if (player == NULL) {
907 errorstream << "Server::ProcessData(): Canceling: "
908 "No player for peer_id=" << pkt->getPeerId()
909 << " disconnecting peer!" << std::endl;
910 m_con.DisconnectPeer(pkt->getPeerId());
914 PlayerSAO *playersao = player->getPlayerSAO();
915 if (playersao == NULL) {
916 errorstream << "Server::ProcessData(): Canceling: "
917 "No player object for peer_id=" << pkt->getPeerId()
918 << " disconnecting peer!" << std::endl;
919 m_con.DisconnectPeer(pkt->getPeerId());
923 // Strip command and create a stream
924 std::string datastring(pkt->getString(0), pkt->getSize());
925 verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
927 std::istringstream is(datastring, std::ios_base::binary);
929 InventoryAction *a = InventoryAction::deSerialize(is);
931 infostream << "TOSERVER_INVENTORY_ACTION: "
932 << "InventoryAction::deSerialize() returned NULL"
937 // If something goes wrong, this player is to blame
938 RollbackScopeActor rollback_scope(m_rollback,
939 std::string("player:")+player->getName());
942 Note: Always set inventory not sent, to repair cases
943 where the client made a bad prediction.
947 Handle restrictions and special cases of the move action
949 if (a->getType() == IACTION_MOVE) {
950 IMoveAction *ma = (IMoveAction*)a;
952 ma->from_inv.applyCurrentPlayer(player->getName());
953 ma->to_inv.applyCurrentPlayer(player->getName());
955 setInventoryModified(ma->from_inv, false);
956 setInventoryModified(ma->to_inv, false);
958 bool from_inv_is_current_player =
959 (ma->from_inv.type == InventoryLocation::PLAYER) &&
960 (ma->from_inv.name == player->getName());
962 bool to_inv_is_current_player =
963 (ma->to_inv.type == InventoryLocation::PLAYER) &&
964 (ma->to_inv.name == player->getName());
967 Disable moving items out of craftpreview
969 if (ma->from_list == "craftpreview") {
970 infostream << "Ignoring IMoveAction from "
971 << (ma->from_inv.dump()) << ":" << ma->from_list
972 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
973 << " because src is " << ma->from_list << std::endl;
979 Disable moving items into craftresult and craftpreview
981 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
982 infostream << "Ignoring IMoveAction from "
983 << (ma->from_inv.dump()) << ":" << ma->from_list
984 << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
985 << " because dst is " << ma->to_list << std::endl;
990 // Disallow moving items in elsewhere than player's inventory
991 // if not allowed to interact
992 if (!checkPriv(player->getName(), "interact") &&
993 (!from_inv_is_current_player ||
994 !to_inv_is_current_player)) {
995 infostream << "Cannot move outside of player's inventory: "
996 << "No interact privilege" << std::endl;
1002 Handle restrictions and special cases of the drop action
1004 else if (a->getType() == IACTION_DROP) {
1005 IDropAction *da = (IDropAction*)a;
1007 da->from_inv.applyCurrentPlayer(player->getName());
1009 setInventoryModified(da->from_inv, false);
1012 Disable dropping items out of craftpreview
1014 if (da->from_list == "craftpreview") {
1015 infostream << "Ignoring IDropAction from "
1016 << (da->from_inv.dump()) << ":" << da->from_list
1017 << " because src is " << da->from_list << std::endl;
1022 // Disallow dropping items if not allowed to interact
1023 if (!checkPriv(player->getName(), "interact")) {
1029 Handle restrictions and special cases of the craft action
1031 else if (a->getType() == IACTION_CRAFT) {
1032 ICraftAction *ca = (ICraftAction*)a;
1034 ca->craft_inv.applyCurrentPlayer(player->getName());
1036 setInventoryModified(ca->craft_inv, false);
1038 //bool craft_inv_is_current_player =
1039 // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
1040 // (ca->craft_inv.name == player->getName());
1042 // Disallow crafting if not allowed to interact
1043 if (!checkPriv(player->getName(), "interact")) {
1044 infostream << "Cannot craft: "
1045 << "No interact privilege" << std::endl;
1052 a->apply(this, playersao, this);
1056 SendInventory(playersao);
1059 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
1069 std::wstring message;
1070 for (u16 i = 0; i < len; i++) {
1074 message += (wchar_t)tmp_wchar;
1077 Player *player = m_env->getPlayer(pkt->getPeerId());
1078 if (player == NULL) {
1079 errorstream << "Server::ProcessData(): Canceling: "
1080 "No player for peer_id=" << pkt->getPeerId()
1081 << " disconnecting peer!" << std::endl;
1082 m_con.DisconnectPeer(pkt->getPeerId());
1086 // If something goes wrong, this player is to blame
1087 RollbackScopeActor rollback_scope(m_rollback,
1088 std::string("player:")+player->getName());
1090 // Get player name of this client
1091 std::wstring name = narrow_to_wide(player->getName());
1094 bool ate = m_script->on_chat_message(player->getName(),
1095 wide_to_narrow(message));
1096 // If script ate the message, don't proceed
1100 // Line to send to players
1102 // Whether to send to the player that sent the line
1103 bool send_to_sender_only = false;
1105 // Commands are implemented in Lua, so only catch invalid
1106 // commands that were not "eaten" and send an error back
1107 if (message[0] == L'/') {
1108 message = message.substr(1);
1109 send_to_sender_only = true;
1110 if (message.length() == 0)
1111 line += L"-!- Empty command";
1113 line += L"-!- Invalid command: " + str_split(message, L' ')[0];
1116 if (checkPriv(player->getName(), "shout")) {
1122 line += L"-!- You don't have permission to shout.";
1123 send_to_sender_only = true;
1130 Send the message to sender
1132 if (send_to_sender_only) {
1133 SendChatMessage(pkt->getPeerId(), line);
1136 Send the message to others
1139 actionstream << "CHAT: " << wide_to_narrow(line)<<std::endl;
1141 std::vector<u16> clients = m_clients.getClientIDs();
1143 for (std::vector<u16>::iterator i = clients.begin();
1144 i != clients.end(); ++i) {
1145 if (*i != pkt->getPeerId())
1146 SendChatMessage(*i, line);
1152 void Server::handleCommand_Damage(NetworkPacket* pkt)
1158 Player *player = m_env->getPlayer(pkt->getPeerId());
1159 if (player == NULL) {
1160 errorstream << "Server::ProcessData(): Canceling: "
1161 "No player for peer_id=" << pkt->getPeerId()
1162 << " disconnecting peer!" << std::endl;
1163 m_con.DisconnectPeer(pkt->getPeerId());
1167 PlayerSAO *playersao = player->getPlayerSAO();
1168 if (playersao == NULL) {
1169 errorstream << "Server::ProcessData(): Canceling: "
1170 "No player object for peer_id=" << pkt->getPeerId()
1171 << " disconnecting peer!" << std::endl;
1172 m_con.DisconnectPeer(pkt->getPeerId());
1176 if (g_settings->getBool("enable_damage")) {
1177 actionstream << player->getName() << " damaged by "
1178 << (int)damage << " hp at " << PP(player->getPosition() / BS)
1181 playersao->setHP(playersao->getHP() - damage);
1182 SendPlayerHPOrDie(playersao->getPeerID(), playersao->getHP() == 0);
1186 void Server::handleCommand_Breath(NetworkPacket* pkt)
1192 Player *player = m_env->getPlayer(pkt->getPeerId());
1193 if (player == NULL) {
1194 errorstream << "Server::ProcessData(): Canceling: "
1195 "No player for peer_id=" << pkt->getPeerId()
1196 << " disconnecting peer!" << std::endl;
1197 m_con.DisconnectPeer(pkt->getPeerId());
1202 * If player is dead, we don't need to update the breath
1205 if (player->isDead()) {
1206 verbosestream << "TOSERVER_BREATH: " << player->getName()
1207 << " is dead. Ignoring packet";
1212 PlayerSAO *playersao = player->getPlayerSAO();
1213 if (playersao == NULL) {
1214 errorstream << "Server::ProcessData(): Canceling: "
1215 "No player object for peer_id=" << pkt->getPeerId()
1216 << " disconnecting peer!" << std::endl;
1217 m_con.DisconnectPeer(pkt->getPeerId());
1221 playersao->setBreath(breath);
1222 SendPlayerBreath(pkt->getPeerId());
1225 void Server::handleCommand_Password(NetworkPacket* pkt)
1227 errorstream << "PAssword packet size: " << pkt->getSize() << " size required: " << PASSWORD_SIZE * 2 << std::endl;
1228 if ((pkt->getCommand() == TOSERVER_PASSWORD && pkt->getSize() < 4) ||
1229 pkt->getSize() != PASSWORD_SIZE * 2)
1235 if (pkt->getCommand() == TOSERVER_PASSWORD) {
1236 *pkt >> oldpwd >> newpwd;
1239 // Protocol v24 compat. Please remove in 1 year after
1240 // client convergence to 0.4.13/0.5.x
1242 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1243 char c = pkt->getChar(i);
1249 for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1250 char c = pkt->getChar(PASSWORD_SIZE + i);
1257 Player *player = m_env->getPlayer(pkt->getPeerId());
1258 if (player == NULL) {
1259 errorstream << "Server::ProcessData(): Canceling: "
1260 "No player for peer_id=" << pkt->getPeerId()
1261 << " disconnecting peer!" << std::endl;
1262 m_con.DisconnectPeer(pkt->getPeerId());
1266 if (!base64_is_valid(newpwd)) {
1267 infostream<<"Server: " << player->getName() <<
1268 " supplied invalid password hash" << std::endl;
1269 // Wrong old password supplied!!
1270 SendChatMessage(pkt->getPeerId(), L"Invalid new password hash supplied. Password NOT changed.");
1274 infostream << "Server: Client requests a password change from "
1275 << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
1277 std::string playername = player->getName();
1279 std::string checkpwd;
1280 m_script->getAuth(playername, &checkpwd, NULL);
1282 if (oldpwd != checkpwd) {
1283 infostream << "Server: invalid old password" << std::endl;
1284 // Wrong old password supplied!!
1285 SendChatMessage(pkt->getPeerId(), L"Invalid old password supplied. Password NOT changed.");
1289 bool success = m_script->setPassword(playername, newpwd);
1291 actionstream << player->getName() << " changes password" << std::endl;
1292 SendChatMessage(pkt->getPeerId(), L"Password change successful.");
1294 actionstream << player->getName() << " tries to change password but "
1295 << "it fails" << std::endl;
1296 SendChatMessage(pkt->getPeerId(), L"Password change failed or unavailable.");
1300 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
1302 if (pkt->getSize() < 2)
1305 Player *player = m_env->getPlayer(pkt->getPeerId());
1306 if (player == NULL) {
1307 errorstream << "Server::ProcessData(): Canceling: "
1308 "No player for peer_id=" << pkt->getPeerId()
1309 << " disconnecting peer!" << std::endl;
1310 m_con.DisconnectPeer(pkt->getPeerId());
1314 PlayerSAO *playersao = player->getPlayerSAO();
1315 if (playersao == NULL) {
1316 errorstream << "Server::ProcessData(): Canceling: "
1317 "No player object for peer_id=" << pkt->getPeerId()
1318 << " disconnecting peer!" << std::endl;
1319 m_con.DisconnectPeer(pkt->getPeerId());
1327 playersao->setWieldIndex(item);
1330 void Server::handleCommand_Respawn(NetworkPacket* pkt)
1332 Player *player = m_env->getPlayer(pkt->getPeerId());
1333 if (player == NULL) {
1334 errorstream << "Server::ProcessData(): Canceling: "
1335 "No player for peer_id=" << pkt->getPeerId()
1336 << " disconnecting peer!" << std::endl;
1337 m_con.DisconnectPeer(pkt->getPeerId());
1341 if (!player->isDead())
1344 RespawnPlayer(pkt->getPeerId());
1346 actionstream << player->getName() << " respawns at "
1347 << PP(player->getPosition()/BS) << std::endl;
1349 // ActiveObject is added to environment in AsyncRunStep after
1350 // the previous addition has been successfully removed
1353 void Server::handleCommand_Interact(NetworkPacket* pkt)
1355 std::string datastring(pkt->getString(0), pkt->getSize());
1356 std::istringstream is(datastring, std::ios_base::binary);
1362 [5] u32 length of the next item
1363 [9] serialized PointedThing
1365 0: start digging (from undersurface) or use
1366 1: stop digging (all parameters ignored)
1367 2: digging completed
1368 3: place block or item (to abovesurface)
1371 u8 action = readU8(is);
1372 u16 item_i = readU16(is);
1373 std::istringstream tmp_is(deSerializeLongString(is), std::ios::binary);
1374 PointedThing pointed;
1375 pointed.deSerialize(tmp_is);
1377 verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
1378 << item_i << ", pointed=" << pointed.dump() << std::endl;
1380 Player *player = m_env->getPlayer(pkt->getPeerId());
1381 if (player == NULL) {
1382 errorstream << "Server::ProcessData(): Canceling: "
1383 "No player for peer_id=" << pkt->getPeerId()
1384 << " disconnecting peer!" << std::endl;
1385 m_con.DisconnectPeer(pkt->getPeerId());
1389 PlayerSAO *playersao = player->getPlayerSAO();
1390 if (playersao == NULL) {
1391 errorstream << "Server::ProcessData(): Canceling: "
1392 "No player object for peer_id=" << pkt->getPeerId()
1393 << " disconnecting peer!" << std::endl;
1394 m_con.DisconnectPeer(pkt->getPeerId());
1398 if (player->isDead()) {
1399 verbosestream << "TOSERVER_INTERACT: " << player->getName()
1400 << " is dead. Ignoring packet";
1404 v3f player_pos = playersao->getLastGoodPosition();
1406 // Update wielded item
1407 playersao->setWieldIndex(item_i);
1409 // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1410 v3s16 p_under = pointed.node_undersurface;
1411 v3s16 p_above = pointed.node_abovesurface;
1413 // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1414 ServerActiveObject *pointed_object = NULL;
1415 if (pointed.type == POINTEDTHING_OBJECT) {
1416 pointed_object = m_env->getActiveObject(pointed.object_id);
1417 if (pointed_object == NULL) {
1418 verbosestream << "TOSERVER_INTERACT: "
1419 "pointed object is NULL" << std::endl;
1425 v3f pointed_pos_under = player_pos;
1426 v3f pointed_pos_above = player_pos;
1427 if (pointed.type == POINTEDTHING_NODE) {
1428 pointed_pos_under = intToFloat(p_under, BS);
1429 pointed_pos_above = intToFloat(p_above, BS);
1431 else if (pointed.type == POINTEDTHING_OBJECT) {
1432 pointed_pos_under = pointed_object->getBasePosition();
1433 pointed_pos_above = pointed_pos_under;
1437 Check that target is reasonably close
1438 (only when digging or placing things)
1440 if (action == 0 || action == 2 || action == 3) {
1441 float d = player_pos.getDistanceFrom(pointed_pos_under);
1442 float max_d = BS * 14; // Just some large enough value
1444 actionstream << "Player " << player->getName()
1445 << " tried to access " << pointed.dump()
1446 << " from too far: "
1447 << "d=" << d <<", max_d=" << max_d
1448 << ". ignoring." << std::endl;
1449 // Re-send block to revert change on client-side
1450 RemoteClient *client = getClient(pkt->getPeerId());
1451 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1452 client->SetBlockNotSent(blockpos);
1454 m_script->on_cheat(playersao, "interacted_too_far");
1461 Make sure the player is allowed to do it
1463 if (!checkPriv(player->getName(), "interact")) {
1464 actionstream<<player->getName()<<" attempted to interact with "
1465 <<pointed.dump()<<" without 'interact' privilege"
1467 // Re-send block to revert change on client-side
1468 RemoteClient *client = getClient(pkt->getPeerId());
1469 // Digging completed -> under
1471 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1472 client->SetBlockNotSent(blockpos);
1474 // Placement -> above
1476 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1477 client->SetBlockNotSent(blockpos);
1483 If something goes wrong, this player is to blame
1485 RollbackScopeActor rollback_scope(m_rollback,
1486 std::string("player:")+player->getName());
1489 0: start digging or punch object
1492 if (pointed.type == POINTEDTHING_NODE) {
1494 NOTE: This can be used in the future to check if
1495 somebody is cheating, by checking the timing.
1497 MapNode n(CONTENT_IGNORE);
1499 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1501 n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1504 infostream << "Server: Not punching: Node not found."
1505 << " Adding block to emerge queue."
1507 m_emerge->enqueueBlockEmerge(pkt->getPeerId(), getNodeBlockPos(p_above), false);
1510 if (n.getContent() != CONTENT_IGNORE)
1511 m_script->node_on_punch(p_under, n, playersao, pointed);
1513 playersao->noCheatDigStart(p_under);
1515 else if (pointed.type == POINTEDTHING_OBJECT) {
1516 // Skip if object has been removed
1517 if (pointed_object->m_removed)
1520 actionstream<<player->getName()<<" punches object "
1521 <<pointed.object_id<<": "
1522 <<pointed_object->getDescription()<<std::endl;
1524 ItemStack punchitem = playersao->getWieldedItem();
1525 ToolCapabilities toolcap =
1526 punchitem.getToolCapabilities(m_itemdef);
1527 v3f dir = (pointed_object->getBasePosition() -
1528 (player->getPosition() + player->getEyeOffset())
1530 float time_from_last_punch =
1531 playersao->resetTimeFromLastPunch();
1533 s16 src_original_hp = pointed_object->getHP();
1534 s16 dst_origin_hp = playersao->getHP();
1536 pointed_object->punch(dir, &toolcap, playersao,
1537 time_from_last_punch);
1539 // If the object is a player and its HP changed
1540 if (src_original_hp != pointed_object->getHP() &&
1541 pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1542 SendPlayerHPOrDie(((PlayerSAO*)pointed_object)->getPeerID(),
1543 pointed_object->getHP() == 0);
1546 // If the puncher is a player and its HP changed
1547 if (dst_origin_hp != playersao->getHP()) {
1548 SendPlayerHPOrDie(playersao->getPeerID(), playersao->getHP() == 0);
1557 else if (action == 1) {
1561 2: Digging completed
1563 else if (action == 2) {
1564 // Only digging of nodes
1565 if (pointed.type == POINTEDTHING_NODE) {
1567 MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1569 infostream << "Server: Not finishing digging: Node not found."
1570 << " Adding block to emerge queue."
1572 m_emerge->enqueueBlockEmerge(pkt->getPeerId(), getNodeBlockPos(p_above), false);
1575 /* Cheat prevention */
1576 bool is_valid_dig = true;
1577 if (!isSingleplayer() && !g_settings->getBool("disable_anticheat")) {
1578 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1579 float nocheat_t = playersao->getNoCheatDigTime();
1580 playersao->noCheatDigEnd();
1581 // If player didn't start digging this, ignore dig
1582 if (nocheat_p != p_under) {
1583 infostream << "Server: NoCheat: " << player->getName()
1584 << " started digging "
1585 << PP(nocheat_p) << " and completed digging "
1586 << PP(p_under) << "; not digging." << std::endl;
1587 is_valid_dig = false;
1589 m_script->on_cheat(playersao, "finished_unknown_dig");
1591 // Get player's wielded item
1592 ItemStack playeritem;
1593 InventoryList *mlist = playersao->getInventory()->getList("main");
1595 playeritem = mlist->getItem(playersao->getWieldIndex());
1596 ToolCapabilities playeritem_toolcap =
1597 playeritem.getToolCapabilities(m_itemdef);
1598 // Get diggability and expected digging time
1599 DigParams params = getDigParams(m_nodedef->get(n).groups,
1600 &playeritem_toolcap);
1601 // If can't dig, try hand
1602 if (!params.diggable) {
1603 const ItemDefinition &hand = m_itemdef->get("");
1604 const ToolCapabilities *tp = hand.tool_capabilities;
1606 params = getDigParams(m_nodedef->get(n).groups, tp);
1608 // If can't dig, ignore dig
1609 if (!params.diggable) {
1610 infostream << "Server: NoCheat: " << player->getName()
1611 << " completed digging " << PP(p_under)
1612 << ", which is not diggable with tool. not digging."
1614 is_valid_dig = false;
1616 m_script->on_cheat(playersao, "dug_unbreakable");
1618 // Check digging time
1619 // If already invalidated, we don't have to
1620 if (!is_valid_dig) {
1621 // Well not our problem then
1623 // Clean and long dig
1624 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1625 // All is good, but grab time from pool; don't care if
1626 // it's actually available
1627 playersao->getDigPool().grab(params.time);
1629 // Short or laggy dig
1630 // Try getting the time from pool
1631 else if (playersao->getDigPool().grab(params.time)) {
1636 infostream << "Server: NoCheat: " << player->getName()
1637 << " completed digging " << PP(p_under)
1638 << "too fast; not digging." << std::endl;
1639 is_valid_dig = false;
1641 m_script->on_cheat(playersao, "dug_too_fast");
1645 /* Actually dig node */
1647 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1648 m_script->node_on_dig(p_under, n, playersao);
1650 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1651 RemoteClient *client = getClient(pkt->getPeerId());
1652 // Send unusual result (that is, node not being removed)
1653 if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1654 // Re-send block to revert change on client-side
1655 client->SetBlockNotSent(blockpos);
1658 client->ResendBlockIfOnWire(blockpos);
1664 3: place block or right-click object
1666 else if (action == 3) {
1667 ItemStack item = playersao->getWieldedItem();
1669 // Reset build time counter
1670 if (pointed.type == POINTEDTHING_NODE &&
1671 item.getDefinition(m_itemdef).type == ITEM_NODE)
1672 getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1674 if (pointed.type == POINTEDTHING_OBJECT) {
1675 // Right click object
1677 // Skip if object has been removed
1678 if (pointed_object->m_removed)
1681 actionstream << player->getName() << " right-clicks object "
1682 << pointed.object_id << ": "
1683 << pointed_object->getDescription() << std::endl;
1686 pointed_object->rightClick(playersao);
1688 else if (m_script->item_OnPlace(
1689 item, playersao, pointed)) {
1690 // Placement was handled in lua
1692 // Apply returned ItemStack
1693 if (playersao->setWieldedItem(item)) {
1694 SendInventory(playersao);
1698 // If item has node placement prediction, always send the
1699 // blocks to make sure the client knows what exactly happened
1700 RemoteClient *client = getClient(pkt->getPeerId());
1701 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1702 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1703 if (item.getDefinition(m_itemdef).node_placement_prediction != "") {
1704 client->SetBlockNotSent(blockpos);
1705 if (blockpos2 != blockpos) {
1706 client->SetBlockNotSent(blockpos2);
1710 client->ResendBlockIfOnWire(blockpos);
1711 if (blockpos2 != blockpos) {
1712 client->ResendBlockIfOnWire(blockpos2);
1720 else if (action == 4) {
1721 ItemStack item = playersao->getWieldedItem();
1723 actionstream << player->getName() << " uses " << item.name
1724 << ", pointing at " << pointed.dump() << std::endl;
1726 if (m_script->item_OnUse(
1727 item, playersao, pointed)) {
1728 // Apply returned ItemStack
1729 if (playersao->setWieldedItem(item)) {
1730 SendInventory(playersao);
1738 Catch invalid actions
1741 infostream << "WARNING: Server: Invalid action "
1742 << action << std::endl;
1746 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1750 for (u16 k = 0; k < num; k++) {
1755 std::map<s32, ServerPlayingSound>::iterator i =
1756 m_playing_sounds.find(id);
1758 if (i == m_playing_sounds.end())
1761 ServerPlayingSound &psound = i->second;
1762 psound.clients.erase(pkt->getPeerId());
1763 if (psound.clients.empty())
1764 m_playing_sounds.erase(i++);
1768 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1771 std::string formname;
1774 *pkt >> p >> formname >> num;
1776 std::map<std::string, std::string> fields;
1777 for (u16 k = 0; k < num; k++) {
1778 std::string fieldname;
1780 fields[fieldname] = pkt->readLongString();
1783 Player *player = m_env->getPlayer(pkt->getPeerId());
1784 if (player == NULL) {
1785 errorstream << "Server::ProcessData(): Canceling: "
1786 "No player for peer_id=" << pkt->getPeerId()
1787 << " disconnecting peer!" << std::endl;
1788 m_con.DisconnectPeer(pkt->getPeerId());
1792 PlayerSAO *playersao = player->getPlayerSAO();
1793 if (playersao == NULL) {
1794 errorstream << "Server::ProcessData(): Canceling: "
1795 "No player object for peer_id=" << pkt->getPeerId()
1796 << " disconnecting peer!" << std::endl;
1797 m_con.DisconnectPeer(pkt->getPeerId());
1801 // If something goes wrong, this player is to blame
1802 RollbackScopeActor rollback_scope(m_rollback,
1803 std::string("player:")+player->getName());
1805 // Check the target node for rollback data; leave others unnoticed
1806 RollbackNode rn_old(&m_env->getMap(), p, this);
1808 m_script->node_on_receive_fields(p, formname, fields, playersao);
1810 // Report rollback data
1811 RollbackNode rn_new(&m_env->getMap(), p, this);
1812 if (rollback() && rn_new != rn_old) {
1813 RollbackAction action;
1814 action.setSetNode(p, rn_old, rn_new);
1815 rollback()->reportAction(action);
1819 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1821 std::string formname;
1824 *pkt >> formname >> num;
1826 std::map<std::string, std::string> fields;
1827 for (u16 k = 0; k < num; k++) {
1828 std::string fieldname;
1830 fields[fieldname] = pkt->readLongString();
1833 Player *player = m_env->getPlayer(pkt->getPeerId());
1834 if (player == NULL) {
1835 errorstream << "Server::ProcessData(): Canceling: "
1836 "No player for peer_id=" << pkt->getPeerId()
1837 << " disconnecting peer!" << std::endl;
1838 m_con.DisconnectPeer(pkt->getPeerId());
1842 PlayerSAO *playersao = player->getPlayerSAO();
1843 if (playersao == NULL) {
1844 errorstream << "Server::ProcessData(): Canceling: "
1845 "No player object for peer_id=" << pkt->getPeerId()
1846 << " disconnecting peer!" << std::endl;
1847 m_con.DisconnectPeer(pkt->getPeerId());
1851 m_script->on_playerReceiveFields(playersao, formname, fields);