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