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