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