2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2015, 2018-2020 Sadie Powell <sadie@witchery.services>
5 * Copyright (C) 2012-2016 Attila Molnar <attilamolnar@hush.com>
6 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
7 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
8 * Copyright (C) 2008, 2012 Robin Burchell <robin+git@viroteck.net>
9 * Copyright (C) 2008, 2010 Craig Edwards <brain@inspircd.org>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include "treeserver.h"
28 #include "treesocket.h"
30 /** FJOIN builder for rebuilding incoming FJOINs and splitting them up into multiple messages if necessary
32 class FwdFJoinBuilder : public CommandFJoin::Builder
34 TreeServer* const sourceserver;
37 FwdFJoinBuilder(Channel* chan, TreeServer* server)
38 : CommandFJoin::Builder(chan, server)
39 , sourceserver(server)
43 void add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend);
46 /** FJOIN, almost identical to TS6 SJOIN, except for nicklist handling. */
47 CmdResult CommandFJoin::Handle(User* srcuser, Params& params)
49 /* 1.1+ FJOIN works as follows:
51 * Each FJOIN is sent along with a timestamp, and the side with the lowest
52 * timestamp 'wins'. From this point on we will refer to this side as the
53 * winner. The side with the higher timestamp loses, from this point on we
54 * will call this side the loser or losing side. This should be familiar to
55 * anyone who's dealt with dreamforge or TS6 before.
57 * When two sides of a split heal and this occurs, the following things
60 * If the timestamps are exactly equal, both sides merge their privilages
61 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
62 * re-created during a split, this is safe to do.
64 * If the timestamps are NOT equal, the losing side removes all of its
65 * modes from the channel, before introducing new users into the channel
66 * which are listed in the FJOIN command's parameters. The losing side then
67 * LOWERS its timestamp value of the channel to match that of the winning
68 * side, and the modes of the users of the winning side are merged in with
71 * The winning side on the other hand will ignore all user modes from the
72 * losing side, so only its own modes get applied. Life is simple for those
73 * who succeed at internets. :-)
75 * Outside of netbursts, the winning side also resyncs the losing side if it
76 * detects that the other side recreated the channel.
79 * :<sid> FJOIN <chan> <TS> <modes> :[<member> [<member> ...]]
80 * The last parameter is a list consisting of zero or more channel members
81 * (permanent channels may have zero users). Each entry on the list is in the
83 * [[<modes>,]<uuid>[:<membid>]
84 * <modes> is a concatenation of the mode letters the user has on the channel
85 * (e.g.: "ov" if the user is opped and voiced). The order of the mode letters
86 * are not important but if a server ecounters an unknown mode letter, it will
87 * drop the link to avoid desync.
89 * InspIRCd 2.0 and older required a comma before the uuid even if the user
90 * had no prefix modes on the channel, InspIRCd 3.0 and later does not require
91 * a comma in this case anymore.
93 * <membid> is a positive integer representing the id of the membership.
94 * If not present (in FJOINs coming from pre-1205 servers), 0 is assumed.
97 * FJOIN messages are forwarded with the new TS and modes. Prefix modes of
98 * members on the losing side are not forwarded.
99 * This is required to only have one server on each side of the network who
100 * decides the fate of a channel during a network merge. Otherwise, if the
101 * clock of a server is slightly off it may make a different decision than
102 * the rest of the network and desync.
103 * The prefix modes are always forwarded as-is, or not at all.
104 * One incoming FJOIN may result in more than one FJOIN being generated
105 * and forwarded mainly due to compatibility reasons with non-InspIRCd
106 * servers that don't handle more than 512 char long lines.
108 * Forwarding examples:
109 * Existing channel #chan with TS 1000, modes +n.
110 * Incoming: :220 FJOIN #chan 1000 +t :o,220AAAAAB:0
111 * Forwarded: :220 FJOIN #chan 1000 +nt :o,220AAAAAB:0
112 * Merge modes and forward the result. Forward their prefix modes as well.
114 * Existing channel #chan with TS 1000, modes +nt.
115 * Incoming: :220 FJOIN #CHAN 2000 +i :ov,220AAAAAB:0 o,220AAAAAC:20
116 * Forwarded: :220 FJOIN #chan 1000 +nt :,220AAAAAB:0 ,220AAAAAC:20
117 * Drop their modes, forward our modes and TS, use our channel name
118 * capitalization. Don't forward prefix modes.
122 time_t TS = ServerCommand::ExtractTS(params[1]);
124 const std::string& channel = params[0];
125 Channel* chan = ServerInstance->FindChan(channel);
126 bool apply_other_sides_modes = true;
127 TreeServer* const sourceserver = TreeServer::Get(srcuser);
131 chan = new Channel(channel, TS);
135 time_t ourTS = chan->age;
138 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Merge FJOIN received for %s, ourTS: %lu, TS: %lu, difference: %ld",
139 chan->name.c_str(), (unsigned long)ourTS, (unsigned long)TS, (long)(ourTS - TS));
140 /* If our TS is less than theirs, we dont accept their modes */
143 // If the source server isn't bursting then this FJOIN is the result of them recreating the channel with a higher TS.
144 // This happens if the last user on the channel hops and before the PART propagates a user on another server joins. Fix it by doing a resync.
145 // Servers behind us won't react this way because the forwarded FJOIN will have the correct TS.
146 if (!sourceserver->IsBursting())
148 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Server %s recreated channel %s with higher TS, resyncing", sourceserver->GetName().c_str(), chan->name.c_str());
149 sourceserver->GetSocket()->SyncChannel(chan);
151 apply_other_sides_modes = false;
155 // Our TS is greater than theirs, remove all modes, extensions, etc. from the channel
156 LowerTS(chan, TS, channel);
158 // XXX: If the channel does not exist in the chan hash at this point, create it so the remote modes can be applied on it.
159 // This happens to 0-user permanent channels on the losing side, because those are removed (from the chan hash, then
160 // deleted later) as soon as the permchan mode is removed from them.
161 if (ServerInstance->FindChan(channel) == NULL)
163 chan = new Channel(channel, TS);
169 // Apply their channel modes if we have to
170 Modes::ChangeList modechangelist;
171 if (apply_other_sides_modes)
173 ServerInstance->Modes.ModeParamsToChangeList(srcuser, MODETYPE_CHANNEL, params, modechangelist, 2, params.size() - 1);
174 ServerInstance->Modes->Process(srcuser, chan, NULL, modechangelist, ModeParser::MODE_LOCALONLY | ModeParser::MODE_MERGE);
175 // Reuse for prefix modes
176 modechangelist.clear();
179 // Build a new FJOIN for forwarding. Put the correct TS in it and the current modes of the channel
180 // after applying theirs. If they lost, the prefix modes from their message are not forwarded.
181 FwdFJoinBuilder fwdfjoin(chan, sourceserver);
183 // Process every member in the message
184 irc::spacesepstream users(params.back());
186 Modes::ChangeList* modechangelistptr = (apply_other_sides_modes ? &modechangelist : NULL);
187 while (users.GetToken(item))
189 ProcessModeUUIDPair(item, sourceserver, chan, modechangelistptr, fwdfjoin);
193 fwdfjoin.Forward(sourceserver->GetRoute());
195 // Set prefix modes on their users if we lost the FJOIN or had equal TS
196 if (apply_other_sides_modes)
197 ServerInstance->Modes->Process(srcuser, chan, NULL, modechangelist, ModeParser::MODE_LOCALONLY);
202 void CommandFJoin::ProcessModeUUIDPair(const std::string& item, TreeServer* sourceserver, Channel* chan, Modes::ChangeList* modechangelist, FwdFJoinBuilder& fwdfjoin)
204 std::string::size_type comma = item.find(',');
206 // Comma not required anymore if the user has no modes
207 const std::string::size_type ubegin = (comma == std::string::npos ? 0 : comma+1);
208 std::string uuid(item, ubegin, UIDGenerator::UUID_LENGTH);
209 User* who = ServerInstance->FindUUID(uuid);
212 // Probably KILLed, ignore
216 TreeSocket* src_socket = sourceserver->GetSocket();
217 /* Check that the user's 'direction' is correct */
218 TreeServer* route_back_again = TreeServer::Get(who);
219 if (route_back_again->GetSocket() != src_socket)
224 std::string::const_iterator modeendit = item.begin(); // End of the "ov" mode string
225 /* Check if the user received at least one mode */
226 if ((modechangelist) && (comma != std::string::npos))
229 /* Iterate through the modes and see if they are valid here, if so, apply */
230 for (std::string::const_iterator i = item.begin(); i != modeendit; ++i)
232 ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL);
234 throw ProtocolException("Unrecognised mode '" + std::string(1, *i) + "'");
236 /* Add any modes this user had to the mode stack */
237 modechangelist->push_add(mh, who->nick);
241 Membership* memb = chan->ForceJoin(who, NULL, sourceserver->IsBursting());
244 // User was already on the channel, forward because of the modes they potentially got
245 memb = chan->GetUser(who);
247 fwdfjoin.add(memb, item.begin(), modeendit);
251 // Assign the id to the new Membership
252 Membership::Id membid = 0;
253 const std::string::size_type colon = item.rfind(':');
254 if (colon != std::string::npos)
255 membid = Membership::IdFromString(item.substr(colon+1));
258 // Add member to fwdfjoin with prefix modes
259 fwdfjoin.add(memb, item.begin(), modeendit);
262 void CommandFJoin::RemoveStatus(Channel* c)
264 Modes::ChangeList changelist;
266 const ModeParser::ModeHandlerMap& mhs = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL);
267 for (ModeParser::ModeHandlerMap::const_iterator i = mhs.begin(); i != mhs.end(); ++i)
269 ModeHandler* mh = i->second;
271 // Add the removal of this mode to the changelist. This handles all kinds of modes, including prefix modes.
272 mh->RemoveMode(c, changelist);
275 ServerInstance->Modes->Process(ServerInstance->FakeClient, c, NULL, changelist, ModeParser::MODE_LOCALONLY);
278 void CommandFJoin::LowerTS(Channel* chan, time_t TS, const std::string& newname)
280 if (Utils->AnnounceTSChange)
282 // WriteRemoteNotice is not used here because the message only needs to go to the local server.
283 chan->WriteNotice(InspIRCd::Format("Creation time of %s changed from %s to %s", newname.c_str(),
284 InspIRCd::TimeString(chan->age).c_str(), InspIRCd::TimeString(TS).c_str()));
287 // While the name is equal in case-insensitive compare, it might differ in case; use the remote version
288 chan->name = newname;
292 CommandFJoin::RemoveStatus(chan);
294 // Unset all extensions
295 chan->FreeAllExtItems();
298 chan->SetTopic(ServerInstance->FakeClient, std::string(), 0);
302 CommandFJoin::Builder::Builder(Channel* chan, TreeServer* source)
303 : CmdBuilder(source, "FJOIN")
305 push(chan->name).push_int(chan->age).push_raw(" +");
307 push_raw(chan->ChanModes(true)).push_raw(" :");
310 void CommandFJoin::Builder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
312 push_raw(mbegin, mend).push_raw(',').push_raw(memb->user->uuid);
313 push_raw(':').push_raw_int(memb->id);
317 bool CommandFJoin::Builder::has_room(std::string::size_type nummodes) const
319 return ((str().size() + nummodes + UIDGenerator::UUID_LENGTH + 2 + membid_max_digits + 1) <= maxline);
322 void CommandFJoin::Builder::clear()
328 const std::string& CommandFJoin::Builder::finalize()
330 if (*content.rbegin() == ' ')
331 content.erase(content.size()-1);
335 void FwdFJoinBuilder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
337 // Pseudoserver compatibility:
338 // Some pseudoservers do not handle lines longer than 512 so we split long FJOINs into multiple messages.
339 // The forwarded FJOIN can end up being longer than the original one if we have more modes set and won, for example.
341 // Check if the member fits into the current message. If not, send it and prepare a new one.
342 if (!has_room(std::distance(mbegin, mend)))
345 Forward(sourceserver);
348 // Add the member and their modes exactly as they sent them
349 CommandFJoin::Builder::add(memb, mbegin, mend);