]> git.lizzy.rs Git - minetest.git/blob - src/network/serverpackethandler.cpp
91caee0bd9ba452049619bff55502569dd9826ba
[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 "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         SendCSMRestrictionFlags(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_state.isTimerRunning()) {
406                 SendChatMessage(pkt->getPeerId(), m_shutdown_state.getShutdownTimerMessage());
407         }
408 }
409
410 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
411 {
412         if (pkt->getSize() < 1)
413                 return;
414
415         /*
416                 [0] u16 command
417                 [2] u8 count
418                 [3] v3s16 pos_0
419                 [3+6] v3s16 pos_1
420                 ...
421         */
422
423         u8 count;
424         *pkt >> count;
425
426         RemoteClient *client = getClient(pkt->getPeerId());
427
428         if ((s16)pkt->getSize() < 1 + (int)count * 6) {
429                 throw con::InvalidIncomingDataException
430                                 ("GOTBLOCKS length is too short");
431         }
432
433         for (u16 i = 0; i < count; i++) {
434                 v3s16 p;
435                 *pkt >> p;
436                 client->GotBlock(p);
437         }
438 }
439
440 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
441         NetworkPacket *pkt)
442 {
443         if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
444                 return;
445
446         v3s32 ps, ss;
447         s32 f32pitch, f32yaw;
448         u8 f32fov;
449
450         *pkt >> ps;
451         *pkt >> ss;
452         *pkt >> f32pitch;
453         *pkt >> f32yaw;
454
455         f32 pitch = (f32)f32pitch / 100.0f;
456         f32 yaw = (f32)f32yaw / 100.0f;
457         u32 keyPressed = 0;
458
459         // default behavior (in case an old client doesn't send these)
460         f32 fov = 0;
461         u8 wanted_range = 0;
462
463         *pkt >> keyPressed;
464         *pkt >> f32fov;
465         fov = (f32)f32fov / 80.0f;
466         *pkt >> wanted_range;
467
468         v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
469         v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
470
471         pitch = modulo360f(pitch);
472         yaw = wrapDegrees_0_360(yaw);
473
474         playersao->setBasePosition(position);
475         player->setSpeed(speed);
476         playersao->setPitch(pitch);
477         playersao->setYaw(yaw);
478         playersao->setFov(fov);
479         playersao->setWantedRange(wanted_range);
480         player->keyPressed = keyPressed;
481         player->control.up = (keyPressed & 1);
482         player->control.down = (keyPressed & 2);
483         player->control.left = (keyPressed & 4);
484         player->control.right = (keyPressed & 8);
485         player->control.jump = (keyPressed & 16);
486         player->control.aux1 = (keyPressed & 32);
487         player->control.sneak = (keyPressed & 64);
488         player->control.LMB = (keyPressed & 128);
489         player->control.RMB = (keyPressed & 256);
490
491         if (playersao->checkMovementCheat()) {
492                 // Call callbacks
493                 m_script->on_cheat(playersao, "moved_too_fast");
494                 SendMovePlayer(pkt->getPeerId());
495         }
496 }
497
498 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
499 {
500         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
501         if (player == NULL) {
502                 errorstream << "Server::ProcessData(): Canceling: "
503                                 "No player for peer_id=" << pkt->getPeerId()
504                                 << " disconnecting peer!" << std::endl;
505                 DisconnectPeer(pkt->getPeerId());
506                 return;
507         }
508
509         PlayerSAO *playersao = player->getPlayerSAO();
510         if (playersao == NULL) {
511                 errorstream << "Server::ProcessData(): Canceling: "
512                                 "No player object for peer_id=" << pkt->getPeerId()
513                                 << " disconnecting peer!" << std::endl;
514                 DisconnectPeer(pkt->getPeerId());
515                 return;
516         }
517
518         // If player is dead we don't care of this packet
519         if (playersao->isDead()) {
520                 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
521                                 << " is dead. Ignoring packet";
522                 return;
523         }
524
525         process_PlayerPos(player, playersao, pkt);
526 }
527
528 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
529 {
530         if (pkt->getSize() < 1)
531                 return;
532
533         /*
534                 [0] u16 command
535                 [2] u8 count
536                 [3] v3s16 pos_0
537                 [3+6] v3s16 pos_1
538                 ...
539         */
540
541         u8 count;
542         *pkt >> count;
543
544         RemoteClient *client = getClient(pkt->getPeerId());
545
546         if ((s16)pkt->getSize() < 1 + (int)count * 6) {
547                 throw con::InvalidIncomingDataException
548                                 ("DELETEDBLOCKS length is too short");
549         }
550
551         for (u16 i = 0; i < count; i++) {
552                 v3s16 p;
553                 *pkt >> p;
554                 client->SetBlockNotSent(p);
555         }
556 }
557
558 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
559 {
560         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
561
562         if (player == NULL) {
563                 errorstream << "Server::ProcessData(): Canceling: "
564                                 "No player for peer_id=" << pkt->getPeerId()
565                                 << " disconnecting peer!" << std::endl;
566                 DisconnectPeer(pkt->getPeerId());
567                 return;
568         }
569
570         PlayerSAO *playersao = player->getPlayerSAO();
571         if (playersao == NULL) {
572                 errorstream << "Server::ProcessData(): Canceling: "
573                                 "No player object for peer_id=" << pkt->getPeerId()
574                                 << " disconnecting peer!" << std::endl;
575                 DisconnectPeer(pkt->getPeerId());
576                 return;
577         }
578
579         // Strip command and create a stream
580         std::string datastring(pkt->getString(0), pkt->getSize());
581         verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
582                 << std::endl;
583         std::istringstream is(datastring, std::ios_base::binary);
584         // Create an action
585         InventoryAction *a = InventoryAction::deSerialize(is);
586         if (!a) {
587                 infostream << "TOSERVER_INVENTORY_ACTION: "
588                                 << "InventoryAction::deSerialize() returned NULL"
589                                 << std::endl;
590                 return;
591         }
592
593         // If something goes wrong, this player is to blame
594         RollbackScopeActor rollback_scope(m_rollback,
595                         std::string("player:")+player->getName());
596
597         /*
598                 Note: Always set inventory not sent, to repair cases
599                 where the client made a bad prediction.
600         */
601
602         /*
603                 Handle restrictions and special cases of the move action
604         */
605         if (a->getType() == IAction::Move) {
606                 IMoveAction *ma = (IMoveAction*)a;
607
608                 ma->from_inv.applyCurrentPlayer(player->getName());
609                 ma->to_inv.applyCurrentPlayer(player->getName());
610
611                 setInventoryModified(ma->from_inv, false);
612                 setInventoryModified(ma->to_inv, false);
613
614                 bool from_inv_is_current_player =
615                         (ma->from_inv.type == InventoryLocation::PLAYER) &&
616                         (ma->from_inv.name == player->getName());
617
618                 bool to_inv_is_current_player =
619                         (ma->to_inv.type == InventoryLocation::PLAYER) &&
620                         (ma->to_inv.name == player->getName());
621
622                 InventoryLocation *remote = from_inv_is_current_player ?
623                         &ma->to_inv : &ma->from_inv;
624
625                 // Check for out-of-range interaction
626                 if (remote->type == InventoryLocation::NODEMETA) {
627                         v3f node_pos   = intToFloat(remote->p, BS);
628                         v3f player_pos = player->getPlayerSAO()->getBasePosition();
629                         f32 d = player_pos.getDistanceFrom(node_pos);
630                         if (!checkInteractDistance(player, d, "inventory"))
631                                 return;
632                 }
633
634                 /*
635                         Disable moving items out of craftpreview
636                 */
637                 if (ma->from_list == "craftpreview") {
638                         infostream << "Ignoring IMoveAction from "
639                                         << (ma->from_inv.dump()) << ":" << ma->from_list
640                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
641                                         << " because src is " << ma->from_list << std::endl;
642                         delete a;
643                         return;
644                 }
645
646                 /*
647                         Disable moving items into craftresult and craftpreview
648                 */
649                 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
650                         infostream << "Ignoring IMoveAction from "
651                                         << (ma->from_inv.dump()) << ":" << ma->from_list
652                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
653                                         << " because dst is " << ma->to_list << std::endl;
654                         delete a;
655                         return;
656                 }
657
658                 // Disallow moving items in elsewhere than player's inventory
659                 // if not allowed to interact
660                 if (!checkPriv(player->getName(), "interact") &&
661                                 (!from_inv_is_current_player ||
662                                 !to_inv_is_current_player)) {
663                         infostream << "Cannot move outside of player's inventory: "
664                                         << "No interact privilege" << std::endl;
665                         delete a;
666                         return;
667                 }
668         }
669         /*
670                 Handle restrictions and special cases of the drop action
671         */
672         else if (a->getType() == IAction::Drop) {
673                 IDropAction *da = (IDropAction*)a;
674
675                 da->from_inv.applyCurrentPlayer(player->getName());
676
677                 setInventoryModified(da->from_inv, false);
678
679                 /*
680                         Disable dropping items out of craftpreview
681                 */
682                 if (da->from_list == "craftpreview") {
683                         infostream << "Ignoring IDropAction from "
684                                         << (da->from_inv.dump()) << ":" << da->from_list
685                                         << " because src is " << da->from_list << std::endl;
686                         delete a;
687                         return;
688                 }
689
690                 // Disallow dropping items if not allowed to interact
691                 if (!checkPriv(player->getName(), "interact")) {
692                         delete a;
693                         return;
694                 }
695
696                 // Disallow dropping items if dead
697                 if (playersao->isDead()) {
698                         infostream << "Ignoring IDropAction from "
699                                         << (da->from_inv.dump()) << ":" << da->from_list
700                                         << " because player is dead." << std::endl;
701                         delete a;
702                         return;
703                 }
704         }
705         /*
706                 Handle restrictions and special cases of the craft action
707         */
708         else if (a->getType() == IAction::Craft) {
709                 ICraftAction *ca = (ICraftAction*)a;
710
711                 ca->craft_inv.applyCurrentPlayer(player->getName());
712
713                 setInventoryModified(ca->craft_inv, false);
714
715                 //bool craft_inv_is_current_player =
716                 //      (ca->craft_inv.type == InventoryLocation::PLAYER) &&
717                 //      (ca->craft_inv.name == player->getName());
718
719                 // Disallow crafting if not allowed to interact
720                 if (!checkPriv(player->getName(), "interact")) {
721                         infostream << "Cannot craft: "
722                                         << "No interact privilege" << std::endl;
723                         delete a;
724                         return;
725                 }
726         }
727
728         // Do the action
729         a->apply(this, playersao, this);
730         // Eat the action
731         delete a;
732
733         SendInventory(playersao);
734 }
735
736 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
737 {
738         /*
739                 u16 command
740                 u16 length
741                 wstring message
742         */
743         u16 len;
744         *pkt >> len;
745
746         std::wstring message;
747         for (u16 i = 0; i < len; i++) {
748                 u16 tmp_wchar;
749                 *pkt >> tmp_wchar;
750
751                 message += (wchar_t)tmp_wchar;
752         }
753
754         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
755         if (player == NULL) {
756                 errorstream << "Server::ProcessData(): Canceling: "
757                                 "No player for peer_id=" << pkt->getPeerId()
758                                 << " disconnecting peer!" << std::endl;
759                 DisconnectPeer(pkt->getPeerId());
760                 return;
761         }
762
763         // Get player name of this client
764         std::string name = player->getName();
765         std::wstring wname = narrow_to_wide(name);
766
767         std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
768         if (!answer_to_sender.empty()) {
769                 // Send the answer to sender
770                 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
771                                 answer_to_sender, wname));
772         }
773 }
774
775 void Server::handleCommand_Damage(NetworkPacket* pkt)
776 {
777         u8 damage;
778
779         *pkt >> damage;
780
781         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
782
783         if (player == NULL) {
784                 errorstream << "Server::ProcessData(): Canceling: "
785                                 "No player for peer_id=" << pkt->getPeerId()
786                                 << " disconnecting peer!" << std::endl;
787                 DisconnectPeer(pkt->getPeerId());
788                 return;
789         }
790
791         PlayerSAO *playersao = player->getPlayerSAO();
792         if (playersao == NULL) {
793                 errorstream << "Server::ProcessData(): Canceling: "
794                                 "No player object for peer_id=" << pkt->getPeerId()
795                                 << " disconnecting peer!" << std::endl;
796                 DisconnectPeer(pkt->getPeerId());
797                 return;
798         }
799
800         if (g_settings->getBool("enable_damage")) {
801                 if (playersao->isDead()) {
802                         verbosestream << "Server::ProcessData(): Info: "
803                                 "Ignoring damage as player " << player->getName()
804                                 << " is already dead." << std::endl;
805                         return;
806                 }
807
808                 actionstream << player->getName() << " damaged by "
809                                 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
810                                 << std::endl;
811
812                 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
813                 playersao->setHP(playersao->getHP() - damage, reason);
814                 SendPlayerHPOrDie(playersao, reason);
815         }
816 }
817
818 void Server::handleCommand_Password(NetworkPacket* pkt)
819 {
820         if (pkt->getSize() != PASSWORD_SIZE * 2)
821                 return;
822
823         std::string oldpwd;
824         std::string newpwd;
825
826         // Deny for clients using the new protocol
827         RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
828         if (client->net_proto_version >= 25) {
829                 infostream << "Server::handleCommand_Password(): Denying change: "
830                         << " Client protocol version for peer_id=" << pkt->getPeerId()
831                         << " too new!" << std::endl;
832                 return;
833         }
834
835         for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
836                 char c = pkt->getChar(i);
837                 if (c == 0)
838                         break;
839                 oldpwd += c;
840         }
841
842         for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
843                 char c = pkt->getChar(PASSWORD_SIZE + i);
844                 if (c == 0)
845                         break;
846                 newpwd += c;
847         }
848
849         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
850         if (player == NULL) {
851                 errorstream << "Server::ProcessData(): Canceling: "
852                                 "No player for peer_id=" << pkt->getPeerId()
853                                 << " disconnecting peer!" << std::endl;
854                 DisconnectPeer(pkt->getPeerId());
855                 return;
856         }
857
858         if (!base64_is_valid(newpwd)) {
859                 infostream<<"Server: " << player->getName() <<
860                                 " supplied invalid password hash" << std::endl;
861                 // Wrong old password supplied!!
862                 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
863                                 L"Invalid new password hash supplied. Password NOT changed."));
864                 return;
865         }
866
867         infostream << "Server: Client requests a password change from "
868                         << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
869
870         std::string playername = player->getName();
871
872         std::string checkpwd;
873         m_script->getAuth(playername, &checkpwd, NULL);
874
875         if (oldpwd != checkpwd) {
876                 infostream << "Server: invalid old password" << std::endl;
877                 // Wrong old password supplied!!
878                 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
879                                 L"Invalid old password supplied. Password NOT changed."));
880                 return;
881         }
882
883         bool success = m_script->setPassword(playername, newpwd);
884         if (success) {
885                 actionstream << player->getName() << " changes password" << std::endl;
886                 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
887                                 L"Password change successful."));
888         } else {
889                 actionstream << player->getName() << " tries to change password but "
890                                 << "it fails" << std::endl;
891                 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
892                                 L"Password change failed or unavailable."));
893         }
894 }
895
896 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
897 {
898         if (pkt->getSize() < 2)
899                 return;
900
901         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
902
903         if (player == NULL) {
904                 errorstream << "Server::ProcessData(): Canceling: "
905                                 "No player for peer_id=" << pkt->getPeerId()
906                                 << " disconnecting peer!" << std::endl;
907                 DisconnectPeer(pkt->getPeerId());
908                 return;
909         }
910
911         PlayerSAO *playersao = player->getPlayerSAO();
912         if (playersao == NULL) {
913                 errorstream << "Server::ProcessData(): Canceling: "
914                                 "No player object for peer_id=" << pkt->getPeerId()
915                                 << " disconnecting peer!" << std::endl;
916                 DisconnectPeer(pkt->getPeerId());
917                 return;
918         }
919
920         u16 item;
921
922         *pkt >> item;
923
924         playersao->setWieldIndex(item);
925 }
926
927 void Server::handleCommand_Respawn(NetworkPacket* pkt)
928 {
929         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
930         if (player == NULL) {
931                 errorstream << "Server::ProcessData(): Canceling: "
932                                 "No player for peer_id=" << pkt->getPeerId()
933                                 << " disconnecting peer!" << std::endl;
934                 DisconnectPeer(pkt->getPeerId());
935                 return;
936         }
937
938         PlayerSAO *playersao = player->getPlayerSAO();
939         assert(playersao);
940
941         if (!playersao->isDead())
942                 return;
943
944         RespawnPlayer(pkt->getPeerId());
945
946         actionstream << player->getName() << " respawns at "
947                         << PP(playersao->getBasePosition() / BS) << std::endl;
948
949         // ActiveObject is added to environment in AsyncRunStep after
950         // the previous addition has been successfully removed
951 }
952
953 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string what)
954 {
955         PlayerSAO *playersao = player->getPlayerSAO();
956         const InventoryList *hlist = playersao->getInventory()->getList("hand");
957         const ItemDefinition &playeritem_def =
958                 playersao->getWieldedItem().getDefinition(m_itemdef);
959         const ItemDefinition &hand_def =
960                 hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
961
962         float max_d = BS * playeritem_def.range;
963         float max_d_hand = BS * hand_def.range;
964
965         if (max_d < 0 && max_d_hand >= 0)
966                 max_d = max_d_hand;
967         else if (max_d < 0)
968                 max_d = BS * 4.0f;
969
970         // cube diagonal: sqrt(3) = 1.732
971         if (d > max_d * 1.732) {
972                 actionstream << "Player " << player->getName()
973                                 << " tried to access " << what
974                                 << " from too far: "
975                                 << "d=" << d <<", max_d=" << max_d
976                                 << ". ignoring." << std::endl;
977                 // Call callbacks
978                 m_script->on_cheat(playersao, "interacted_too_far");
979                 return false;
980         }
981         return true;
982 }
983
984 void Server::handleCommand_Interact(NetworkPacket* pkt)
985 {
986         /*
987                 [0] u16 command
988                 [2] u8 action
989                 [3] u16 item
990                 [5] u32 length of the next item (plen)
991                 [9] serialized PointedThing
992                 [9 + plen] player position information
993                 actions:
994                 0: start digging (from undersurface) or use
995                 1: stop digging (all parameters ignored)
996                 2: digging completed
997                 3: place block or item (to abovesurface)
998                 4: use item
999                 5: rightclick air ("activate")
1000         */
1001         u8 action;
1002         u16 item_i;
1003         *pkt >> action;
1004         *pkt >> item_i;
1005         std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
1006         PointedThing pointed;
1007         pointed.deSerialize(tmp_is);
1008
1009         verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
1010                         << item_i << ", pointed=" << pointed.dump() << std::endl;
1011
1012         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1013
1014         if (player == NULL) {
1015                 errorstream << "Server::ProcessData(): Canceling: "
1016                                 "No player for peer_id=" << pkt->getPeerId()
1017                                 << " disconnecting peer!" << std::endl;
1018                 DisconnectPeer(pkt->getPeerId());
1019                 return;
1020         }
1021
1022         PlayerSAO *playersao = player->getPlayerSAO();
1023         if (playersao == NULL) {
1024                 errorstream << "Server::ProcessData(): Canceling: "
1025                                 "No player object for peer_id=" << pkt->getPeerId()
1026                                 << " disconnecting peer!" << std::endl;
1027                 DisconnectPeer(pkt->getPeerId());
1028                 return;
1029         }
1030
1031         if (playersao->isDead()) {
1032                 actionstream << "Server: NoCheat: " << player->getName()
1033                                 << " tried to interact while dead; ignoring." << std::endl;
1034                 if (pointed.type == POINTEDTHING_NODE) {
1035                         // Re-send block to revert change on client-side
1036                         RemoteClient *client = getClient(pkt->getPeerId());
1037                         v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1038                         client->SetBlockNotSent(blockpos);
1039                 }
1040                 // Call callbacks
1041                 m_script->on_cheat(playersao, "interacted_while_dead");
1042                 return;
1043         }
1044
1045         process_PlayerPos(player, playersao, pkt);
1046
1047         v3f player_pos = playersao->getLastGoodPosition();
1048
1049         // Update wielded item
1050         playersao->setWieldIndex(item_i);
1051
1052         // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1053         v3s16 p_under = pointed.node_undersurface;
1054         v3s16 p_above = pointed.node_abovesurface;
1055
1056         // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1057         ServerActiveObject *pointed_object = NULL;
1058         if (pointed.type == POINTEDTHING_OBJECT) {
1059                 pointed_object = m_env->getActiveObject(pointed.object_id);
1060                 if (pointed_object == NULL) {
1061                         verbosestream << "TOSERVER_INTERACT: "
1062                                 "pointed object is NULL" << std::endl;
1063                         return;
1064                 }
1065
1066         }
1067
1068         v3f pointed_pos_under = player_pos;
1069         v3f pointed_pos_above = player_pos;
1070         if (pointed.type == POINTEDTHING_NODE) {
1071                 pointed_pos_under = intToFloat(p_under, BS);
1072                 pointed_pos_above = intToFloat(p_above, BS);
1073         }
1074         else if (pointed.type == POINTEDTHING_OBJECT) {
1075                 pointed_pos_under = pointed_object->getBasePosition();
1076                 pointed_pos_above = pointed_pos_under;
1077         }
1078
1079         /*
1080                 Make sure the player is allowed to do it
1081         */
1082         if (!checkPriv(player->getName(), "interact")) {
1083                 actionstream<<player->getName()<<" attempted to interact with "
1084                                 <<pointed.dump()<<" without 'interact' privilege"
1085                                 <<std::endl;
1086                 // Re-send block to revert change on client-side
1087                 RemoteClient *client = getClient(pkt->getPeerId());
1088                 // Digging completed -> under
1089                 if (action == 2) {
1090                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1091                         client->SetBlockNotSent(blockpos);
1092                 }
1093                 // Placement -> above
1094                 else if (action == 3) {
1095                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1096                         client->SetBlockNotSent(blockpos);
1097                 }
1098                 return;
1099         }
1100
1101         /*
1102                 Check that target is reasonably close
1103                 (only when digging or placing things)
1104         */
1105         static thread_local const bool enable_anticheat =
1106                         !g_settings->getBool("disable_anticheat");
1107
1108         if ((action == 0 || action == 2 || action == 3 || action == 4) &&
1109                         enable_anticheat && !isSingleplayer()) {
1110                 float d = player_pos.getDistanceFrom(pointed_pos_under);
1111                 if (!checkInteractDistance(player, d, pointed.dump())) {
1112                         // Re-send block to revert change on client-side
1113                         RemoteClient *client = getClient(pkt->getPeerId());
1114                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1115                         client->SetBlockNotSent(blockpos);
1116                         return;
1117                 }
1118         }
1119
1120         /*
1121                 If something goes wrong, this player is to blame
1122         */
1123         RollbackScopeActor rollback_scope(m_rollback,
1124                         std::string("player:")+player->getName());
1125
1126         /*
1127                 0: start digging or punch object
1128         */
1129         if (action == 0) {
1130                 if (pointed.type == POINTEDTHING_NODE) {
1131                         MapNode n(CONTENT_IGNORE);
1132                         bool pos_ok;
1133
1134                         n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1135                         if (!pos_ok) {
1136                                 infostream << "Server: Not punching: Node not found."
1137                                                 << " Adding block to emerge queue."
1138                                                 << std::endl;
1139                                 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1140                                         getNodeBlockPos(p_above), false);
1141                         }
1142
1143                         if (n.getContent() != CONTENT_IGNORE)
1144                                 m_script->node_on_punch(p_under, n, playersao, pointed);
1145
1146                         // Cheat prevention
1147                         playersao->noCheatDigStart(p_under);
1148                 }
1149                 else if (pointed.type == POINTEDTHING_OBJECT) {
1150                         // Skip if object can't be interacted with anymore
1151                         if (pointed_object->isGone())
1152                                 return;
1153
1154                         actionstream<<player->getName()<<" punches object "
1155                                         <<pointed.object_id<<": "
1156                                         <<pointed_object->getDescription()<<std::endl;
1157
1158                         ItemStack punchitem = playersao->getWieldedItemOrHand();
1159                         ToolCapabilities toolcap =
1160                                         punchitem.getToolCapabilities(m_itemdef);
1161                         v3f dir = (pointed_object->getBasePosition() -
1162                                         (playersao->getBasePosition() + playersao->getEyeOffset())
1163                                                 ).normalize();
1164                         float time_from_last_punch =
1165                                 playersao->resetTimeFromLastPunch();
1166
1167                         s16 src_original_hp = pointed_object->getHP();
1168                         s16 dst_origin_hp = playersao->getHP();
1169
1170                         pointed_object->punch(dir, &toolcap, playersao,
1171                                         time_from_last_punch);
1172
1173                         // If the object is a player and its HP changed
1174                         if (src_original_hp != pointed_object->getHP() &&
1175                                         pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1176                                 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1177                                                 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1178                         }
1179
1180                         // If the puncher is a player and its HP changed
1181                         if (dst_origin_hp != playersao->getHP())
1182                                 SendPlayerHPOrDie(playersao,
1183                                                 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
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                         auto it = fields.find("quit");
1515                         if (it != fields.end() && it->second == "true")
1516                                 m_formspec_state_data.erase(peer_state_iterator);
1517
1518                         m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1519                         return;
1520                 }
1521                 actionstream << "'" << player->getName()
1522                         << "' submitted formspec ('" << client_formspec_name
1523                         << "') but the name of the formspec doesn't match the"
1524                         " expected name ('" << server_formspec_name << "')";
1525
1526         } else {
1527                 actionstream << "'" << player->getName()
1528                         << "' submitted formspec ('" << client_formspec_name
1529                         << "') but server hasn't sent formspec to client";
1530         }
1531         actionstream << ", possible exploitation attempt" << std::endl;
1532 }
1533
1534 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1535 {
1536         RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1537         ClientState cstate = client->getState();
1538
1539         std::string playername = client->getName();
1540
1541         std::string salt;
1542         std::string verification_key;
1543
1544         std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1545         u8 is_empty;
1546
1547         *pkt >> salt >> verification_key >> is_empty;
1548
1549         verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1550                 << ", with is_empty=" << (is_empty == 1) << std::endl;
1551
1552         // Either this packet is sent because the user is new or to change the password
1553         if (cstate == CS_HelloSent) {
1554                 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1555                         actionstream << "Server: Client from " << addr_s
1556                                         << " tried to set password without being "
1557                                         << "authenticated, or the username being new." << std::endl;
1558                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1559                         return;
1560                 }
1561
1562                 if (!isSingleplayer() &&
1563                                 g_settings->getBool("disallow_empty_password") &&
1564                                 is_empty == 1) {
1565                         actionstream << "Server: " << playername
1566                                         << " supplied empty password from " << addr_s << std::endl;
1567                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1568                         return;
1569                 }
1570
1571                 std::string initial_ver_key;
1572
1573                 initial_ver_key = encode_srp_verifier(verification_key, salt);
1574                 m_script->createAuth(playername, initial_ver_key);
1575
1576                 acceptAuth(pkt->getPeerId(), false);
1577         } else {
1578                 if (cstate < CS_SudoMode) {
1579                         infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1580                                         << addr_s << ": " << "Client has wrong state " << cstate << "."
1581                                         << std::endl;
1582                         return;
1583                 }
1584                 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1585                 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1586                 bool success = m_script->setPassword(playername, pw_db_field);
1587                 if (success) {
1588                         actionstream << playername << " changes password" << std::endl;
1589                         SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1590                                         L"Password change successful."));
1591                 } else {
1592                         actionstream << playername << " tries to change password but "
1593                                 << "it fails" << std::endl;
1594                         SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1595                                         L"Password change failed or unavailable."));
1596                 }
1597         }
1598 }
1599
1600 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1601 {
1602         RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1603         ClientState cstate = client->getState();
1604
1605         bool wantSudo = (cstate == CS_Active);
1606
1607         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1608                 actionstream << "Server: got SRP _A packet in wrong state "
1609                         << cstate << " from "
1610                         << getPeerAddress(pkt->getPeerId()).serializeString()
1611                         << ". Ignoring." << std::endl;
1612                 return;
1613         }
1614
1615         if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1616                 actionstream << "Server: got SRP _A packet, while auth"
1617                         << "is already going on with mech " << client->chosen_mech
1618                         << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1619                         << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1620                 if (wantSudo) {
1621                         DenySudoAccess(pkt->getPeerId());
1622                         return;
1623                 }
1624
1625                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1626                 return;
1627         }
1628
1629         std::string bytes_A;
1630         u8 based_on;
1631         *pkt >> bytes_A >> based_on;
1632
1633         infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1634                 << "based_on=" << int(based_on) << " and len_A="
1635                 << bytes_A.length() << "." << std::endl;
1636
1637         AuthMechanism chosen = (based_on == 0) ?
1638                 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1639
1640         if (wantSudo) {
1641                 if (!client->isSudoMechAllowed(chosen)) {
1642                         actionstream << "Server: Player \"" << client->getName()
1643                                 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1644                                 << " tried to change password using unallowed mech "
1645                                 << chosen << "." << std::endl;
1646                         DenySudoAccess(pkt->getPeerId());
1647                         return;
1648                 }
1649         } else {
1650                 if (!client->isMechAllowed(chosen)) {
1651                         actionstream << "Server: Client tried to authenticate from "
1652                                 << getPeerAddress(pkt->getPeerId()).serializeString()
1653                                 << " using unallowed mech " << chosen << "." << std::endl;
1654                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1655                         return;
1656                 }
1657         }
1658
1659         client->chosen_mech = chosen;
1660
1661         std::string salt;
1662         std::string verifier;
1663
1664         if (based_on == 0) {
1665
1666                 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1667                         &verifier, &salt);
1668         } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1669                 // Non-base64 errors should have been catched in the init handler
1670                 actionstream << "Server: User " << client->getName()
1671                         << " tried to log in, but srp verifier field"
1672                         << " was invalid (most likely invalid base64)." << std::endl;
1673                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1674                 return;
1675         }
1676
1677         char *bytes_B = 0;
1678         size_t len_B = 0;
1679
1680         client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1681                 client->getName().c_str(),
1682                 (const unsigned char *) salt.c_str(), salt.size(),
1683                 (const unsigned char *) verifier.c_str(), verifier.size(),
1684                 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1685                 NULL, 0,
1686                 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1687
1688         if (!bytes_B) {
1689                 actionstream << "Server: User " << client->getName()
1690                         << " tried to log in, SRP-6a safety check violated in _A handler."
1691                         << std::endl;
1692                 if (wantSudo) {
1693                         DenySudoAccess(pkt->getPeerId());
1694                         return;
1695                 }
1696
1697                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1698                 return;
1699         }
1700
1701         NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1702         resp_pkt << salt << std::string(bytes_B, len_B);
1703         Send(&resp_pkt);
1704 }
1705
1706 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1707 {
1708         RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1709         ClientState cstate = client->getState();
1710
1711         bool wantSudo = (cstate == CS_Active);
1712
1713         verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
1714
1715         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1716                 actionstream << "Server: got SRP _M packet in wrong state "
1717                         << cstate << " from "
1718                         << getPeerAddress(pkt->getPeerId()).serializeString()
1719                         << ". Ignoring." << std::endl;
1720                 return;
1721         }
1722
1723         if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1724                         client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1725                 actionstream << "Server: got SRP _M packet, while auth"
1726                         << "is going on with mech " << client->chosen_mech
1727                         << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1728                         << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1729                 if (wantSudo) {
1730                         DenySudoAccess(pkt->getPeerId());
1731                         return;
1732                 }
1733
1734                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1735                 return;
1736         }
1737
1738         std::string bytes_M;
1739         *pkt >> bytes_M;
1740
1741         if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1742                         != bytes_M.size()) {
1743                 actionstream << "Server: User " << client->getName()
1744                         << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1745                         << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1746                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1747                 return;
1748         }
1749
1750         unsigned char *bytes_HAMK = 0;
1751
1752         srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1753                 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1754
1755         if (!bytes_HAMK) {
1756                 if (wantSudo) {
1757                         actionstream << "Server: User " << client->getName()
1758                                 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1759                                 << " tried to change their password, but supplied wrong"
1760                                 << " (SRP) password for authentication." << std::endl;
1761                         DenySudoAccess(pkt->getPeerId());
1762                         return;
1763                 }
1764
1765                 std::string ip = getPeerAddress(pkt->getPeerId()).serializeString();
1766                 actionstream << "Server: User " << client->getName()
1767                         << " at " << ip
1768                         << " supplied wrong password (auth mechanism: SRP)."
1769                         << std::endl;
1770                 m_script->on_auth_failure(client->getName(), ip);
1771                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
1772                 return;
1773         }
1774
1775         if (client->create_player_on_auth_success) {
1776                 std::string playername = client->getName();
1777                 m_script->createAuth(playername, client->enc_pwd);
1778
1779                 std::string checkpwd; // not used, but needed for passing something
1780                 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1781                         actionstream << "Server: " << playername << " cannot be authenticated"
1782                                 << " (auth handler does not work?)" << std::endl;
1783                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1784                         return;
1785                 }
1786                 client->create_player_on_auth_success = false;
1787         }
1788
1789         acceptAuth(pkt->getPeerId(), wantSudo);
1790 }
1791
1792 /*
1793  * Mod channels
1794  */
1795
1796 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1797 {
1798         std::string channel_name;
1799         *pkt >> channel_name;
1800
1801         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1802                 pkt->getPeerId());
1803
1804         // Send signal to client to notify join succeed or not
1805         if (g_settings->getBool("enable_mod_channels") &&
1806                         m_modchannel_mgr->joinChannel(channel_name, pkt->getPeerId())) {
1807                 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1808                 infostream << "Peer " << pkt->getPeerId() << " joined channel " << channel_name
1809                                 << std::endl;
1810         }
1811         else {
1812                 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1813                 infostream << "Peer " << pkt->getPeerId() << " tried to join channel "
1814                         << channel_name << ", but was already registered." << std::endl;
1815         }
1816         resp_pkt << channel_name;
1817         Send(&resp_pkt);
1818 }
1819
1820 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1821 {
1822         std::string channel_name;
1823         *pkt >> channel_name;
1824
1825         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1826                 pkt->getPeerId());
1827
1828         // Send signal to client to notify join succeed or not
1829         if (g_settings->getBool("enable_mod_channels") &&
1830                         m_modchannel_mgr->leaveChannel(channel_name, pkt->getPeerId())) {
1831                 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1832                 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1833                                 << std::endl;
1834         } else {
1835                 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1836                 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1837                                 << ", but was not registered." << std::endl;
1838         }
1839         resp_pkt << channel_name;
1840         Send(&resp_pkt);
1841 }
1842
1843 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1844 {
1845         std::string channel_name, channel_msg;
1846         *pkt >> channel_name >> channel_msg;
1847
1848         verbosestream << "Mod channel message received from peer " << pkt->getPeerId()
1849                         << " on channel " << channel_name << " message: " << channel_msg << std::endl;
1850
1851         // If mod channels are not enabled, discard message
1852         if (!g_settings->getBool("enable_mod_channels")) {
1853                 return;
1854         }
1855
1856         // If channel not registered, signal it and ignore message
1857         if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1858                 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1859                         pkt->getPeerId());
1860                 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1861                 Send(&resp_pkt);
1862                 return;
1863         }
1864
1865         // @TODO: filter, rate limit
1866
1867         broadcastModChannelMessage(channel_name, channel_msg, pkt->getPeerId());
1868 }