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