]> git.lizzy.rs Git - minetest.git/blob - src/network/serverpackethandler.cpp
Remove redundant on_dieplayer calls
[minetest.git] / src / network / serverpackethandler.cpp
1 /*
2 Minetest
3 Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "chatmessage.h"
21 #include "server.h"
22 #include "log.h"
23 #include "emerge.h"
24 #include "mapblock.h"
25 #include "modchannels.h"
26 #include "nodedef.h"
27 #include "remoteplayer.h"
28 #include "rollback_interface.h"
29 #include "scripting_server.h"
30 #include "settings.h"
31 #include "tool.h"
32 #include "version.h"
33 #include "network/connection.h"
34 #include "network/networkprotocol.h"
35 #include "network/serveropcodes.h"
36 #include "server/player_sao.h"
37 #include "server/serverinventorymgr.h"
38 #include "util/auth.h"
39 #include "util/base64.h"
40 #include "util/pointedthing.h"
41 #include "util/serialize.h"
42 #include "util/srp.h"
43
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.jump  = (keyPressed & (0x1 << 4));
514         player->control.aux1  = (keyPressed & (0x1 << 5));
515         player->control.sneak = (keyPressed & (0x1 << 6));
516         player->control.dig   = (keyPressed & (0x1 << 7));
517         player->control.place = (keyPressed & (0x1 << 8));
518         player->control.zoom  = (keyPressed & (0x1 << 9));
519
520         if (playersao->checkMovementCheat()) {
521                 // Call callbacks
522                 m_script->on_cheat(playersao, "moved_too_fast");
523                 SendMovePlayer(pkt->getPeerId());
524         }
525 }
526
527 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
528 {
529         session_t peer_id = pkt->getPeerId();
530         RemotePlayer *player = m_env->getPlayer(peer_id);
531         if (player == NULL) {
532                 errorstream <<
533                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
534                         peer_id << " disconnecting peer!" << std::endl;
535                 DisconnectPeer(peer_id);
536                 return;
537         }
538
539         PlayerSAO *playersao = player->getPlayerSAO();
540         if (playersao == NULL) {
541                 errorstream <<
542                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
543                         peer_id << " disconnecting peer!" << std::endl;
544                 DisconnectPeer(peer_id);
545                 return;
546         }
547
548         // If player is dead we don't care of this packet
549         if (playersao->isDead()) {
550                 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
551                                 << " is dead. Ignoring packet";
552                 return;
553         }
554
555         process_PlayerPos(player, playersao, pkt);
556 }
557
558 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
559 {
560         if (pkt->getSize() < 1)
561                 return;
562
563         /*
564                 [0] u16 command
565                 [2] u8 count
566                 [3] v3s16 pos_0
567                 [3+6] v3s16 pos_1
568                 ...
569         */
570
571         u8 count;
572         *pkt >> count;
573
574         RemoteClient *client = getClient(pkt->getPeerId());
575
576         if ((s16)pkt->getSize() < 1 + (int)count * 6) {
577                 throw con::InvalidIncomingDataException
578                                 ("DELETEDBLOCKS length is too short");
579         }
580
581         for (u16 i = 0; i < count; i++) {
582                 v3s16 p;
583                 *pkt >> p;
584                 client->SetBlockNotSent(p);
585         }
586 }
587
588 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
589 {
590         session_t peer_id = pkt->getPeerId();
591         RemotePlayer *player = m_env->getPlayer(peer_id);
592
593         if (player == NULL) {
594                 errorstream <<
595                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
596                         peer_id << " disconnecting peer!" << std::endl;
597                 DisconnectPeer(peer_id);
598                 return;
599         }
600
601         PlayerSAO *playersao = player->getPlayerSAO();
602         if (playersao == NULL) {
603                 errorstream <<
604                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
605                         peer_id << " disconnecting peer!" << std::endl;
606                 DisconnectPeer(peer_id);
607                 return;
608         }
609
610         // Strip command and create a stream
611         std::string datastring(pkt->getString(0), pkt->getSize());
612         verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
613                 << std::endl;
614         std::istringstream is(datastring, std::ios_base::binary);
615         // Create an action
616         std::unique_ptr<InventoryAction> a(InventoryAction::deSerialize(is));
617         if (!a) {
618                 infostream << "TOSERVER_INVENTORY_ACTION: "
619                                 << "InventoryAction::deSerialize() returned NULL"
620                                 << std::endl;
621                 return;
622         }
623
624         // If something goes wrong, this player is to blame
625         RollbackScopeActor rollback_scope(m_rollback,
626                         std::string("player:")+player->getName());
627
628         /*
629                 Note: Always set inventory not sent, to repair cases
630                 where the client made a bad prediction.
631         */
632
633         const bool player_has_interact = checkPriv(player->getName(), "interact");
634
635         auto check_inv_access = [player, player_has_interact, this] (
636                         const InventoryLocation &loc) -> bool {
637
638                 // Players without interact may modify their own inventory
639                 if (!player_has_interact && loc.type != InventoryLocation::PLAYER) {
640                         infostream << "Cannot modify foreign inventory: "
641                                         << "No interact privilege" << std::endl;
642                         return false;
643                 }
644
645                 switch (loc.type) {
646                 case InventoryLocation::CURRENT_PLAYER:
647                         // Only used internally on the client, never sent
648                         return false;
649                 case InventoryLocation::PLAYER:
650                         // Allow access to own inventory in all cases
651                         return loc.name == player->getName();
652                 case InventoryLocation::NODEMETA:
653                         {
654                                 // Check for out-of-range interaction
655                                 v3f node_pos   = intToFloat(loc.p, BS);
656                                 v3f player_pos = player->getPlayerSAO()->getEyePosition();
657                                 f32 d = player_pos.getDistanceFrom(node_pos);
658                                 return checkInteractDistance(player, d, "inventory");
659                         }
660                 case InventoryLocation::DETACHED:
661                         return getInventoryMgr()->checkDetachedInventoryAccess(loc, player->getName());
662                 default:
663                         return false;
664                 }
665         };
666
667         /*
668                 Handle restrictions and special cases of the move action
669         */
670         if (a->getType() == IAction::Move) {
671                 IMoveAction *ma = (IMoveAction*)a.get();
672
673                 ma->from_inv.applyCurrentPlayer(player->getName());
674                 ma->to_inv.applyCurrentPlayer(player->getName());
675
676                 m_inventory_mgr->setInventoryModified(ma->from_inv);
677                 if (ma->from_inv != ma->to_inv)
678                         m_inventory_mgr->setInventoryModified(ma->to_inv);
679
680                 if (!check_inv_access(ma->from_inv) ||
681                                 !check_inv_access(ma->to_inv))
682                         return;
683
684                 /*
685                         Disable moving items out of craftpreview
686                 */
687                 if (ma->from_list == "craftpreview") {
688                         infostream << "Ignoring IMoveAction from "
689                                         << (ma->from_inv.dump()) << ":" << ma->from_list
690                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
691                                         << " because src is " << ma->from_list << std::endl;
692                         return;
693                 }
694
695                 /*
696                         Disable moving items into craftresult and craftpreview
697                 */
698                 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
699                         infostream << "Ignoring IMoveAction from "
700                                         << (ma->from_inv.dump()) << ":" << ma->from_list
701                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
702                                         << " because dst is " << ma->to_list << std::endl;
703                         return;
704                 }
705         }
706         /*
707                 Handle restrictions and special cases of the drop action
708         */
709         else if (a->getType() == IAction::Drop) {
710                 IDropAction *da = (IDropAction*)a.get();
711
712                 da->from_inv.applyCurrentPlayer(player->getName());
713
714                 m_inventory_mgr->setInventoryModified(da->from_inv);
715
716                 /*
717                         Disable dropping items out of craftpreview
718                 */
719                 if (da->from_list == "craftpreview") {
720                         infostream << "Ignoring IDropAction from "
721                                         << (da->from_inv.dump()) << ":" << da->from_list
722                                         << " because src is " << da->from_list << std::endl;
723                         return;
724                 }
725
726                 // Disallow dropping items if not allowed to interact
727                 if (!player_has_interact || !check_inv_access(da->from_inv))
728                         return;
729
730                 // Disallow dropping items if dead
731                 if (playersao->isDead()) {
732                         infostream << "Ignoring IDropAction from "
733                                         << (da->from_inv.dump()) << ":" << da->from_list
734                                         << " because player is dead." << std::endl;
735                         return;
736                 }
737         }
738         /*
739                 Handle restrictions and special cases of the craft action
740         */
741         else if (a->getType() == IAction::Craft) {
742                 ICraftAction *ca = (ICraftAction*)a.get();
743
744                 ca->craft_inv.applyCurrentPlayer(player->getName());
745
746                 m_inventory_mgr->setInventoryModified(ca->craft_inv);
747
748                 // Disallow crafting if not allowed to interact
749                 if (!player_has_interact) {
750                         infostream << "Cannot craft: "
751                                         << "No interact privilege" << std::endl;
752                         return;
753                 }
754
755                 if (!check_inv_access(ca->craft_inv))
756                         return;
757         } else {
758                 // Unknown action. Ignored.
759                 return;
760         }
761
762         // Do the action
763         a->apply(m_inventory_mgr.get(), playersao, this);
764 }
765
766 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
767 {
768         std::wstring message;
769         *pkt >> message;
770
771         session_t peer_id = pkt->getPeerId();
772         RemotePlayer *player = m_env->getPlayer(peer_id);
773         if (player == NULL) {
774                 errorstream <<
775                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
776                         peer_id << " disconnecting peer!" << std::endl;
777                 DisconnectPeer(peer_id);
778                 return;
779         }
780
781         std::string name = player->getName();
782
783         std::wstring answer_to_sender = handleChat(name, message, true, player);
784         if (!answer_to_sender.empty()) {
785                 // Send the answer to sender
786                 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
787                         answer_to_sender));
788         }
789 }
790
791 void Server::handleCommand_Damage(NetworkPacket* pkt)
792 {
793         u16 damage;
794
795         *pkt >> damage;
796
797         session_t peer_id = pkt->getPeerId();
798         RemotePlayer *player = m_env->getPlayer(peer_id);
799
800         if (player == NULL) {
801                 errorstream <<
802                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
803                         peer_id << " disconnecting peer!" << std::endl;
804                 DisconnectPeer(peer_id);
805                 return;
806         }
807
808         PlayerSAO *playersao = player->getPlayerSAO();
809         if (playersao == NULL) {
810                 errorstream <<
811                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
812                         peer_id << " disconnecting peer!" << std::endl;
813                 DisconnectPeer(peer_id);
814                 return;
815         }
816
817         if (!playersao->isImmortal()) {
818                 if (playersao->isDead()) {
819                         verbosestream << "Server::ProcessData(): Info: "
820                                 "Ignoring damage as player " << player->getName()
821                                 << " is already dead." << std::endl;
822                         return;
823                 }
824
825                 actionstream << player->getName() << " damaged by "
826                                 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
827                                 << std::endl;
828
829                 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
830                 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
831         }
832 }
833
834 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
835 {
836         if (pkt->getSize() < 2)
837                 return;
838
839         session_t peer_id = pkt->getPeerId();
840         RemotePlayer *player = m_env->getPlayer(peer_id);
841
842         if (player == NULL) {
843                 errorstream <<
844                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
845                         peer_id << " disconnecting peer!" << std::endl;
846                 DisconnectPeer(peer_id);
847                 return;
848         }
849
850         PlayerSAO *playersao = player->getPlayerSAO();
851         if (playersao == NULL) {
852                 errorstream <<
853                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
854                         peer_id << " disconnecting peer!" << std::endl;
855                 DisconnectPeer(peer_id);
856                 return;
857         }
858
859         u16 item;
860
861         *pkt >> item;
862
863         if (item >= player->getHotbarItemcount()) {
864                 actionstream << "Player: " << player->getName()
865                         << " tried to access item=" << item
866                         << " out of hotbar_itemcount="
867                         << player->getHotbarItemcount()
868                         << "; ignoring." << std::endl;
869                 return;
870         }
871
872         playersao->getPlayer()->setWieldIndex(item);
873 }
874
875 void Server::handleCommand_Respawn(NetworkPacket* pkt)
876 {
877         session_t peer_id = pkt->getPeerId();
878         RemotePlayer *player = m_env->getPlayer(peer_id);
879         if (player == NULL) {
880                 errorstream <<
881                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
882                         peer_id << " disconnecting peer!" << std::endl;
883                 DisconnectPeer(peer_id);
884                 return;
885         }
886
887         PlayerSAO *playersao = player->getPlayerSAO();
888         assert(playersao);
889
890         if (!playersao->isDead())
891                 return;
892
893         RespawnPlayer(peer_id);
894
895         actionstream << player->getName() << " respawns at "
896                         << PP(playersao->getBasePosition() / BS) << std::endl;
897
898         // ActiveObject is added to environment in AsyncRunStep after
899         // the previous addition has been successfully removed
900 }
901
902 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
903 {
904         ItemStack selected_item, hand_item;
905         player->getWieldedItem(&selected_item, &hand_item);
906         f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
907                         hand_item.getDefinition(m_itemdef));
908
909         // Cube diagonal * 1.5 for maximal supported node extents:
910         // sqrt(3) * 1.5 â‰… 2.6
911         if (d > max_d + 2.6f * BS) {
912                 actionstream << "Player " << player->getName()
913                                 << " tried to access " << what
914                                 << " from too far: "
915                                 << "d=" << d << ", max_d=" << max_d
916                                 << "; ignoring." << std::endl;
917                 // Call callbacks
918                 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
919                 return false;
920         }
921         return true;
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                 u16 wear = pointed_object->punch(dir, &toolcap, playersao,
1116                                 time_from_last_punch);
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                         // If can't dig, try hand
1171                         if (!params.diggable) {
1172                                 params = getDigParams(m_nodedef->get(n).groups,
1173                                         &hand_item.getToolCapabilities(m_itemdef));
1174                         }
1175                         // If can't dig, ignore dig
1176                         if (!params.diggable) {
1177                                 infostream << "Server: " << player->getName()
1178                                                 << " completed digging " << PP(p_under)
1179                                                 << ", which is not diggable with tool; not digging."
1180                                                 << std::endl;
1181                                 is_valid_dig = false;
1182                                 // Call callbacks
1183                                 m_script->on_cheat(playersao, "dug_unbreakable");
1184                         }
1185                         // Check digging time
1186                         // If already invalidated, we don't have to
1187                         if (!is_valid_dig) {
1188                                 // Well not our problem then
1189                         }
1190                         // Clean and long dig
1191                         else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1192                                 // All is good, but grab time from pool; don't care if
1193                                 // it's actually available
1194                                 playersao->getDigPool().grab(params.time);
1195                         }
1196                         // Short or laggy dig
1197                         // Try getting the time from pool
1198                         else if (playersao->getDigPool().grab(params.time)) {
1199                                 // All is good
1200                         }
1201                         // Dig not possible
1202                         else {
1203                                 infostream << "Server: " << player->getName()
1204                                                 << " completed digging " << PP(p_under)
1205                                                 << "too fast; not digging." << std::endl;
1206                                 is_valid_dig = false;
1207                                 // Call callbacks
1208                                 m_script->on_cheat(playersao, "dug_too_fast");
1209                         }
1210                 }
1211
1212                 /* Actually dig node */
1213
1214                 if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1215                         m_script->node_on_dig(p_under, n, playersao);
1216
1217                 v3s16 blockpos = getNodeBlockPos(p_under);
1218                 RemoteClient *client = getClient(peer_id);
1219                 // Send unusual result (that is, node not being removed)
1220                 if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR)
1221                         // Re-send block to revert change on client-side
1222                         client->SetBlockNotSent(blockpos);
1223                 else
1224                         client->ResendBlockIfOnWire(blockpos);
1225
1226                 return;
1227         } // action == INTERACT_DIGGING_COMPLETED
1228
1229         // Place block or right-click object
1230         case INTERACT_PLACE: {
1231                 ItemStack selected_item;
1232                 playersao->getWieldedItem(&selected_item, nullptr);
1233
1234                 // Reset build time counter
1235                 if (pointed.type == POINTEDTHING_NODE &&
1236                                 selected_item.getDefinition(m_itemdef).type == ITEM_NODE)
1237                         getClient(peer_id)->m_time_from_building = 0.0;
1238
1239                 if (pointed.type == POINTEDTHING_OBJECT) {
1240                         // Right click object
1241
1242                         // Skip if object can't be interacted with anymore
1243                         if (pointed_object->isGone())
1244                                 return;
1245
1246                         actionstream << player->getName() << " right-clicks object "
1247                                         << pointed.object_id << ": "
1248                                         << pointed_object->getDescription() << std::endl;
1249
1250                         // Do stuff
1251                         if (m_script->item_OnSecondaryUse(
1252                                         selected_item, playersao, pointed)) {
1253                                 if (playersao->setWieldedItem(selected_item)) {
1254                                         SendInventory(playersao, true);
1255                                 }
1256                         }
1257
1258                         pointed_object->rightClick(playersao);
1259                 } else if (m_script->item_OnPlace(selected_item, playersao, pointed)) {
1260                         // Placement was handled in lua
1261
1262                         // Apply returned ItemStack
1263                         if (playersao->setWieldedItem(selected_item))
1264                                 SendInventory(playersao, true);
1265                 }
1266
1267                 if (pointed.type != POINTEDTHING_NODE)
1268                         return;
1269
1270                 // If item has node placement prediction, always send the
1271                 // blocks to make sure the client knows what exactly happened
1272                 RemoteClient *client = getClient(peer_id);
1273                 v3s16 blockpos = getNodeBlockPos(pointed.node_abovesurface);
1274                 v3s16 blockpos2 = getNodeBlockPos(pointed.node_undersurface);
1275                 if (!selected_item.getDefinition(m_itemdef
1276                                 ).node_placement_prediction.empty()) {
1277                         client->SetBlockNotSent(blockpos);
1278                         if (blockpos2 != blockpos)
1279                                 client->SetBlockNotSent(blockpos2);
1280                 } else {
1281                         client->ResendBlockIfOnWire(blockpos);
1282                         if (blockpos2 != blockpos)
1283                                 client->ResendBlockIfOnWire(blockpos2);
1284                 }
1285
1286                 return;
1287         } // action == INTERACT_PLACE
1288
1289         case INTERACT_USE: {
1290                 ItemStack selected_item;
1291                 playersao->getWieldedItem(&selected_item, nullptr);
1292
1293                 actionstream << player->getName() << " uses " << selected_item.name
1294                                 << ", pointing at " << pointed.dump() << std::endl;
1295
1296                 if (m_script->item_OnUse(selected_item, playersao, pointed)) {
1297                         // Apply returned ItemStack
1298                         if (playersao->setWieldedItem(selected_item))
1299                                 SendInventory(playersao, true);
1300                 }
1301
1302                 return;
1303         }
1304
1305         // Rightclick air
1306         case INTERACT_ACTIVATE: {
1307                 ItemStack selected_item;
1308                 playersao->getWieldedItem(&selected_item, nullptr);
1309
1310                 actionstream << player->getName() << " activates "
1311                                 << selected_item.name << std::endl;
1312
1313                 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1314
1315                 if (m_script->item_OnSecondaryUse(selected_item, playersao, pointed)) {
1316                         if (playersao->setWieldedItem(selected_item))
1317                                 SendInventory(playersao, true);
1318                 }
1319
1320                 return;
1321         }
1322
1323         default:
1324                 warningstream << "Server: Invalid action " << action << std::endl;
1325
1326         }
1327 }
1328
1329 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1330 {
1331         u16 num;
1332         *pkt >> num;
1333         for (u16 k = 0; k < num; k++) {
1334                 s32 id;
1335
1336                 *pkt >> id;
1337
1338                 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1339                         m_playing_sounds.find(id);
1340                 if (i == m_playing_sounds.end())
1341                         continue;
1342
1343                 ServerPlayingSound &psound = i->second;
1344                 psound.clients.erase(pkt->getPeerId());
1345                 if (psound.clients.empty())
1346                         m_playing_sounds.erase(i++);
1347         }
1348 }
1349
1350 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1351 {
1352         v3s16 p;
1353         std::string formname;
1354         u16 num;
1355
1356         *pkt >> p >> formname >> num;
1357
1358         StringMap fields;
1359         for (u16 k = 0; k < num; k++) {
1360                 std::string fieldname;
1361                 *pkt >> fieldname;
1362                 fields[fieldname] = pkt->readLongString();
1363         }
1364
1365         session_t peer_id = pkt->getPeerId();
1366         RemotePlayer *player = m_env->getPlayer(peer_id);
1367
1368         if (player == NULL) {
1369                 errorstream <<
1370                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
1371                         peer_id << " disconnecting peer!" << std::endl;
1372                 DisconnectPeer(peer_id);
1373                 return;
1374         }
1375
1376         PlayerSAO *playersao = player->getPlayerSAO();
1377         if (playersao == NULL) {
1378                 errorstream <<
1379                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1380                         peer_id << " disconnecting peer!" << std::endl;
1381                 DisconnectPeer(peer_id);
1382                 return;
1383         }
1384
1385         // If something goes wrong, this player is to blame
1386         RollbackScopeActor rollback_scope(m_rollback,
1387                         std::string("player:")+player->getName());
1388
1389         // Check the target node for rollback data; leave others unnoticed
1390         RollbackNode rn_old(&m_env->getMap(), p, this);
1391
1392         m_script->node_on_receive_fields(p, formname, fields, playersao);
1393
1394         // Report rollback data
1395         RollbackNode rn_new(&m_env->getMap(), p, this);
1396         if (rollback() && rn_new != rn_old) {
1397                 RollbackAction action;
1398                 action.setSetNode(p, rn_old, rn_new);
1399                 rollback()->reportAction(action);
1400         }
1401 }
1402
1403 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1404 {
1405         std::string client_formspec_name;
1406         u16 num;
1407
1408         *pkt >> client_formspec_name >> num;
1409
1410         StringMap fields;
1411         for (u16 k = 0; k < num; k++) {
1412                 std::string fieldname;
1413                 *pkt >> fieldname;
1414                 fields[fieldname] = pkt->readLongString();
1415         }
1416
1417         session_t peer_id = pkt->getPeerId();
1418         RemotePlayer *player = m_env->getPlayer(peer_id);
1419
1420         if (player == NULL) {
1421                 errorstream <<
1422                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
1423                         peer_id << " disconnecting peer!" << std::endl;
1424                 DisconnectPeer(peer_id);
1425                 return;
1426         }
1427
1428         PlayerSAO *playersao = player->getPlayerSAO();
1429         if (playersao == NULL) {
1430                 errorstream <<
1431                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1432                         peer_id << " disconnecting peer!" << std::endl;
1433                 DisconnectPeer(peer_id);
1434                 return;
1435         }
1436
1437         if (client_formspec_name.empty()) { // pass through inventory submits
1438                 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1439                 return;
1440         }
1441
1442         // verify that we displayed the formspec to the user
1443         const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1444         if (peer_state_iterator != m_formspec_state_data.end()) {
1445                 const std::string &server_formspec_name = peer_state_iterator->second;
1446                 if (client_formspec_name == server_formspec_name) {
1447                         auto it = fields.find("quit");
1448                         if (it != fields.end() && it->second == "true")
1449                                 m_formspec_state_data.erase(peer_state_iterator);
1450
1451                         m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1452                         return;
1453                 }
1454                 actionstream << "'" << player->getName()
1455                         << "' submitted formspec ('" << client_formspec_name
1456                         << "') but the name of the formspec doesn't match the"
1457                         " expected name ('" << server_formspec_name << "')";
1458
1459         } else {
1460                 actionstream << "'" << player->getName()
1461                         << "' submitted formspec ('" << client_formspec_name
1462                         << "') but server hasn't sent formspec to client";
1463         }
1464         actionstream << ", possible exploitation attempt" << std::endl;
1465 }
1466
1467 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1468 {
1469         session_t peer_id = pkt->getPeerId();
1470         RemoteClient *client = getClient(peer_id, CS_Invalid);
1471         ClientState cstate = client->getState();
1472
1473         std::string playername = client->getName();
1474
1475         std::string salt;
1476         std::string verification_key;
1477
1478         std::string addr_s = getPeerAddress(peer_id).serializeString();
1479         u8 is_empty;
1480
1481         *pkt >> salt >> verification_key >> is_empty;
1482
1483         verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1484                 << ", with is_empty=" << (is_empty == 1) << std::endl;
1485
1486         // Either this packet is sent because the user is new or to change the password
1487         if (cstate == CS_HelloSent) {
1488                 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1489                         actionstream << "Server: Client from " << addr_s
1490                                         << " tried to set password without being "
1491                                         << "authenticated, or the username being new." << std::endl;
1492                         DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1493                         return;
1494                 }
1495
1496                 if (!isSingleplayer() &&
1497                                 g_settings->getBool("disallow_empty_password") &&
1498                                 is_empty == 1) {
1499                         actionstream << "Server: " << playername
1500                                         << " supplied empty password from " << addr_s << std::endl;
1501                         DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1502                         return;
1503                 }
1504
1505                 std::string initial_ver_key;
1506
1507                 initial_ver_key = encode_srp_verifier(verification_key, salt);
1508                 m_script->createAuth(playername, initial_ver_key);
1509                 m_script->on_authplayer(playername, addr_s, true);
1510
1511                 acceptAuth(peer_id, false);
1512         } else {
1513                 if (cstate < CS_SudoMode) {
1514                         infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1515                                         << addr_s << ": " << "Client has wrong state " << cstate << "."
1516                                         << std::endl;
1517                         return;
1518                 }
1519                 m_clients.event(peer_id, CSE_SudoLeave);
1520                 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1521                 bool success = m_script->setPassword(playername, pw_db_field);
1522                 if (success) {
1523                         actionstream << playername << " changes password" << std::endl;
1524                         SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1525                                 L"Password change successful."));
1526                 } else {
1527                         actionstream << playername <<
1528                                 " tries to change password but it fails" << std::endl;
1529                         SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1530                                 L"Password change failed or unavailable."));
1531                 }
1532         }
1533 }
1534
1535 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1536 {
1537         session_t peer_id = pkt->getPeerId();
1538         RemoteClient *client = getClient(peer_id, CS_Invalid);
1539         ClientState cstate = client->getState();
1540
1541         bool wantSudo = (cstate == CS_Active);
1542
1543         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1544                 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1545                         " from " << getPeerAddress(peer_id).serializeString() <<
1546                         ". Ignoring." << std::endl;
1547                 return;
1548         }
1549
1550         if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1551                 actionstream << "Server: got SRP _A packet, while auth is already "
1552                         "going on with mech " << client->chosen_mech << " from " <<
1553                         getPeerAddress(peer_id).serializeString() <<
1554                         " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1555                 if (wantSudo) {
1556                         DenySudoAccess(peer_id);
1557                         return;
1558                 }
1559
1560                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1561                 return;
1562         }
1563
1564         std::string bytes_A;
1565         u8 based_on;
1566         *pkt >> bytes_A >> based_on;
1567
1568         infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1569                 << "based_on=" << int(based_on) << " and len_A="
1570                 << bytes_A.length() << "." << std::endl;
1571
1572         AuthMechanism chosen = (based_on == 0) ?
1573                 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1574
1575         if (wantSudo) {
1576                 if (!client->isSudoMechAllowed(chosen)) {
1577                         actionstream << "Server: Player \"" << client->getName() <<
1578                                 "\" at " << getPeerAddress(peer_id).serializeString() <<
1579                                 " tried to change password using unallowed mech " << chosen <<
1580                                 "." << std::endl;
1581                         DenySudoAccess(peer_id);
1582                         return;
1583                 }
1584         } else {
1585                 if (!client->isMechAllowed(chosen)) {
1586                         actionstream << "Server: Client tried to authenticate from " <<
1587                                 getPeerAddress(peer_id).serializeString() <<
1588                                 " using unallowed mech " << chosen << "." << std::endl;
1589                         DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1590                         return;
1591                 }
1592         }
1593
1594         client->chosen_mech = chosen;
1595
1596         std::string salt;
1597         std::string verifier;
1598
1599         if (based_on == 0) {
1600
1601                 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1602                         &verifier, &salt);
1603         } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1604                 // Non-base64 errors should have been catched in the init handler
1605                 actionstream << "Server: User " << client->getName() <<
1606                         " tried to log in, but srp verifier field was invalid (most likely "
1607                         "invalid base64)." << std::endl;
1608                 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1609                 return;
1610         }
1611
1612         char *bytes_B = 0;
1613         size_t len_B = 0;
1614
1615         client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1616                 client->getName().c_str(),
1617                 (const unsigned char *) salt.c_str(), salt.size(),
1618                 (const unsigned char *) verifier.c_str(), verifier.size(),
1619                 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1620                 NULL, 0,
1621                 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1622
1623         if (!bytes_B) {
1624                 actionstream << "Server: User " << client->getName()
1625                         << " tried to log in, SRP-6a safety check violated in _A handler."
1626                         << std::endl;
1627                 if (wantSudo) {
1628                         DenySudoAccess(peer_id);
1629                         return;
1630                 }
1631
1632                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1633                 return;
1634         }
1635
1636         NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1637         resp_pkt << salt << std::string(bytes_B, len_B);
1638         Send(&resp_pkt);
1639 }
1640
1641 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1642 {
1643         session_t peer_id = pkt->getPeerId();
1644         RemoteClient *client = getClient(peer_id, CS_Invalid);
1645         ClientState cstate = client->getState();
1646         std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1647         std::string playername = client->getName();
1648
1649         bool wantSudo = (cstate == CS_Active);
1650
1651         verbosestream << "Server: Received TOSERVER_SRP_BYTES_M." << std::endl;
1652
1653         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1654                 warningstream << "Server: got SRP_M packet in wrong state "
1655                         << cstate << " from " << addr_s << ". Ignoring." << std::endl;
1656                 return;
1657         }
1658
1659         if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1660                         client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1661                 warningstream << "Server: got SRP_M packet, while auth "
1662                         "is going on with mech " << client->chosen_mech << " from "
1663                         << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1664                 if (wantSudo) {
1665                         DenySudoAccess(peer_id);
1666                         return;
1667                 }
1668
1669                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1670                 return;
1671         }
1672
1673         std::string bytes_M;
1674         *pkt >> bytes_M;
1675
1676         if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1677                         != bytes_M.size()) {
1678                 actionstream << "Server: User " << playername << " at " << addr_s
1679                         << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1680                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1681                 return;
1682         }
1683
1684         unsigned char *bytes_HAMK = 0;
1685
1686         srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1687                 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1688
1689         if (!bytes_HAMK) {
1690                 if (wantSudo) {
1691                         actionstream << "Server: User " << playername << " at " << addr_s
1692                                 << " tried to change their password, but supplied wrong"
1693                                 << " (SRP) password for authentication." << std::endl;
1694                         DenySudoAccess(peer_id);
1695                         return;
1696                 }
1697
1698                 actionstream << "Server: User " << playername << " at " << addr_s
1699                         << " supplied wrong password (auth mechanism: SRP)." << std::endl;
1700                 m_script->on_authplayer(playername, addr_s, false);
1701                 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1702                 return;
1703         }
1704
1705         if (client->create_player_on_auth_success) {
1706                 m_script->createAuth(playername, client->enc_pwd);
1707
1708                 std::string checkpwd; // not used, but needed for passing something
1709                 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1710                         errorstream << "Server: " << playername <<
1711                                 " cannot be authenticated (auth handler does not work?)" <<
1712                                 std::endl;
1713                         DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1714                         return;
1715                 }
1716                 client->create_player_on_auth_success = false;
1717         }
1718
1719         m_script->on_authplayer(playername, addr_s, true);
1720         acceptAuth(peer_id, wantSudo);
1721 }
1722
1723 /*
1724  * Mod channels
1725  */
1726
1727 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1728 {
1729         std::string channel_name;
1730         *pkt >> channel_name;
1731
1732         session_t peer_id = pkt->getPeerId();
1733         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1734                 1 + 2 + channel_name.size(), peer_id);
1735
1736         // Send signal to client to notify join succeed or not
1737         if (g_settings->getBool("enable_mod_channels") &&
1738                         m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1739                 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1740                 infostream << "Peer " << peer_id << " joined channel " <<
1741                         channel_name << std::endl;
1742         }
1743         else {
1744                 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1745                 infostream << "Peer " << peer_id << " tried to join channel " <<
1746                         channel_name << ", but was already registered." << std::endl;
1747         }
1748         resp_pkt << channel_name;
1749         Send(&resp_pkt);
1750 }
1751
1752 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1753 {
1754         std::string channel_name;
1755         *pkt >> channel_name;
1756
1757         session_t peer_id = pkt->getPeerId();
1758         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1759                 1 + 2 + channel_name.size(), peer_id);
1760
1761         // Send signal to client to notify join succeed or not
1762         if (g_settings->getBool("enable_mod_channels") &&
1763                         m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1764                 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1765                 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1766                         std::endl;
1767         } else {
1768                 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1769                 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1770                         ", but was not registered." << std::endl;
1771         }
1772         resp_pkt << channel_name;
1773         Send(&resp_pkt);
1774 }
1775
1776 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1777 {
1778         std::string channel_name, channel_msg;
1779         *pkt >> channel_name >> channel_msg;
1780
1781         session_t peer_id = pkt->getPeerId();
1782         verbosestream << "Mod channel message received from peer " << peer_id <<
1783                 " on channel " << channel_name << " message: " << channel_msg <<
1784                 std::endl;
1785
1786         // If mod channels are not enabled, discard message
1787         if (!g_settings->getBool("enable_mod_channels")) {
1788                 return;
1789         }
1790
1791         // If channel not registered, signal it and ignore message
1792         if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1793                 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1794                         1 + 2 + channel_name.size(), peer_id);
1795                 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1796                 Send(&resp_pkt);
1797                 return;
1798         }
1799
1800         // @TODO: filter, rate limit
1801
1802         broadcastModChannelMessage(channel_name, channel_msg, peer_id);
1803 }