]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/fjoin.cpp
Update copyright headers.
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / fjoin.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2015, 2018-2019 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>
10  *
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.
14  *
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
18  * details.
19  *
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/>.
22  */
23
24
25 #include "inspircd.h"
26 #include "commands.h"
27 #include "treeserver.h"
28 #include "treesocket.h"
29
30 /** FJOIN builder for rebuilding incoming FJOINs and splitting them up into multiple messages if necessary
31  */
32 class FwdFJoinBuilder : public CommandFJoin::Builder
33 {
34         TreeServer* const sourceserver;
35
36  public:
37         FwdFJoinBuilder(Channel* chan, TreeServer* server)
38                 : CommandFJoin::Builder(chan, server)
39                 , sourceserver(server)
40         {
41         }
42
43         void add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend);
44 };
45
46 /** FJOIN, almost identical to TS6 SJOIN, except for nicklist handling. */
47 CmdResult CommandFJoin::Handle(User* srcuser, Params& params)
48 {
49         /* 1.1+ FJOIN works as follows:
50          *
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.
56          *
57          * When two sides of a split heal and this occurs, the following things
58          * will happen:
59          *
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.
63          *
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
69          * the losing side.
70          *
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. :-)
74          *
75          * Outside of netbursts, the winning side also resyncs the losing side if it
76          * detects that the other side recreated the channel.
77          *
78          * Syntax:
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
82          * following format:
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.
88          *
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.
92          *
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.
95          *
96          * Forwarding:
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.
107          *
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.
113          *
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.
119          *
120          */
121
122         time_t TS = ServerCommand::ExtractTS(params[1]);
123
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);
128
129         if (!chan)
130         {
131                 chan = new Channel(channel, TS);
132         }
133         else
134         {
135                 time_t ourTS = chan->age;
136                 if (TS != ourTS)
137                 {
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 */
141                         if (ourTS < TS)
142                         {
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())
147                                 {
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);
150                                 }
151                                 apply_other_sides_modes = false;
152                         }
153                         else if (ourTS > TS)
154                         {
155                                 // Our TS is greater than theirs, remove all modes, extensions, etc. from the channel
156                                 LowerTS(chan, TS, channel);
157
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)
162                                 {
163                                         chan = new Channel(channel, TS);
164                                 }
165                         }
166                 }
167         }
168
169         // Apply their channel modes if we have to
170         Modes::ChangeList modechangelist;
171         if (apply_other_sides_modes)
172         {
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();
177         }
178
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);
182
183         // Process every member in the message
184         irc::spacesepstream users(params.back());
185         std::string item;
186         Modes::ChangeList* modechangelistptr = (apply_other_sides_modes ? &modechangelist : NULL);
187         while (users.GetToken(item))
188         {
189                 ProcessModeUUIDPair(item, sourceserver, chan, modechangelistptr, fwdfjoin);
190         }
191
192         fwdfjoin.finalize();
193         fwdfjoin.Forward(sourceserver->GetRoute());
194
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);
198
199         return CMD_SUCCESS;
200 }
201
202 void CommandFJoin::ProcessModeUUIDPair(const std::string& item, TreeServer* sourceserver, Channel* chan, Modes::ChangeList* modechangelist, FwdFJoinBuilder& fwdfjoin)
203 {
204         std::string::size_type comma = item.find(',');
205
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);
210         if (!who)
211         {
212                 // Probably KILLed, ignore
213                 return;
214         }
215
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)
220         {
221                 return;
222         }
223
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))
227         {
228                 modeendit += comma;
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)
231                 {
232                         ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL);
233                         if (!mh)
234                                 throw ProtocolException("Unrecognised mode '" + std::string(1, *i) + "'");
235
236                         /* Add any modes this user had to the mode stack */
237                         modechangelist->push_add(mh, who->nick);
238                 }
239         }
240
241         Membership* memb = chan->ForceJoin(who, NULL, sourceserver->IsBursting());
242         if (!memb)
243         {
244                 // User was already on the channel, forward because of the modes they potentially got
245                 memb = chan->GetUser(who);
246                 if (memb)
247                         fwdfjoin.add(memb, item.begin(), modeendit);
248                 return;
249         }
250
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));
256         memb->id = membid;
257
258         // Add member to fwdfjoin with prefix modes
259         fwdfjoin.add(memb, item.begin(), modeendit);
260 }
261
262 void CommandFJoin::RemoveStatus(Channel* c)
263 {
264         Modes::ChangeList changelist;
265
266         const ModeParser::ModeHandlerMap& mhs = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL);
267         for (ModeParser::ModeHandlerMap::const_iterator i = mhs.begin(); i != mhs.end(); ++i)
268         {
269                 ModeHandler* mh = i->second;
270
271                 // Add the removal of this mode to the changelist. This handles all kinds of modes, including prefix modes.
272                 mh->RemoveMode(c, changelist);
273         }
274
275         ServerInstance->Modes->Process(ServerInstance->FakeClient, c, NULL, changelist, ModeParser::MODE_LOCALONLY);
276 }
277
278 void CommandFJoin::LowerTS(Channel* chan, time_t TS, const std::string& newname)
279 {
280         if (Utils->AnnounceTSChange)
281         {
282                 // WriteNotice is not used here because the message only needs to go to the local server.
283                 const std::string tsmessage  = 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());
285                 ClientProtocol::Messages::Privmsg privmsg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, chan, tsmessage, MSG_NOTICE);
286                 chan->Write(ServerInstance->GetRFCEvents().privmsg, privmsg);
287         }
288
289         // While the name is equal in case-insensitive compare, it might differ in case; use the remote version
290         chan->name = newname;
291         chan->age = TS;
292
293         // Clear all modes
294         CommandFJoin::RemoveStatus(chan);
295
296         // Unset all extensions
297         chan->FreeAllExtItems();
298
299         // Clear the topic
300         chan->SetTopic(ServerInstance->FakeClient, std::string(), 0);
301         chan->setby.clear();
302 }
303
304 CommandFJoin::Builder::Builder(Channel* chan, TreeServer* source)
305         : CmdBuilder(source, "FJOIN")
306 {
307         push(chan->name).push_int(chan->age).push_raw(" +");
308         pos = str().size();
309         push_raw(chan->ChanModes(true)).push_raw(" :");
310 }
311
312 void CommandFJoin::Builder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
313 {
314         push_raw(mbegin, mend).push_raw(',').push_raw(memb->user->uuid);
315         push_raw(':').push_raw_int(memb->id);
316         push_raw(' ');
317 }
318
319 bool CommandFJoin::Builder::has_room(std::string::size_type nummodes) const
320 {
321         return ((str().size() + nummodes + UIDGenerator::UUID_LENGTH + 2 + membid_max_digits + 1) <= maxline);
322 }
323
324 void CommandFJoin::Builder::clear()
325 {
326         content.erase(pos);
327         push_raw(" :");
328 }
329
330 const std::string& CommandFJoin::Builder::finalize()
331 {
332         if (*content.rbegin() == ' ')
333                 content.erase(content.size()-1);
334         return str();
335 }
336
337 void FwdFJoinBuilder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
338 {
339         // Pseudoserver compatibility:
340         // Some pseudoservers do not handle lines longer than 512 so we split long FJOINs into multiple messages.
341         // The forwarded FJOIN can end up being longer than the original one if we have more modes set and won, for example.
342
343         // Check if the member fits into the current message. If not, send it and prepare a new one.
344         if (!has_room(std::distance(mbegin, mend)))
345         {
346                 finalize();
347                 Forward(sourceserver);
348                 clear();
349         }
350         // Add the member and their modes exactly as they sent them
351         CommandFJoin::Builder::add(memb, mbegin, mend);
352 }