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