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