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