]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/fjoin.cpp
Rewrite invite system
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / fjoin.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
8  *
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.
12  *
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
16  * details.
17  *
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/>.
20  */
21
22
23 #include "inspircd.h"
24 #include "commands.h"
25 #include "treeserver.h"
26 #include "treesocket.h"
27
28 /** FJOIN builder for rebuilding incoming FJOINs and splitting them up into multiple messages if necessary
29  */
30 class FwdFJoinBuilder : public CommandFJoin::Builder
31 {
32         TreeServer* const sourceserver;
33
34  public:
35         FwdFJoinBuilder(Channel* chan, TreeServer* server)
36                 : CommandFJoin::Builder(chan, server)
37                 , sourceserver(server)
38         {
39         }
40
41         void add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend);
42 };
43
44 /** FJOIN, almost identical to TS6 SJOIN, except for nicklist handling. */
45 CmdResult CommandFJoin::Handle(User* srcuser, std::vector<std::string>& params)
46 {
47         /* 1.1+ FJOIN works as follows:
48          *
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.
54          *
55          * When two sides of a split heal and this occurs, the following things
56          * will happen:
57          *
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.
61          *
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
67          * the losing side.
68          *
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. :-)
72          *
73          * Syntax:
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
77          * following format:
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.
83          *
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.
87          *
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.
90          *
91          * Forwarding:
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.
102          *
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.
108          *
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.
114          *
115          */
116
117         time_t TS = ServerCommand::ExtractTS(params[1]);
118
119         const std::string& channel = params[0];
120         Channel* chan = ServerInstance->FindChan(channel);
121         bool apply_other_sides_modes = true;
122
123         if (!chan)
124         {
125                 chan = new Channel(channel, TS);
126         }
127         else
128         {
129                 time_t ourTS = chan->age;
130                 if (TS != ourTS)
131                 {
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 */
135                         if (ourTS < TS)
136                         {
137                                 apply_other_sides_modes = false;
138                         }
139                         else if (ourTS > TS)
140                         {
141                                 // Our TS is greater than theirs, remove all modes, extensions, etc. from the channel
142                                 LowerTS(chan, TS, channel);
143
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)
148                                 {
149                                         chan = new Channel(channel, TS);
150                                 }
151                         }
152                 }
153         }
154
155         // Apply their channel modes if we have to
156         Modes::ChangeList modechangelist;
157         if (apply_other_sides_modes)
158         {
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();
163         }
164
165         TreeServer* const sourceserver = TreeServer::Get(srcuser);
166
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);
170
171         // Process every member in the message
172         irc::tokenstream users(params.back());
173         std::string item;
174         Modes::ChangeList* modechangelistptr = (apply_other_sides_modes ? &modechangelist : NULL);
175         while (users.GetToken(item))
176         {
177                 ProcessModeUUIDPair(item, sourceserver, chan, modechangelistptr, fwdfjoin);
178         }
179
180         fwdfjoin.finalize();
181         fwdfjoin.Forward(sourceserver);
182
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);
186
187         return CMD_SUCCESS;
188 }
189
190 void CommandFJoin::ProcessModeUUIDPair(const std::string& item, TreeServer* sourceserver, Channel* chan, Modes::ChangeList* modechangelist, FwdFJoinBuilder& fwdfjoin)
191 {
192         std::string::size_type comma = item.find(',');
193
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);
198         if (!who)
199         {
200                 // Probably KILLed, ignore
201                 return;
202         }
203
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)
208         {
209                 return;
210         }
211
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))
215         {
216                 modeendit += comma;
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)
219                 {
220                         ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL);
221                         if (!mh)
222                                 throw ProtocolException("Unrecognised mode '" + std::string(1, *i) + "'");
223
224                         /* Add any modes this user had to the mode stack */
225                         modechangelist->push_add(mh, who->nick);
226                 }
227         }
228
229         Membership* memb = chan->ForceJoin(who, NULL, sourceserver->IsBursting());
230         if (!memb)
231         {
232                 // User was already on the channel, forward because of the modes they potentially got
233                 memb = chan->GetUser(who);
234                 if (memb)
235                         fwdfjoin.add(memb, item.begin(), modeendit);
236                 return;
237         }
238
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));
244         memb->id = membid;
245
246         // Add member to fwdfjoin with prefix modes
247         fwdfjoin.add(memb, item.begin(), modeendit);
248 }
249
250 void CommandFJoin::RemoveStatus(Channel* c)
251 {
252         Modes::ChangeList changelist;
253
254         const ModeParser::ModeHandlerMap& mhs = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL);
255         for (ModeParser::ModeHandlerMap::const_iterator i = mhs.begin(); i != mhs.end(); ++i)
256         {
257                 ModeHandler* mh = i->second;
258
259                 // Add the removal of this mode to the changelist. This handles all kinds of modes, including prefix modes.
260                 mh->RemoveMode(c, changelist);
261         }
262
263         ServerInstance->Modes->Process(ServerInstance->FakeClient, c, NULL, changelist, ModeParser::MODE_LOCALONLY);
264 }
265
266 void CommandFJoin::LowerTS(Channel* chan, time_t TS, const std::string& newname)
267 {
268         if (Utils->AnnounceTSChange)
269                 chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE %s :TS for %s changed from %lu to %lu", chan->name.c_str(), newname.c_str(), (unsigned long) chan->age, (unsigned long) TS);
270
271         // While the name is equal in case-insensitive compare, it might differ in case; use the remote version
272         chan->name = newname;
273         chan->age = TS;
274
275         // Clear all modes
276         CommandFJoin::RemoveStatus(chan);
277
278         // Unset all extensions
279         chan->FreeAllExtItems();
280
281         // Clear the topic, if it isn't empty then send a topic change message to local users
282         if (!chan->topic.empty())
283         {
284                 chan->topic.clear();
285                 chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "TOPIC %s :", chan->name.c_str());
286         }
287         chan->setby.clear();
288         chan->topicset = 0;
289 }
290
291 CommandFJoin::Builder::Builder(Channel* chan, TreeServer* source)
292         : CmdBuilder(source->GetID(), "FJOIN")
293 {
294         push(chan->name).push_int(chan->age).push_raw(" +");
295         pos = str().size();
296         push_raw(chan->ChanModes(true)).push_raw(" :");
297 }
298
299 void CommandFJoin::Builder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
300 {
301         push_raw(mbegin, mend).push_raw(',').push_raw(memb->user->uuid);
302         push_raw(':').push_raw_int(memb->id);
303         push_raw(' ');
304 }
305
306 bool CommandFJoin::Builder::has_room(std::string::size_type nummodes) const
307 {
308         return ((str().size() + nummodes + UIDGenerator::UUID_LENGTH + 2 + membid_max_digits + 1) <= maxline);
309 }
310
311 void CommandFJoin::Builder::clear()
312 {
313         content.erase(pos);
314         push_raw(" :");
315 }
316
317 const std::string& CommandFJoin::Builder::finalize()
318 {
319         if (*content.rbegin() == ' ')
320                 content.erase(content.size()-1);
321         return str();
322 }
323
324 void FwdFJoinBuilder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
325 {
326         // Pseudoserver compatibility:
327         // Some pseudoservers do not handle lines longer than 512 so we split long FJOINs into multiple messages.
328         // The forwarded FJOIN can end up being longer than the original one if we have more modes set and won, for example.
329
330         // Check if the member fits into the current message. If not, send it and prepare a new one.
331         if (!has_room(std::distance(mbegin, mend)))
332         {
333                 finalize();
334                 Forward(sourceserver);
335                 clear();
336         }
337         // Add the member and their modes exactly as they sent them
338         CommandFJoin::Builder::add(memb, mbegin, mend);
339 }