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