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