Tooltips: Unify the tooltip[] and list[] description tooltip display functions (...
[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 "server.h"
21 #include "log.h"
22
23 #include "content_abm.h"
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         // Warnings about protocol version can be issued here
647         if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
648                 SendChatMessage(pkt->getPeerId(), L"# Server: WARNING: YOUR CLIENT'S "
649                                 L"VERSION MAY NOT BE FULLY COMPATIBLE WITH THIS SERVER!");
650         }
651 }
652
653 void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
654 {
655         std::vector<std::string> tosend;
656         u16 numfiles;
657
658         *pkt >> numfiles;
659
660         infostream << "Sending " << numfiles << " files to "
661                         << getPlayerName(pkt->getPeerId()) << std::endl;
662         verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
663
664         for (u16 i = 0; i < numfiles; i++) {
665                 std::string name;
666
667                 *pkt >> name;
668
669                 tosend.push_back(name);
670                 verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
671                                 << name << std::endl;
672         }
673
674         sendRequestedMedia(pkt->getPeerId(), tosend);
675 }
676
677 void Server::handleCommand_ClientReady(NetworkPacket* pkt)
678 {
679         u16 peer_id = pkt->getPeerId();
680         u16 peer_proto_ver = getClient(peer_id, CS_InitDone)->net_proto_version;
681
682         // clients <= protocol version 22 did not send ready message,
683         // they're already initialized
684         if (peer_proto_ver <= 22) {
685                 infostream << "Client sent message not expected by a "
686                         << "client using protocol version <= 22,"
687                         << "disconnecting peer_id: " << peer_id << std::endl;
688                 m_con.DisconnectPeer(peer_id);
689                 return;
690         }
691
692         PlayerSAO* playersao = StageTwoClientInit(peer_id);
693
694         if (playersao == NULL) {
695                 actionstream
696                         << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
697                         << peer_id << std::endl;
698                 m_con.DisconnectPeer(peer_id);
699                 return;
700         }
701
702
703         if (pkt->getSize() < 8) {
704                 errorstream
705                         << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
706                         << peer_id << std::endl;
707                 m_con.DisconnectPeer(peer_id);
708                 return;
709         }
710
711         u8 major_ver, minor_ver, patch_ver, reserved;
712         std::string full_ver;
713         *pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
714
715         m_clients.setClientVersion(
716                         peer_id, major_ver, minor_ver, patch_ver,
717                         full_ver);
718
719         m_clients.event(peer_id, CSE_SetClientReady);
720         m_script->on_joinplayer(playersao);
721         // Send shutdown timer if shutdown has been scheduled
722         if (m_shutdown_timer > 0.0f) {
723                 std::wstringstream ws;
724                 ws << L"*** Server shutting down in "
725                                 << duration_to_string(myround(m_shutdown_timer)).c_str() << ".";
726                 SendChatMessage(pkt->getPeerId(), ws.str());
727         }
728 }
729
730 void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
731 {
732         if (pkt->getSize() < 1)
733                 return;
734
735         /*
736                 [0] u16 command
737                 [2] u8 count
738                 [3] v3s16 pos_0
739                 [3+6] v3s16 pos_1
740                 ...
741         */
742
743         u8 count;
744         *pkt >> count;
745
746         RemoteClient *client = getClient(pkt->getPeerId());
747
748         if ((s16)pkt->getSize() < 1 + (int)count * 6) {
749                 throw con::InvalidIncomingDataException
750                                 ("GOTBLOCKS length is too short");
751         }
752
753         for (u16 i = 0; i < count; i++) {
754                 v3s16 p;
755                 *pkt >> p;
756                 client->GotBlock(p);
757         }
758 }
759
760 void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
761         NetworkPacket *pkt)
762 {
763         if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4)
764                 return;
765
766         v3s32 ps, ss;
767         s32 f32pitch, f32yaw;
768         u8 f32fov;
769
770         *pkt >> ps;
771         *pkt >> ss;
772         *pkt >> f32pitch;
773         *pkt >> f32yaw;
774
775         f32 pitch = (f32)f32pitch / 100.0;
776         f32 yaw = (f32)f32yaw / 100.0;
777         u32 keyPressed = 0;
778
779         // default behavior (in case an old client doesn't send these)
780         f32 fov = 0;
781         u8 wanted_range = 0;
782
783         if (pkt->getRemainingBytes() >= 4)
784                 *pkt >> keyPressed;
785         if (pkt->getRemainingBytes() >= 1) {
786                 *pkt >> f32fov;
787                 fov = (f32)f32fov / 80.0;
788         }
789         if (pkt->getRemainingBytes() >= 1)
790                 *pkt >> wanted_range;
791
792         v3f position((f32)ps.X / 100.0, (f32)ps.Y / 100.0, (f32)ps.Z / 100.0);
793         v3f speed((f32)ss.X / 100.0, (f32)ss.Y / 100.0, (f32)ss.Z / 100.0);
794
795         pitch = modulo360f(pitch);
796         yaw = wrapDegrees_0_360(yaw);
797
798         playersao->setBasePosition(position);
799         player->setSpeed(speed);
800         playersao->setPitch(pitch);
801         playersao->setYaw(yaw);
802         playersao->setFov(fov);
803         playersao->setWantedRange(wanted_range);
804         player->keyPressed = keyPressed;
805         player->control.up = (keyPressed & 1);
806         player->control.down = (keyPressed & 2);
807         player->control.left = (keyPressed & 4);
808         player->control.right = (keyPressed & 8);
809         player->control.jump = (keyPressed & 16);
810         player->control.aux1 = (keyPressed & 32);
811         player->control.sneak = (keyPressed & 64);
812         player->control.LMB = (keyPressed & 128);
813         player->control.RMB = (keyPressed & 256);
814
815         if (playersao->checkMovementCheat()) {
816                 // Call callbacks
817                 m_script->on_cheat(playersao, "moved_too_fast");
818                 SendMovePlayer(pkt->getPeerId());
819         }
820 }
821
822 void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
823 {
824         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
825         if (player == NULL) {
826                 errorstream << "Server::ProcessData(): Canceling: "
827                                 "No player for peer_id=" << pkt->getPeerId()
828                                 << " disconnecting peer!" << std::endl;
829                 m_con.DisconnectPeer(pkt->getPeerId());
830                 return;
831         }
832
833         PlayerSAO *playersao = player->getPlayerSAO();
834         if (playersao == NULL) {
835                 errorstream << "Server::ProcessData(): Canceling: "
836                                 "No player object for peer_id=" << pkt->getPeerId()
837                                 << " disconnecting peer!" << std::endl;
838                 m_con.DisconnectPeer(pkt->getPeerId());
839                 return;
840         }
841
842         // If player is dead we don't care of this packet
843         if (playersao->isDead()) {
844                 verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
845                                 << " is dead. Ignoring packet";
846                 return;
847         }
848
849         process_PlayerPos(player, playersao, pkt);
850 }
851
852 void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
853 {
854         if (pkt->getSize() < 1)
855                 return;
856
857         /*
858                 [0] u16 command
859                 [2] u8 count
860                 [3] v3s16 pos_0
861                 [3+6] v3s16 pos_1
862                 ...
863         */
864
865         u8 count;
866         *pkt >> count;
867
868         RemoteClient *client = getClient(pkt->getPeerId());
869
870         if ((s16)pkt->getSize() < 1 + (int)count * 6) {
871                 throw con::InvalidIncomingDataException
872                                 ("DELETEDBLOCKS length is too short");
873         }
874
875         for (u16 i = 0; i < count; i++) {
876                 v3s16 p;
877                 *pkt >> p;
878                 client->SetBlockNotSent(p);
879         }
880 }
881
882 void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
883 {
884         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
885
886         if (player == NULL) {
887                 errorstream << "Server::ProcessData(): Canceling: "
888                                 "No player for peer_id=" << pkt->getPeerId()
889                                 << " disconnecting peer!" << std::endl;
890                 m_con.DisconnectPeer(pkt->getPeerId());
891                 return;
892         }
893
894         PlayerSAO *playersao = player->getPlayerSAO();
895         if (playersao == NULL) {
896                 errorstream << "Server::ProcessData(): Canceling: "
897                                 "No player object for peer_id=" << pkt->getPeerId()
898                                 << " disconnecting peer!" << std::endl;
899                 m_con.DisconnectPeer(pkt->getPeerId());
900                 return;
901         }
902
903         // Strip command and create a stream
904         std::string datastring(pkt->getString(0), pkt->getSize());
905         verbosestream << "TOSERVER_INVENTORY_ACTION: data=" << datastring
906                 << std::endl;
907         std::istringstream is(datastring, std::ios_base::binary);
908         // Create an action
909         InventoryAction *a = InventoryAction::deSerialize(is);
910         if (a == NULL) {
911                 infostream << "TOSERVER_INVENTORY_ACTION: "
912                                 << "InventoryAction::deSerialize() returned NULL"
913                                 << std::endl;
914                 return;
915         }
916
917         // If something goes wrong, this player is to blame
918         RollbackScopeActor rollback_scope(m_rollback,
919                         std::string("player:")+player->getName());
920
921         /*
922                 Note: Always set inventory not sent, to repair cases
923                 where the client made a bad prediction.
924         */
925
926         /*
927                 Handle restrictions and special cases of the move action
928         */
929         if (a->getType() == IACTION_MOVE) {
930                 IMoveAction *ma = (IMoveAction*)a;
931
932                 ma->from_inv.applyCurrentPlayer(player->getName());
933                 ma->to_inv.applyCurrentPlayer(player->getName());
934
935                 setInventoryModified(ma->from_inv, false);
936                 setInventoryModified(ma->to_inv, false);
937
938                 bool from_inv_is_current_player =
939                         (ma->from_inv.type == InventoryLocation::PLAYER) &&
940                         (ma->from_inv.name == player->getName());
941
942                 bool to_inv_is_current_player =
943                         (ma->to_inv.type == InventoryLocation::PLAYER) &&
944                         (ma->to_inv.name == player->getName());
945
946                 /*
947                         Disable moving items out of craftpreview
948                 */
949                 if (ma->from_list == "craftpreview") {
950                         infostream << "Ignoring IMoveAction from "
951                                         << (ma->from_inv.dump()) << ":" << ma->from_list
952                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
953                                         << " because src is " << ma->from_list << std::endl;
954                         delete a;
955                         return;
956                 }
957
958                 /*
959                         Disable moving items into craftresult and craftpreview
960                 */
961                 if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
962                         infostream << "Ignoring IMoveAction from "
963                                         << (ma->from_inv.dump()) << ":" << ma->from_list
964                                         << " to " << (ma->to_inv.dump()) << ":" << ma->to_list
965                                         << " because dst is " << ma->to_list << std::endl;
966                         delete a;
967                         return;
968                 }
969
970                 // Disallow moving items in elsewhere than player's inventory
971                 // if not allowed to interact
972                 if (!checkPriv(player->getName(), "interact") &&
973                                 (!from_inv_is_current_player ||
974                                 !to_inv_is_current_player)) {
975                         infostream << "Cannot move outside of player's inventory: "
976                                         << "No interact privilege" << std::endl;
977                         delete a;
978                         return;
979                 }
980         }
981         /*
982                 Handle restrictions and special cases of the drop action
983         */
984         else if (a->getType() == IACTION_DROP) {
985                 IDropAction *da = (IDropAction*)a;
986
987                 da->from_inv.applyCurrentPlayer(player->getName());
988
989                 setInventoryModified(da->from_inv, false);
990
991                 /*
992                         Disable dropping items out of craftpreview
993                 */
994                 if (da->from_list == "craftpreview") {
995                         infostream << "Ignoring IDropAction from "
996                                         << (da->from_inv.dump()) << ":" << da->from_list
997                                         << " because src is " << da->from_list << std::endl;
998                         delete a;
999                         return;
1000                 }
1001
1002                 // Disallow dropping items if not allowed to interact
1003                 if (!checkPriv(player->getName(), "interact")) {
1004                         delete a;
1005                         return;
1006                 }
1007
1008                 // Disallow dropping items if dead
1009                 if (playersao->isDead()) {
1010                         infostream << "Ignoring IDropAction from "
1011                                         << (da->from_inv.dump()) << ":" << da->from_list
1012                                         << " because player is dead." << std::endl;
1013                         delete a;
1014                         return;
1015                 }
1016         }
1017         /*
1018                 Handle restrictions and special cases of the craft action
1019         */
1020         else if (a->getType() == IACTION_CRAFT) {
1021                 ICraftAction *ca = (ICraftAction*)a;
1022
1023                 ca->craft_inv.applyCurrentPlayer(player->getName());
1024
1025                 setInventoryModified(ca->craft_inv, false);
1026
1027                 //bool craft_inv_is_current_player =
1028                 //      (ca->craft_inv.type == InventoryLocation::PLAYER) &&
1029                 //      (ca->craft_inv.name == player->getName());
1030
1031                 // Disallow crafting if not allowed to interact
1032                 if (!checkPriv(player->getName(), "interact")) {
1033                         infostream << "Cannot craft: "
1034                                         << "No interact privilege" << std::endl;
1035                         delete a;
1036                         return;
1037                 }
1038         }
1039
1040         // Do the action
1041         a->apply(this, playersao, this);
1042         // Eat the action
1043         delete a;
1044
1045         SendInventory(playersao);
1046 }
1047
1048 void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
1049 {
1050         /*
1051                 u16 command
1052                 u16 length
1053                 wstring message
1054         */
1055         u16 len;
1056         *pkt >> len;
1057
1058         std::wstring message;
1059         for (u16 i = 0; i < len; i++) {
1060                 u16 tmp_wchar;
1061                 *pkt >> tmp_wchar;
1062
1063                 message += (wchar_t)tmp_wchar;
1064         }
1065
1066         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1067         if (player == NULL) {
1068                 errorstream << "Server::ProcessData(): Canceling: "
1069                                 "No player for peer_id=" << pkt->getPeerId()
1070                                 << " disconnecting peer!" << std::endl;
1071                 m_con.DisconnectPeer(pkt->getPeerId());
1072                 return;
1073         }
1074
1075         // Get player name of this client
1076         std::string name = player->getName();
1077         std::wstring wname = narrow_to_wide(name);
1078
1079         std::wstring answer_to_sender = handleChat(name, wname, message,
1080                 true, dynamic_cast<RemotePlayer *>(player));
1081         if (!answer_to_sender.empty()) {
1082                 // Send the answer to sender
1083                 SendChatMessage(pkt->getPeerId(), answer_to_sender);
1084         }
1085 }
1086
1087 void Server::handleCommand_Damage(NetworkPacket* pkt)
1088 {
1089         u8 damage;
1090
1091         *pkt >> damage;
1092
1093         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1094
1095         if (player == NULL) {
1096                 errorstream << "Server::ProcessData(): Canceling: "
1097                                 "No player for peer_id=" << pkt->getPeerId()
1098                                 << " disconnecting peer!" << std::endl;
1099                 m_con.DisconnectPeer(pkt->getPeerId());
1100                 return;
1101         }
1102
1103         PlayerSAO *playersao = player->getPlayerSAO();
1104         if (playersao == NULL) {
1105                 errorstream << "Server::ProcessData(): Canceling: "
1106                                 "No player object for peer_id=" << pkt->getPeerId()
1107                                 << " disconnecting peer!" << std::endl;
1108                 m_con.DisconnectPeer(pkt->getPeerId());
1109                 return;
1110         }
1111
1112         if (g_settings->getBool("enable_damage")) {
1113                 if (playersao->isDead()) {
1114                         verbosestream << "Server::ProcessData(): Info: "
1115                                 "Ignoring damage as player " << player->getName()
1116                                 << " is already dead." << std::endl;
1117                         return;
1118                 }
1119
1120                 actionstream << player->getName() << " damaged by "
1121                                 << (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
1122                                 << std::endl;
1123
1124                 playersao->setHP(playersao->getHP() - damage);
1125                 SendPlayerHPOrDie(playersao);
1126         }
1127 }
1128
1129 void Server::handleCommand_Password(NetworkPacket* pkt)
1130 {
1131         if (pkt->getSize() != PASSWORD_SIZE * 2)
1132                 return;
1133
1134         std::string oldpwd;
1135         std::string newpwd;
1136
1137         // Deny for clients using the new protocol
1138         RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
1139         if (client->net_proto_version >= 25) {
1140                 infostream << "Server::handleCommand_Password(): Denying change: "
1141                         << " Client protocol version for peer_id=" << pkt->getPeerId()
1142                         << " too new!" << std::endl;
1143                 return;
1144         }
1145
1146         for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1147                 char c = pkt->getChar(i);
1148                 if (c == 0)
1149                         break;
1150                 oldpwd += c;
1151         }
1152
1153         for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
1154                 char c = pkt->getChar(PASSWORD_SIZE + i);
1155                 if (c == 0)
1156                         break;
1157                 newpwd += c;
1158         }
1159
1160         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1161         if (player == NULL) {
1162                 errorstream << "Server::ProcessData(): Canceling: "
1163                                 "No player for peer_id=" << pkt->getPeerId()
1164                                 << " disconnecting peer!" << std::endl;
1165                 m_con.DisconnectPeer(pkt->getPeerId());
1166                 return;
1167         }
1168
1169         if (!base64_is_valid(newpwd)) {
1170                 infostream<<"Server: " << player->getName() <<
1171                                 " supplied invalid password hash" << std::endl;
1172                 // Wrong old password supplied!!
1173                 SendChatMessage(pkt->getPeerId(), L"Invalid new password hash supplied. Password NOT changed.");
1174                 return;
1175         }
1176
1177         infostream << "Server: Client requests a password change from "
1178                         << "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
1179
1180         std::string playername = player->getName();
1181
1182         std::string checkpwd;
1183         m_script->getAuth(playername, &checkpwd, NULL);
1184
1185         if (oldpwd != checkpwd) {
1186                 infostream << "Server: invalid old password" << std::endl;
1187                 // Wrong old password supplied!!
1188                 SendChatMessage(pkt->getPeerId(), L"Invalid old password supplied. Password NOT changed.");
1189                 return;
1190         }
1191
1192         bool success = m_script->setPassword(playername, newpwd);
1193         if (success) {
1194                 actionstream << player->getName() << " changes password" << std::endl;
1195                 SendChatMessage(pkt->getPeerId(), L"Password change successful.");
1196         } else {
1197                 actionstream << player->getName() << " tries to change password but "
1198                                 << "it fails" << std::endl;
1199                 SendChatMessage(pkt->getPeerId(), L"Password change failed or unavailable.");
1200         }
1201 }
1202
1203 void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
1204 {
1205         if (pkt->getSize() < 2)
1206                 return;
1207
1208         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1209
1210         if (player == NULL) {
1211                 errorstream << "Server::ProcessData(): Canceling: "
1212                                 "No player for peer_id=" << pkt->getPeerId()
1213                                 << " disconnecting peer!" << std::endl;
1214                 m_con.DisconnectPeer(pkt->getPeerId());
1215                 return;
1216         }
1217
1218         PlayerSAO *playersao = player->getPlayerSAO();
1219         if (playersao == NULL) {
1220                 errorstream << "Server::ProcessData(): Canceling: "
1221                                 "No player object for peer_id=" << pkt->getPeerId()
1222                                 << " disconnecting peer!" << std::endl;
1223                 m_con.DisconnectPeer(pkt->getPeerId());
1224                 return;
1225         }
1226
1227         u16 item;
1228
1229         *pkt >> item;
1230
1231         playersao->setWieldIndex(item);
1232 }
1233
1234 void Server::handleCommand_Respawn(NetworkPacket* pkt)
1235 {
1236         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1237         if (player == NULL) {
1238                 errorstream << "Server::ProcessData(): Canceling: "
1239                                 "No player for peer_id=" << pkt->getPeerId()
1240                                 << " disconnecting peer!" << std::endl;
1241                 m_con.DisconnectPeer(pkt->getPeerId());
1242                 return;
1243         }
1244
1245         PlayerSAO *playersao = player->getPlayerSAO();
1246         assert(playersao);
1247
1248         if (!playersao->isDead())
1249                 return;
1250
1251         RespawnPlayer(pkt->getPeerId());
1252
1253         actionstream << player->getName() << " respawns at "
1254                         << PP(playersao->getBasePosition() / BS) << std::endl;
1255
1256         // ActiveObject is added to environment in AsyncRunStep after
1257         // the previous addition has been successfully removed
1258 }
1259
1260 void Server::handleCommand_Interact(NetworkPacket* pkt)
1261 {
1262         /*
1263                 [0] u16 command
1264                 [2] u8 action
1265                 [3] u16 item
1266                 [5] u32 length of the next item (plen)
1267                 [9] serialized PointedThing
1268                 [9 + plen] player position information
1269                 actions:
1270                 0: start digging (from undersurface) or use
1271                 1: stop digging (all parameters ignored)
1272                 2: digging completed
1273                 3: place block or item (to abovesurface)
1274                 4: use item
1275                 5: rightclick air ("activate")
1276         */
1277         u8 action;
1278         u16 item_i;
1279         *pkt >> action;
1280         *pkt >> item_i;
1281         std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
1282         PointedThing pointed;
1283         pointed.deSerialize(tmp_is);
1284
1285         verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
1286                         << item_i << ", pointed=" << pointed.dump() << std::endl;
1287
1288         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1289
1290         if (player == NULL) {
1291                 errorstream << "Server::ProcessData(): Canceling: "
1292                                 "No player for peer_id=" << pkt->getPeerId()
1293                                 << " disconnecting peer!" << std::endl;
1294                 m_con.DisconnectPeer(pkt->getPeerId());
1295                 return;
1296         }
1297
1298         PlayerSAO *playersao = player->getPlayerSAO();
1299         if (playersao == NULL) {
1300                 errorstream << "Server::ProcessData(): Canceling: "
1301                                 "No player object for peer_id=" << pkt->getPeerId()
1302                                 << " disconnecting peer!" << std::endl;
1303                 m_con.DisconnectPeer(pkt->getPeerId());
1304                 return;
1305         }
1306
1307         if (playersao->isDead()) {
1308                 actionstream << "Server: NoCheat: " << player->getName()
1309                                 << " tried to interact while dead; ignoring." << std::endl;
1310                 if (pointed.type == POINTEDTHING_NODE) {
1311                         // Re-send block to revert change on client-side
1312                         RemoteClient *client = getClient(pkt->getPeerId());
1313                         v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
1314                         client->SetBlockNotSent(blockpos);
1315                 }
1316                 // Call callbacks
1317                 m_script->on_cheat(playersao, "interacted_while_dead");
1318                 return;
1319         }
1320
1321         process_PlayerPos(player, playersao, pkt);
1322
1323         v3f player_pos = playersao->getLastGoodPosition();
1324
1325         // Update wielded item
1326         playersao->setWieldIndex(item_i);
1327
1328         // Get pointed to node (undefined if not POINTEDTYPE_NODE)
1329         v3s16 p_under = pointed.node_undersurface;
1330         v3s16 p_above = pointed.node_abovesurface;
1331
1332         // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
1333         ServerActiveObject *pointed_object = NULL;
1334         if (pointed.type == POINTEDTHING_OBJECT) {
1335                 pointed_object = m_env->getActiveObject(pointed.object_id);
1336                 if (pointed_object == NULL) {
1337                         verbosestream << "TOSERVER_INTERACT: "
1338                                 "pointed object is NULL" << std::endl;
1339                         return;
1340                 }
1341
1342         }
1343
1344         v3f pointed_pos_under = player_pos;
1345         v3f pointed_pos_above = player_pos;
1346         if (pointed.type == POINTEDTHING_NODE) {
1347                 pointed_pos_under = intToFloat(p_under, BS);
1348                 pointed_pos_above = intToFloat(p_above, BS);
1349         }
1350         else if (pointed.type == POINTEDTHING_OBJECT) {
1351                 pointed_pos_under = pointed_object->getBasePosition();
1352                 pointed_pos_above = pointed_pos_under;
1353         }
1354
1355         /*
1356                 Make sure the player is allowed to do it
1357         */
1358         if (!checkPriv(player->getName(), "interact")) {
1359                 actionstream<<player->getName()<<" attempted to interact with "
1360                                 <<pointed.dump()<<" without 'interact' privilege"
1361                                 <<std::endl;
1362                 // Re-send block to revert change on client-side
1363                 RemoteClient *client = getClient(pkt->getPeerId());
1364                 // Digging completed -> under
1365                 if (action == 2) {
1366                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1367                         client->SetBlockNotSent(blockpos);
1368                 }
1369                 // Placement -> above
1370                 if (action == 3) {
1371                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1372                         client->SetBlockNotSent(blockpos);
1373                 }
1374                 return;
1375         }
1376
1377         /*
1378                 Check that target is reasonably close
1379                 (only when digging or placing things)
1380         */
1381         static const bool enable_anticheat = !g_settings->getBool("disable_anticheat");
1382         if ((action == 0 || action == 2 || action == 3 || action == 4) &&
1383                         (enable_anticheat && !isSingleplayer())) {
1384                 float d = player_pos.getDistanceFrom(pointed_pos_under);
1385                 const ItemDefinition &playeritem_def =
1386                         playersao->getWieldedItem().getDefinition(m_itemdef);
1387                 float max_d = BS * playeritem_def.range;
1388                 InventoryList *hlist = playersao->getInventory()->getList("hand");
1389                 const ItemDefinition &hand_def =
1390                         hlist ? (hlist->getItem(0).getDefinition(m_itemdef)) : (m_itemdef->get(""));
1391                 float max_d_hand = BS * hand_def.range;
1392                 if (max_d < 0 && max_d_hand >= 0)
1393                         max_d = max_d_hand;
1394                 else if (max_d < 0)
1395                         max_d = BS * 4.0;
1396                 // cube diagonal: sqrt(3) = 1.73
1397                 if (d > max_d * 1.73) {
1398                         actionstream << "Player " << player->getName()
1399                                         << " tried to access " << pointed.dump()
1400                                         << " from too far: "
1401                                         << "d=" << d <<", max_d=" << max_d
1402                                         << ". ignoring." << std::endl;
1403                         // Re-send block to revert change on client-side
1404                         RemoteClient *client = getClient(pkt->getPeerId());
1405                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1406                         client->SetBlockNotSent(blockpos);
1407                         // Call callbacks
1408                         m_script->on_cheat(playersao, "interacted_too_far");
1409                         // Do nothing else
1410                         return;
1411                 }
1412         }
1413
1414         /*
1415                 If something goes wrong, this player is to blame
1416         */
1417         RollbackScopeActor rollback_scope(m_rollback,
1418                         std::string("player:")+player->getName());
1419
1420         /*
1421                 0: start digging or punch object
1422         */
1423         if (action == 0) {
1424                 if (pointed.type == POINTEDTHING_NODE) {
1425                         MapNode n(CONTENT_IGNORE);
1426                         bool pos_ok;
1427
1428                         n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1429                         if (!pos_ok) {
1430                                 infostream << "Server: Not punching: Node not found."
1431                                                 << " Adding block to emerge queue."
1432                                                 << std::endl;
1433                                 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1434                                         getNodeBlockPos(p_above), false);
1435                         }
1436
1437                         if (n.getContent() != CONTENT_IGNORE)
1438                                 m_script->node_on_punch(p_under, n, playersao, pointed);
1439
1440                         // Cheat prevention
1441                         playersao->noCheatDigStart(p_under);
1442                 }
1443                 else if (pointed.type == POINTEDTHING_OBJECT) {
1444                         // Skip if object has been removed
1445                         if (pointed_object->m_removed)
1446                                 return;
1447
1448                         actionstream<<player->getName()<<" punches object "
1449                                         <<pointed.object_id<<": "
1450                                         <<pointed_object->getDescription()<<std::endl;
1451
1452                         ItemStack punchitem = playersao->getWieldedItemOrHand();
1453                         ToolCapabilities toolcap =
1454                                         punchitem.getToolCapabilities(m_itemdef);
1455                         v3f dir = (pointed_object->getBasePosition() -
1456                                         (playersao->getBasePosition() + playersao->getEyeOffset())
1457                                                 ).normalize();
1458                         float time_from_last_punch =
1459                                 playersao->resetTimeFromLastPunch();
1460
1461                         s16 src_original_hp = pointed_object->getHP();
1462                         s16 dst_origin_hp = playersao->getHP();
1463
1464                         pointed_object->punch(dir, &toolcap, playersao,
1465                                         time_from_last_punch);
1466
1467                         // If the object is a player and its HP changed
1468                         if (src_original_hp != pointed_object->getHP() &&
1469                                         pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
1470                                 SendPlayerHPOrDie((PlayerSAO *)pointed_object);
1471                         }
1472
1473                         // If the puncher is a player and its HP changed
1474                         if (dst_origin_hp != playersao->getHP())
1475                                 SendPlayerHPOrDie(playersao);
1476                 }
1477
1478         } // action == 0
1479
1480         /*
1481                 1: stop digging
1482         */
1483         else if (action == 1) {
1484         } // action == 1
1485
1486         /*
1487                 2: Digging completed
1488         */
1489         else if (action == 2) {
1490                 // Only digging of nodes
1491                 if (pointed.type == POINTEDTHING_NODE) {
1492                         bool pos_ok;
1493                         MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
1494                         if (!pos_ok) {
1495                                 infostream << "Server: Not finishing digging: Node not found."
1496                                                 << " Adding block to emerge queue."
1497                                                 << std::endl;
1498                                 m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
1499                                         getNodeBlockPos(p_above), false);
1500                         }
1501
1502                         /* Cheat prevention */
1503                         bool is_valid_dig = true;
1504                         if (enable_anticheat && !isSingleplayer()) {
1505                                 v3s16 nocheat_p = playersao->getNoCheatDigPos();
1506                                 float nocheat_t = playersao->getNoCheatDigTime();
1507                                 playersao->noCheatDigEnd();
1508                                 // If player didn't start digging this, ignore dig
1509                                 if (nocheat_p != p_under) {
1510                                         infostream << "Server: NoCheat: " << player->getName()
1511                                                         << " started digging "
1512                                                         << PP(nocheat_p) << " and completed digging "
1513                                                         << PP(p_under) << "; not digging." << std::endl;
1514                                         is_valid_dig = false;
1515                                         // Call callbacks
1516                                         m_script->on_cheat(playersao, "finished_unknown_dig");
1517                                 }
1518                                 // Get player's wielded item
1519                                 ItemStack playeritem = playersao->getWieldedItemOrHand();
1520                                 ToolCapabilities playeritem_toolcap =
1521                                                 playeritem.getToolCapabilities(m_itemdef);
1522                                 // Get diggability and expected digging time
1523                                 DigParams params = getDigParams(m_nodedef->get(n).groups,
1524                                                 &playeritem_toolcap);
1525                                 // If can't dig, try hand
1526                                 if (!params.diggable) {
1527                                         InventoryList *hlist = playersao->getInventory()->getList("hand");
1528                                         const ItemDefinition &hand =
1529                                                 hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
1530                                         const ToolCapabilities *tp = hand.tool_capabilities;
1531                                         if (tp)
1532                                                 params = getDigParams(m_nodedef->get(n).groups, tp);
1533                                 }
1534                                 // If can't dig, ignore dig
1535                                 if (!params.diggable) {
1536                                         infostream << "Server: NoCheat: " << player->getName()
1537                                                         << " completed digging " << PP(p_under)
1538                                                         << ", which is not diggable with tool. not digging."
1539                                                         << std::endl;
1540                                         is_valid_dig = false;
1541                                         // Call callbacks
1542                                         m_script->on_cheat(playersao, "dug_unbreakable");
1543                                 }
1544                                 // Check digging time
1545                                 // If already invalidated, we don't have to
1546                                 if (!is_valid_dig) {
1547                                         // Well not our problem then
1548                                 }
1549                                 // Clean and long dig
1550                                 else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
1551                                         // All is good, but grab time from pool; don't care if
1552                                         // it's actually available
1553                                         playersao->getDigPool().grab(params.time);
1554                                 }
1555                                 // Short or laggy dig
1556                                 // Try getting the time from pool
1557                                 else if (playersao->getDigPool().grab(params.time)) {
1558                                         // All is good
1559                                 }
1560                                 // Dig not possible
1561                                 else {
1562                                         infostream << "Server: NoCheat: " << player->getName()
1563                                                         << " completed digging " << PP(p_under)
1564                                                         << "too fast; not digging." << std::endl;
1565                                         is_valid_dig = false;
1566                                         // Call callbacks
1567                                         m_script->on_cheat(playersao, "dug_too_fast");
1568                                 }
1569                         }
1570
1571                         /* Actually dig node */
1572
1573                         if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
1574                                 m_script->node_on_dig(p_under, n, playersao);
1575
1576                         v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1577                         RemoteClient *client = getClient(pkt->getPeerId());
1578                         // Send unusual result (that is, node not being removed)
1579                         if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
1580                                 // Re-send block to revert change on client-side
1581                                 client->SetBlockNotSent(blockpos);
1582                         }
1583                         else {
1584                                 client->ResendBlockIfOnWire(blockpos);
1585                         }
1586                 }
1587         } // action == 2
1588
1589         /*
1590                 3: place block or right-click object
1591         */
1592         else if (action == 3) {
1593                 ItemStack item = playersao->getWieldedItem();
1594
1595                 // Reset build time counter
1596                 if (pointed.type == POINTEDTHING_NODE &&
1597                                 item.getDefinition(m_itemdef).type == ITEM_NODE)
1598                         getClient(pkt->getPeerId())->m_time_from_building = 0.0;
1599
1600                 if (pointed.type == POINTEDTHING_OBJECT) {
1601                         // Right click object
1602
1603                         // Skip if object has been removed
1604                         if (pointed_object->m_removed)
1605                                 return;
1606
1607                         actionstream << player->getName() << " right-clicks object "
1608                                         << pointed.object_id << ": "
1609                                         << pointed_object->getDescription() << std::endl;
1610
1611                         // Do stuff
1612                         pointed_object->rightClick(playersao);
1613                 }
1614                 else if (m_script->item_OnPlace(
1615                                 item, playersao, pointed)) {
1616                         // Placement was handled in lua
1617
1618                         // Apply returned ItemStack
1619                         if (playersao->setWieldedItem(item)) {
1620                                 SendInventory(playersao);
1621                         }
1622                 }
1623
1624                 // If item has node placement prediction, always send the
1625                 // blocks to make sure the client knows what exactly happened
1626                 RemoteClient *client = getClient(pkt->getPeerId());
1627                 v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
1628                 v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
1629                 if (item.getDefinition(m_itemdef).node_placement_prediction != "") {
1630                         client->SetBlockNotSent(blockpos);
1631                         if (blockpos2 != blockpos) {
1632                                 client->SetBlockNotSent(blockpos2);
1633                         }
1634                 }
1635                 else {
1636                         client->ResendBlockIfOnWire(blockpos);
1637                         if (blockpos2 != blockpos) {
1638                                 client->ResendBlockIfOnWire(blockpos2);
1639                         }
1640                 }
1641         } // action == 3
1642
1643         /*
1644                 4: use
1645         */
1646         else if (action == 4) {
1647                 ItemStack item = playersao->getWieldedItem();
1648
1649                 actionstream << player->getName() << " uses " << item.name
1650                                 << ", pointing at " << pointed.dump() << std::endl;
1651
1652                 if (m_script->item_OnUse(
1653                                 item, playersao, pointed)) {
1654                         // Apply returned ItemStack
1655                         if (playersao->setWieldedItem(item)) {
1656                                 SendInventory(playersao);
1657                         }
1658                 }
1659
1660         } // action == 4
1661
1662         /*
1663                 5: rightclick air
1664         */
1665         else if (action == 5) {
1666                 ItemStack item = playersao->getWieldedItem();
1667
1668                 actionstream << player->getName() << " activates "
1669                                 << item.name << std::endl;
1670
1671                 if (m_script->item_OnSecondaryUse(
1672                                 item, playersao)) {
1673                         if( playersao->setWieldedItem(item)) {
1674                                 SendInventory(playersao);
1675                         }
1676                 }
1677         }
1678
1679
1680         /*
1681                 Catch invalid actions
1682         */
1683         else {
1684                 warningstream << "Server: Invalid action "
1685                                 << action << std::endl;
1686         }
1687 }
1688
1689 void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
1690 {
1691         u16 num;
1692         *pkt >> num;
1693         for (u16 k = 0; k < num; k++) {
1694                 s32 id;
1695
1696                 *pkt >> id;
1697
1698                 UNORDERED_MAP<s32, ServerPlayingSound>::iterator i = m_playing_sounds.find(id);
1699                 if (i == m_playing_sounds.end())
1700                         continue;
1701
1702                 ServerPlayingSound &psound = i->second;
1703                 psound.clients.erase(pkt->getPeerId());
1704                 if (psound.clients.empty())
1705                         m_playing_sounds.erase(i++);
1706         }
1707 }
1708
1709 void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
1710 {
1711         v3s16 p;
1712         std::string formname;
1713         u16 num;
1714
1715         *pkt >> p >> formname >> num;
1716
1717         StringMap fields;
1718         for (u16 k = 0; k < num; k++) {
1719                 std::string fieldname;
1720                 *pkt >> fieldname;
1721                 fields[fieldname] = pkt->readLongString();
1722         }
1723
1724         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1725
1726         if (player == NULL) {
1727                 errorstream << "Server::ProcessData(): Canceling: "
1728                                 "No player for peer_id=" << pkt->getPeerId()
1729                                 << " disconnecting peer!" << std::endl;
1730                 m_con.DisconnectPeer(pkt->getPeerId());
1731                 return;
1732         }
1733
1734         PlayerSAO *playersao = player->getPlayerSAO();
1735         if (playersao == NULL) {
1736                 errorstream << "Server::ProcessData(): Canceling: "
1737                                 "No player object for peer_id=" << pkt->getPeerId()
1738                                 << " disconnecting peer!"  << std::endl;
1739                 m_con.DisconnectPeer(pkt->getPeerId());
1740                 return;
1741         }
1742
1743         // If something goes wrong, this player is to blame
1744         RollbackScopeActor rollback_scope(m_rollback,
1745                         std::string("player:")+player->getName());
1746
1747         // Check the target node for rollback data; leave others unnoticed
1748         RollbackNode rn_old(&m_env->getMap(), p, this);
1749
1750         m_script->node_on_receive_fields(p, formname, fields, playersao);
1751
1752         // Report rollback data
1753         RollbackNode rn_new(&m_env->getMap(), p, this);
1754         if (rollback() && rn_new != rn_old) {
1755                 RollbackAction action;
1756                 action.setSetNode(p, rn_old, rn_new);
1757                 rollback()->reportAction(action);
1758         }
1759 }
1760
1761 void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
1762 {
1763         std::string formname;
1764         u16 num;
1765
1766         *pkt >> formname >> num;
1767
1768         StringMap fields;
1769         for (u16 k = 0; k < num; k++) {
1770                 std::string fieldname;
1771                 *pkt >> fieldname;
1772                 fields[fieldname] = pkt->readLongString();
1773         }
1774
1775         RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
1776
1777         if (player == NULL) {
1778                 errorstream << "Server::ProcessData(): Canceling: "
1779                                 "No player for peer_id=" << pkt->getPeerId()
1780                                 << " disconnecting peer!" << std::endl;
1781                 m_con.DisconnectPeer(pkt->getPeerId());
1782                 return;
1783         }
1784
1785         PlayerSAO *playersao = player->getPlayerSAO();
1786         if (playersao == NULL) {
1787                 errorstream << "Server::ProcessData(): Canceling: "
1788                                 "No player object for peer_id=" << pkt->getPeerId()
1789                                 << " disconnecting peer!" << std::endl;
1790                 m_con.DisconnectPeer(pkt->getPeerId());
1791                 return;
1792         }
1793
1794         m_script->on_playerReceiveFields(playersao, formname, fields);
1795 }
1796
1797 void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
1798 {
1799         RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1800         ClientState cstate = client->getState();
1801
1802         std::string playername = client->getName();
1803
1804         std::string salt;
1805         std::string verification_key;
1806
1807         std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
1808         u8 is_empty;
1809
1810         *pkt >> salt >> verification_key >> is_empty;
1811
1812         verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
1813                 << ", with is_empty=" << (is_empty == 1) << std::endl;
1814
1815         // Either this packet is sent because the user is new or to change the password
1816         if (cstate == CS_HelloSent) {
1817                 if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
1818                         actionstream << "Server: Client from " << addr_s
1819                                         << " tried to set password without being "
1820                                         << "authenticated, or the username being new." << std::endl;
1821                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1822                         return;
1823                 }
1824
1825                 if (!isSingleplayer() &&
1826                                 g_settings->getBool("disallow_empty_password") &&
1827                                 is_empty == 1) {
1828                         actionstream << "Server: " << playername
1829                                         << " supplied empty password from " << addr_s << std::endl;
1830                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
1831                         return;
1832                 }
1833
1834                 std::string initial_ver_key;
1835
1836                 initial_ver_key = encode_srp_verifier(verification_key, salt);
1837                 m_script->createAuth(playername, initial_ver_key);
1838
1839                 acceptAuth(pkt->getPeerId(), false);
1840         } else {
1841                 if (cstate < CS_SudoMode) {
1842                         infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
1843                                         << addr_s << ": " << "Client has wrong state " << cstate << "."
1844                                         << std::endl;
1845                         return;
1846                 }
1847                 m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
1848                 std::string pw_db_field = encode_srp_verifier(verification_key, salt);
1849                 bool success = m_script->setPassword(playername, pw_db_field);
1850                 if (success) {
1851                         actionstream << playername << " changes password" << std::endl;
1852                         SendChatMessage(pkt->getPeerId(), L"Password change successful.");
1853                 } else {
1854                         actionstream << playername << " tries to change password but "
1855                                 << "it fails" << std::endl;
1856                         SendChatMessage(pkt->getPeerId(), L"Password change failed or unavailable.");
1857                 }
1858         }
1859 }
1860
1861 void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
1862 {
1863         RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1864         ClientState cstate = client->getState();
1865
1866         bool wantSudo = (cstate == CS_Active);
1867
1868         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1869                 actionstream << "Server: got SRP _A packet in wrong state "
1870                         << cstate << " from "
1871                         << getPeerAddress(pkt->getPeerId()).serializeString()
1872                         << ". Ignoring." << std::endl;
1873                 return;
1874         }
1875
1876         if (client->chosen_mech != AUTH_MECHANISM_NONE) {
1877                 actionstream << "Server: got SRP _A packet, while auth"
1878                         << "is already going on with mech " << client->chosen_mech
1879                         << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1880                         << " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
1881                 if (wantSudo) {
1882                         DenySudoAccess(pkt->getPeerId());
1883                         return;
1884                 } else {
1885                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1886                         return;
1887                 }
1888         }
1889
1890         std::string bytes_A;
1891         u8 based_on;
1892         *pkt >> bytes_A >> based_on;
1893
1894         infostream << "Server: TOSERVER_SRP_BYTES_A received with "
1895                 << "based_on=" << int(based_on) << " and len_A="
1896                 << bytes_A.length() << "." << std::endl;
1897
1898         AuthMechanism chosen = (based_on == 0) ?
1899                 AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
1900
1901         if (wantSudo) {
1902                 if (!client->isSudoMechAllowed(chosen)) {
1903                         actionstream << "Server: Player \"" << client->getName()
1904                                 << "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
1905                                 << " tried to change password using unallowed mech "
1906                                 << chosen << "." << std::endl;
1907                         DenySudoAccess(pkt->getPeerId());
1908                         return;
1909                 }
1910         } else {
1911                 if (!client->isMechAllowed(chosen)) {
1912                         actionstream << "Server: Client tried to authenticate from "
1913                                 << getPeerAddress(pkt->getPeerId()).serializeString()
1914                                 << " using unallowed mech " << chosen << "." << std::endl;
1915                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1916                         return;
1917                 }
1918         }
1919
1920         client->chosen_mech = chosen;
1921
1922         std::string salt;
1923         std::string verifier;
1924
1925         if (based_on == 0) {
1926
1927                 generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
1928                         &verifier, &salt);
1929         } else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
1930                 // Non-base64 errors should have been catched in the init handler
1931                 actionstream << "Server: User " << client->getName()
1932                         << " tried to log in, but srp verifier field"
1933                         << " was invalid (most likely invalid base64)." << std::endl;
1934                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
1935                 return;
1936         }
1937
1938         char *bytes_B = 0;
1939         size_t len_B = 0;
1940
1941         client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
1942                 client->getName().c_str(),
1943                 (const unsigned char *) salt.c_str(), salt.size(),
1944                 (const unsigned char *) verifier.c_str(), verifier.size(),
1945                 (const unsigned char *) bytes_A.c_str(), bytes_A.size(),
1946                 NULL, 0,
1947                 (unsigned char **) &bytes_B, &len_B, NULL, NULL);
1948
1949         if (!bytes_B) {
1950                 actionstream << "Server: User " << client->getName()
1951                         << " tried to log in, SRP-6a safety check violated in _A handler."
1952                         << std::endl;
1953                 if (wantSudo) {
1954                         DenySudoAccess(pkt->getPeerId());
1955                         return;
1956                 } else {
1957                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1958                         return;
1959                 }
1960         }
1961
1962         NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
1963         resp_pkt << salt << std::string(bytes_B, len_B);
1964         Send(&resp_pkt);
1965 }
1966
1967 void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
1968 {
1969         RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
1970         ClientState cstate = client->getState();
1971
1972         bool wantSudo = (cstate == CS_Active);
1973
1974         verbosestream << "Server: Recieved TOCLIENT_SRP_BYTES_M." << std::endl;
1975
1976         if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
1977                 actionstream << "Server: got SRP _M packet in wrong state "
1978                         << cstate << " from "
1979                         << getPeerAddress(pkt->getPeerId()).serializeString()
1980                         << ". Ignoring." << std::endl;
1981                 return;
1982         }
1983
1984         if ((client->chosen_mech != AUTH_MECHANISM_SRP)
1985                 && (client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD)) {
1986                 actionstream << "Server: got SRP _M packet, while auth"
1987                         << "is going on with mech " << client->chosen_mech
1988                         << " from " << getPeerAddress(pkt->getPeerId()).serializeString()
1989                         << " (wantSudo=" << wantSudo << "). Denying." << std::endl;
1990                 if (wantSudo) {
1991                         DenySudoAccess(pkt->getPeerId());
1992                         return;
1993                 } else {
1994                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
1995                         return;
1996                 }
1997         }
1998
1999         std::string bytes_M;
2000         *pkt >> bytes_M;
2001
2002         if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
2003                         != bytes_M.size()) {
2004                 actionstream << "Server: User " << client->getName()
2005                         << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2006                         << " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
2007                 DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
2008                 return;
2009         }
2010
2011         unsigned char *bytes_HAMK = 0;
2012
2013         srp_verifier_verify_session((SRPVerifier *) client->auth_data,
2014                 (unsigned char *)bytes_M.c_str(), &bytes_HAMK);
2015
2016         if (!bytes_HAMK) {
2017                 if (wantSudo) {
2018                         actionstream << "Server: User " << client->getName()
2019                                 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2020                                 << " tried to change their password, but supplied wrong"
2021                                 << " (SRP) password for authentication." << std::endl;
2022                         DenySudoAccess(pkt->getPeerId());
2023                         return;
2024                 } else {
2025                         actionstream << "Server: User " << client->getName()
2026                                 << " at " << getPeerAddress(pkt->getPeerId()).serializeString()
2027                                 << " supplied wrong password (auth mechanism: SRP)."
2028                                 << std::endl;
2029                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
2030                         return;
2031                 }
2032         }
2033
2034         if (client->create_player_on_auth_success) {
2035                 std::string playername = client->getName();
2036                 m_script->createAuth(playername, client->enc_pwd);
2037
2038                 std::string checkpwd; // not used, but needed for passing something
2039                 if (!m_script->getAuth(playername, &checkpwd, NULL)) {
2040                         actionstream << "Server: " << playername << " cannot be authenticated"
2041                                 << " (auth handler does not work?)" << std::endl;
2042                         DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
2043                         return;
2044                 }
2045                 client->create_player_on_auth_success = false;
2046         }
2047
2048         acceptAuth(pkt->getPeerId(), wantSudo);
2049 }