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