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. :-)
74 * :<sid> FJOIN <chan> <TS> <modes> :[<member> [<member> ...]]
75 * The last parameter is a list consisting of zero or more channel members
76 * (permanent channels may have zero users). Each entry on the list is in the
78 * [[<modes>,]<uuid>[:<membid>]
79 * <modes> is a concatenation of the mode letters the user has on the channel
80 * (e.g.: "ov" if the user is opped and voiced). The order of the mode letters
81 * are not important but if a server ecounters an unknown mode letter, it will
82 * drop the link to avoid desync.
84 * InspIRCd 2.0 and older required a comma before the uuid even if the user
85 * had no prefix modes on the channel, InspIRCd 2.2 and later does not require
86 * a comma in this case anymore.
88 * <membid> is a positive integer representing the id of the membership.
89 * If not present (in FJOINs coming from pre-1205 servers), 0 is assumed.
92 * FJOIN messages are forwarded with the new TS and modes. Prefix modes of
93 * members on the losing side are not forwarded.
94 * This is required to only have one server on each side of the network who
95 * decides the fate of a channel during a network merge. Otherwise, if the
96 * clock of a server is slightly off it may make a different decision than
97 * the rest of the network and desync.
98 * The prefix modes are always forwarded as-is, or not at all.
99 * One incoming FJOIN may result in more than one FJOIN being generated
100 * and forwarded mainly due to compatibility reasons with non-InspIRCd
101 * servers that don't handle more than 512 char long lines.
103 * Forwarding examples:
104 * Existing channel #chan with TS 1000, modes +n.
105 * Incoming: :220 FJOIN #chan 1000 +t :o,220AAAAAB:0
106 * Forwarded: :220 FJOIN #chan 1000 +nt :o,220AAAAAB:0
107 * Merge modes and forward the result. Forward their prefix modes as well.
109 * Existing channel #chan with TS 1000, modes +nt.
110 * Incoming: :220 FJOIN #CHAN 2000 +i :ov,220AAAAAB:0 o,220AAAAAC:20
111 * Forwarded: :220 FJOIN #chan 1000 +nt :,220AAAAAB:0 ,220AAAAAC:20
112 * Drop their modes, forward our modes and TS, use our channel name
113 * capitalization. Don't forward prefix modes.
117 time_t TS = ServerCommand::ExtractTS(params[1]);
119 const std::string& channel = params[0];
120 Channel* chan = ServerInstance->FindChan(channel);
121 bool apply_other_sides_modes = true;
125 chan = new Channel(channel, TS);
129 time_t ourTS = chan->age;
132 ServerInstance->SNO->WriteToSnoMask('d', "Merge FJOIN received for %s, ourTS: %lu, TS: %lu, difference: %ld",
133 chan->name.c_str(), (unsigned long)ourTS, (unsigned long)TS, (long)(ourTS - TS));
134 /* If our TS is less than theirs, we dont accept their modes */
137 apply_other_sides_modes = false;
141 // Our TS is greater than theirs, remove all modes, extensions, etc. from the channel
142 LowerTS(chan, TS, channel);
144 // 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.
145 // This happens to 0-user permanent channels on the losing side, because those are removed (from the chan hash, then
146 // deleted later) as soon as the permchan mode is removed from them.
147 if (ServerInstance->FindChan(channel) == NULL)
149 chan = new Channel(channel, TS);
155 // Apply their channel modes if we have to
156 Modes::ChangeList modechangelist;
157 if (apply_other_sides_modes)
159 ServerInstance->Modes.ModeParamsToChangeList(srcuser, MODETYPE_CHANNEL, params, modechangelist, 2, params.size() - 1);
160 ServerInstance->Modes->Process(srcuser, chan, NULL, modechangelist, ModeParser::MODE_LOCALONLY | ModeParser::MODE_MERGE);
161 // Reuse for prefix modes
162 modechangelist.clear();
165 TreeServer* const sourceserver = TreeServer::Get(srcuser);
167 // Build a new FJOIN for forwarding. Put the correct TS in it and the current modes of the channel
168 // after applying theirs. If they lost, the prefix modes from their message are not forwarded.
169 FwdFJoinBuilder fwdfjoin(chan, sourceserver);
171 // Process every member in the message
172 irc::tokenstream users(params.back());
174 Modes::ChangeList* modechangelistptr = (apply_other_sides_modes ? &modechangelist : NULL);
175 while (users.GetToken(item))
177 ProcessModeUUIDPair(item, sourceserver, chan, modechangelistptr, fwdfjoin);
181 fwdfjoin.Forward(sourceserver);
183 // Set prefix modes on their users if we lost the FJOIN or had equal TS
184 if (apply_other_sides_modes)
185 ServerInstance->Modes->Process(srcuser, chan, NULL, modechangelist, ModeParser::MODE_LOCALONLY);
190 void CommandFJoin::ProcessModeUUIDPair(const std::string& item, TreeServer* sourceserver, Channel* chan, Modes::ChangeList* modechangelist, FwdFJoinBuilder& fwdfjoin)
192 std::string::size_type comma = item.find(',');
194 // Comma not required anymore if the user has no modes
195 const std::string::size_type ubegin = (comma == std::string::npos ? 0 : comma+1);
196 std::string uuid(item, ubegin, UIDGenerator::UUID_LENGTH);
197 User* who = ServerInstance->FindUUID(uuid);
200 // Probably KILLed, ignore
204 TreeSocket* src_socket = sourceserver->GetSocket();
205 /* Check that the user's 'direction' is correct */
206 TreeServer* route_back_again = TreeServer::Get(who);
207 if (route_back_again->GetSocket() != src_socket)
212 std::string::const_iterator modeendit = item.begin(); // End of the "ov" mode string
213 /* Check if the user received at least one mode */
214 if ((modechangelist) && (comma != std::string::npos))
217 /* Iterate through the modes and see if they are valid here, if so, apply */
218 for (std::string::const_iterator i = item.begin(); i != modeendit; ++i)
220 ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL);
222 throw ProtocolException("Unrecognised mode '" + std::string(1, *i) + "'");
224 /* Add any modes this user had to the mode stack */
225 modechangelist->push_add(mh, who->nick);
229 Membership* memb = chan->ForceJoin(who, NULL, sourceserver->IsBursting());
232 // User was already on the channel, forward because of the modes they potentially got
233 memb = chan->GetUser(who);
235 fwdfjoin.add(memb, item.begin(), modeendit);
239 // Assign the id to the new Membership
240 Membership::Id membid = 0;
241 const std::string::size_type colon = item.rfind(':');
242 if (colon != std::string::npos)
243 membid = Membership::IdFromString(item.substr(colon+1));
246 // Add member to fwdfjoin with prefix modes
247 fwdfjoin.add(memb, item.begin(), modeendit);
250 void CommandFJoin::RemoveStatus(Channel* c)
252 Modes::ChangeList changelist;
254 const ModeParser::ModeHandlerMap& mhs = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL);
255 for (ModeParser::ModeHandlerMap::const_iterator i = mhs.begin(); i != mhs.end(); ++i)
257 ModeHandler* mh = i->second;
259 // Add the removal of this mode to the changelist. This handles all kinds of modes, including prefix modes.
260 mh->RemoveMode(c, changelist);
263 ServerInstance->Modes->Process(ServerInstance->FakeClient, c, NULL, changelist, ModeParser::MODE_LOCALONLY);
266 void CommandFJoin::LowerTS(Channel* chan, time_t TS, const std::string& newname)
268 if (Utils->AnnounceTSChange)
269 chan->WriteNotice(InspIRCd::Format("TS for %s changed from %lu to %lu", newname.c_str(), (unsigned long) chan->age, (unsigned long) TS));
271 // While the name is equal in case-insensitive compare, it might differ in case; use the remote version
272 chan->name = newname;
276 CommandFJoin::RemoveStatus(chan);
278 // Unset all extensions
279 chan->FreeAllExtItems();
282 chan->SetTopic(ServerInstance->FakeClient, std::string(), 0);
286 CommandFJoin::Builder::Builder(Channel* chan, TreeServer* source)
287 : CmdBuilder(source->GetID(), "FJOIN")
289 push(chan->name).push_int(chan->age).push_raw(" +");
291 push_raw(chan->ChanModes(true)).push_raw(" :");
294 void CommandFJoin::Builder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
296 push_raw(mbegin, mend).push_raw(',').push_raw(memb->user->uuid);
297 push_raw(':').push_raw_int(memb->id);
301 bool CommandFJoin::Builder::has_room(std::string::size_type nummodes) const
303 return ((str().size() + nummodes + UIDGenerator::UUID_LENGTH + 2 + membid_max_digits + 1) <= maxline);
306 void CommandFJoin::Builder::clear()
312 const std::string& CommandFJoin::Builder::finalize()
314 if (*content.rbegin() == ' ')
315 content.erase(content.size()-1);
319 void FwdFJoinBuilder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
321 // Pseudoserver compatibility:
322 // Some pseudoservers do not handle lines longer than 512 so we split long FJOINs into multiple messages.
323 // The forwarded FJOIN can end up being longer than the original one if we have more modes set and won, for example.
325 // Check if the member fits into the current message. If not, send it and prepare a new one.
326 if (!has_room(std::distance(mbegin, mend)))
329 Forward(sourceserver);
332 // Add the member and their modes exactly as they sent them
333 CommandFJoin::Builder::add(memb, mbegin, mend);