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