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