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