]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/fjoin.cpp
m_spanningtree Replace manual string building of outgoing commands with CmdBuilder...
[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, almost identical to TS6 SJOIN, except for nicklist handling. */
29 CmdResult CommandFJoin::Handle(User* srcuser, std::vector<std::string>& params)
30 {
31         /* 1.1+ FJOIN works as follows:
32          *
33          * Each FJOIN is sent along with a timestamp, and the side with the lowest
34          * timestamp 'wins'. From this point on we will refer to this side as the
35          * winner. The side with the higher timestamp loses, from this point on we
36          * will call this side the loser or losing side. This should be familiar to
37          * anyone who's dealt with dreamforge or TS6 before.
38          *
39          * When two sides of a split heal and this occurs, the following things
40          * will happen:
41          *
42          * If the timestamps are exactly equal, both sides merge their privilages
43          * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
44          * re-created during a split, this is safe to do.
45          *
46          * If the timestamps are NOT equal, the losing side removes all of its
47          * modes from the channel, before introducing new users into the channel
48          * which are listed in the FJOIN command's parameters. The losing side then
49          * LOWERS its timestamp value of the channel to match that of the winning
50          * side, and the modes of the users of the winning side are merged in with
51          * the losing side.
52          *
53          * The winning side on the other hand will ignore all user modes from the
54          * losing side, so only its own modes get applied. Life is simple for those
55          * who succeed at internets. :-)
56          *
57          * Syntax:
58          * :<sid> FJOIN <chan> <TS> <modes> :[<member> [<member> ...]]
59          * The last parameter is a list consisting of zero or more channel members
60          * (permanent channels may have zero users). Each entry on the list is in the
61          * following format:
62          * [[<modes>,]<uuid>[:<membid>]
63          * <modes> is a concatenation of the mode letters the user has on the channel
64          * (e.g.: "ov" if the user is opped and voiced). The order of the mode letters
65          * are not important but if a server ecounters an unknown mode letter, it will
66          * drop the link to avoid desync.
67          *
68          * InspIRCd 2.0 and older required a comma before the uuid even if the user
69          * had no prefix modes on the channel, InspIRCd 2.2 and later does not require
70          * a comma in this case anymore.
71          *
72          * <membid> is a positive integer representing the id of the membership.
73          * If not present (in FJOINs coming from pre-1205 servers), 0 is assumed.
74          *
75          */
76
77         time_t TS = ServerCommand::ExtractTS(params[1]);
78
79         const std::string& channel = params[0];
80         Channel* chan = ServerInstance->FindChan(channel);
81         bool apply_other_sides_modes = true;
82
83         if (!chan)
84         {
85                 chan = new Channel(channel, TS);
86         }
87         else
88         {
89                 time_t ourTS = chan->age;
90                 if (TS != ourTS)
91                 {
92                         ServerInstance->SNO->WriteToSnoMask('d', "Merge FJOIN received for %s, ourTS: %lu, TS: %lu, difference: %lu",
93                                 chan->name.c_str(), (unsigned long)ourTS, (unsigned long)TS, (unsigned long)(ourTS - TS));
94                         /* If our TS is less than theirs, we dont accept their modes */
95                         if (ourTS < TS)
96                         {
97                                 apply_other_sides_modes = false;
98                         }
99                         else if (ourTS > TS)
100                         {
101                                 // Our TS is greater than theirs, remove all modes, extensions, etc. from the channel
102                                 LowerTS(chan, TS, channel);
103
104                                 // 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.
105                                 // This happens to 0-user permanent channels on the losing side, because those are removed (from the chan hash, then
106                                 // deleted later) as soon as the permchan mode is removed from them.
107                                 if (ServerInstance->FindChan(channel) == NULL)
108                                 {
109                                         chan = new Channel(channel, TS);
110                                 }
111                         }
112                 }
113         }
114
115         /* First up, apply their channel modes if they won the TS war */
116         if (apply_other_sides_modes)
117         {
118                 // Need to use a modestacker here due to maxmodes
119                 irc::modestacker stack(true);
120                 std::vector<std::string>::const_iterator paramit = params.begin() + 3;
121                 const std::vector<std::string>::const_iterator lastparamit = ((params.size() > 3) ? (params.end() - 1) : params.end());
122                 for (std::string::const_iterator i = params[2].begin(); i != params[2].end(); ++i)
123                 {
124                         ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL);
125                         if (!mh)
126                                 continue;
127
128                         std::string modeparam;
129                         if ((paramit != lastparamit) && (mh->GetNumParams(true)))
130                         {
131                                 modeparam = *paramit;
132                                 ++paramit;
133                         }
134
135                         stack.Push(*i, modeparam);
136                 }
137
138                 std::vector<std::string> modelist;
139
140                 // Mode parser needs to know what channel to act on.
141                 modelist.push_back(params[0]);
142
143                 while (stack.GetStackedLine(modelist))
144                 {
145                         ServerInstance->Modes->Process(modelist, srcuser, ModeParser::MODE_LOCALONLY | ModeParser::MODE_MERGE);
146                         modelist.erase(modelist.begin() + 1, modelist.end());
147                 }
148         }
149
150         irc::modestacker modestack(true);
151         TreeSocket* src_socket = TreeServer::Get(srcuser)->GetSocket();
152
153         /* Now, process every 'modes,uuid' pair */
154         irc::tokenstream users(params.back());
155         std::string item;
156         irc::modestacker* modestackptr = (apply_other_sides_modes ? &modestack : NULL);
157         while (users.GetToken(item))
158         {
159                 ProcessModeUUIDPair(item, src_socket, chan, modestackptr);
160         }
161
162         /* Flush mode stacker if we lost the FJOIN or had equal TS */
163         if (apply_other_sides_modes)
164                 CommandFJoin::ApplyModeStack(srcuser, chan, modestack);
165
166         return CMD_SUCCESS;
167 }
168
169 void CommandFJoin::ProcessModeUUIDPair(const std::string& item, TreeSocket* src_socket, Channel* chan, irc::modestacker* modestack)
170 {
171         std::string::size_type comma = item.find(',');
172
173         // Comma not required anymore if the user has no modes
174         const std::string::size_type ubegin = (comma == std::string::npos ? 0 : comma+1);
175         std::string uuid(item, ubegin, UIDGenerator::UUID_LENGTH);
176         User* who = ServerInstance->FindUUID(uuid);
177         if (!who)
178         {
179                 // Probably KILLed, ignore
180                 return;
181         }
182
183         /* Check that the user's 'direction' is correct */
184         TreeServer* route_back_again = TreeServer::Get(who);
185         if (route_back_again->GetSocket() != src_socket)
186         {
187                 return;
188         }
189
190         /* Check if the user received at least one mode */
191         if ((modestack) && (comma > 0) && (comma != std::string::npos))
192         {
193                 /* Iterate through the modes and see if they are valid here, if so, apply */
194                 std::string::const_iterator commait = item.begin()+comma;
195                 for (std::string::const_iterator i = item.begin(); i != commait; ++i)
196                 {
197                         if (!ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL))
198                                 throw ProtocolException("Unrecognised mode '" + std::string(1, *i) + "'");
199
200                         /* Add any modes this user had to the mode stack */
201                         modestack->Push(*i, who->nick);
202                 }
203         }
204
205         Membership* memb = chan->ForceJoin(who, NULL, route_back_again->bursting);
206         if (!memb)
207                 return;
208
209         // Assign the id to the new Membership
210         Membership::Id membid = 0;
211         const std::string::size_type colon = item.rfind(':');
212         if (colon != std::string::npos)
213                 membid = Membership::IdFromString(item.substr(colon+1));
214         memb->id = membid;
215 }
216
217 void CommandFJoin::RemoveStatus(Channel* c)
218 {
219         irc::modestacker stack(false);
220
221         const ModeParser::ModeHandlerMap& mhs = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL);
222         for (ModeParser::ModeHandlerMap::const_iterator i = mhs.begin(); i != mhs.end(); ++i)
223         {
224                 ModeHandler* mh = i->second;
225
226                 /* Passing a pointer to a modestacker here causes the mode to be put onto the mode stack,
227                  * rather than applied immediately. Module unloads require this to be done immediately,
228                  * for this function we require tidyness instead. Fixes bug #493
229                  */
230                 mh->RemoveMode(c, stack);
231         }
232
233         ApplyModeStack(ServerInstance->FakeClient, c, stack);
234 }
235
236 void CommandFJoin::ApplyModeStack(User* srcuser, Channel* c, irc::modestacker& stack)
237 {
238         parameterlist stackresult;
239         stackresult.push_back(c->name);
240
241         while (stack.GetStackedLine(stackresult))
242         {
243                 ServerInstance->Modes->Process(stackresult, srcuser, ModeParser::MODE_LOCALONLY);
244                 stackresult.erase(stackresult.begin() + 1, stackresult.end());
245         }
246 }
247
248 void CommandFJoin::LowerTS(Channel* chan, time_t TS, const std::string& newname)
249 {
250         if (Utils->AnnounceTSChange)
251                 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);
252
253         // While the name is equal in case-insensitive compare, it might differ in case; use the remote version
254         chan->name = newname;
255         chan->age = TS;
256
257         // Remove all pending invites
258         chan->ClearInvites();
259
260         // Clear all modes
261         CommandFJoin::RemoveStatus(chan);
262
263         // Unset all extensions
264         chan->FreeAllExtItems();
265
266         // Clear the topic, if it isn't empty then send a topic change message to local users
267         if (!chan->topic.empty())
268         {
269                 chan->topic.clear();
270                 chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "TOPIC %s :", chan->name.c_str());
271         }
272         chan->setby.clear();
273         chan->topicset = 0;
274 }
275
276 CommandFJoin::Builder::Builder(Channel* chan)
277         : CmdBuilder("FJOIN")
278 {
279         push(chan->name).push_int(chan->age).push_raw(" +");
280         pos = str().size();
281         push_raw(chan->ChanModes(true)).push_raw(" :");
282 }
283
284 void CommandFJoin::Builder::add(Membership* memb)
285 {
286         push_raw(memb->modes).push_raw(',').push_raw(memb->user->uuid);
287         push_raw(':').push_raw_int(memb->id);
288         push_raw(' ');
289 }
290
291 bool CommandFJoin::Builder::has_room(Membership* memb) const
292 {
293         return ((str().size() + memb->modes.size() + UIDGenerator::UUID_LENGTH + 2 + membid_max_digits + 1) <= maxline);
294 }
295
296 void CommandFJoin::Builder::clear()
297 {
298         content.erase(pos);
299         push_raw(" :");
300 }
301
302 const std::string& CommandFJoin::Builder::finalize()
303 {
304         if (*content.rbegin() == ' ')
305                 content.erase(content.size()-1);
306         return str();
307 }