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