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