]> git.lizzy.rs Git - dragonfireclient.git/blob - src/network/serverpackethandler.cpp
Client::Interact: Use InteractAction enum instead of numeric constants
[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         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->setLookPitch(pitch);
477         playersao->setPlayerYaw(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                 if (ma->from_inv != ma->to_inv) {
613                         setInventoryModified(ma->to_inv, false);
614                 }
615
616                 bool from_inv_is_current_player =
617                         (ma->from_inv.type == InventoryLocation::PLAYER) &&
618                         (ma->from_inv.name == player->getName());
619
620                 bool to_inv_is_current_player =
621                         (ma->to_inv.type == InventoryLocation::PLAYER) &&
622                         (ma->to_inv.name == player->getName());
623
624                 InventoryLocation *remote = from_inv_is_current_player ?
625                         &ma->to_inv : &ma->from_inv;
626
627                 // Check for out-of-range interaction
628                 if (remote->type == InventoryLocation::NODEMETA) {
629                         v3f node_pos   = intToFloat(remote->p, BS);
630                         v3f player_pos = player->getPlayerSAO()->getEyePosition();
631                         f32 d = player_pos.getDistanceFrom(node_pos);
632                         if (!checkInteractDistance(player, d, "inventory"))
633                                 return;
634                 }
635
636                 /*
637                         Disable moving items out of craftpreview
638                 */
639                 if (ma->from_list == "craftpreview") {
640                         infostream << "Ignoring IMoveAction from "
641                                         << (ma->from_inv.dump()) << ":" << ma->from_list
642                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
643                                         << " because src is " << ma->from_list << std::endl;
644                         delete a;
645                         return;
646                 }
647
648                 /*
649                         Disable moving items into craftresult and craftpreview
650                 */
651                 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
652                         infostream << "Ignoring IMoveAction from "
653                                         << (ma->from_inv.dump()) << ":" << ma->from_list
654                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
655                                         << " because dst is " << ma->to_list << std::endl;
656                         delete a;
657                         return;
658                 }
659
660                 // Disallow moving items in elsewhere than player's inventory
661                 // if not allowed to interact
662                 if (!checkPriv(player->getName(), "interact") &&
663                                 (!from_inv_is_current_player ||
664                                 !to_inv_is_current_player)) {
665                         infostream << "Cannot move outside of player's inventory: "
666                                         << "No interact privilege" << std::endl;
667                         delete a;
668                         return;
669                 }
670         }
671         /*
672                 Handle restrictions and special cases of the drop action
673         */
674         else if (a->getType() == IAction::Drop) {
675                 IDropAction *da = (IDropAction*)a;
676
677                 da->from_inv.applyCurrentPlayer(player->getName());
678
679                 setInventoryModified(da->from_inv, false);
680
681                 /*
682                         Disable dropping items out of craftpreview
683                 */
684                 if (da->from_list == "craftpreview") {
685                         infostream << "Ignoring IDropAction from "
686                                         << (da->from_inv.dump()) << ":" << da->from_list
687                                         << " because src is " << da->from_list << std::endl;
688                         delete a;
689                         return;
690                 }
691
692                 // Disallow dropping items if not allowed to interact
693                 if (!checkPriv(player->getName(), "interact")) {
694                         delete a;
695                         return;
696                 }
697
698                 // Disallow dropping items if dead
699                 if (playersao->isDead()) {
700                         infostream << "Ignoring IDropAction from "
701                                         << (da->from_inv.dump()) << ":" << da->from_list
702                                         << " because player is dead." << std::endl;
703                         delete a;
704                         return;
705                 }
706         }
707         /*
708                 Handle restrictions and special cases of the craft action
709         */
710         else if (a->getType() == IAction::Craft) {
711                 ICraftAction *ca = (ICraftAction*)a;
712
713                 ca->craft_inv.applyCurrentPlayer(player->getName());
714
715                 setInventoryModified(ca->craft_inv, false);
716
717                 //bool craft_inv_is_current_player =
718                 //      (ca->craft_inv.type == InventoryLocation::PLAYER) &&
719                 //      (ca->craft_inv.name == player->getName());
720
721                 // Disallow crafting if not allowed to interact
722                 if (!checkPriv(player->getName(), "interact")) {
723                         infostream << "Cannot craft: "
724                                         << "No interact privilege" << std::endl;
725                         delete a;
726                         return;
727                 }
728         }
729
730         // Do the action
731         a->apply(this, playersao, this);
732         // Eat the action
733         delete a;
734
735         SendInventory(playersao);
736 }
737
738 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
739 {
740         /*
741                 u16 command
742                 u16 length
743                 wstring message
744         */
745         u16 len;
746         *pkt >> len;
747
748         std::wstring message;
749         for (u16 i = 0; i < len; i++) {
750                 u16 tmp_wchar;
751                 *pkt >> tmp_wchar;
752
753                 message += (wchar_t)tmp_wchar;
754         }
755
756         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
757         if (player == NULL) {
758                 errorstream << "Server::ProcessData(): Canceling: "
759                                 "No player for peer_id=" << pkt->getPeerId()
760                                 << " disconnecting peer!" << std::endl;
761                 DisconnectPeer(pkt->getPeerId());
762                 return;
763         }
764
765         // Get player name of this client
766         std::string name = player->getName();
767         std::wstring wname = narrow_to_wide(name);
768
769         std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
770         if (!answer_to_sender.empty()) {
771                 // Send the answer to sender
772                 SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
773                                 answer_to_sender, wname));
774         }
775 }
776
777 void Server::handleCommand_Damage(NetworkPacket* pkt)
778 {
779         u16 damage;
780
781         *pkt >> damage;
782
783         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
784
785         if (player == NULL) {
786                 errorstream << "Server::ProcessData(): Canceling: "
787                                 "No player for peer_id=" << pkt->getPeerId()
788                                 << " disconnecting peer!" << std::endl;
789                 DisconnectPeer(pkt->getPeerId());
790                 return;
791         }
792
793         PlayerSAO *playersao = player->getPlayerSAO();
794         if (playersao == NULL) {
795                 errorstream << "Server::ProcessData(): Canceling: "
796                                 "No player object for peer_id=" << pkt->getPeerId()
797                                 << " disconnecting peer!" << std::endl;
798                 DisconnectPeer(pkt->getPeerId());
799                 return;
800         }
801
802         if (!playersao->isImmortal()) {
803                 if (playersao->isDead()) {
804                         verbosestream << "Server::ProcessData(): Info: "
805                                 "Ignoring damage as player " << player->getName()
806                                 << " is already dead." << std::endl;
807                         return;
808                 }
809
810                 actionstream << player->getName() << " damaged by "
811                                 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
812                                 << std::endl;
813
814                 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
815                 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
816                 SendPlayerHPOrDie(playersao, reason);
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->getPlayer()->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         ItemStack selected_item, hand_item;
958         player->getWieldedItem(&selected_item, &hand_item);
959         f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
960                         hand_item.getDefinition(m_itemdef));
961
962         // Cube diagonal * 1.5 for maximal supported node extents:
963         // sqrt(3) * 1.5 â‰… 2.6
964         if (d > max_d + 2.6f * BS) {
965                 actionstream << "Player " << player->getName()
966                                 << " tried to access " << what
967                                 << " from too far: "
968                                 << "d=" << d <<", max_d=" << max_d
969                                 << ". ignoring." << std::endl;
970                 // Call callbacks
971                 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
972                 return false;
973         }
974         return true;
975 }
976
977 void Server::handleCommand_Interact(NetworkPacket *pkt)
978 {
979         /*
980                 [0] u16 command
981                 [2] u8 action
982                 [3] u16 item
983                 [5] u32 length of the next item (plen)
984                 [9] serialized PointedThing
985                 [9 + plen] player position information
986         */
987
988         InteractAction action;
989         u16 item_i;
990
991         *pkt >> (u8 &)action;
992         *pkt >> item_i;
993
994         std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
995         PointedThing pointed;
996         pointed.deSerialize(tmp_is);
997
998         verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
999                         << item_i << ", pointed=" << pointed.dump() << std::endl;
1000
1001         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1002
1003         if (player == NULL) {
1004                 errorstream << "Server::ProcessData(): Canceling: "
1005                                 "No player for peer_id=" << pkt->getPeerId()
1006                                 << " disconnecting peer!" << std::endl;
1007                 DisconnectPeer(pkt->getPeerId());
1008                 return;
1009         }
1010
1011         PlayerSAO *playersao = player->getPlayerSAO();
1012         if (playersao == NULL) {
1013                 errorstream << "Server::ProcessData(): Canceling: "
1014                                 "No player object for peer_id=" << pkt->getPeerId()
1015                                 << " disconnecting peer!" << std::endl;
1016                 DisconnectPeer(pkt->getPeerId());
1017                 return;
1018         }
1019
1020         if (playersao->isDead()) {
1021                 actionstream << "Server: NoCheat: " << player->getName()
1022                                 << " tried to interact while dead; ignoring." << std::endl;
1023                 if (pointed.type == POINTEDTHING_NODE) {
1024                         // Re-send block to revert change on client-side
1025                         RemoteClient *client = getClient(pkt->getPeerId());
1026                         v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1027                         client->SetBlockNotSent(blockpos);
1028                 }
1029                 // Call callbacks
1030                 m_script->on_cheat(playersao, "interacted_while_dead");
1031                 return;
1032         }
1033
1034         process_PlayerPos(player, playersao, pkt);
1035
1036         v3f player_pos = playersao->getLastGoodPosition();
1037
1038         // Update wielded item
1039         playersao->getPlayer()->setWieldIndex(item_i);
1040
1041         // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1042         v3s16 p_under = pointed.node_undersurface;
1043         v3s16 p_above = pointed.node_abovesurface;
1044
1045         // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1046         ServerActiveObject *pointed_object = NULL;
1047         if (pointed.type == POINTEDTHING_OBJECT) {
1048                 pointed_object = m_env->getActiveObject(pointed.object_id);
1049                 if (pointed_object == NULL) {
1050                         verbosestream << "TOSERVER_INTERACT: "
1051                                 "pointed object is NULL" << std::endl;
1052                         return;
1053                 }
1054
1055         }
1056
1057         v3f pointed_pos_under = player_pos;
1058         v3f pointed_pos_above = player_pos;
1059         if (pointed.type == POINTEDTHING_NODE) {
1060                 pointed_pos_under = intToFloat(p_under, BS);
1061                 pointed_pos_above = intToFloat(p_above, BS);
1062         }
1063         else if (pointed.type == POINTEDTHING_OBJECT) {
1064                 pointed_pos_under = pointed_object->getBasePosition();
1065                 pointed_pos_above = pointed_pos_under;
1066         }
1067
1068         /*
1069                 Make sure the player is allowed to do it
1070         */
1071         if (!checkPriv(player->getName(), "interact")) {
1072                 actionstream << player->getName() << " attempted to interact with " <<
1073                                 pointed.dump() << " without 'interact' privilege" << std::endl;
1074
1075                 // Re-send block to revert change on client-side
1076                 RemoteClient *client = getClient(pkt->getPeerId());
1077                 // Digging completed -> under
1078                 if (action == INTERACT_DIGGING_COMPLETED) {
1079                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1080                         client->SetBlockNotSent(blockpos);
1081                 }
1082                 // Placement -> above
1083                 else if (action == INTERACT_PLACE) {
1084                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1085                         client->SetBlockNotSent(blockpos);
1086                 }
1087                 return;
1088         }
1089
1090         /*
1091                 Check that target is reasonably close
1092                 (only when digging or placing things)
1093         */
1094         static thread_local const bool enable_anticheat =
1095                         !g_settings->getBool("disable_anticheat");
1096
1097         if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1098                         action == INTERACT_PLACE || action == INTERACT_USE) &&
1099                         enable_anticheat && !isSingleplayer()) {
1100                 float d = playersao->getEyePosition().getDistanceFrom(pointed_pos_under);
1101
1102                 if (!checkInteractDistance(player, d, pointed.dump())) {
1103                         // Re-send block to revert change on client-side
1104                         RemoteClient *client = getClient(pkt->getPeerId());
1105                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1106                         client->SetBlockNotSent(blockpos);
1107                         return;
1108                 }
1109         }
1110
1111         /*
1112                 If something goes wrong, this player is to blame
1113         */
1114         RollbackScopeActor rollback_scope(m_rollback,
1115                         std::string("player:")+player->getName());
1116
1117         /*
1118                 0: start digging or punch object
1119         */
1120         if (action == INTERACT_START_DIGGING) {
1121                 if (pointed.type == POINTEDTHING_NODE) {
1122                         MapNode n(CONTENT_IGNORE);
1123                         bool pos_ok;
1124
1125                         n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1126                         if (!pos_ok) {
1127                                 infostream << "Server: Not punching: Node not found."
1128                                                 << " Adding block to emerge queue."
1129                                                 << std::endl;
1130                                 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1131                                         getNodeBlockPos(p_above), false);
1132                         }
1133
1134                         if (n.getContent() != CONTENT_IGNORE)
1135                                 m_script->node_on_punch(p_under, n, playersao, pointed);
1136
1137                         // Cheat prevention
1138                         playersao->noCheatDigStart(p_under);
1139                 }
1140                 else if (pointed.type == POINTEDTHING_OBJECT) {
1141                         // Skip if object can't be interacted with anymore
1142                         if (pointed_object->isGone())
1143                                 return;
1144
1145                         ItemStack punchitem = playersao->getWieldedItem();
1146                         ToolCapabilities toolcap =
1147                                         punchitem.getToolCapabilities(m_itemdef);
1148                         v3f dir = (pointed_object->getBasePosition() -
1149                                         (playersao->getBasePosition() + playersao->getEyeOffset())
1150                                                 ).normalize();
1151                         float time_from_last_punch =
1152                                 playersao->resetTimeFromLastPunch();
1153
1154                         u16 src_original_hp = pointed_object->getHP();
1155                         u16 dst_origin_hp = playersao->getHP();
1156
1157                         pointed_object->punch(dir, &toolcap, playersao,
1158                                         time_from_last_punch);
1159
1160                         // If the object is a player and its HP changed
1161                         if (src_original_hp != pointed_object->getHP() &&
1162                                         pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1163                                 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1164                                                 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1165                         }
1166
1167                         // If the puncher is a player and its HP changed
1168                         if (dst_origin_hp != playersao->getHP())
1169                                 SendPlayerHPOrDie(playersao,
1170                                                 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1171                 }
1172
1173         } // action == INTERACT_START_DIGGING
1174
1175         /*
1176                 1: stop digging
1177         */
1178         else if (action == INTERACT_STOP_DIGGING) {
1179         } // action == INTERACT_STOP_DIGGING
1180
1181         /*
1182                 2: Digging completed
1183         */
1184         else if (action == INTERACT_DIGGING_COMPLETED) {
1185                 // Only digging of nodes
1186                 if (pointed.type == POINTEDTHING_NODE) {
1187                         bool pos_ok;
1188                         MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1189                         if (!pos_ok) {
1190                                 infostream << "Server: Not finishing digging: Node not found."
1191                                                 << " Adding block to emerge queue."
1192                                                 << std::endl;
1193                                 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1194                                         getNodeBlockPos(p_above), false);
1195                         }
1196
1197                         /* Cheat prevention */
1198                         bool is_valid_dig = true;
1199                         if (enable_anticheat && !isSingleplayer()) {
1200                                 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1201                                 float nocheat_t = playersao->getNoCheatDigTime();
1202                                 playersao->noCheatDigEnd();
1203                                 // If player didn't start digging this, ignore dig
1204                                 if (nocheat_p != p_under) {
1205                                         infostream << "Server: NoCheat: " << player->getName()
1206                                                         << " started digging "
1207                                                         << PP(nocheat_p) << " and completed digging "
1208                                                         << PP(p_under) << "; not digging." << std::endl;
1209                                         is_valid_dig = false;
1210                                         // Call callbacks
1211                                         m_script->on_cheat(playersao, "finished_unknown_dig");
1212                                 }
1213
1214                                 // Get player's wielded item
1215                                 // See also: Game::handleDigging
1216                                 ItemStack selected_item, hand_item;
1217                                 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1218
1219                                 // Get diggability and expected digging time
1220                                 DigParams params = getDigParams(m_nodedef->get(n).groups,
1221                                                 &selected_item.getToolCapabilities(m_itemdef));
1222                                 // If can't dig, try hand
1223                                 if (!params.diggable) {
1224                                         params = getDigParams(m_nodedef->get(n).groups,
1225                                                 &hand_item.getToolCapabilities(m_itemdef));
1226                                 }
1227                                 // If can't dig, ignore dig
1228                                 if (!params.diggable) {
1229                                         infostream << "Server: NoCheat: " << player->getName()
1230                                                         << " completed digging " << PP(p_under)
1231                                                         << ", which is not diggable with tool. not digging."
1232                                                         << std::endl;
1233                                         is_valid_dig = false;
1234                                         // Call callbacks
1235                                         m_script->on_cheat(playersao, "dug_unbreakable");
1236                                 }
1237                                 // Check digging time
1238                                 // If already invalidated, we don't have to
1239                                 if (!is_valid_dig) {
1240                                         // Well not our problem then
1241                                 }
1242                                 // Clean and long dig
1243                                 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1244                                         // All is good, but grab time from pool; don't care if
1245                                         // it's actually available
1246                                         playersao->getDigPool().grab(params.time);
1247                                 }
1248                                 // Short or laggy dig
1249                                 // Try getting the time from pool
1250                                 else if (playersao->getDigPool().grab(params.time)) {
1251                                         // All is good
1252                                 }
1253                                 // Dig not possible
1254                                 else {
1255                                         infostream << "Server: NoCheat: " << player->getName()
1256                                                         << " completed digging " << PP(p_under)
1257                                                         << "too fast; not digging." << std::endl;
1258                                         is_valid_dig = false;
1259                                         // Call callbacks
1260                                         m_script->on_cheat(playersao, "dug_too_fast");
1261                                 }
1262                         }
1263
1264                         /* Actually dig node */
1265
1266                         if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1267                                 m_script->node_on_dig(p_under, n, playersao);
1268
1269                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1270                         RemoteClient *client = getClient(pkt->getPeerId());
1271                         // Send unusual result (that is, node not being removed)
1272                         if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1273                                 // Re-send block to revert change on client-side
1274                                 client->SetBlockNotSent(blockpos);
1275                         }
1276                         else {
1277                                 client->ResendBlockIfOnWire(blockpos);
1278                         }
1279                 }
1280         } // action == INTERACT_DIGGING_COMPLETED
1281
1282         /*
1283                 3: place block or right-click object
1284         */
1285         else if (action == INTERACT_PLACE) {
1286                 ItemStack item = playersao->getWieldedItem();
1287
1288                 // Reset build time counter
1289                 if (pointed.type == POINTEDTHING_NODE &&
1290                                 item.getDefinition(m_itemdef).type == ITEM_NODE)
1291                         getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1292
1293                 if (pointed.type == POINTEDTHING_OBJECT) {
1294                         // Right click object
1295
1296                         // Skip if object can't be interacted with anymore
1297                         if (pointed_object->isGone())
1298                                 return;
1299
1300                         actionstream << player->getName() << " right-clicks object "
1301                                         << pointed.object_id << ": "
1302                                         << pointed_object->getDescription() << std::endl;
1303
1304                         // Do stuff
1305                         pointed_object->rightClick(playersao);
1306                 }
1307                 else if (m_script->item_OnPlace(
1308                                 item, playersao, pointed)) {
1309                         // Placement was handled in lua
1310
1311                         // Apply returned ItemStack
1312                         if (playersao->setWieldedItem(item)) {
1313                                 SendInventory(playersao);
1314                         }
1315                 }
1316
1317                 // If item has node placement prediction, always send the
1318                 // blocks to make sure the client knows what exactly happened
1319                 RemoteClient *client = getClient(pkt->getPeerId());
1320                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1321                 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1322                 if (!item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
1323                         client->SetBlockNotSent(blockpos);
1324                         if (blockpos2 != blockpos) {
1325                                 client->SetBlockNotSent(blockpos2);
1326                         }
1327                 }
1328                 else {
1329                         client->ResendBlockIfOnWire(blockpos);
1330                         if (blockpos2 != blockpos) {
1331                                 client->ResendBlockIfOnWire(blockpos2);
1332                         }
1333                 }
1334         } // action == INTERACT_PLACE
1335
1336         /*
1337                 4: use
1338         */
1339         else if (action == INTERACT_USE) {
1340                 ItemStack item = playersao->getWieldedItem();
1341
1342                 actionstream << player->getName() << " uses " << item.name
1343                                 << ", pointing at " << pointed.dump() << std::endl;
1344
1345                 if (m_script->item_OnUse(
1346                                 item, playersao, pointed)) {
1347                         // Apply returned ItemStack
1348                         if (playersao->setWieldedItem(item)) {
1349                                 SendInventory(playersao);
1350                         }
1351                 }
1352
1353         } // action == INTERACT_USE
1354
1355         /*
1356                 5: rightclick air
1357         */
1358         else if (action == INTERACT_ACTIVATE) {
1359                 ItemStack item = playersao->getWieldedItem();
1360
1361                 actionstream << player->getName() << " activates "
1362                                 << item.name << std::endl;
1363
1364                 if (m_script->item_OnSecondaryUse(
1365                                 item, playersao)) {
1366                         if( playersao->setWieldedItem(item)) {
1367                                 SendInventory(playersao);
1368                         }
1369                 }
1370         } // action == INTERACT_ACTIVATE
1371
1372
1373         /*
1374                 Catch invalid actions
1375         */
1376         else {
1377                 warningstream << "Server: Invalid action "
1378                                 << action << std::endl;
1379         }
1380 }
1381
1382 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1383 {
1384         u16 num;
1385         *pkt >> num;
1386         for (u16 k = 0; k < num; k++) {
1387                 s32 id;
1388
1389                 *pkt >> id;
1390
1391                 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1392                         m_playing_sounds.find(id);
1393                 if (i == m_playing_sounds.end())
1394                         continue;
1395
1396                 ServerPlayingSound &psound = i->second;
1397                 psound.clients.erase(pkt->getPeerId());
1398                 if (psound.clients.empty())
1399                         m_playing_sounds.erase(i++);
1400         }
1401 }
1402
1403 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1404 {
1405         v3s16 p;
1406         std::string formname;
1407         u16 num;
1408
1409         *pkt >> p >> formname >> num;
1410
1411         StringMap fields;
1412         for (u16 k = 0; k < num; k++) {
1413                 std::string fieldname;
1414                 *pkt >> fieldname;
1415                 fields[fieldname] = pkt->readLongString();
1416         }
1417
1418         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1419
1420         if (player == NULL) {
1421                 errorstream << "Server::ProcessData(): Canceling: "
1422                                 "No player for peer_id=" << pkt->getPeerId()
1423                                 << " disconnecting peer!" << std::endl;
1424                 DisconnectPeer(pkt->getPeerId());
1425                 return;
1426         }
1427
1428         PlayerSAO *playersao = player->getPlayerSAO();
1429         if (playersao == NULL) {
1430                 errorstream << "Server::ProcessData(): Canceling: "
1431                                 "No player object for peer_id=" << pkt->getPeerId()
1432                                 << " disconnecting peer!"  << std::endl;
1433                 DisconnectPeer(pkt->getPeerId());
1434                 return;
1435         }
1436
1437         // If something goes wrong, this player is to blame
1438         RollbackScopeActor rollback_scope(m_rollback,
1439                         std::string("player:")+player->getName());
1440
1441         // Check the target node for rollback data; leave others unnoticed
1442         RollbackNode rn_old(&m_env->getMap(), p, this);
1443
1444         m_script->node_on_receive_fields(p, formname, fields, playersao);
1445
1446         // Report rollback data
1447         RollbackNode rn_new(&m_env->getMap(), p, this);
1448         if (rollback() && rn_new != rn_old) {
1449                 RollbackAction action;
1450                 action.setSetNode(p, rn_old, rn_new);
1451                 rollback()->reportAction(action);
1452         }
1453 }
1454
1455 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1456 {
1457         std::string client_formspec_name;
1458         u16 num;
1459
1460         *pkt >> client_formspec_name >> num;
1461
1462         StringMap fields;
1463         for (u16 k = 0; k < num; k++) {
1464                 std::string fieldname;
1465                 *pkt >> fieldname;
1466                 fields[fieldname] = pkt->readLongString();
1467         }
1468
1469         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1470
1471         if (player == NULL) {
1472                 errorstream << "Server::ProcessData(): Canceling: "
1473                                 "No player for peer_id=" << pkt->getPeerId()
1474                                 << " disconnecting peer!" << std::endl;
1475                 DisconnectPeer(pkt->getPeerId());
1476                 return;
1477         }
1478
1479         PlayerSAO *playersao = player->getPlayerSAO();
1480         if (playersao == NULL) {
1481                 errorstream << "Server::ProcessData(): Canceling: "
1482                                 "No player object for peer_id=" << pkt->getPeerId()
1483                                 << " disconnecting peer!" << std::endl;
1484                 DisconnectPeer(pkt->getPeerId());
1485                 return;
1486         }
1487
1488         if (client_formspec_name.empty()) { // pass through inventory submits
1489                 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1490                 return;
1491         }
1492
1493         // verify that we displayed the formspec to the user
1494         const auto peer_state_iterator = m_formspec_state_data.find(pkt->getPeerId());
1495         if (peer_state_iterator != m_formspec_state_data.end()) {
1496                 const std::string &server_formspec_name = peer_state_iterator->second;
1497                 if (client_formspec_name == server_formspec_name) {
1498                         auto it = fields.find("quit");
1499                         if (it != fields.end() && it->second == "true")
1500                                 m_formspec_state_data.erase(peer_state_iterator);
1501
1502                         m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1503                         return;
1504                 }
1505                 actionstream << "'" << player->getName()
1506                         << "' submitted formspec ('" << client_formspec_name
1507                         << "') but the name of the formspec doesn't match the"
1508                         " expected name ('" << server_formspec_name << "')";
1509
1510         } else {
1511                 actionstream << "'" << player->getName()
1512                         << "' submitted formspec ('" << client_formspec_name
1513                         << "') but server hasn't sent formspec to client";
1514         }
1515         actionstream << ", possible exploitation attempt" << std::endl;
1516 }
1517
1518 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1519 {
1520         RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1521         ClientState cstate = client->getState();
1522
1523         std::string playername = client->getName();
1524
1525         std::string salt;
1526         std::string verification_key;
1527
1528         std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1529         u8 is_empty;
1530
1531         *pkt >> salt >> verification_key >> is_empty;
1532
1533         verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1534                 << ", with is_empty=" << (is_empty == 1) << std::endl;
1535
1536         // Either this packet is sent because the user is new or to change the password
1537         if (cstate == CS_HelloSent) {
1538                 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1539                         actionstream << "Server: Client from " << addr_s
1540                                         << " tried to set password without being "
1541                                         << "authenticated, or the username being new." << std::endl;
1542                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1543                         return;
1544                 }
1545
1546                 if (!isSingleplayer() &&
1547                                 g_settings->getBool("disallow_empty_password") &&
1548                                 is_empty == 1) {
1549                         actionstream << "Server: " << playername
1550                                         << " supplied empty password from " << addr_s << std::endl;
1551                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1552                         return;
1553                 }
1554
1555                 std::string initial_ver_key;
1556
1557                 initial_ver_key = encode_srp_verifier(verification_key, salt);
1558                 m_script->createAuth(playername, initial_ver_key);
1559
1560                 acceptAuth(pkt->getPeerId(), false);
1561         } else {
1562                 if (cstate < CS_SudoMode) {
1563                         infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1564                                         << addr_s << ": " << "Client has wrong state " << cstate << "."
1565                                         << std::endl;
1566                         return;
1567                 }
1568                 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1569                 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1570                 bool success = m_script->setPassword(playername, pw_db_field);
1571                 if (success) {
1572                         actionstream << playername << " changes password" << std::endl;
1573                         SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1574                                         L"Password change successful."));
1575                 } else {
1576                         actionstream << playername << " tries to change password but "
1577                                 << "it fails" << std::endl;
1578                         SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1579                                         L"Password change failed or unavailable."));
1580                 }
1581         }
1582 }
1583
1584 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1585 {
1586         RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1587         ClientState cstate = client->getState();
1588
1589         bool wantSudo = (cstate == CS_Active);
1590
1591         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1592                 actionstream << "Server: got SRP _A packet in wrong state "
1593                         << cstate << " from "
1594                         << getPeerAddress(pkt->getPeerId()).serializeString()
1595                         << ". Ignoring." << std::endl;
1596                 return;
1597         }
1598
1599         if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1600                 actionstream << "Server: got SRP _A packet, while auth"
1601                         << "is already going on with mech " << client->chosen_mech
1602                         << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1603                         << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1604                 if (wantSudo) {
1605                         DenySudoAccess(pkt->getPeerId());
1606                         return;
1607                 }
1608
1609                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1610                 return;
1611         }
1612
1613         std::string bytes_A;
1614         u8 based_on;
1615         *pkt >> bytes_A >> based_on;
1616
1617         infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1618                 << "based_on=" << int(based_on) << " and len_A="
1619                 << bytes_A.length() << "." << std::endl;
1620
1621         AuthMechanism chosen = (based_on == 0) ?
1622                 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1623
1624         if (wantSudo) {
1625                 if (!client->isSudoMechAllowed(chosen)) {
1626                         actionstream << "Server: Player \"" << client->getName()
1627                                 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1628                                 << " tried to change password using unallowed mech "
1629                                 << chosen << "." << std::endl;
1630                         DenySudoAccess(pkt->getPeerId());
1631                         return;
1632                 }
1633         } else {
1634                 if (!client->isMechAllowed(chosen)) {
1635                         actionstream << "Server: Client tried to authenticate from "
1636                                 << getPeerAddress(pkt->getPeerId()).serializeString()
1637                                 << " using unallowed mech " << chosen << "." << std::endl;
1638                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1639                         return;
1640                 }
1641         }
1642
1643         client->chosen_mech = chosen;
1644
1645         std::string salt;
1646         std::string verifier;
1647
1648         if (based_on == 0) {
1649
1650                 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1651                         &verifier, &salt);
1652         } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1653                 // Non-base64 errors should have been catched in the init handler
1654                 actionstream << "Server: User " << client->getName()
1655                         << " tried to log in, but srp verifier field"
1656                         << " was invalid (most likely invalid base64)." << std::endl;
1657                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1658                 return;
1659         }
1660
1661         char *bytes_B = 0;
1662         size_t len_B = 0;
1663
1664         client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1665                 client->getName().c_str(),
1666                 (const unsigned char *) salt.c_str(), salt.size(),
1667                 (const unsigned char *) verifier.c_str(), verifier.size(),
1668                 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1669                 NULL, 0,
1670                 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1671
1672         if (!bytes_B) {
1673                 actionstream << "Server: User " << client->getName()
1674                         << " tried to log in, SRP-6a safety check violated in _A handler."
1675                         << std::endl;
1676                 if (wantSudo) {
1677                         DenySudoAccess(pkt->getPeerId());
1678                         return;
1679                 }
1680
1681                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1682                 return;
1683         }
1684
1685         NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1686         resp_pkt << salt << std::string(bytes_B, len_B);
1687         Send(&resp_pkt);
1688 }
1689
1690 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1691 {
1692         RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1693         ClientState cstate = client->getState();
1694
1695         bool wantSudo = (cstate == CS_Active);
1696
1697         verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
1698
1699         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1700                 actionstream << "Server: got SRP _M packet in wrong state "
1701                         << cstate << " from "
1702                         << getPeerAddress(pkt->getPeerId()).serializeString()
1703                         << ". Ignoring." << std::endl;
1704                 return;
1705         }
1706
1707         if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1708                         client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1709                 actionstream << "Server: got SRP _M packet, while auth"
1710                         << "is going on with mech " << client->chosen_mech
1711                         << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1712                         << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1713                 if (wantSudo) {
1714                         DenySudoAccess(pkt->getPeerId());
1715                         return;
1716                 }
1717
1718                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1719                 return;
1720         }
1721
1722         std::string bytes_M;
1723         *pkt >> bytes_M;
1724
1725         if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1726                         != bytes_M.size()) {
1727                 actionstream << "Server: User " << client->getName()
1728                         << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1729                         << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1730                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1731                 return;
1732         }
1733
1734         unsigned char *bytes_HAMK = 0;
1735
1736         srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1737                 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1738
1739         if (!bytes_HAMK) {
1740                 if (wantSudo) {
1741                         actionstream << "Server: User " << client->getName()
1742                                 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
1743                                 << " tried to change their password, but supplied wrong"
1744                                 << " (SRP) password for authentication." << std::endl;
1745                         DenySudoAccess(pkt->getPeerId());
1746                         return;
1747                 }
1748
1749                 std::string ip = getPeerAddress(pkt->getPeerId()).serializeString();
1750                 actionstream << "Server: User " << client->getName()
1751                         << " at " << ip
1752                         << " supplied wrong password (auth mechanism: SRP)."
1753                         << std::endl;
1754                 m_script->on_auth_failure(client->getName(), ip);
1755                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
1756                 return;
1757         }
1758
1759         if (client->create_player_on_auth_success) {
1760                 std::string playername = client->getName();
1761                 m_script->createAuth(playername, client->enc_pwd);
1762
1763                 std::string checkpwd; // not used, but needed for passing something
1764                 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1765                         actionstream << "Server: " << playername << " cannot be authenticated"
1766                                 << " (auth handler does not work?)" << std::endl;
1767                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1768                         return;
1769                 }
1770                 client->create_player_on_auth_success = false;
1771         }
1772
1773         acceptAuth(pkt->getPeerId(), wantSudo);
1774 }
1775
1776 /*
1777  * Mod channels
1778  */
1779
1780 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1781 {
1782         std::string channel_name;
1783         *pkt >> channel_name;
1784
1785         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1786                 pkt->getPeerId());
1787
1788         // Send signal to client to notify join succeed or not
1789         if (g_settings->getBool("enable_mod_channels") &&
1790                         m_modchannel_mgr->joinChannel(channel_name, pkt->getPeerId())) {
1791                 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1792                 infostream << "Peer " << pkt->getPeerId() << " joined channel " << channel_name
1793                                 << std::endl;
1794         }
1795         else {
1796                 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1797                 infostream << "Peer " << pkt->getPeerId() << " tried to join channel "
1798                         << channel_name << ", but was already registered." << std::endl;
1799         }
1800         resp_pkt << channel_name;
1801         Send(&resp_pkt);
1802 }
1803
1804 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1805 {
1806         std::string channel_name;
1807         *pkt >> channel_name;
1808
1809         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1810                 pkt->getPeerId());
1811
1812         // Send signal to client to notify join succeed or not
1813         if (g_settings->getBool("enable_mod_channels") &&
1814                         m_modchannel_mgr->leaveChannel(channel_name, pkt->getPeerId())) {
1815                 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1816                 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1817                                 << std::endl;
1818         } else {
1819                 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1820                 infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
1821                                 << ", but was not registered." << std::endl;
1822         }
1823         resp_pkt << channel_name;
1824         Send(&resp_pkt);
1825 }
1826
1827 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1828 {
1829         std::string channel_name, channel_msg;
1830         *pkt >> channel_name >> channel_msg;
1831
1832         verbosestream << "Mod channel message received from peer " << pkt->getPeerId()
1833                         << " on channel " << channel_name << " message: " << channel_msg << std::endl;
1834
1835         // If mod channels are not enabled, discard message
1836         if (!g_settings->getBool("enable_mod_channels")) {
1837                 return;
1838         }
1839
1840         // If channel not registered, signal it and ignore message
1841         if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1842                 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
1843                         pkt->getPeerId());
1844                 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1845                 Send(&resp_pkt);
1846                 return;
1847         }
1848
1849         // @TODO: filter, rate limit
1850
1851         broadcastModChannelMessage(channel_name, channel_msg, pkt->getPeerId());
1852 }