2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2008 Dennis Friis <peavey@inspircd.org>
7 * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc>
9 * This file is part of InspIRCd. InspIRCd is free software: you can
10 * redistribute it and/or modify it under the terms of the GNU General Public
11 * License as published by the Free Software Foundation, version 2.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "treeserver.h"
26 #include "treesocket.h"
28 /** FJOIN builder for rebuilding incoming FJOINs and splitting them up into multiple messages if necessary
30 class FwdFJoinBuilder : public CommandFJoin::Builder
32 TreeServer* const sourceserver;
35 FwdFJoinBuilder(Channel* chan, TreeServer* server)
36 : CommandFJoin::Builder(chan, server)
37 , sourceserver(server)
41 void add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend);
44 /** FJOIN, almost identical to TS6 SJOIN, except for nicklist handling. */
45 CmdResult CommandFJoin::Handle(User* srcuser, std::vector<std::string>& params)
47 /* 1.1+ FJOIN works as follows:
49 * Each FJOIN is sent along with a timestamp, and the side with the lowest
50 * timestamp 'wins'. From this point on we will refer to this side as the
51 * winner. The side with the higher timestamp loses, from this point on we
52 * will call this side the loser or losing side. This should be familiar to
53 * anyone who's dealt with dreamforge or TS6 before.
55 * When two sides of a split heal and this occurs, the following things
58 * If the timestamps are exactly equal, both sides merge their privilages
59 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
60 * re-created during a split, this is safe to do.
62 * If the timestamps are NOT equal, the losing side removes all of its
63 * modes from the channel, before introducing new users into the channel
64 * which are listed in the FJOIN command's parameters. The losing side then
65 * LOWERS its timestamp value of the channel to match that of the winning
66 * side, and the modes of the users of the winning side are merged in with
69 * The winning side on the other hand will ignore all user modes from the
70 * losing side, so only its own modes get applied. Life is simple for those
71 * who succeed at internets. :-)
73 * Outside of netbursts, the winning side also resyncs the losing side if it
74 * detects that the other side recreated the channel.
77 * :<sid> FJOIN <chan> <TS> <modes> :[<member> [<member> ...]]
78 * The last parameter is a list consisting of zero or more channel members
79 * (permanent channels may have zero users). Each entry on the list is in the
81 * [[<modes>,]<uuid>[:<membid>]
82 * <modes> is a concatenation of the mode letters the user has on the channel
83 * (e.g.: "ov" if the user is opped and voiced). The order of the mode letters
84 * are not important but if a server ecounters an unknown mode letter, it will
85 * drop the link to avoid desync.
87 * InspIRCd 2.0 and older required a comma before the uuid even if the user
88 * had no prefix modes on the channel, InspIRCd 3.0 and later does not require
89 * a comma in this case anymore.
91 * <membid> is a positive integer representing the id of the membership.
92 * If not present (in FJOINs coming from pre-1205 servers), 0 is assumed.
95 * FJOIN messages are forwarded with the new TS and modes. Prefix modes of
96 * members on the losing side are not forwarded.
97 * This is required to only have one server on each side of the network who
98 * decides the fate of a channel during a network merge. Otherwise, if the
99 * clock of a server is slightly off it may make a different decision than
100 * the rest of the network and desync.
101 * The prefix modes are always forwarded as-is, or not at all.
102 * One incoming FJOIN may result in more than one FJOIN being generated
103 * and forwarded mainly due to compatibility reasons with non-InspIRCd
104 * servers that don't handle more than 512 char long lines.
106 * Forwarding examples:
107 * Existing channel #chan with TS 1000, modes +n.
108 * Incoming: :220 FJOIN #chan 1000 +t :o,220AAAAAB:0
109 * Forwarded: :220 FJOIN #chan 1000 +nt :o,220AAAAAB:0
110 * Merge modes and forward the result. Forward their prefix modes as well.
112 * Existing channel #chan with TS 1000, modes +nt.
113 * Incoming: :220 FJOIN #CHAN 2000 +i :ov,220AAAAAB:0 o,220AAAAAC:20
114 * Forwarded: :220 FJOIN #chan 1000 +nt :,220AAAAAB:0 ,220AAAAAC:20
115 * Drop their modes, forward our modes and TS, use our channel name
116 * capitalization. Don't forward prefix modes.
120 time_t TS = ServerCommand::ExtractTS(params[1]);
122 const std::string& channel = params[0];
123 Channel* chan = ServerInstance->FindChan(channel);
124 bool apply_other_sides_modes = true;
125 TreeServer* const sourceserver = TreeServer::Get(srcuser);
129 chan = new Channel(channel, TS);
133 time_t ourTS = chan->age;
136 ServerInstance->SNO->WriteToSnoMask('d', "Merge FJOIN received for %s, ourTS: %lu, TS: %lu, difference: %ld",
137 chan->name.c_str(), (unsigned long)ourTS, (unsigned long)TS, (long)(ourTS - TS));
138 /* If our TS is less than theirs, we dont accept their modes */
141 // If the source server isn't bursting then this FJOIN is the result of them recreating the channel with a higher TS.
142 // 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.
143 // Servers behind us won't react this way because the forwarded FJOIN will have the correct TS.
144 if (!sourceserver->IsBursting())
146 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Server %s recreated channel %s with higher TS, resyncing", sourceserver->GetName().c_str(), chan->name.c_str());
147 sourceserver->GetSocket()->SyncChannel(chan);
149 apply_other_sides_modes = false;
153 // Our TS is greater than theirs, remove all modes, extensions, etc. from the channel
154 LowerTS(chan, TS, channel);
156 // 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.
157 // This happens to 0-user permanent channels on the losing side, because those are removed (from the chan hash, then
158 // deleted later) as soon as the permchan mode is removed from them.
159 if (ServerInstance->FindChan(channel) == NULL)
161 chan = new Channel(channel, TS);
167 // Apply their channel modes if we have to
168 Modes::ChangeList modechangelist;
169 if (apply_other_sides_modes)
171 ServerInstance->Modes.ModeParamsToChangeList(srcuser, MODETYPE_CHANNEL, params, modechangelist, 2, params.size() - 1);
172 ServerInstance->Modes->Process(srcuser, chan, NULL, modechangelist, ModeParser::MODE_LOCALONLY | ModeParser::MODE_MERGE);
173 // Reuse for prefix modes
174 modechangelist.clear();
177 // Build a new FJOIN for forwarding. Put the correct TS in it and the current modes of the channel
178 // after applying theirs. If they lost, the prefix modes from their message are not forwarded.
179 FwdFJoinBuilder fwdfjoin(chan, sourceserver);
181 // Process every member in the message
182 irc::tokenstream users(params.back());
184 Modes::ChangeList* modechangelistptr = (apply_other_sides_modes ? &modechangelist : NULL);
185 while (users.GetToken(item))
187 ProcessModeUUIDPair(item, sourceserver, chan, modechangelistptr, fwdfjoin);
191 fwdfjoin.Forward(sourceserver->GetRoute());
193 // Set prefix modes on their users if we lost the FJOIN or had equal TS
194 if (apply_other_sides_modes)
195 ServerInstance->Modes->Process(srcuser, chan, NULL, modechangelist, ModeParser::MODE_LOCALONLY);
200 void CommandFJoin::ProcessModeUUIDPair(const std::string& item, TreeServer* sourceserver, Channel* chan, Modes::ChangeList* modechangelist, FwdFJoinBuilder& fwdfjoin)
202 std::string::size_type comma = item.find(',');
204 // Comma not required anymore if the user has no modes
205 const std::string::size_type ubegin = (comma == std::string::npos ? 0 : comma+1);
206 std::string uuid(item, ubegin, UIDGenerator::UUID_LENGTH);
207 User* who = ServerInstance->FindUUID(uuid);
210 // Probably KILLed, ignore
214 TreeSocket* src_socket = sourceserver->GetSocket();
215 /* Check that the user's 'direction' is correct */
216 TreeServer* route_back_again = TreeServer::Get(who);
217 if (route_back_again->GetSocket() != src_socket)
222 std::string::const_iterator modeendit = item.begin(); // End of the "ov" mode string
223 /* Check if the user received at least one mode */
224 if ((modechangelist) && (comma != std::string::npos))
227 /* Iterate through the modes and see if they are valid here, if so, apply */
228 for (std::string::const_iterator i = item.begin(); i != modeendit; ++i)
230 ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL);
232 throw ProtocolException("Unrecognised mode '" + std::string(1, *i) + "'");
234 /* Add any modes this user had to the mode stack */
235 modechangelist->push_add(mh, who->nick);
239 Membership* memb = chan->ForceJoin(who, NULL, sourceserver->IsBursting());
242 // User was already on the channel, forward because of the modes they potentially got
243 memb = chan->GetUser(who);
245 fwdfjoin.add(memb, item.begin(), modeendit);
249 // Assign the id to the new Membership
250 Membership::Id membid = 0;
251 const std::string::size_type colon = item.rfind(':');
252 if (colon != std::string::npos)
253 membid = Membership::IdFromString(item.substr(colon+1));
256 // Add member to fwdfjoin with prefix modes
257 fwdfjoin.add(memb, item.begin(), modeendit);
260 void CommandFJoin::RemoveStatus(Channel* c)
262 Modes::ChangeList changelist;
264 const ModeParser::ModeHandlerMap& mhs = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL);
265 for (ModeParser::ModeHandlerMap::const_iterator i = mhs.begin(); i != mhs.end(); ++i)
267 ModeHandler* mh = i->second;
269 // Add the removal of this mode to the changelist. This handles all kinds of modes, including prefix modes.
270 mh->RemoveMode(c, changelist);
273 ServerInstance->Modes->Process(ServerInstance->FakeClient, c, NULL, changelist, ModeParser::MODE_LOCALONLY);
276 void CommandFJoin::LowerTS(Channel* chan, time_t TS, const std::string& newname)
278 if (Utils->AnnounceTSChange)
279 chan->WriteNotice(InspIRCd::Format("TS for %s changed from %lu to %lu", newname.c_str(), (unsigned long) chan->age, (unsigned long) TS));
281 // While the name is equal in case-insensitive compare, it might differ in case; use the remote version
282 chan->name = newname;
286 CommandFJoin::RemoveStatus(chan);
288 // Unset all extensions
289 chan->FreeAllExtItems();
292 chan->SetTopic(ServerInstance->FakeClient, std::string(), 0);
296 CommandFJoin::Builder::Builder(Channel* chan, TreeServer* source)
297 : CmdBuilder(source->GetID(), "FJOIN")
299 push(chan->name).push_int(chan->age).push_raw(" +");
301 push_raw(chan->ChanModes(true)).push_raw(" :");
304 void CommandFJoin::Builder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
306 push_raw(mbegin, mend).push_raw(',').push_raw(memb->user->uuid);
307 push_raw(':').push_raw_int(memb->id);
311 bool CommandFJoin::Builder::has_room(std::string::size_type nummodes) const
313 return ((str().size() + nummodes + UIDGenerator::UUID_LENGTH + 2 + membid_max_digits + 1) <= maxline);
316 void CommandFJoin::Builder::clear()
322 const std::string& CommandFJoin::Builder::finalize()
324 if (*content.rbegin() == ' ')
325 content.erase(content.size()-1);
329 void FwdFJoinBuilder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
331 // Pseudoserver compatibility:
332 // Some pseudoservers do not handle lines longer than 512 so we split long FJOINs into multiple messages.
333 // The forwarded FJOIN can end up being longer than the original one if we have more modes set and won, for example.
335 // Check if the member fits into the current message. If not, send it and prepare a new one.
336 if (!has_room(std::distance(mbegin, mend)))
339 Forward(sourceserver);
342 // Add the member and their modes exactly as they sent them
343 CommandFJoin::Builder::add(memb, mbegin, mend);