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