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