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