1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2015, 2018-2020 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:
FwdFJoinBuilder(Channel * chan,TreeServer * server)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. */
Handle(User * srcuser,Params & params)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 privileges
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 encounters 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 
ProcessModeUUIDPair(const std::string & item,TreeServer * sourceserver,Channel * chan,Modes::ChangeList * modechangelist,FwdFJoinBuilder & fwdfjoin)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 
RemoveStatus(Channel * c)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 
LowerTS(Channel * chan,time_t TS,const std::string & newname)278 void CommandFJoin::LowerTS(Channel* chan, time_t TS, const std::string& newname)
279 {
280 	if (Utils->AnnounceTSChange)
281 	{
282 		// WriteRemoteNotice is not used here because the message only needs to go to the local server.
283 		chan->WriteNotice(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 	}
286 
287 	// While the name is equal in case-insensitive compare, it might differ in case; use the remote version
288 	chan->name = newname;
289 	chan->age = TS;
290 
291 	// Clear all modes
292 	CommandFJoin::RemoveStatus(chan);
293 
294 	// Unset all extensions
295 	chan->FreeAllExtItems();
296 
297 	// Clear the topic
298 	chan->SetTopic(ServerInstance->FakeClient, std::string(), 0);
299 	chan->setby.clear();
300 }
301 
Builder(Channel * chan,TreeServer * source)302 CommandFJoin::Builder::Builder(Channel* chan, TreeServer* source)
303 	: CmdBuilder(source, "FJOIN")
304 {
305 	push(chan->name).push_int(chan->age).push_raw(" +");
306 	pos = str().size();
307 	push_raw(chan->ChanModes(true)).push_raw(" :");
308 }
309 
add(Membership * memb,std::string::const_iterator mbegin,std::string::const_iterator mend)310 void CommandFJoin::Builder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
311 {
312 	push_raw(mbegin, mend).push_raw(',').push_raw(memb->user->uuid);
313 	push_raw(':').push_raw_int(memb->id);
314 	push_raw(' ');
315 }
316 
has_room(std::string::size_type nummodes) const317 bool CommandFJoin::Builder::has_room(std::string::size_type nummodes) const
318 {
319 	return ((str().size() + nummodes + UIDGenerator::UUID_LENGTH + 2 + membid_max_digits + 1) <= maxline);
320 }
321 
clear()322 void CommandFJoin::Builder::clear()
323 {
324 	content.erase(pos);
325 	push_raw(" :");
326 }
327 
finalize()328 const std::string& CommandFJoin::Builder::finalize()
329 {
330 	if (*content.rbegin() == ' ')
331 		content.erase(content.size()-1);
332 	return str();
333 }
334 
add(Membership * memb,std::string::const_iterator mbegin,std::string::const_iterator mend)335 void FwdFJoinBuilder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend)
336 {
337 	// Pseudoserver compatibility:
338 	// Some pseudoservers do not handle lines longer than 512 so we split long FJOINs into multiple messages.
339 	// The forwarded FJOIN can end up being longer than the original one if we have more modes set and won, for example.
340 
341 	// Check if the member fits into the current message. If not, send it and prepare a new one.
342 	if (!has_room(std::distance(mbegin, mend)))
343 	{
344 		finalize();
345 		Forward(sourceserver);
346 		clear();
347 	}
348 	// Add the member and their modes exactly as they sent them
349 	CommandFJoin::Builder::add(memb, mbegin, mend);
350 }
351