]> git.lizzy.rs Git - minetest.git/blob - src/network/serverpackethandler.cpp
Dual wielding
[minetest.git] / src / network / serverpackethandler.cpp
1 /*
2 Minetest
3 Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
4
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.
9
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.
14
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.
18 */
19
20 #include "chatmessage.h"
21 #include "server.h"
22 #include "log.h"
23 #include "emerge.h"
24 #include "mapblock.h"
25 #include "modchannels.h"
26 #include "nodedef.h"
27 #include "remoteplayer.h"
28 #include "rollback_interface.h"
29 #include "scripting_server.h"
30 #include "settings.h"
31 #include "tool.h"
32 #include "version.h"
33 #include "network/connection.h"
34 #include "network/networkprotocol.h"
35 #include "network/serveropcodes.h"
36 #include "server/player_sao.h"
37 #include "server/serverinventorymgr.h"
38 #include "util/auth.h"
39 #include "util/base64.h"
40 #include "util/pointedthing.h"
41 #include "util/serialize.h"
42 #include "util/srp.h"
43 #include "clientdynamicinfo.h"
44
45 void Server::handleCommand_Deprecated(NetworkPacket* pkt)
46 {
47         infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
48                 << " not supported anymore" << std::endl;
49 }
50
51 void Server::handleCommand_Init(NetworkPacket* pkt)
52 {
53
54         if(pkt->getSize() < 1)
55                 return;
56
57         session_t peer_id = pkt->getPeerId();
58         RemoteClient *client = getClient(peer_id, CS_Created);
59
60         Address addr;
61         std::string addr_s;
62         try {
63                 addr = m_con->GetPeerAddress(peer_id);
64                 addr_s = addr.serializeString();
65         } catch (con::PeerNotFoundException &e) {
66                 /*
67                  * no peer for this packet found
68                  * most common reason is peer timeout, e.g. peer didn't
69                  * respond for some time, your server was overloaded or
70                  * things like that.
71                  */
72                 infostream << "Server::ProcessData(): Canceling: peer " << peer_id <<
73                         " not found" << std::endl;
74                 return;
75         }
76
77         if (client->getState() > CS_Created) {
78                 verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " <<
79                         addr_s << " (peer_id=" << peer_id << ")" << std::endl;
80                 return;
81         }
82
83         client->setCachedAddress(addr);
84
85         verbosestream << "Server: Got TOSERVER_INIT from " << addr_s <<
86                 " (peer_id=" << peer_id << ")" << std::endl;
87
88         // Do not allow multiple players in simple singleplayer mode.
89         // This isn't a perfect way to do it, but will suffice for now
90         if (m_simple_singleplayer_mode && !m_clients.getClientIDs().empty()) {
91                 infostream << "Server: Not allowing another client (" << addr_s <<
92                         ") to connect in simple singleplayer mode" << std::endl;
93                 DenyAccess(peer_id, SERVER_ACCESSDENIED_SINGLEPLAYER);
94                 return;
95         }
96
97         // First byte after command is maximum supported
98         // serialization version
99         u8 client_max;
100         u16 supp_compr_modes;
101         u16 min_net_proto_version = 0;
102         u16 max_net_proto_version;
103         std::string playerName;
104
105         *pkt >> client_max >> supp_compr_modes >> min_net_proto_version
106                         >> max_net_proto_version >> playerName;
107
108         u8 our_max = SER_FMT_VER_HIGHEST_READ;
109         // Use the highest version supported by both
110         u8 depl_serial_v = std::min(client_max, our_max);
111         // If it's lower than the lowest supported, give up.
112 #if SER_FMT_VER_LOWEST_READ > 0
113         if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
114                 depl_serial_v = SER_FMT_VER_INVALID;
115 #endif
116
117         if (depl_serial_v == SER_FMT_VER_INVALID) {
118                 actionstream << "Server: A mismatched client tried to connect from " <<
119                         addr_s << " ser_fmt_max=" << (int)client_max << std::endl;
120                 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
121                 return;
122         }
123
124         client->setPendingSerializationVersion(depl_serial_v);
125
126         /*
127                 Read and check network protocol version
128         */
129
130         u16 net_proto_version = 0;
131
132         // Figure out a working version if it is possible at all
133         if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
134                         min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
135                 // If maximum is larger than our maximum, go with our maximum
136                 if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
137                         net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
138                 // Else go with client's maximum
139                 else
140                         net_proto_version = max_net_proto_version;
141         }
142
143         verbosestream << "Server: " << addr_s << ": Protocol version: min: "
144                         << min_net_proto_version << ", max: " << max_net_proto_version
145                         << ", chosen: " << net_proto_version << std::endl;
146
147         client->net_proto_version = net_proto_version;
148
149         if ((g_settings->getBool("strict_protocol_version_checking") &&
150                         net_proto_version != LATEST_PROTOCOL_VERSION) ||
151                         net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
152                         net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
153                 actionstream << "Server: A mismatched client tried to connect from " <<
154                         addr_s << " proto_max=" << (int)max_net_proto_version << std::endl;
155                 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_VERSION);
156                 return;
157         }
158
159         /*
160                 Validate player name
161         */
162         const char* playername = playerName.c_str();
163
164         size_t pns = playerName.size();
165         if (pns == 0 || pns > PLAYERNAME_SIZE) {
166                 actionstream << "Server: Player with " <<
167                         ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty") <<
168                         " name tried to connect from " << addr_s << std::endl;
169                 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
170                 return;
171         }
172
173         if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
174                 actionstream << "Server: Player with an invalid name tried to connect "
175                         "from " << addr_s << std::endl;
176                 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
177                 return;
178         }
179
180         RemotePlayer *player = m_env->getPlayer(playername);
181
182         // If player is already connected, cancel
183         if (player && player->getPeerId() != PEER_ID_INEXISTENT) {
184                 actionstream << "Server: Player with name \"" << playername <<
185                         "\" tried to connect, but player with same name is already connected" << std::endl;
186                 DenyAccess(peer_id, SERVER_ACCESSDENIED_ALREADY_CONNECTED);
187                 return;
188         }
189
190         m_clients.setPlayerName(peer_id, playername);
191         //TODO (later) case insensitivity
192
193         std::string legacyPlayerNameCasing = playerName;
194
195         if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
196                 actionstream << "Server: Player with the name \"singleplayer\" tried "
197                         "to connect from " << addr_s << std::endl;
198                 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_NAME);
199                 return;
200         }
201
202         {
203                 std::string reason;
204                 if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
205                         actionstream << "Server: Player with the name \"" << playerName <<
206                                 "\" tried to connect from " << addr_s <<
207                                 " but it was disallowed for the following reason: " << reason <<
208                                 std::endl;
209                         DenyAccess(peer_id, SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
210                         return;
211                 }
212         }
213
214         infostream << "Server: New connection: \"" << playerName << "\" from " <<
215                 addr_s << " (peer_id=" << peer_id << ")" << std::endl;
216
217         // Enforce user limit.
218         // Don't enforce for users that have some admin right or mod permits it.
219         if (m_clients.isUserLimitReached() &&
220                         playername != g_settings->get("name") &&
221                         !m_script->can_bypass_userlimit(playername, addr_s)) {
222                 actionstream << "Server: " << playername << " tried to join from " <<
223                         addr_s << ", but there are already max_users=" <<
224                         g_settings->getU16("max_users") << " players." << std::endl;
225                 DenyAccess(peer_id, SERVER_ACCESSDENIED_TOO_MANY_USERS);
226                 return;
227         }
228
229         /*
230                 Compose auth methods for answer
231         */
232         std::string encpwd; // encrypted Password field for the user
233         bool has_auth = m_script->getAuth(playername, &encpwd, nullptr);
234         u32 auth_mechs = 0;
235
236         client->chosen_mech = AUTH_MECHANISM_NONE;
237
238         if (has_auth) {
239                 std::vector<std::string> pwd_components = str_split(encpwd, '#');
240                 if (pwd_components.size() == 4) {
241                         if (pwd_components[1] == "1") { // 1 means srp
242                                 auth_mechs |= AUTH_MECHANISM_SRP;
243                                 client->enc_pwd = encpwd;
244                         } else {
245                                 actionstream << "User " << playername << " tried to log in, "
246                                         "but password field was invalid (unknown mechcode)." <<
247                                         std::endl;
248                                 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
249                                 return;
250                         }
251                 } else if (base64_is_valid(encpwd)) {
252                         auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
253                         client->enc_pwd = encpwd;
254                 } else {
255                         actionstream << "User " << playername << " tried to log in, but "
256                                 "password field was invalid (invalid base64)." << std::endl;
257                         DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
258                         return;
259                 }
260         } else {
261                 std::string default_password = g_settings->get("default_password");
262                 if (default_password.length() == 0) {
263                         auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
264                 } else {
265                         // Take care of default passwords.
266                         client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
267                         auth_mechs |= AUTH_MECHANISM_SRP;
268                         // Allocate player in db, but only on successful login.
269                         client->create_player_on_auth_success = true;
270                 }
271         }
272
273         /*
274                 Answer with a TOCLIENT_HELLO
275         */
276
277         verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
278                 << auth_mechs << std::endl;
279
280         NetworkPacket resp_pkt(TOCLIENT_HELLO,
281                 1 + 4 + legacyPlayerNameCasing.size(), peer_id);
282
283         u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
284         resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
285                 << auth_mechs << legacyPlayerNameCasing;
286
287         Send(&resp_pkt);
288
289         client->allowed_auth_mechs = auth_mechs;
290         client->setDeployedCompressionMode(depl_compress_mode);
291
292         m_clients.event(peer_id, CSE_Hello);
293 }
294
295 void Server::handleCommand_Init2(NetworkPacket* pkt)
296 {
297         session_t peer_id = pkt->getPeerId();
298         verbosestream << "Server: Got TOSERVER_INIT2 from " << peer_id << std::endl;
299
300         m_clients.event(peer_id, CSE_GotInit2);
301         u16 protocol_version = m_clients.getProtocolVersion(peer_id);
302
303         std::string lang;
304         if (pkt->getSize() > 0)
305                 *pkt >> lang;
306
307         /*
308                 Send some initialization data
309         */
310
311         infostream << "Server: Sending content to " << getPlayerName(peer_id) <<
312                 std::endl;
313
314         // Send item definitions
315         SendItemDef(peer_id, m_itemdef, protocol_version);
316
317         // Send node definitions
318         SendNodeDef(peer_id, m_nodedef, protocol_version);
319
320         m_clients.event(peer_id, CSE_SetDefinitionsSent);
321
322         // Send media announcement
323         sendMediaAnnouncement(peer_id, lang);
324
325         RemoteClient *client = getClient(peer_id, CS_InitDone);
326
327         // Keep client language for server translations
328         client->setLangCode(lang);
329
330         // Send active objects
331         {
332                 PlayerSAO *sao = getPlayerSAO(peer_id);
333                 if (sao)
334                         SendActiveObjectRemoveAdd(client, sao);
335         }
336
337         // Send detached inventories
338         sendDetachedInventories(peer_id, false);
339
340         // Send player movement settings
341         SendMovement(peer_id);
342
343         // Send time of day
344         u16 time = m_env->getTimeOfDay();
345         float time_speed = g_settings->getFloat("time_speed");
346         SendTimeOfDay(peer_id, time, time_speed);
347
348         SendCSMRestrictionFlags(peer_id);
349
350         // Warnings about protocol version can be issued here
351         if (client->net_proto_version < LATEST_PROTOCOL_VERSION) {
352                 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
353                         L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
354                         L"WITH THIS SERVER!"));
355         }
356 }
357
358 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
359 {
360         std::vector<std::string> tosend;
361         u16 numfiles;
362
363         *pkt >> numfiles;
364
365         session_t peer_id = pkt->getPeerId();
366         infostream << "Sending " << numfiles << " files to " <<
367                 getPlayerName(peer_id) << std::endl;
368         verbosestream << "TOSERVER_REQUEST_MEDIA: requested file(s)" << std::endl;
369
370         for (u16 i = 0; i < numfiles; i++) {
371                 std::string name;
372
373                 *pkt >> name;
374
375                 tosend.emplace_back(name);
376                 verbosestream << "  " << name << std::endl;
377         }
378
379         sendRequestedMedia(peer_id, tosend);
380 }
381
382 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
383 {
384         session_t peer_id = pkt->getPeerId();
385
386         // decode all information first
387         u8 major_ver, minor_ver, patch_ver, reserved;
388         u16 formspec_ver = 1; // v1 for clients older than 5.1.0-dev
389         std::string full_ver;
390
391         *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
392         if (pkt->getRemainingBytes() >= 2)
393                 *pkt >> formspec_ver;
394
395         m_clients.setClientVersion(peer_id, major_ver, minor_ver, patch_ver,
396                 full_ver);
397
398         // Emerge player
399         PlayerSAO* playersao = StageTwoClientInit(peer_id);
400         if (!playersao) {
401                 errorstream << "Server: stage 2 client init failed "
402                         "peer_id=" << peer_id << std::endl;
403                 DisconnectPeer(peer_id);
404                 return;
405         }
406
407         playersao->getPlayer()->formspec_version = formspec_ver;
408         m_clients.event(peer_id, CSE_SetClientReady);
409
410         // Send player list to this client
411         {
412                 const std::vector<std::string> &players = m_clients.getPlayerNames();
413                 NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
414                 list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
415                 for (const auto &player : players)
416                         list_pkt << player;
417                 Send(peer_id, &list_pkt);
418         }
419
420         s64 last_login;
421         m_script->getAuth(playersao->getPlayer()->getName(), nullptr, nullptr, &last_login);
422         m_script->on_joinplayer(playersao, last_login);
423
424         // Send shutdown timer if shutdown has been scheduled
425         if (m_shutdown_state.isTimerRunning())
426                 SendChatMessage(peer_id, m_shutdown_state.getShutdownTimerMessage());
427 }
428
429 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
430 {
431         if (pkt->getSize() < 1)
432                 return;
433
434         /*
435                 [0] u16 command
436                 [2] u8 count
437                 [3] v3s16 pos_0
438                 [3+6] v3s16 pos_1
439                 ...
440         */
441
442         u8 count;
443         *pkt >> count;
444
445         if ((s16)pkt->getSize() < 1 + (int)count * 6) {
446                 throw con::InvalidIncomingDataException
447                                 ("GOTBLOCKS length is too short");
448         }
449
450         ClientInterface::AutoLock lock(m_clients);
451         RemoteClient *client = m_clients.lockedGetClientNoEx(pkt->getPeerId());
452
453         for (u16 i = 0; i < count; i++) {
454                 v3s16 p;
455                 *pkt >> p;
456                 client->GotBlock(p);
457         }
458 }
459
460 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
461         NetworkPacket *pkt)
462 {
463         if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
464                 return;
465
466         v3s32 ps, ss;
467         s32 f32pitch, f32yaw;
468         u8 f32fov;
469
470         *pkt >> ps;
471         *pkt >> ss;
472         *pkt >> f32pitch;
473         *pkt >> f32yaw;
474
475         f32 pitch = (f32)f32pitch / 100.0f;
476         f32 yaw = (f32)f32yaw / 100.0f;
477         u32 keyPressed = 0;
478
479         f32 fov = 0;
480         u8 wanted_range = 0;
481
482         *pkt >> keyPressed;
483         *pkt >> f32fov;
484         fov = (f32)f32fov / 80.0f;
485         *pkt >> wanted_range;
486
487         v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
488         v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
489
490         pitch = modulo360f(pitch);
491         yaw = wrapDegrees_0_360(yaw);
492
493         if (!playersao->isAttached()) {
494                 // Only update player positions when moving freely
495                 // to not interfere with attachment handling
496                 playersao->setBasePosition(position);
497                 player->setSpeed(speed);
498         }
499         playersao->setLookPitch(pitch);
500         playersao->setPlayerYaw(yaw);
501         playersao->setFov(fov);
502         playersao->setWantedRange(wanted_range);
503
504         player->control.unpackKeysPressed(keyPressed);
505
506         if (playersao->checkMovementCheat()) {
507                 // Call callbacks
508                 m_script->on_cheat(playersao, "moved_too_fast");
509                 SendMovePlayer(pkt->getPeerId());
510         }
511 }
512
513 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
514 {
515         session_t peer_id = pkt->getPeerId();
516         RemotePlayer *player = m_env->getPlayer(peer_id);
517         if (player == NULL) {
518                 errorstream <<
519                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
520                         peer_id << " disconnecting peer!" << std::endl;
521                 DisconnectPeer(peer_id);
522                 return;
523         }
524
525         PlayerSAO *playersao = player->getPlayerSAO();
526         if (playersao == NULL) {
527                 errorstream <<
528                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
529                         peer_id << " disconnecting peer!" << std::endl;
530                 DisconnectPeer(peer_id);
531                 return;
532         }
533
534         // If player is dead we don't care of this packet
535         if (playersao->isDead()) {
536                 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
537                                 << " is dead. Ignoring packet";
538                 return;
539         }
540
541         process_PlayerPos(player, playersao, pkt);
542 }
543
544 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
545 {
546         if (pkt->getSize() < 1)
547                 return;
548
549         /*
550                 [0] u16 command
551                 [2] u8 count
552                 [3] v3s16 pos_0
553                 [3+6] v3s16 pos_1
554                 ...
555         */
556
557         u8 count;
558         *pkt >> count;
559
560         RemoteClient *client = getClient(pkt->getPeerId());
561
562         if ((s16)pkt->getSize() < 1 + (int)count * 6) {
563                 throw con::InvalidIncomingDataException
564                                 ("DELETEDBLOCKS length is too short");
565         }
566
567         for (u16 i = 0; i < count; i++) {
568                 v3s16 p;
569                 *pkt >> p;
570                 client->SetBlockNotSent(p);
571         }
572 }
573
574 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
575 {
576         session_t peer_id = pkt->getPeerId();
577         RemotePlayer *player = m_env->getPlayer(peer_id);
578
579         if (player == NULL) {
580                 errorstream <<
581                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
582                         peer_id << " disconnecting peer!" << std::endl;
583                 DisconnectPeer(peer_id);
584                 return;
585         }
586
587         PlayerSAO *playersao = player->getPlayerSAO();
588         if (playersao == NULL) {
589                 errorstream <<
590                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
591                         peer_id << " disconnecting peer!" << std::endl;
592                 DisconnectPeer(peer_id);
593                 return;
594         }
595
596         // Strip command and create a stream
597         std::string datastring(pkt->getString(0), pkt->getSize());
598         verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
599                 << std::endl;
600         std::istringstream is(datastring, std::ios_base::binary);
601         // Create an action
602         std::unique_ptr<InventoryAction> a(InventoryAction::deSerialize(is));
603         if (!a) {
604                 infostream << "TOSERVER_INVENTORY_ACTION: "
605                                 << "InventoryAction::deSerialize() returned NULL"
606                                 << std::endl;
607                 return;
608         }
609
610         // If something goes wrong, this player is to blame
611         RollbackScopeActor rollback_scope(m_rollback,
612                         std::string("player:")+player->getName());
613
614         /*
615                 Note: Always set inventory not sent, to repair cases
616                 where the client made a bad prediction.
617         */
618
619         const bool player_has_interact = checkPriv(player->getName(), "interact");
620
621         auto check_inv_access = [player, player_has_interact, this] (
622                         const InventoryLocation &loc) -> bool {
623
624                 // Players without interact may modify their own inventory
625                 if (!player_has_interact && loc.type != InventoryLocation::PLAYER) {
626                         infostream << "Cannot modify foreign inventory: "
627                                         << "No interact privilege" << std::endl;
628                         return false;
629                 }
630
631                 switch (loc.type) {
632                 case InventoryLocation::CURRENT_PLAYER:
633                         // Only used internally on the client, never sent
634                         return false;
635                 case InventoryLocation::PLAYER:
636                         // Allow access to own inventory in all cases
637                         return loc.name == player->getName();
638                 case InventoryLocation::NODEMETA:
639                         {
640                                 // Check for out-of-range interaction
641                                 v3f node_pos   = intToFloat(loc.p, BS);
642                                 v3f player_pos = player->getPlayerSAO()->getEyePosition();
643                                 f32 d = player_pos.getDistanceFrom(node_pos);
644                                 return checkInteractDistance(player, d, "inventory");
645                         }
646                 case InventoryLocation::DETACHED:
647                         return getInventoryMgr()->checkDetachedInventoryAccess(loc, player->getName());
648                 default:
649                         return false;
650                 }
651         };
652
653         /*
654                 Handle restrictions and special cases of the move action
655         */
656         if (a->getType() == IAction::Move) {
657                 IMoveAction *ma = (IMoveAction*)a.get();
658
659                 ma->from_inv.applyCurrentPlayer(player->getName());
660                 ma->to_inv.applyCurrentPlayer(player->getName());
661
662                 m_inventory_mgr->setInventoryModified(ma->from_inv);
663                 if (ma->from_inv != ma->to_inv)
664                         m_inventory_mgr->setInventoryModified(ma->to_inv);
665
666                 if (!check_inv_access(ma->from_inv) ||
667                                 !check_inv_access(ma->to_inv))
668                         return;
669
670                 /*
671                         Disable moving items out of craftpreview
672                 */
673                 if (ma->from_list == "craftpreview") {
674                         infostream << "Ignoring IMoveAction from "
675                                         << (ma->from_inv.dump()) << ":" << ma->from_list
676                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
677                                         << " because src is " << ma->from_list << std::endl;
678                         return;
679                 }
680
681                 /*
682                         Disable moving items into craftresult and craftpreview
683                 */
684                 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
685                         infostream << "Ignoring IMoveAction from "
686                                         << (ma->from_inv.dump()) << ":" << ma->from_list
687                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
688                                         << " because dst is " << ma->to_list << std::endl;
689                         return;
690                 }
691         }
692         /*
693                 Handle restrictions and special cases of the drop action
694         */
695         else if (a->getType() == IAction::Drop) {
696                 IDropAction *da = (IDropAction*)a.get();
697
698                 da->from_inv.applyCurrentPlayer(player->getName());
699
700                 m_inventory_mgr->setInventoryModified(da->from_inv);
701
702                 /*
703                         Disable dropping items out of craftpreview
704                 */
705                 if (da->from_list == "craftpreview") {
706                         infostream << "Ignoring IDropAction from "
707                                         << (da->from_inv.dump()) << ":" << da->from_list
708                                         << " because src is " << da->from_list << std::endl;
709                         return;
710                 }
711
712                 // Disallow dropping items if not allowed to interact
713                 if (!player_has_interact || !check_inv_access(da->from_inv))
714                         return;
715
716                 // Disallow dropping items if dead
717                 if (playersao->isDead()) {
718                         infostream << "Ignoring IDropAction from "
719                                         << (da->from_inv.dump()) << ":" << da->from_list
720                                         << " because player is dead." << std::endl;
721                         return;
722                 }
723         }
724         /*
725                 Handle restrictions and special cases of the craft action
726         */
727         else if (a->getType() == IAction::Craft) {
728                 ICraftAction *ca = (ICraftAction*)a.get();
729
730                 ca->craft_inv.applyCurrentPlayer(player->getName());
731
732                 m_inventory_mgr->setInventoryModified(ca->craft_inv);
733
734                 // Disallow crafting if not allowed to interact
735                 if (!player_has_interact) {
736                         infostream << "Cannot craft: "
737                                         << "No interact privilege" << std::endl;
738                         return;
739                 }
740
741                 if (!check_inv_access(ca->craft_inv))
742                         return;
743         } else {
744                 // Unknown action. Ignored.
745                 return;
746         }
747
748         // Do the action
749         a->apply(m_inventory_mgr.get(), playersao, this);
750 }
751
752 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
753 {
754         std::wstring message;
755         *pkt >> message;
756
757         session_t peer_id = pkt->getPeerId();
758         RemotePlayer *player = m_env->getPlayer(peer_id);
759         if (player == NULL) {
760                 errorstream <<
761                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
762                         peer_id << " disconnecting peer!" << std::endl;
763                 DisconnectPeer(peer_id);
764                 return;
765         }
766
767         std::string name = player->getName();
768
769         std::wstring answer_to_sender = handleChat(name, message, true, player);
770         if (!answer_to_sender.empty()) {
771                 // Send the answer to sender
772                 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
773                         answer_to_sender));
774         }
775 }
776
777 void Server::handleCommand_Damage(NetworkPacket* pkt)
778 {
779         u16 damage;
780
781         *pkt >> damage;
782
783         session_t peer_id = pkt->getPeerId();
784         RemotePlayer *player = m_env->getPlayer(peer_id);
785
786         if (player == NULL) {
787                 errorstream <<
788                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
789                         peer_id << " disconnecting peer!" << std::endl;
790                 DisconnectPeer(peer_id);
791                 return;
792         }
793
794         PlayerSAO *playersao = player->getPlayerSAO();
795         if (playersao == NULL) {
796                 errorstream <<
797                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
798                         peer_id << " disconnecting peer!" << std::endl;
799                 DisconnectPeer(peer_id);
800                 return;
801         }
802
803         if (!playersao->isImmortal()) {
804                 if (playersao->isDead()) {
805                         verbosestream << "Server::ProcessData(): Info: "
806                                 "Ignoring damage as player " << player->getName()
807                                 << " is already dead." << std::endl;
808                         return;
809                 }
810
811                 actionstream << player->getName() << " damaged by "
812                                 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
813                                 << std::endl;
814
815                 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
816                 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason, true);
817         }
818 }
819
820 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
821 {
822         if (pkt->getSize() < 2)
823                 return;
824
825         session_t peer_id = pkt->getPeerId();
826         RemotePlayer *player = m_env->getPlayer(peer_id);
827
828         if (player == NULL) {
829                 errorstream <<
830                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
831                         peer_id << " disconnecting peer!" << std::endl;
832                 DisconnectPeer(peer_id);
833                 return;
834         }
835
836         PlayerSAO *playersao = player->getPlayerSAO();
837         if (playersao == NULL) {
838                 errorstream <<
839                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
840                         peer_id << " disconnecting peer!" << std::endl;
841                 DisconnectPeer(peer_id);
842                 return;
843         }
844
845         u16 item;
846
847         *pkt >> item;
848
849         if (item >= player->getHotbarItemcount()) {
850                 actionstream << "Player: " << player->getName()
851                         << " tried to access item=" << item
852                         << " out of hotbar_itemcount="
853                         << player->getHotbarItemcount()
854                         << "; ignoring." << std::endl;
855                 return;
856         }
857
858         playersao->getPlayer()->setWieldIndex(item);
859 }
860
861 void Server::handleCommand_Respawn(NetworkPacket* pkt)
862 {
863         session_t peer_id = pkt->getPeerId();
864         RemotePlayer *player = m_env->getPlayer(peer_id);
865         if (player == NULL) {
866                 errorstream <<
867                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
868                         peer_id << " disconnecting peer!" << std::endl;
869                 DisconnectPeer(peer_id);
870                 return;
871         }
872
873         PlayerSAO *playersao = player->getPlayerSAO();
874         assert(playersao);
875
876         if (!playersao->isDead())
877                 return;
878
879         RespawnPlayer(peer_id);
880
881         actionstream << player->getName() << " respawns at "
882                         << PP(playersao->getBasePosition() / BS) << std::endl;
883
884         // ActiveObject is added to environment in AsyncRunStep after
885         // the previous addition has been successfully removed
886 }
887
888 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
889 {
890         ItemStack selected_item, main_item;
891         player->getWieldedItem(&selected_item, &main_item);
892         f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
893                         main_item.getDefinition(m_itemdef));
894
895         // Cube diagonal * 1.5 for maximal supported node extents:
896         // sqrt(3) * 1.5 â‰… 2.6
897         if (d > max_d + 2.6f * BS) {
898                 actionstream << "Player " << player->getName()
899                                 << " tried to access " << what
900                                 << " from too far: "
901                                 << "d=" << d << ", max_d=" << max_d
902                                 << "; ignoring." << std::endl;
903                 // Call callbacks
904                 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
905                 return false;
906         }
907         return true;
908 }
909
910 // Tiny helper to retrieve the selected item into an Optional
911 static inline void getWieldedItem(const PlayerSAO *playersao, Optional<ItemStack> &ret)
912 {
913         ret = ItemStack();
914         playersao->getWieldedItem(&(*ret));
915 }
916
917 static inline bool getOffhandWieldedItem(const PlayerSAO *playersao, Optional<ItemStack> &offhand,
918         Optional<ItemStack> &place, IItemDefManager *idef, const PointedThing &pointed)
919 {
920         offhand = ItemStack();
921         place = ItemStack();
922         return playersao->getOffhandWieldedItem(&(*offhand), &(*place), idef, pointed);
923 }
924
925 void Server::handleCommand_Interact(NetworkPacket *pkt)
926 {
927         /*
928                 [0] u16 command
929                 [2] u8 action
930                 [3] u16 item
931                 [5] u32 length of the next item (plen)
932                 [9] serialized PointedThing
933                 [9 + plen] player position information
934         */
935
936         InteractAction action;
937         u16 item_i;
938
939         *pkt >> (u8 &)action;
940         *pkt >> item_i;
941
942         std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
943         PointedThing pointed;
944         pointed.deSerialize(tmp_is);
945
946         verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
947                         << item_i << ", pointed=" << pointed.dump() << std::endl;
948
949         session_t peer_id = pkt->getPeerId();
950         RemotePlayer *player = m_env->getPlayer(peer_id);
951
952         if (player == NULL) {
953                 errorstream <<
954                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
955                         peer_id << " disconnecting peer!" << std::endl;
956                 DisconnectPeer(peer_id);
957                 return;
958         }
959
960         PlayerSAO *playersao = player->getPlayerSAO();
961         if (playersao == NULL) {
962                 errorstream <<
963                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
964                         peer_id << " disconnecting peer!" << std::endl;
965                 DisconnectPeer(peer_id);
966                 return;
967         }
968
969         if (playersao->isDead()) {
970                 actionstream << "Server: " << player->getName()
971                                 << " tried to interact while dead; ignoring." << std::endl;
972                 if (pointed.type == POINTEDTHING_NODE) {
973                         // Re-send block to revert change on client-side
974                         RemoteClient *client = getClient(peer_id);
975                         v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
976                         client->SetBlockNotSent(blockpos);
977                 }
978                 // Call callbacks
979                 m_script->on_cheat(playersao, "interacted_while_dead");
980                 return;
981         }
982
983         process_PlayerPos(player, playersao, pkt);
984
985         v3f player_pos = playersao->getLastGoodPosition();
986
987         // Update wielded item
988
989         if (item_i >= player->getHotbarItemcount()) {
990                 actionstream << "Player: " << player->getName()
991                         << " tried to access item=" << item_i
992                         << " out of hotbar_itemcount="
993                         << player->getHotbarItemcount()
994                         << "; ignoring." << std::endl;
995                 return;
996         }
997
998         playersao->getPlayer()->setWieldIndex(item_i);
999
1000         // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1001         ServerActiveObject *pointed_object = NULL;
1002         if (pointed.type == POINTEDTHING_OBJECT) {
1003                 pointed_object = m_env->getActiveObject(pointed.object_id);
1004                 if (pointed_object == NULL) {
1005                         verbosestream << "TOSERVER_INTERACT: "
1006                                 "pointed object is NULL" << std::endl;
1007                         return;
1008                 }
1009
1010         }
1011
1012         /*
1013                 Make sure the player is allowed to do it
1014         */
1015         if (!checkPriv(player->getName(), "interact")) {
1016                 actionstream << player->getName() << " attempted to interact with " <<
1017                                 pointed.dump() << " without 'interact' privilege" << std::endl;
1018
1019                 if (pointed.type != POINTEDTHING_NODE)
1020                         return;
1021
1022                 // Re-send block to revert change on client-side
1023                 RemoteClient *client = getClient(peer_id);
1024                 // Digging completed -> under
1025                 if (action == INTERACT_DIGGING_COMPLETED) {
1026                         v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1027                         client->SetBlockNotSent(blockpos);
1028                 }
1029                 // Placement -> above
1030                 else if (action == INTERACT_PLACE) {
1031                         v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1032                         client->SetBlockNotSent(blockpos);
1033                 }
1034                 return;
1035         }
1036
1037         /*
1038                 Check that target is reasonably close
1039         */
1040         static thread_local const bool enable_anticheat =
1041                         !g_settings->getBool("disable_anticheat");
1042
1043         if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1044                         action == INTERACT_PLACE || action == INTERACT_USE) &&
1045                         enable_anticheat && !isSingleplayer()) {
1046                 v3f target_pos = player_pos;
1047                 if (pointed.type == POINTEDTHING_NODE) {
1048                         target_pos = intToFloat(pointed.node_undersurface, BS);
1049                 } else if (pointed.type == POINTEDTHING_OBJECT) {
1050                         if (playersao->getId() == pointed_object->getId()) {
1051                                 actionstream << "Server: " << player->getName()
1052                                         << " attempted to interact with themselves" << std::endl;
1053                                 m_script->on_cheat(playersao, "interacted_with_self");
1054                                 return;
1055                         }
1056                         target_pos = pointed_object->getBasePosition();
1057                 }
1058                 float d = playersao->getEyePosition().getDistanceFrom(target_pos);
1059
1060                 if (!checkInteractDistance(player, d, pointed.dump())) {
1061                         if (pointed.type == POINTEDTHING_NODE) {
1062                                 // Re-send block to revert change on client-side
1063                                 RemoteClient *client = getClient(peer_id);
1064                                 v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1065                                 client->SetBlockNotSent(blockpos);
1066                         }
1067                         return;
1068                 }
1069         }
1070
1071         /*
1072                 If something goes wrong, this player is to blame
1073         */
1074         RollbackScopeActor rollback_scope(m_rollback,
1075                         std::string("player:")+player->getName());
1076
1077         switch (action) {
1078         // Start digging or punch object
1079         case INTERACT_START_DIGGING: {
1080                 if (pointed.type == POINTEDTHING_NODE) {
1081                         MapNode n(CONTENT_IGNORE);
1082                         bool pos_ok;
1083
1084                         v3s16 p_under = pointed.node_undersurface;
1085                         n = m_env->getMap().getNode(p_under, &pos_ok);
1086                         if (!pos_ok) {
1087                                 infostream << "Server: Not punching: Node not found. "
1088                                         "Adding block to emerge queue." << std::endl;
1089                                 m_emerge->enqueueBlockEmerge(peer_id,
1090                                         getNodeBlockPos(pointed.node_abovesurface), false);
1091                         }
1092
1093                         if (n.getContent() != CONTENT_IGNORE)
1094                                 m_script->node_on_punch(p_under, n, playersao, pointed);
1095
1096                         // Cheat prevention
1097                         playersao->noCheatDigStart(p_under);
1098
1099                         return;
1100                 }
1101
1102                 // Skip if the object can't be interacted with anymore
1103                 if (pointed.type != POINTEDTHING_OBJECT || pointed_object->isGone())
1104                         return;
1105
1106                 ItemStack selected_item, hand_item;
1107                 ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
1108                 ToolCapabilities toolcap =
1109                                 tool_item.getToolCapabilities(m_itemdef);
1110                 v3f dir = (pointed_object->getBasePosition() -
1111                                 (playersao->getBasePosition() + playersao->getEyeOffset())
1112                                         ).normalize();
1113                 float time_from_last_punch =
1114                         playersao->resetTimeFromLastPunch();
1115
1116                 u32 wear = pointed_object->punch(dir, &toolcap, playersao,
1117                                 time_from_last_punch, tool_item.wear);
1118
1119                 // Callback may have changed item, so get it again
1120                 playersao->getWieldedItem(&selected_item);
1121                 bool changed = selected_item.addWear(wear, m_itemdef);
1122                 if (changed)
1123                         playersao->setWieldedItem(selected_item);
1124
1125                 return;
1126         } // action == INTERACT_START_DIGGING
1127
1128         case INTERACT_STOP_DIGGING:
1129                 // Nothing to do
1130                 return;
1131
1132         case INTERACT_DIGGING_COMPLETED: {
1133                 // Only digging of nodes
1134                 if (pointed.type != POINTEDTHING_NODE)
1135                         return;
1136                 bool pos_ok;
1137                 v3s16 p_under = pointed.node_undersurface;
1138                 MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1139                 if (!pos_ok) {
1140                         infostream << "Server: Not finishing digging: Node not found. "
1141                                 "Adding block to emerge queue." << std::endl;
1142                         m_emerge->enqueueBlockEmerge(peer_id,
1143                                 getNodeBlockPos(pointed.node_abovesurface), false);
1144                 }
1145
1146                 /* Cheat prevention */
1147                 bool is_valid_dig = true;
1148                 if (enable_anticheat && !isSingleplayer()) {
1149                         v3s16 nocheat_p = playersao->getNoCheatDigPos();
1150                         float nocheat_t = playersao->getNoCheatDigTime();
1151                         playersao->noCheatDigEnd();
1152                         // If player didn't start digging this, ignore dig
1153                         if (nocheat_p != p_under) {
1154                                 infostream << "Server: " << player->getName()
1155                                                 << " started digging "
1156                                                 << PP(nocheat_p) << " and completed digging "
1157                                                 << PP(p_under) << "; not digging." << std::endl;
1158                                 is_valid_dig = false;
1159                                 // Call callbacks
1160                                 m_script->on_cheat(playersao, "finished_unknown_dig");
1161                         }
1162
1163                         // Get player's wielded item
1164                         // See also: Game::handleDigging
1165                         ItemStack selected_item, main_item;
1166                         playersao->getPlayer()->getWieldedItem(&selected_item, &main_item);
1167
1168                         // Get diggability and expected digging time
1169                         DigParams params = getDigParams(m_nodedef->get(n).groups,
1170                                         &selected_item.getToolCapabilities(m_itemdef),
1171                                         selected_item.wear);
1172                         // If can't dig, try hand
1173                         if (!params.diggable) {
1174                                 params = getDigParams(m_nodedef->get(n).groups,
1175                                         &main_item.getToolCapabilities(m_itemdef));
1176                         }
1177                         // If can't dig, ignore dig
1178                         if (!params.diggable) {
1179                                 infostream << "Server: " << player->getName()
1180                                                 << " completed digging " << PP(p_under)
1181                                                 << ", which is not diggable with tool; not digging."
1182                                                 << std::endl;
1183                                 is_valid_dig = false;
1184                                 // Call callbacks
1185                                 m_script->on_cheat(playersao, "dug_unbreakable");
1186                         }
1187                         // Check digging time
1188                         // If already invalidated, we don't have to
1189                         if (!is_valid_dig) {
1190                                 // Well not our problem then
1191                         }
1192                         // Clean and long dig
1193                         else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1194                                 // All is good, but grab time from pool; don't care if
1195                                 // it's actually available
1196                                 playersao->getDigPool().grab(params.time);
1197                         }
1198                         // Short or laggy dig
1199                         // Try getting the time from pool
1200                         else if (playersao->getDigPool().grab(params.time)) {
1201                                 // All is good
1202                         }
1203                         // Dig not possible
1204                         else {
1205                                 infostream << "Server: " << player->getName()
1206                                                 << " completed digging " << PP(p_under)
1207                                                 << "too fast; not digging." << std::endl;
1208                                 is_valid_dig = false;
1209                                 // Call callbacks
1210                                 m_script->on_cheat(playersao, "dug_too_fast");
1211                         }
1212                 }
1213
1214                 /* Actually dig node */
1215
1216                 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1217                         m_script->node_on_dig(p_under, n, playersao);
1218
1219                 v3s16 blockpos = getNodeBlockPos(p_under);
1220                 RemoteClient *client = getClient(peer_id);
1221                 // Send unusual result (that is, node not being removed)
1222                 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR)
1223                         // Re-send block to revert change on client-side
1224                         client->SetBlockNotSent(blockpos);
1225                 else
1226                         client->ResendBlockIfOnWire(blockpos);
1227
1228                 return;
1229         } // action == INTERACT_DIGGING_COMPLETED
1230
1231         // Place block or right-click object
1232         case INTERACT_PLACE: {
1233                 Optional<ItemStack> main_item, offhand_item, place_item;
1234                 getWieldedItem(playersao, main_item);
1235                 bool use_offhand = getOffhandWieldedItem(playersao, offhand_item, place_item, m_itemdef, pointed);
1236
1237                 // Reset build time counter
1238                 if (pointed.type == POINTEDTHING_NODE &&
1239                                 place_item->getDefinition(m_itemdef).type == ITEM_NODE)
1240                         getClient(peer_id)->m_time_from_building = 0.0;
1241
1242                 const bool had_prediction = !place_item->getDefinition(m_itemdef).
1243                         node_placement_prediction.empty();
1244
1245                 if (pointed.type == POINTEDTHING_OBJECT) {
1246                         // Right click object
1247
1248                         // Skip if object can't be interacted with anymore
1249                         if (pointed_object->isGone())
1250                                 return;
1251
1252                         actionstream << player->getName() << " right-clicks object "
1253                                         << pointed.object_id << ": "
1254                                         << pointed_object->getDescription() << std::endl;
1255
1256                         // Do stuff
1257                         if (m_script->item_OnSecondaryUse(use_offhand ? offhand_item : main_item, playersao, pointed)) {
1258                                 if (use_offhand
1259                                                 ? (offhand_item.has_value() && playersao->setOffhandWieldedItem(*offhand_item))
1260                                                 : (main_item.has_value() && playersao->setWieldedItem(*main_item)))
1261                                         SendInventory(playersao, true);
1262                         }
1263
1264                         pointed_object->rightClick(playersao);
1265                 } else if (m_script->item_OnPlace(use_offhand ? offhand_item : main_item, playersao, pointed)) {
1266                         // Placement was handled in lua
1267
1268                         // Apply returned ItemStack
1269                         if (use_offhand
1270                                         ? (offhand_item.has_value() && playersao->setOffhandWieldedItem(*offhand_item))
1271                                         : (main_item.has_value() && playersao->setWieldedItem(*main_item)))
1272                                 SendInventory(playersao, true);
1273                 }
1274
1275                 if (pointed.type != POINTEDTHING_NODE)
1276                         return;
1277
1278                 // If item has node placement prediction, always send the
1279                 // blocks to make sure the client knows what exactly happened
1280                 RemoteClient *client = getClient(peer_id);
1281                 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1282                 v3s16 blockpos2 = getNodeBlockPos(pointed.node_undersurface);
1283                 if (had_prediction) {
1284                         client->SetBlockNotSent(blockpos);
1285                         if (blockpos2 != blockpos)
1286                                 client->SetBlockNotSent(blockpos2);
1287                 } else {
1288                         client->ResendBlockIfOnWire(blockpos);
1289                         if (blockpos2 != blockpos)
1290                                 client->ResendBlockIfOnWire(blockpos2);
1291                 }
1292
1293                 return;
1294         } // action == INTERACT_PLACE
1295
1296         case INTERACT_USE: {
1297                 Optional<ItemStack> selected_item;
1298                 getWieldedItem(playersao, selected_item);
1299
1300                 actionstream << player->getName() << " uses " << selected_item->name
1301                                 << ", pointing at " << pointed.dump() << std::endl;
1302
1303                 if (m_script->item_OnUse(selected_item, playersao, pointed)) {
1304                         // Apply returned ItemStack
1305                         if (selected_item.has_value() && playersao->setWieldedItem(*selected_item))
1306                                 SendInventory(playersao, true);
1307                 }
1308
1309                 return;
1310         }
1311
1312         // Rightclick air
1313         case INTERACT_ACTIVATE: {
1314                 Optional<ItemStack> main_item, offhand_item, place_item;
1315                 getWieldedItem(playersao, main_item);
1316                 bool use_offhand = getOffhandWieldedItem(playersao, offhand_item, place_item, m_itemdef, pointed);
1317
1318                 actionstream << player->getName() << " activates "
1319                                 << place_item->name << std::endl;
1320
1321                 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1322
1323                 if (m_script->item_OnSecondaryUse(use_offhand ? offhand_item : main_item, playersao, pointed)) {
1324                         // Apply returned ItemStack
1325                         if (use_offhand
1326                                         ? (offhand_item.has_value() && playersao->setOffhandWieldedItem(*offhand_item))
1327                                         : (main_item.has_value() && playersao->setWieldedItem(*main_item)))
1328                                 SendInventory(playersao, true);
1329                 }
1330
1331                 return;
1332         }
1333
1334         default:
1335                 warningstream << "Server: Invalid action " << action << std::endl;
1336
1337         }
1338 }
1339
1340 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1341 {
1342         u16 num;
1343         *pkt >> num;
1344         for (u16 k = 0; k < num; k++) {
1345                 s32 id;
1346
1347                 *pkt >> id;
1348
1349                 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1350                         m_playing_sounds.find(id);
1351                 if (i == m_playing_sounds.end())
1352                         continue;
1353
1354                 ServerPlayingSound &psound = i->second;
1355                 psound.clients.erase(pkt->getPeerId());
1356                 if (psound.clients.empty())
1357                         m_playing_sounds.erase(i++);
1358         }
1359 }
1360
1361 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1362 {
1363         v3s16 p;
1364         std::string formname;
1365         u16 num;
1366
1367         *pkt >> p >> formname >> num;
1368
1369         StringMap fields;
1370         for (u16 k = 0; k < num; k++) {
1371                 std::string fieldname;
1372                 *pkt >> fieldname;
1373                 fields[fieldname] = pkt->readLongString();
1374         }
1375
1376         session_t peer_id = pkt->getPeerId();
1377         RemotePlayer *player = m_env->getPlayer(peer_id);
1378
1379         if (player == NULL) {
1380                 errorstream <<
1381                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
1382                         peer_id << " disconnecting peer!" << std::endl;
1383                 DisconnectPeer(peer_id);
1384                 return;
1385         }
1386
1387         PlayerSAO *playersao = player->getPlayerSAO();
1388         if (playersao == NULL) {
1389                 errorstream <<
1390                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1391                         peer_id << " disconnecting peer!" << std::endl;
1392                 DisconnectPeer(peer_id);
1393                 return;
1394         }
1395
1396         // If something goes wrong, this player is to blame
1397         RollbackScopeActor rollback_scope(m_rollback,
1398                         std::string("player:")+player->getName());
1399
1400         // Check the target node for rollback data; leave others unnoticed
1401         RollbackNode rn_old(&m_env->getMap(), p, this);
1402
1403         m_script->node_on_receive_fields(p, formname, fields, playersao);
1404
1405         // Report rollback data
1406         RollbackNode rn_new(&m_env->getMap(), p, this);
1407         if (rollback() && rn_new != rn_old) {
1408                 RollbackAction action;
1409                 action.setSetNode(p, rn_old, rn_new);
1410                 rollback()->reportAction(action);
1411         }
1412 }
1413
1414 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1415 {
1416         std::string client_formspec_name;
1417         u16 num;
1418
1419         *pkt >> client_formspec_name >> num;
1420
1421         StringMap fields;
1422         for (u16 k = 0; k < num; k++) {
1423                 std::string fieldname;
1424                 *pkt >> fieldname;
1425                 fields[fieldname] = pkt->readLongString();
1426         }
1427
1428         session_t peer_id = pkt->getPeerId();
1429         RemotePlayer *player = m_env->getPlayer(peer_id);
1430
1431         if (player == NULL) {
1432                 errorstream <<
1433                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
1434                         peer_id << " disconnecting peer!" << std::endl;
1435                 DisconnectPeer(peer_id);
1436                 return;
1437         }
1438
1439         PlayerSAO *playersao = player->getPlayerSAO();
1440         if (playersao == NULL) {
1441                 errorstream <<
1442                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1443                         peer_id << " disconnecting peer!" << std::endl;
1444                 DisconnectPeer(peer_id);
1445                 return;
1446         }
1447
1448         if (client_formspec_name.empty()) { // pass through inventory submits
1449                 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1450                 return;
1451         }
1452
1453         // verify that we displayed the formspec to the user
1454         const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1455         if (peer_state_iterator != m_formspec_state_data.end()) {
1456                 const std::string &server_formspec_name = peer_state_iterator->second;
1457                 if (client_formspec_name == server_formspec_name) {
1458                         auto it = fields.find("quit");
1459                         if (it != fields.end() && it->second == "true")
1460                                 m_formspec_state_data.erase(peer_state_iterator);
1461
1462                         m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1463                         return;
1464                 }
1465                 actionstream << "'" << player->getName()
1466                         << "' submitted formspec ('" << client_formspec_name
1467                         << "') but the name of the formspec doesn't match the"
1468                         " expected name ('" << server_formspec_name << "')";
1469
1470         } else {
1471                 actionstream << "'" << player->getName()
1472                         << "' submitted formspec ('" << client_formspec_name
1473                         << "') but server hasn't sent formspec to client";
1474         }
1475         actionstream << ", possible exploitation attempt" << std::endl;
1476 }
1477
1478 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1479 {
1480         session_t peer_id = pkt->getPeerId();
1481         RemoteClient *client = getClient(peer_id, CS_Invalid);
1482         ClientState cstate = client->getState();
1483         const std::string playername = client->getName();
1484
1485         std::string salt, verification_key;
1486
1487         std::string addr_s = getPeerAddress(peer_id).serializeString();
1488         u8 is_empty;
1489
1490         *pkt >> salt >> verification_key >> is_empty;
1491
1492         verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1493                 << ", with is_empty=" << (is_empty == 1) << std::endl;
1494
1495         const bool empty_disallowed = !isSingleplayer() && is_empty == 1 &&
1496                 g_settings->getBool("disallow_empty_password");
1497
1498         // Either this packet is sent because the user is new or to change the password
1499         if (cstate == CS_HelloSent) {
1500                 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1501                         actionstream << "Server: Client from " << addr_s
1502                                         << " tried to set password without being "
1503                                         << "authenticated, or the username being new." << std::endl;
1504                         DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1505                         return;
1506                 }
1507
1508                 if (empty_disallowed) {
1509                         actionstream << "Server: " << playername
1510                                         << " supplied empty password from " << addr_s << std::endl;
1511                         DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1512                         return;
1513                 }
1514
1515                 std::string initial_ver_key;
1516                 initial_ver_key = encode_srp_verifier(verification_key, salt);
1517
1518                 // It is possible for multiple connections to get this far with the same
1519                 // player name. In the end only one player with a given name will be emerged
1520                 // (see Server::StateTwoClientInit) but we still have to be careful here.
1521                 if (m_script->getAuth(playername, nullptr, nullptr)) {
1522                         // Another client beat us to it
1523                         actionstream << "Server: Client from " << addr_s
1524                                 << " tried to register " << playername << " a second time."
1525                                 << std::endl;
1526                         DenyAccess(peer_id, SERVER_ACCESSDENIED_ALREADY_CONNECTED);
1527                         return;
1528                 }
1529                 m_script->createAuth(playername, initial_ver_key);
1530                 m_script->on_authplayer(playername, addr_s, true);
1531
1532                 acceptAuth(peer_id, false);
1533         } else {
1534                 if (cstate < CS_SudoMode) {
1535                         infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1536                                         << addr_s << ": " << "Client has wrong state " << cstate << "."
1537                                         << std::endl;
1538                         return;
1539                 }
1540                 m_clients.event(peer_id, CSE_SudoLeave);
1541
1542                 if (empty_disallowed) {
1543                         actionstream << "Server: " << playername
1544                                         << " supplied empty password" << std::endl;
1545                         SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1546                                 L"Changing to an empty password is not allowed."));
1547                         return;
1548                 }
1549
1550                 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1551                 bool success = m_script->setPassword(playername, pw_db_field);
1552                 if (success) {
1553                         actionstream << playername << " changes password" << std::endl;
1554                         SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1555                                 L"Password change successful."));
1556                 } else {
1557                         actionstream << playername <<
1558                                 " tries to change password but it fails" << std::endl;
1559                         SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1560                                 L"Password change failed or unavailable."));
1561                 }
1562         }
1563 }
1564
1565 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1566 {
1567         session_t peer_id = pkt->getPeerId();
1568         RemoteClient *client = getClient(peer_id, CS_Invalid);
1569         ClientState cstate = client->getState();
1570
1571         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1572                 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1573                         " from " << getPeerAddress(peer_id).serializeString() <<
1574                         ". Ignoring." << std::endl;
1575                 return;
1576         }
1577
1578         const bool wantSudo = (cstate == CS_Active);
1579
1580         if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1581                 actionstream << "Server: got SRP _A packet, while auth is already "
1582                         "going on with mech " << client->chosen_mech << " from " <<
1583                         getPeerAddress(peer_id).serializeString() <<
1584                         " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1585                 if (wantSudo) {
1586                         DenySudoAccess(peer_id);
1587                         return;
1588                 }
1589
1590                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1591                 return;
1592         }
1593
1594         std::string bytes_A;
1595         u8 based_on;
1596         *pkt >> bytes_A >> based_on;
1597
1598         infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1599                 << "based_on=" << int(based_on) << " and len_A="
1600                 << bytes_A.length() << "." << std::endl;
1601
1602         AuthMechanism chosen = (based_on == 0) ?
1603                 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1604
1605         if (wantSudo) {
1606                 if (!client->isSudoMechAllowed(chosen)) {
1607                         actionstream << "Server: Player \"" << client->getName() <<
1608                                 "\" at " << getPeerAddress(peer_id).serializeString() <<
1609                                 " tried to change password using unallowed mech " << chosen <<
1610                                 "." << std::endl;
1611                         DenySudoAccess(peer_id);
1612                         return;
1613                 }
1614         } else {
1615                 if (!client->isMechAllowed(chosen)) {
1616                         actionstream << "Server: Client tried to authenticate from " <<
1617                                 getPeerAddress(peer_id).serializeString() <<
1618                                 " using unallowed mech " << chosen << "." << std::endl;
1619                         DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1620                         return;
1621                 }
1622         }
1623
1624         client->chosen_mech = chosen;
1625
1626         std::string salt, verifier;
1627
1628         if (based_on == 0) {
1629
1630                 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1631                         &verifier, &salt);
1632         } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1633                 // Non-base64 errors should have been catched in the init handler
1634                 actionstream << "Server: User " << client->getName() <<
1635                         " tried to log in, but srp verifier field was invalid (most likely "
1636                         "invalid base64)." << std::endl;
1637                 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1638                 return;
1639         }
1640
1641         char *bytes_B = 0;
1642         size_t len_B = 0;
1643
1644         client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1645                 client->getName().c_str(),
1646                 (const unsigned char *) salt.c_str(), salt.size(),
1647                 (const unsigned char *) verifier.c_str(), verifier.size(),
1648                 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1649                 NULL, 0,
1650                 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1651
1652         if (!bytes_B) {
1653                 actionstream << "Server: User " << client->getName()
1654                         << " tried to log in, SRP-6a safety check violated in _A handler."
1655                         << std::endl;
1656                 if (wantSudo) {
1657                         DenySudoAccess(peer_id);
1658                         client->resetChosenMech();
1659                         return;
1660                 }
1661
1662                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1663                 return;
1664         }
1665
1666         NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1667         resp_pkt << salt << std::string(bytes_B, len_B);
1668         Send(&resp_pkt);
1669 }
1670
1671 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1672 {
1673         session_t peer_id = pkt->getPeerId();
1674         RemoteClient *client = getClient(peer_id, CS_Invalid);
1675         ClientState cstate = client->getState();
1676         const std::string addr_s = client->getAddress().serializeString();
1677         const std::string playername = client->getName();
1678
1679         const bool wantSudo = (cstate == CS_Active);
1680
1681         verbosestream << "Server: Received TOSERVER_SRP_BYTES_M." << std::endl;
1682
1683         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1684                 warningstream << "Server: got SRP_M packet in wrong state "
1685                         << cstate << " from " << addr_s << ". Ignoring." << std::endl;
1686                 return;
1687         }
1688
1689         if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1690                         client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1691                 warningstream << "Server: got SRP_M packet, while auth "
1692                         "is going on with mech " << client->chosen_mech << " from "
1693                         << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1694                 if (wantSudo) {
1695                         DenySudoAccess(peer_id);
1696                         return;
1697                 }
1698
1699                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1700                 return;
1701         }
1702
1703         std::string bytes_M;
1704         *pkt >> bytes_M;
1705
1706         if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1707                         != bytes_M.size()) {
1708                 actionstream << "Server: User " << playername << " at " << addr_s
1709                         << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1710                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1711                 return;
1712         }
1713
1714         unsigned char *bytes_HAMK = 0;
1715
1716         srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1717                 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1718
1719         if (!bytes_HAMK) {
1720                 if (wantSudo) {
1721                         actionstream << "Server: User " << playername << " at " << addr_s
1722                                 << " tried to change their password, but supplied wrong"
1723                                 << " (SRP) password for authentication." << std::endl;
1724                         DenySudoAccess(peer_id);
1725                         client->resetChosenMech();
1726                         return;
1727                 }
1728
1729                 actionstream << "Server: User " << playername << " at " << addr_s
1730                         << " supplied wrong password (auth mechanism: SRP)." << std::endl;
1731                 m_script->on_authplayer(playername, addr_s, false);
1732                 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1733                 return;
1734         }
1735
1736         if (client->create_player_on_auth_success) {
1737                 m_script->createAuth(playername, client->enc_pwd);
1738
1739                 if (!m_script->getAuth(playername, nullptr, nullptr)) {
1740                         errorstream << "Server: " << playername <<
1741                                 " cannot be authenticated (auth handler does not work?)" <<
1742                                 std::endl;
1743                         DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1744                         return;
1745                 }
1746                 client->create_player_on_auth_success = false;
1747         }
1748
1749         m_script->on_authplayer(playername, addr_s, true);
1750         acceptAuth(peer_id, wantSudo);
1751 }
1752
1753 /*
1754  * Mod channels
1755  */
1756
1757 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1758 {
1759         std::string channel_name;
1760         *pkt >> channel_name;
1761
1762         session_t peer_id = pkt->getPeerId();
1763         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1764                 1 + 2 + channel_name.size(), peer_id);
1765
1766         // Send signal to client to notify join succeed or not
1767         if (g_settings->getBool("enable_mod_channels") &&
1768                         m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1769                 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1770                 infostream << "Peer " << peer_id << " joined channel " <<
1771                         channel_name << std::endl;
1772         }
1773         else {
1774                 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1775                 infostream << "Peer " << peer_id << " tried to join channel " <<
1776                         channel_name << ", but was already registered." << std::endl;
1777         }
1778         resp_pkt << channel_name;
1779         Send(&resp_pkt);
1780 }
1781
1782 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1783 {
1784         std::string channel_name;
1785         *pkt >> channel_name;
1786
1787         session_t peer_id = pkt->getPeerId();
1788         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1789                 1 + 2 + channel_name.size(), peer_id);
1790
1791         // Send signal to client to notify join succeed or not
1792         if (g_settings->getBool("enable_mod_channels") &&
1793                         m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1794                 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1795                 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1796                         std::endl;
1797         } else {
1798                 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1799                 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1800                         ", but was not registered." << std::endl;
1801         }
1802         resp_pkt << channel_name;
1803         Send(&resp_pkt);
1804 }
1805
1806 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1807 {
1808         std::string channel_name, channel_msg;
1809         *pkt >> channel_name >> channel_msg;
1810
1811         session_t peer_id = pkt->getPeerId();
1812         verbosestream << "Mod channel message received from peer " << peer_id <<
1813                 " on channel " << channel_name << " message: " << channel_msg <<
1814                 std::endl;
1815
1816         // If mod channels are not enabled, discard message
1817         if (!g_settings->getBool("enable_mod_channels")) {
1818                 return;
1819         }
1820
1821         // If channel not registered, signal it and ignore message
1822         if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1823                 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1824                         1 + 2 + channel_name.size(), peer_id);
1825                 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1826                 Send(&resp_pkt);
1827                 return;
1828         }
1829
1830         // @TODO: filter, rate limit
1831
1832         broadcastModChannelMessage(channel_name, channel_msg, peer_id);
1833 }
1834
1835 void Server::handleCommand_HaveMedia(NetworkPacket *pkt)
1836 {
1837         std::vector<u32> tokens;
1838         u8 numtokens;
1839
1840         *pkt >> numtokens;
1841         for (u16 i = 0; i < numtokens; i++) {
1842                 u32 n;
1843                 *pkt >> n;
1844                 tokens.emplace_back(n);
1845         }
1846
1847         const session_t peer_id = pkt->getPeerId();
1848         auto player = m_env->getPlayer(peer_id);
1849
1850         for (const u32 token : tokens) {
1851                 auto it = m_pending_dyn_media.find(token);
1852                 if (it == m_pending_dyn_media.end())
1853                         continue;
1854                 if (it->second.waiting_players.count(peer_id)) {
1855                         it->second.waiting_players.erase(peer_id);
1856                         if (player)
1857                                 getScriptIface()->on_dynamic_media_added(token, player->getName());
1858                 }
1859         }
1860 }
1861
1862 void Server::handleCommand_UpdateClientInfo(NetworkPacket *pkt)
1863 {
1864         ClientDynamicInfo info;
1865         *pkt >> info.render_target_size.X;
1866         *pkt >> info.render_target_size.Y;
1867         *pkt >> info.real_gui_scaling;
1868         *pkt >> info.real_hud_scaling;
1869         *pkt >> info.max_fs_size.X;
1870         *pkt >> info.max_fs_size.Y;
1871
1872         session_t peer_id = pkt->getPeerId();
1873         RemoteClient *client = getClient(peer_id, CS_Invalid);
1874         client->setDynamicInfo(info);
1875 }