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