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