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