Exposing the zoom key to Lua API (#9903)
[oweals/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         m_clients.event(peer_id, CSE_SetClientReady);
413
414         s64 last_login;
415         m_script->getAuth(playersao->getPlayer()->getName(), nullptr, nullptr, &last_login);
416         m_script->on_joinplayer(playersao, last_login);
417
418         // Send shutdown timer if shutdown has been scheduled
419         if (m_shutdown_state.isTimerRunning()) {
420                 SendChatMessage(peer_id, m_shutdown_state.getShutdownTimerMessage());
421         }
422 }
423
424 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
425 {
426         if (pkt->getSize() < 1)
427                 return;
428
429         /*
430                 [0] u16 command
431                 [2] u8 count
432                 [3] v3s16 pos_0
433                 [3+6] v3s16 pos_1
434                 ...
435         */
436
437         u8 count;
438         *pkt >> count;
439
440         RemoteClient *client = getClient(pkt->getPeerId());
441
442         if ((s16)pkt->getSize() < 1 + (int)count * 6) {
443                 throw con::InvalidIncomingDataException
444                                 ("GOTBLOCKS length is too short");
445         }
446
447         for (u16 i = 0; i < count; i++) {
448                 v3s16 p;
449                 *pkt >> p;
450                 client->GotBlock(p);
451         }
452 }
453
454 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
455         NetworkPacket *pkt)
456 {
457         if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
458                 return;
459
460         v3s32 ps, ss;
461         s32 f32pitch, f32yaw;
462         u8 f32fov;
463
464         *pkt >> ps;
465         *pkt >> ss;
466         *pkt >> f32pitch;
467         *pkt >> f32yaw;
468
469         f32 pitch = (f32)f32pitch / 100.0f;
470         f32 yaw = (f32)f32yaw / 100.0f;
471         u32 keyPressed = 0;
472
473         // default behavior (in case an old client doesn't send these)
474         f32 fov = 0;
475         u8 wanted_range = 0;
476
477         *pkt >> keyPressed;
478         *pkt >> f32fov;
479         fov = (f32)f32fov / 80.0f;
480         *pkt >> wanted_range;
481
482         v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
483         v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
484
485         pitch = modulo360f(pitch);
486         yaw = wrapDegrees_0_360(yaw);
487
488         playersao->setBasePosition(position);
489         player->setSpeed(speed);
490         playersao->setLookPitch(pitch);
491         playersao->setPlayerYaw(yaw);
492         playersao->setFov(fov);
493         playersao->setWantedRange(wanted_range);
494         player->keyPressed = keyPressed;
495         player->control.up = (keyPressed & 1);
496         player->control.down = (keyPressed & 2);
497         player->control.left = (keyPressed & 4);
498         player->control.right = (keyPressed & 8);
499         player->control.jump = (keyPressed & 16);
500         player->control.aux1 = (keyPressed & 32);
501         player->control.sneak = (keyPressed & 64);
502         player->control.LMB = (keyPressed & 128);
503         player->control.RMB = (keyPressed & 256);
504         player->control.zoom = (keyPressed & 512);
505
506         if (playersao->checkMovementCheat()) {
507                 // Call callbacks
508                 m_script->on_cheat(playersao, "moved_too_fast");
509                 SendMovePlayer(pkt->getPeerId());
510         }
511 }
512
513 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
514 {
515         session_t peer_id = pkt->getPeerId();
516         RemotePlayer *player = m_env->getPlayer(peer_id);
517         if (player == NULL) {
518                 errorstream <<
519                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
520                         peer_id << " disconnecting peer!" << std::endl;
521                 DisconnectPeer(peer_id);
522                 return;
523         }
524
525         PlayerSAO *playersao = player->getPlayerSAO();
526         if (playersao == NULL) {
527                 errorstream <<
528                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
529                         peer_id << " disconnecting peer!" << std::endl;
530                 DisconnectPeer(peer_id);
531                 return;
532         }
533
534         // If player is dead we don't care of this packet
535         if (playersao->isDead()) {
536                 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
537                                 << " is dead. Ignoring packet";
538                 return;
539         }
540
541         process_PlayerPos(player, playersao, pkt);
542 }
543
544 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
545 {
546         if (pkt->getSize() < 1)
547                 return;
548
549         /*
550                 [0] u16 command
551                 [2] u8 count
552                 [3] v3s16 pos_0
553                 [3+6] v3s16 pos_1
554                 ...
555         */
556
557         u8 count;
558         *pkt >> count;
559
560         RemoteClient *client = getClient(pkt->getPeerId());
561
562         if ((s16)pkt->getSize() < 1 + (int)count * 6) {
563                 throw con::InvalidIncomingDataException
564                                 ("DELETEDBLOCKS length is too short");
565         }
566
567         for (u16 i = 0; i < count; i++) {
568                 v3s16 p;
569                 *pkt >> p;
570                 client->SetBlockNotSent(p);
571         }
572 }
573
574 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
575 {
576         session_t peer_id = pkt->getPeerId();
577         RemotePlayer *player = m_env->getPlayer(peer_id);
578
579         if (player == NULL) {
580                 errorstream <<
581                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
582                         peer_id << " disconnecting peer!" << std::endl;
583                 DisconnectPeer(peer_id);
584                 return;
585         }
586
587         PlayerSAO *playersao = player->getPlayerSAO();
588         if (playersao == NULL) {
589                 errorstream <<
590                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
591                         peer_id << " disconnecting peer!" << std::endl;
592                 DisconnectPeer(peer_id);
593                 return;
594         }
595
596         // Strip command and create a stream
597         std::string datastring(pkt->getString(0), pkt->getSize());
598         verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
599                 << std::endl;
600         std::istringstream is(datastring, std::ios_base::binary);
601         // Create an action
602         InventoryAction *a = InventoryAction::deSerialize(is);
603         if (!a) {
604                 infostream << "TOSERVER_INVENTORY_ACTION: "
605                                 << "InventoryAction::deSerialize() returned NULL"
606                                 << std::endl;
607                 return;
608         }
609
610         // If something goes wrong, this player is to blame
611         RollbackScopeActor rollback_scope(m_rollback,
612                         std::string("player:")+player->getName());
613
614         /*
615                 Note: Always set inventory not sent, to repair cases
616                 where the client made a bad prediction.
617         */
618
619         /*
620                 Handle restrictions and special cases of the move action
621         */
622         if (a->getType() == IAction::Move) {
623                 IMoveAction *ma = (IMoveAction*)a;
624
625                 ma->from_inv.applyCurrentPlayer(player->getName());
626                 ma->to_inv.applyCurrentPlayer(player->getName());
627
628                 m_inventory_mgr->setInventoryModified(ma->from_inv);
629                 if (ma->from_inv != ma->to_inv)
630                         m_inventory_mgr->setInventoryModified(ma->to_inv);
631
632                 bool from_inv_is_current_player =
633                         (ma->from_inv.type == InventoryLocation::PLAYER) &&
634                         (ma->from_inv.name == player->getName());
635
636                 bool to_inv_is_current_player =
637                         (ma->to_inv.type == InventoryLocation::PLAYER) &&
638                         (ma->to_inv.name == player->getName());
639
640                 InventoryLocation *remote = from_inv_is_current_player ?
641                         &ma->to_inv : &ma->from_inv;
642
643                 // Check for out-of-range interaction
644                 if (remote->type == InventoryLocation::NODEMETA) {
645                         v3f node_pos   = intToFloat(remote->p, BS);
646                         v3f player_pos = player->getPlayerSAO()->getEyePosition();
647                         f32 d = player_pos.getDistanceFrom(node_pos);
648                         if (!checkInteractDistance(player, d, "inventory"))
649                                 return;
650                 }
651
652                 /*
653                         Disable moving items out of craftpreview
654                 */
655                 if (ma->from_list == "craftpreview") {
656                         infostream << "Ignoring IMoveAction from "
657                                         << (ma->from_inv.dump()) << ":" << ma->from_list
658                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
659                                         << " because src is " << ma->from_list << std::endl;
660                         delete a;
661                         return;
662                 }
663
664                 /*
665                         Disable moving items into craftresult and craftpreview
666                 */
667                 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
668                         infostream << "Ignoring IMoveAction from "
669                                         << (ma->from_inv.dump()) << ":" << ma->from_list
670                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
671                                         << " because dst is " << ma->to_list << std::endl;
672                         delete a;
673                         return;
674                 }
675
676                 // Disallow moving items in elsewhere than player's inventory
677                 // if not allowed to interact
678                 if (!checkPriv(player->getName(), "interact") &&
679                                 (!from_inv_is_current_player ||
680                                 !to_inv_is_current_player)) {
681                         infostream << "Cannot move outside of player's inventory: "
682                                         << "No interact privilege" << std::endl;
683                         delete a;
684                         return;
685                 }
686         }
687         /*
688                 Handle restrictions and special cases of the drop action
689         */
690         else if (a->getType() == IAction::Drop) {
691                 IDropAction *da = (IDropAction*)a;
692
693                 da->from_inv.applyCurrentPlayer(player->getName());
694
695                 m_inventory_mgr->setInventoryModified(da->from_inv);
696
697                 /*
698                         Disable dropping items out of craftpreview
699                 */
700                 if (da->from_list == "craftpreview") {
701                         infostream << "Ignoring IDropAction from "
702                                         << (da->from_inv.dump()) << ":" << da->from_list
703                                         << " because src is " << da->from_list << std::endl;
704                         delete a;
705                         return;
706                 }
707
708                 // Disallow dropping items if not allowed to interact
709                 if (!checkPriv(player->getName(), "interact")) {
710                         delete a;
711                         return;
712                 }
713
714                 // Disallow dropping items if dead
715                 if (playersao->isDead()) {
716                         infostream << "Ignoring IDropAction from "
717                                         << (da->from_inv.dump()) << ":" << da->from_list
718                                         << " because player is dead." << std::endl;
719                         delete a;
720                         return;
721                 }
722         }
723         /*
724                 Handle restrictions and special cases of the craft action
725         */
726         else if (a->getType() == IAction::Craft) {
727                 ICraftAction *ca = (ICraftAction*)a;
728
729                 ca->craft_inv.applyCurrentPlayer(player->getName());
730
731                 m_inventory_mgr->setInventoryModified(ca->craft_inv);
732
733                 //bool craft_inv_is_current_player =
734                 //      (ca->craft_inv.type == InventoryLocation::PLAYER) &&
735                 //      (ca->craft_inv.name == player->getName());
736
737                 // Disallow crafting if not allowed to interact
738                 if (!checkPriv(player->getName(), "interact")) {
739                         infostream << "Cannot craft: "
740                                         << "No interact privilege" << std::endl;
741                         delete a;
742                         return;
743                 }
744         }
745
746         // Do the action
747         a->apply(m_inventory_mgr.get(), playersao, this);
748         // Eat the action
749         delete a;
750 }
751
752 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
753 {
754         /*
755                 u16 command
756                 u16 length
757                 wstring message
758         */
759         u16 len;
760         *pkt >> len;
761
762         std::wstring message;
763         for (u16 i = 0; i < len; i++) {
764                 u16 tmp_wchar;
765                 *pkt >> tmp_wchar;
766
767                 message += (wchar_t)tmp_wchar;
768         }
769
770         session_t peer_id = pkt->getPeerId();
771         RemotePlayer *player = m_env->getPlayer(peer_id);
772         if (player == NULL) {
773                 errorstream <<
774                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
775                         peer_id << " disconnecting peer!" << std::endl;
776                 DisconnectPeer(peer_id);
777                 return;
778         }
779
780         // Get player name of this client
781         std::string name = player->getName();
782         std::wstring wname = narrow_to_wide(name);
783
784         std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
785         if (!answer_to_sender.empty()) {
786                 // Send the answer to sender
787                 SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_NORMAL,
788                         answer_to_sender, wname));
789         }
790 }
791
792 void Server::handleCommand_Damage(NetworkPacket* pkt)
793 {
794         u16 damage;
795
796         *pkt >> damage;
797
798         session_t peer_id = pkt->getPeerId();
799         RemotePlayer *player = m_env->getPlayer(peer_id);
800
801         if (player == NULL) {
802                 errorstream <<
803                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
804                         peer_id << " disconnecting peer!" << std::endl;
805                 DisconnectPeer(peer_id);
806                 return;
807         }
808
809         PlayerSAO *playersao = player->getPlayerSAO();
810         if (playersao == NULL) {
811                 errorstream <<
812                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
813                         peer_id << " disconnecting peer!" << std::endl;
814                 DisconnectPeer(peer_id);
815                 return;
816         }
817
818         if (!playersao->isImmortal()) {
819                 if (playersao->isDead()) {
820                         verbosestream << "Server::ProcessData(): Info: "
821                                 "Ignoring damage as player " << player->getName()
822                                 << " is already dead." << std::endl;
823                         return;
824                 }
825
826                 actionstream << player->getName() << " damaged by "
827                                 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
828                                 << std::endl;
829
830                 PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
831                 playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
832                 SendPlayerHPOrDie(playersao, reason);
833         }
834 }
835
836 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
837 {
838         if (pkt->getSize() < 2)
839                 return;
840
841         session_t peer_id = pkt->getPeerId();
842         RemotePlayer *player = m_env->getPlayer(peer_id);
843
844         if (player == NULL) {
845                 errorstream <<
846                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
847                         peer_id << " disconnecting peer!" << std::endl;
848                 DisconnectPeer(peer_id);
849                 return;
850         }
851
852         PlayerSAO *playersao = player->getPlayerSAO();
853         if (playersao == NULL) {
854                 errorstream <<
855                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
856                         peer_id << " disconnecting peer!" << std::endl;
857                 DisconnectPeer(peer_id);
858                 return;
859         }
860
861         u16 item;
862
863         *pkt >> item;
864
865         playersao->getPlayer()->setWieldIndex(item);
866 }
867
868 void Server::handleCommand_Respawn(NetworkPacket* pkt)
869 {
870         session_t peer_id = pkt->getPeerId();
871         RemotePlayer *player = m_env->getPlayer(peer_id);
872         if (player == NULL) {
873                 errorstream <<
874                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
875                         peer_id << " disconnecting peer!" << std::endl;
876                 DisconnectPeer(peer_id);
877                 return;
878         }
879
880         PlayerSAO *playersao = player->getPlayerSAO();
881         assert(playersao);
882
883         if (!playersao->isDead())
884                 return;
885
886         RespawnPlayer(peer_id);
887
888         actionstream << player->getName() << " respawns at "
889                         << PP(playersao->getBasePosition() / BS) << std::endl;
890
891         // ActiveObject is added to environment in AsyncRunStep after
892         // the previous addition has been successfully removed
893 }
894
895 bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
896 {
897         ItemStack selected_item, hand_item;
898         player->getWieldedItem(&selected_item, &hand_item);
899         f32 max_d = BS * getToolRange(selected_item.getDefinition(m_itemdef),
900                         hand_item.getDefinition(m_itemdef));
901
902         // Cube diagonal * 1.5 for maximal supported node extents:
903         // sqrt(3) * 1.5 â‰… 2.6
904         if (d > max_d + 2.6f * BS) {
905                 actionstream << "Player " << player->getName()
906                                 << " tried to access " << what
907                                 << " from too far: "
908                                 << "d=" << d << ", max_d=" << max_d
909                                 << "; ignoring." << std::endl;
910                 // Call callbacks
911                 m_script->on_cheat(player->getPlayerSAO(), "interacted_too_far");
912                 return false;
913         }
914         return true;
915 }
916
917 void Server::handleCommand_Interact(NetworkPacket *pkt)
918 {
919         /*
920                 [0] u16 command
921                 [2] u8 action
922                 [3] u16 item
923                 [5] u32 length of the next item (plen)
924                 [9] serialized PointedThing
925                 [9 + plen] player position information
926         */
927
928         InteractAction action;
929         u16 item_i;
930
931         *pkt >> (u8 &)action;
932         *pkt >> item_i;
933
934         std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
935         PointedThing pointed;
936         pointed.deSerialize(tmp_is);
937
938         verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
939                         << item_i << ", pointed=" << pointed.dump() << std::endl;
940
941         session_t peer_id = pkt->getPeerId();
942         RemotePlayer *player = m_env->getPlayer(peer_id);
943
944         if (player == NULL) {
945                 errorstream <<
946                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
947                         peer_id << " disconnecting peer!" << std::endl;
948                 DisconnectPeer(peer_id);
949                 return;
950         }
951
952         PlayerSAO *playersao = player->getPlayerSAO();
953         if (playersao == NULL) {
954                 errorstream <<
955                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
956                         peer_id << " disconnecting peer!" << std::endl;
957                 DisconnectPeer(peer_id);
958                 return;
959         }
960
961         if (playersao->isDead()) {
962                 actionstream << "Server: " << player->getName()
963                                 << " tried to interact while dead; ignoring." << std::endl;
964                 if (pointed.type == POINTEDTHING_NODE) {
965                         // Re-send block to revert change on client-side
966                         RemoteClient *client = getClient(peer_id);
967                         v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
968                         client->SetBlockNotSent(blockpos);
969                 }
970                 // Call callbacks
971                 m_script->on_cheat(playersao, "interacted_while_dead");
972                 return;
973         }
974
975         process_PlayerPos(player, playersao, pkt);
976
977         v3f player_pos = playersao->getLastGoodPosition();
978
979         // Update wielded item
980         playersao->getPlayer()->setWieldIndex(item_i);
981
982         // Get pointed to node (undefined if not POINTEDTYPE_NODE)
983         v3s16 p_under = pointed.node_undersurface;
984         v3s16 p_above = pointed.node_abovesurface;
985
986         // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
987         ServerActiveObject *pointed_object = NULL;
988         if (pointed.type == POINTEDTHING_OBJECT) {
989                 pointed_object = m_env->getActiveObject(pointed.object_id);
990                 if (pointed_object == NULL) {
991                         verbosestream << "TOSERVER_INTERACT: "
992                                 "pointed object is NULL" << std::endl;
993                         return;
994                 }
995
996         }
997
998         v3f pointed_pos_under = player_pos;
999         v3f pointed_pos_above = player_pos;
1000         if (pointed.type == POINTEDTHING_NODE) {
1001                 pointed_pos_under = intToFloat(p_under, BS);
1002                 pointed_pos_above = intToFloat(p_above, BS);
1003         }
1004         else if (pointed.type == POINTEDTHING_OBJECT) {
1005                 pointed_pos_under = pointed_object->getBasePosition();
1006                 pointed_pos_above = pointed_pos_under;
1007         }
1008
1009         /*
1010                 Make sure the player is allowed to do it
1011         */
1012         if (!checkPriv(player->getName(), "interact")) {
1013                 actionstream << player->getName() << " attempted to interact with " <<
1014                                 pointed.dump() << " without 'interact' privilege" << std::endl;
1015
1016                 // Re-send block to revert change on client-side
1017                 RemoteClient *client = getClient(peer_id);
1018                 // Digging completed -> under
1019                 if (action == INTERACT_DIGGING_COMPLETED) {
1020                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1021                         client->SetBlockNotSent(blockpos);
1022                 }
1023                 // Placement -> above
1024                 else if (action == INTERACT_PLACE) {
1025                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1026                         client->SetBlockNotSent(blockpos);
1027                 }
1028                 return;
1029         }
1030
1031         /*
1032                 Check that target is reasonably close
1033                 (only when digging or placing things)
1034         */
1035         static thread_local const bool enable_anticheat =
1036                         !g_settings->getBool("disable_anticheat");
1037
1038         if ((action == INTERACT_START_DIGGING || action == INTERACT_DIGGING_COMPLETED ||
1039                         action == INTERACT_PLACE || action == INTERACT_USE) &&
1040                         enable_anticheat && !isSingleplayer()) {
1041                 float d = playersao->getEyePosition().getDistanceFrom(pointed_pos_under);
1042
1043                 if (!checkInteractDistance(player, d, pointed.dump())) {
1044                         // Re-send block to revert change on client-side
1045                         RemoteClient *client = getClient(peer_id);
1046                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1047                         client->SetBlockNotSent(blockpos);
1048                         return;
1049                 }
1050         }
1051
1052         /*
1053                 If something goes wrong, this player is to blame
1054         */
1055         RollbackScopeActor rollback_scope(m_rollback,
1056                         std::string("player:")+player->getName());
1057
1058         /*
1059                 0: start digging or punch object
1060         */
1061         if (action == INTERACT_START_DIGGING) {
1062                 if (pointed.type == POINTEDTHING_NODE) {
1063                         MapNode n(CONTENT_IGNORE);
1064                         bool pos_ok;
1065
1066                         n = m_env->getMap().getNode(p_under, &pos_ok);
1067                         if (!pos_ok) {
1068                                 infostream << "Server: Not punching: Node not found. "
1069                                         "Adding block to emerge queue." << std::endl;
1070                                 m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above),
1071                                         false);
1072                         }
1073
1074                         if (n.getContent() != CONTENT_IGNORE)
1075                                 m_script->node_on_punch(p_under, n, playersao, pointed);
1076
1077                         // Cheat prevention
1078                         playersao->noCheatDigStart(p_under);
1079                 }
1080                 else if (pointed.type == POINTEDTHING_OBJECT) {
1081                         // Skip if object can't be interacted with anymore
1082                         if (pointed_object->isGone())
1083                                 return;
1084
1085                         ItemStack selected_item, hand_item;
1086                         ItemStack tool_item = playersao->getWieldedItem(&selected_item, &hand_item);
1087                         ToolCapabilities toolcap =
1088                                         tool_item.getToolCapabilities(m_itemdef);
1089                         v3f dir = (pointed_object->getBasePosition() -
1090                                         (playersao->getBasePosition() + playersao->getEyeOffset())
1091                                                 ).normalize();
1092                         float time_from_last_punch =
1093                                 playersao->resetTimeFromLastPunch();
1094
1095                         u16 src_original_hp = pointed_object->getHP();
1096                         u16 dst_origin_hp = playersao->getHP();
1097
1098                         u16 wear = pointed_object->punch(dir, &toolcap, playersao,
1099                                         time_from_last_punch);
1100
1101                         // Callback may have changed item, so get it again
1102                         playersao->getWieldedItem(&selected_item);
1103                         bool changed = selected_item.addWear(wear, m_itemdef);
1104                         if (changed)
1105                                 playersao->setWieldedItem(selected_item);
1106
1107                         // If the object is a player and its HP changed
1108                         if (src_original_hp != pointed_object->getHP() &&
1109                                         pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1110                                 SendPlayerHPOrDie((PlayerSAO *)pointed_object,
1111                                                 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
1112                         }
1113
1114                         // If the puncher is a player and its HP changed
1115                         if (dst_origin_hp != playersao->getHP())
1116                                 SendPlayerHPOrDie(playersao,
1117                                                 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
1118                 }
1119
1120         } // action == INTERACT_START_DIGGING
1121
1122         /*
1123                 1: stop digging
1124         */
1125         else if (action == INTERACT_STOP_DIGGING) {
1126         } // action == INTERACT_STOP_DIGGING
1127
1128         /*
1129                 2: Digging completed
1130         */
1131         else if (action == INTERACT_DIGGING_COMPLETED) {
1132                 // Only digging of nodes
1133                 if (pointed.type == POINTEDTHING_NODE) {
1134                         bool pos_ok;
1135                         MapNode n = m_env->getMap().getNode(p_under, &pos_ok);
1136                         if (!pos_ok) {
1137                                 infostream << "Server: Not finishing digging: Node not found. "
1138                                         "Adding block to emerge queue." << std::endl;
1139                                 m_emerge->enqueueBlockEmerge(peer_id, getNodeBlockPos(p_above),
1140                                         false);
1141                         }
1142
1143                         /* Cheat prevention */
1144                         bool is_valid_dig = true;
1145                         if (enable_anticheat && !isSingleplayer()) {
1146                                 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1147                                 float nocheat_t = playersao->getNoCheatDigTime();
1148                                 playersao->noCheatDigEnd();
1149                                 // If player didn't start digging this, ignore dig
1150                                 if (nocheat_p != p_under) {
1151                                         infostream << "Server: " << player->getName()
1152                                                         << " started digging "
1153                                                         << PP(nocheat_p) << " and completed digging "
1154                                                         << PP(p_under) << "; not digging." << std::endl;
1155                                         is_valid_dig = false;
1156                                         // Call callbacks
1157                                         m_script->on_cheat(playersao, "finished_unknown_dig");
1158                                 }
1159
1160                                 // Get player's wielded item
1161                                 // See also: Game::handleDigging
1162                                 ItemStack selected_item, hand_item;
1163                                 playersao->getPlayer()->getWieldedItem(&selected_item, &hand_item);
1164
1165                                 // Get diggability and expected digging time
1166                                 DigParams params = getDigParams(m_nodedef->get(n).groups,
1167                                                 &selected_item.getToolCapabilities(m_itemdef));
1168                                 // If can't dig, try hand
1169                                 if (!params.diggable) {
1170                                         params = getDigParams(m_nodedef->get(n).groups,
1171                                                 &hand_item.getToolCapabilities(m_itemdef));
1172                                 }
1173                                 // If can't dig, ignore dig
1174                                 if (!params.diggable) {
1175                                         infostream << "Server: " << player->getName()
1176                                                         << " completed digging " << PP(p_under)
1177                                                         << ", which is not diggable with tool; not digging."
1178                                                         << std::endl;
1179                                         is_valid_dig = false;
1180                                         // Call callbacks
1181                                         m_script->on_cheat(playersao, "dug_unbreakable");
1182                                 }
1183                                 // Check digging time
1184                                 // If already invalidated, we don't have to
1185                                 if (!is_valid_dig) {
1186                                         // Well not our problem then
1187                                 }
1188                                 // Clean and long dig
1189                                 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1190                                         // All is good, but grab time from pool; don't care if
1191                                         // it's actually available
1192                                         playersao->getDigPool().grab(params.time);
1193                                 }
1194                                 // Short or laggy dig
1195                                 // Try getting the time from pool
1196                                 else if (playersao->getDigPool().grab(params.time)) {
1197                                         // All is good
1198                                 }
1199                                 // Dig not possible
1200                                 else {
1201                                         infostream << "Server: " << player->getName()
1202                                                         << " completed digging " << PP(p_under)
1203                                                         << "too fast; not digging." << std::endl;
1204                                         is_valid_dig = false;
1205                                         // Call callbacks
1206                                         m_script->on_cheat(playersao, "dug_too_fast");
1207                                 }
1208                         }
1209
1210                         /* Actually dig node */
1211
1212                         if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1213                                 m_script->node_on_dig(p_under, n, playersao);
1214
1215                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1216                         RemoteClient *client = getClient(peer_id);
1217                         // Send unusual result (that is, node not being removed)
1218                         if (m_env->getMap().getNode(p_under).getContent() != CONTENT_AIR) {
1219                                 // Re-send block to revert change on client-side
1220                                 client->SetBlockNotSent(blockpos);
1221                         }
1222                         else {
1223                                 client->ResendBlockIfOnWire(blockpos);
1224                         }
1225                 }
1226         } // action == INTERACT_DIGGING_COMPLETED
1227
1228         /*
1229                 3: place block or right-click object
1230         */
1231         else if (action == 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(
1261                                 selected_item, playersao, pointed)) {
1262                         // Placement was handled in lua
1263
1264                         // Apply returned ItemStack
1265                         if (playersao->setWieldedItem(selected_item)) {
1266                                 SendInventory(playersao, true);
1267                         }
1268                 }
1269
1270                 // If item has node placement prediction, always send the
1271                 // blocks to make sure the client knows what exactly happened
1272                 RemoteClient *client = getClient(peer_id);
1273                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1274                 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1275                 if (!selected_item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
1276                         client->SetBlockNotSent(blockpos);
1277                         if (blockpos2 != blockpos) {
1278                                 client->SetBlockNotSent(blockpos2);
1279                         }
1280                 }
1281                 else {
1282                         client->ResendBlockIfOnWire(blockpos);
1283                         if (blockpos2 != blockpos) {
1284                                 client->ResendBlockIfOnWire(blockpos2);
1285                         }
1286                 }
1287         } // action == INTERACT_PLACE
1288
1289         /*
1290                 4: use
1291         */
1292         else if (action == INTERACT_USE) {
1293                 ItemStack selected_item;
1294                 playersao->getWieldedItem(&selected_item, nullptr);
1295
1296                 actionstream << player->getName() << " uses " << selected_item.name
1297                                 << ", pointing at " << pointed.dump() << std::endl;
1298
1299                 if (m_script->item_OnUse(
1300                                 selected_item, playersao, pointed)) {
1301                         // Apply returned ItemStack
1302                         if (playersao->setWieldedItem(selected_item)) {
1303                                 SendInventory(playersao, true);
1304                         }
1305                 }
1306
1307         } // action == INTERACT_USE
1308
1309         /*
1310                 5: rightclick air
1311         */
1312         else if (action == INTERACT_ACTIVATE) {
1313                 ItemStack selected_item;
1314                 playersao->getWieldedItem(&selected_item, nullptr);
1315
1316                 actionstream << player->getName() << " activates "
1317                                 << selected_item.name << std::endl;
1318
1319                 pointed.type = POINTEDTHING_NOTHING; // can only ever be NOTHING
1320
1321                 if (m_script->item_OnSecondaryUse(
1322                                 selected_item, playersao, pointed)) {
1323                         if (playersao->setWieldedItem(selected_item)) {
1324                                 SendInventory(playersao, true);
1325                         }
1326                 }
1327         } // action == INTERACT_ACTIVATE
1328
1329
1330         /*
1331                 Catch invalid actions
1332         */
1333         else {
1334                 warningstream << "Server: Invalid action "
1335                                 << action << std::endl;
1336         }
1337 }
1338
1339 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1340 {
1341         u16 num;
1342         *pkt >> num;
1343         for (u16 k = 0; k < num; k++) {
1344                 s32 id;
1345
1346                 *pkt >> id;
1347
1348                 std::unordered_map<s32, ServerPlayingSound>::iterator i =
1349                         m_playing_sounds.find(id);
1350                 if (i == m_playing_sounds.end())
1351                         continue;
1352
1353                 ServerPlayingSound &psound = i->second;
1354                 psound.clients.erase(pkt->getPeerId());
1355                 if (psound.clients.empty())
1356                         m_playing_sounds.erase(i++);
1357         }
1358 }
1359
1360 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1361 {
1362         v3s16 p;
1363         std::string formname;
1364         u16 num;
1365
1366         *pkt >> p >> formname >> num;
1367
1368         StringMap fields;
1369         for (u16 k = 0; k < num; k++) {
1370                 std::string fieldname;
1371                 *pkt >> fieldname;
1372                 fields[fieldname] = pkt->readLongString();
1373         }
1374
1375         session_t peer_id = pkt->getPeerId();
1376         RemotePlayer *player = m_env->getPlayer(peer_id);
1377
1378         if (player == NULL) {
1379                 errorstream <<
1380                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
1381                         peer_id << " disconnecting peer!" << std::endl;
1382                 DisconnectPeer(peer_id);
1383                 return;
1384         }
1385
1386         PlayerSAO *playersao = player->getPlayerSAO();
1387         if (playersao == NULL) {
1388                 errorstream <<
1389                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1390                         peer_id << " disconnecting peer!" << std::endl;
1391                 DisconnectPeer(peer_id);
1392                 return;
1393         }
1394
1395         // If something goes wrong, this player is to blame
1396         RollbackScopeActor rollback_scope(m_rollback,
1397                         std::string("player:")+player->getName());
1398
1399         // Check the target node for rollback data; leave others unnoticed
1400         RollbackNode rn_old(&m_env->getMap(), p, this);
1401
1402         m_script->node_on_receive_fields(p, formname, fields, playersao);
1403
1404         // Report rollback data
1405         RollbackNode rn_new(&m_env->getMap(), p, this);
1406         if (rollback() && rn_new != rn_old) {
1407                 RollbackAction action;
1408                 action.setSetNode(p, rn_old, rn_new);
1409                 rollback()->reportAction(action);
1410         }
1411 }
1412
1413 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1414 {
1415         std::string client_formspec_name;
1416         u16 num;
1417
1418         *pkt >> client_formspec_name >> num;
1419
1420         StringMap fields;
1421         for (u16 k = 0; k < num; k++) {
1422                 std::string fieldname;
1423                 *pkt >> fieldname;
1424                 fields[fieldname] = pkt->readLongString();
1425         }
1426
1427         session_t peer_id = pkt->getPeerId();
1428         RemotePlayer *player = m_env->getPlayer(peer_id);
1429
1430         if (player == NULL) {
1431                 errorstream <<
1432                         "Server::ProcessData(): Canceling: No player for peer_id=" <<
1433                         peer_id << " disconnecting peer!" << std::endl;
1434                 DisconnectPeer(peer_id);
1435                 return;
1436         }
1437
1438         PlayerSAO *playersao = player->getPlayerSAO();
1439         if (playersao == NULL) {
1440                 errorstream <<
1441                         "Server::ProcessData(): Canceling: No player object for peer_id=" <<
1442                         peer_id << " disconnecting peer!" << std::endl;
1443                 DisconnectPeer(peer_id);
1444                 return;
1445         }
1446
1447         if (client_formspec_name.empty()) { // pass through inventory submits
1448                 m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1449                 return;
1450         }
1451
1452         // verify that we displayed the formspec to the user
1453         const auto peer_state_iterator = m_formspec_state_data.find(peer_id);
1454         if (peer_state_iterator != m_formspec_state_data.end()) {
1455                 const std::string &server_formspec_name = peer_state_iterator->second;
1456                 if (client_formspec_name == server_formspec_name) {
1457                         auto it = fields.find("quit");
1458                         if (it != fields.end() && it->second == "true")
1459                                 m_formspec_state_data.erase(peer_state_iterator);
1460
1461                         m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
1462                         return;
1463                 }
1464                 actionstream << "'" << player->getName()
1465                         << "' submitted formspec ('" << client_formspec_name
1466                         << "') but the name of the formspec doesn't match the"
1467                         " expected name ('" << server_formspec_name << "')";
1468
1469         } else {
1470                 actionstream << "'" << player->getName()
1471                         << "' submitted formspec ('" << client_formspec_name
1472                         << "') but server hasn't sent formspec to client";
1473         }
1474         actionstream << ", possible exploitation attempt" << std::endl;
1475 }
1476
1477 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1478 {
1479         session_t peer_id = pkt->getPeerId();
1480         RemoteClient *client = getClient(peer_id, CS_Invalid);
1481         ClientState cstate = client->getState();
1482
1483         std::string playername = client->getName();
1484
1485         std::string salt;
1486         std::string verification_key;
1487
1488         std::string addr_s = getPeerAddress(peer_id).serializeString();
1489         u8 is_empty;
1490
1491         *pkt >> salt >> verification_key >> is_empty;
1492
1493         verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1494                 << ", with is_empty=" << (is_empty == 1) << std::endl;
1495
1496         // Either this packet is sent because the user is new or to change the password
1497         if (cstate == CS_HelloSent) {
1498                 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1499                         actionstream << "Server: Client from " << addr_s
1500                                         << " tried to set password without being "
1501                                         << "authenticated, or the username being new." << std::endl;
1502                         DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1503                         return;
1504                 }
1505
1506                 if (!isSingleplayer() &&
1507                                 g_settings->getBool("disallow_empty_password") &&
1508                                 is_empty == 1) {
1509                         actionstream << "Server: " << playername
1510                                         << " supplied empty password from " << addr_s << std::endl;
1511                         DenyAccess(peer_id, SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1512                         return;
1513                 }
1514
1515                 std::string initial_ver_key;
1516
1517                 initial_ver_key = encode_srp_verifier(verification_key, salt);
1518                 m_script->createAuth(playername, initial_ver_key);
1519                 m_script->on_authplayer(playername, addr_s, true);
1520
1521                 acceptAuth(peer_id, false);
1522         } else {
1523                 if (cstate < CS_SudoMode) {
1524                         infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1525                                         << addr_s << ": " << "Client has wrong state " << cstate << "."
1526                                         << std::endl;
1527                         return;
1528                 }
1529                 m_clients.event(peer_id, CSE_SudoLeave);
1530                 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1531                 bool success = m_script->setPassword(playername, pw_db_field);
1532                 if (success) {
1533                         actionstream << playername << " changes password" << std::endl;
1534                         SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1535                                 L"Password change successful."));
1536                 } else {
1537                         actionstream << playername <<
1538                                 " tries to change password but it fails" << std::endl;
1539                         SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1540                                 L"Password change failed or unavailable."));
1541                 }
1542         }
1543 }
1544
1545 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1546 {
1547         session_t peer_id = pkt->getPeerId();
1548         RemoteClient *client = getClient(peer_id, CS_Invalid);
1549         ClientState cstate = client->getState();
1550
1551         bool wantSudo = (cstate == CS_Active);
1552
1553         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1554                 actionstream << "Server: got SRP _A packet in wrong state " << cstate <<
1555                         " from " << getPeerAddress(peer_id).serializeString() <<
1556                         ". Ignoring." << std::endl;
1557                 return;
1558         }
1559
1560         if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1561                 actionstream << "Server: got SRP _A packet, while auth is already "
1562                         "going on with mech " << client->chosen_mech << " from " <<
1563                         getPeerAddress(peer_id).serializeString() <<
1564                         " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1565                 if (wantSudo) {
1566                         DenySudoAccess(peer_id);
1567                         return;
1568                 }
1569
1570                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1571                 return;
1572         }
1573
1574         std::string bytes_A;
1575         u8 based_on;
1576         *pkt >> bytes_A >> based_on;
1577
1578         infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1579                 << "based_on=" << int(based_on) << " and len_A="
1580                 << bytes_A.length() << "." << std::endl;
1581
1582         AuthMechanism chosen = (based_on == 0) ?
1583                 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1584
1585         if (wantSudo) {
1586                 if (!client->isSudoMechAllowed(chosen)) {
1587                         actionstream << "Server: Player \"" << client->getName() <<
1588                                 "\" at " << getPeerAddress(peer_id).serializeString() <<
1589                                 " tried to change password using unallowed mech " << chosen <<
1590                                 "." << std::endl;
1591                         DenySudoAccess(peer_id);
1592                         return;
1593                 }
1594         } else {
1595                 if (!client->isMechAllowed(chosen)) {
1596                         actionstream << "Server: Client tried to authenticate from " <<
1597                                 getPeerAddress(peer_id).serializeString() <<
1598                                 " using unallowed mech " << chosen << "." << std::endl;
1599                         DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1600                         return;
1601                 }
1602         }
1603
1604         client->chosen_mech = chosen;
1605
1606         std::string salt;
1607         std::string verifier;
1608
1609         if (based_on == 0) {
1610
1611                 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1612                         &verifier, &salt);
1613         } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1614                 // Non-base64 errors should have been catched in the init handler
1615                 actionstream << "Server: User " << client->getName() <<
1616                         " tried to log in, but srp verifier field was invalid (most likely "
1617                         "invalid base64)." << std::endl;
1618                 DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1619                 return;
1620         }
1621
1622         char *bytes_B = 0;
1623         size_t len_B = 0;
1624
1625         client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1626                 client->getName().c_str(),
1627                 (const unsigned char *) salt.c_str(), salt.size(),
1628                 (const unsigned char *) verifier.c_str(), verifier.size(),
1629                 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1630                 NULL, 0,
1631                 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1632
1633         if (!bytes_B) {
1634                 actionstream << "Server: User " << client->getName()
1635                         << " tried to log in, SRP-6a safety check violated in _A handler."
1636                         << std::endl;
1637                 if (wantSudo) {
1638                         DenySudoAccess(peer_id);
1639                         return;
1640                 }
1641
1642                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1643                 return;
1644         }
1645
1646         NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, peer_id);
1647         resp_pkt << salt << std::string(bytes_B, len_B);
1648         Send(&resp_pkt);
1649 }
1650
1651 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1652 {
1653         session_t peer_id = pkt->getPeerId();
1654         RemoteClient *client = getClient(peer_id, CS_Invalid);
1655         ClientState cstate = client->getState();
1656         std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1657         std::string playername = client->getName();
1658
1659         bool wantSudo = (cstate == CS_Active);
1660
1661         verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
1662
1663         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1664                 actionstream << "Server: got SRP _M packet in wrong state "
1665                         << cstate << " from " << addr_s
1666                         << ". Ignoring." << std::endl;
1667                 return;
1668         }
1669
1670         if (client->chosen_mech != AUTH_MECHANISM_SRP &&
1671                         client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
1672                 actionstream << "Server: got SRP _M packet, while auth"
1673                         << "is going on with mech " << client->chosen_mech << " from " 
1674                         << addr_s << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1675                 if (wantSudo) {
1676                         DenySudoAccess(peer_id);
1677                         return;
1678                 }
1679
1680                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1681                 return;
1682         }
1683
1684         std::string bytes_M;
1685         *pkt >> bytes_M;
1686
1687         if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
1688                         != bytes_M.size()) {
1689                 actionstream << "Server: User " << playername << " at " << addr_s
1690                         << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
1691                 DenyAccess(peer_id, SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1692                 return;
1693         }
1694
1695         unsigned char *bytes_HAMK = 0;
1696
1697         srp_verifier_verify_session((SRPVerifier *) client->auth_data,
1698                 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
1699
1700         if (!bytes_HAMK) {
1701                 if (wantSudo) {
1702                         actionstream << "Server: User " << playername << " at " << addr_s
1703                                 << " tried to change their password, but supplied wrong"
1704                                 << " (SRP) password for authentication." << std::endl;
1705                         DenySudoAccess(peer_id);
1706                         return;
1707                 }
1708
1709                 actionstream << "Server: User " << playername << " at " << addr_s
1710                         << " supplied wrong password (auth mechanism: SRP)." << std::endl;
1711                 m_script->on_authplayer(playername, addr_s, false);
1712                 DenyAccess(peer_id, SERVER_ACCESSDENIED_WRONG_PASSWORD);
1713                 return;
1714         }
1715
1716         if (client->create_player_on_auth_success) {
1717                 m_script->createAuth(playername, client->enc_pwd);
1718
1719                 std::string checkpwd; // not used, but needed for passing something
1720                 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
1721                         actionstream << "Server: " << playername <<
1722                                 " cannot be authenticated (auth handler does not work?)" <<
1723                                 std::endl;
1724                         DenyAccess(peer_id, SERVER_ACCESSDENIED_SERVER_FAIL);
1725                         return;
1726                 }
1727                 client->create_player_on_auth_success = false;
1728         }
1729
1730         m_script->on_authplayer(playername, addr_s, true);
1731         acceptAuth(peer_id, wantSudo);
1732 }
1733
1734 /*
1735  * Mod channels
1736  */
1737
1738 void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
1739 {
1740         std::string channel_name;
1741         *pkt >> channel_name;
1742
1743         session_t peer_id = pkt->getPeerId();
1744         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1745                 1 + 2 + channel_name.size(), peer_id);
1746
1747         // Send signal to client to notify join succeed or not
1748         if (g_settings->getBool("enable_mod_channels") &&
1749                         m_modchannel_mgr->joinChannel(channel_name, peer_id)) {
1750                 resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
1751                 infostream << "Peer " << peer_id << " joined channel " <<
1752                         channel_name << std::endl;
1753         }
1754         else {
1755                 resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
1756                 infostream << "Peer " << peer_id << " tried to join channel " <<
1757                         channel_name << ", but was already registered." << std::endl;
1758         }
1759         resp_pkt << channel_name;
1760         Send(&resp_pkt);
1761 }
1762
1763 void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
1764 {
1765         std::string channel_name;
1766         *pkt >> channel_name;
1767
1768         session_t peer_id = pkt->getPeerId();
1769         NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1770                 1 + 2 + channel_name.size(), peer_id);
1771
1772         // Send signal to client to notify join succeed or not
1773         if (g_settings->getBool("enable_mod_channels") &&
1774                         m_modchannel_mgr->leaveChannel(channel_name, peer_id)) {
1775                 resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
1776                 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1777                         std::endl;
1778         } else {
1779                 resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
1780                 infostream << "Peer " << peer_id << " left channel " << channel_name <<
1781                         ", but was not registered." << std::endl;
1782         }
1783         resp_pkt << channel_name;
1784         Send(&resp_pkt);
1785 }
1786
1787 void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
1788 {
1789         std::string channel_name, channel_msg;
1790         *pkt >> channel_name >> channel_msg;
1791
1792         session_t peer_id = pkt->getPeerId();
1793         verbosestream << "Mod channel message received from peer " << peer_id <<
1794                 " on channel " << channel_name << " message: " << channel_msg <<
1795                 std::endl;
1796
1797         // If mod channels are not enabled, discard message
1798         if (!g_settings->getBool("enable_mod_channels")) {
1799                 return;
1800         }
1801
1802         // If channel not registered, signal it and ignore message
1803         if (!m_modchannel_mgr->channelRegistered(channel_name)) {
1804                 NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL,
1805                         1 + 2 + channel_name.size(), peer_id);
1806                 resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
1807                 Send(&resp_pkt);
1808                 return;
1809         }
1810
1811         // @TODO: filter, rate limit
1812
1813         broadcastModChannelMessage(channel_name, channel_msg, peer_id);
1814 }