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