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