1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2014 Justin Crawford <Justasic@Gmail.com>
5  *   Copyright (C) 2013-2014, 2017-2021 Sadie Powell <sadie@witchery.services>
6  *   Copyright (C) 2013-2014, 2016 Attila Molnar <attilamolnar@hush.com>
7  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
8  *   Copyright (C) 2012, 2014 Adam <Adam@anope.org>
9  *   Copyright (C) 2010 Craig Edwards <brain@inspircd.org>
10  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
11  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
12  *   Copyright (C) 2008-2009 Robin Burchell <robin+git@viroteck.net>
13  *
14  * This file is part of InspIRCd.  InspIRCd is free software: you can
15  * redistribute it and/or modify it under the terms of the GNU General Public
16  * License as published by the Free Software Foundation, version 2.
17  *
18  * This program is distributed in the hope that it will be useful, but WITHOUT
19  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
20  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25  */
26 
27 
28 #include "inspircd.h"
29 #include "listmode.h"
30 #include <fstream>
31 
32 
33 /** Handles the +P channel mode
34  */
35 class PermChannel : public ModeHandler
36 {
37  public:
PermChannel(Module * Creator)38 	PermChannel(Module* Creator)
39 		: ModeHandler(Creator, "permanent", 'P', PARAM_NONE, MODETYPE_CHANNEL)
40 	{
41 		oper = true;
42 	}
43 
OnModeChange(User * source,User * dest,Channel * channel,std::string & parameter,bool adding)44 	ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string& parameter, bool adding) CXX11_OVERRIDE
45 	{
46 		if (adding == channel->IsModeSet(this))
47 			return MODEACTION_DENY;
48 
49 		channel->SetMode(this, adding);
50 		if (!adding)
51 			channel->CheckDestroy();
52 
53 		return MODEACTION_ALLOW;
54 	}
55 };
56 
57 // Not in a class due to circular dependency hell.
58 static std::string permchannelsconf;
WriteDatabase(PermChannel & permchanmode,Module * mod,bool save_listmodes)59 static bool WriteDatabase(PermChannel& permchanmode, Module* mod, bool save_listmodes)
60 {
61 	/*
62 	 * We need to perform an atomic write so as not to fuck things up.
63 	 * So, let's write to a temporary file, flush it, then rename the file..
64 	 *     -- w00t
65 	 */
66 
67 	// If the user has not specified a configuration file then we don't write one.
68 	if (permchannelsconf.empty())
69 		return true;
70 
71 	std::string permchannelsnewconf = permchannelsconf + ".tmp";
72 	std::ofstream stream(permchannelsnewconf.c_str());
73 	if (!stream.is_open())
74 	{
75 		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot create database \"%s\"! %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno);
76 		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new permchan db \"%s\": %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno);
77 		return false;
78 	}
79 
80 	stream
81 		<< "# This file was automatically generated by the " << INSPIRCD_VERSION << " permchannels module on " << InspIRCd::TimeString(ServerInstance->Time()) << "." << std::endl
82 		<< "# Any changes to this file will be automatically overwritten." << std::endl
83 		<< std::endl
84 		<< "<config format=\"xml\">" << std::endl;
85 
86 	const chan_hash& chans = ServerInstance->GetChans();
87 	for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); ++i)
88 	{
89 		Channel* chan = i->second;
90 		if (!chan->IsModeSet(permchanmode))
91 			continue;
92 
93 		std::string chanmodes = chan->ChanModes(true);
94 		if (save_listmodes)
95 		{
96 			std::string modes;
97 			std::string params;
98 
99 			const ModeParser::ListModeList& listmodes = ServerInstance->Modes->GetListModes();
100 			for (ModeParser::ListModeList::const_iterator j = listmodes.begin(); j != listmodes.end(); ++j)
101 			{
102 				ListModeBase* lm = *j;
103 				ListModeBase::ModeList* list = lm->GetList(chan);
104 				if (!list || list->empty())
105 					continue;
106 
107 				size_t n = 0;
108 				// Append the parameters
109 				for (ListModeBase::ModeList::const_iterator k = list->begin(); k != list->end(); ++k, n++)
110 				{
111 					params += k->mask;
112 					params += ' ';
113 				}
114 
115 				// Append the mode letters (for example "IIII", "gg")
116 				modes.append(n, lm->GetModeChar());
117 			}
118 
119 			if (!params.empty())
120 			{
121 				// Remove the last space
122 				params.erase(params.end()-1);
123 
124 				// If there is at least a space in chanmodes (that is, a non-listmode has a parameter)
125 				// insert the listmode mode letters before the space. Otherwise just append them.
126 				std::string::size_type p = chanmodes.find(' ');
127 				if (p == std::string::npos)
128 					chanmodes += modes;
129 				else
130 					chanmodes.insert(p, modes);
131 
132 				// Append the listmode parameters (the masks themselves)
133 				chanmodes += ' ';
134 				chanmodes += params;
135 			}
136 		}
137 
138 		stream << "<permchannels channel=\"" << ServerConfig::Escape(chan->name)
139 			<< "\" ts=\"" << chan->age
140 			<< "\" topic=\"" << ServerConfig::Escape(chan->topic)
141 			<< "\" topicts=\"" << chan->topicset
142 			<< "\" topicsetby=\"" << ServerConfig::Escape(chan->setby)
143 			<< "\" modes=\"" << ServerConfig::Escape(chanmodes)
144 			<< "\">" << std::endl;
145 	}
146 
147 	if (stream.fail())
148 	{
149 		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot write to new database \"%s\"! %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno);
150 		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new permchan db \"%s\": %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno);
151 		return false;
152 	}
153 	stream.close();
154 
155 #ifdef _WIN32
156 	remove(permchannelsconf.c_str());
157 #endif
158 	// Use rename to move temporary to new db - this is guaranteed not to fuck up, even in case of a crash.
159 	if (rename(permchannelsnewconf.c_str(), permchannelsconf.c_str()) < 0)
160 	{
161 		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot replace old database \"%s\" with new database \"%s\"! %s (%d)", permchannelsconf.c_str(), permchannelsnewconf.c_str(), strerror(errno), errno);
162 		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old permchan db \"%s\" with new db \"%s\": %s (%d)", permchannelsconf.c_str(), permchannelsnewconf.c_str(), strerror(errno), errno);
163 		return false;
164 	}
165 
166 	return true;
167 }
168 
169 class ModulePermanentChannels
170 	: public Module
171 	, public Timer
172 
173 {
174 	PermChannel p;
175 	bool dirty;
176 	bool loaded;
177 	bool save_listmodes;
178 public:
179 
ModulePermanentChannels()180 	ModulePermanentChannels()
181 		: Timer(0, true)
182 		, p(this)
183 		, dirty(false)
184 		, loaded(false)
185 	{
186 	}
187 
ReadConfig(ConfigStatus & status)188 	void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
189 	{
190 		ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb");
191 		permchannelsconf = tag->getString("filename");
192 		save_listmodes = tag->getBool("listmodes", true);
193 		SetInterval(tag->getDuration("saveperiod", 5));
194 
195 		if (!permchannelsconf.empty())
196 			permchannelsconf = ServerInstance->Config->Paths.PrependConfig(permchannelsconf);
197 	}
198 
LoadDatabase()199 	void LoadDatabase()
200 	{
201 		/*
202 		 * Process config-defined list of permanent channels.
203 		 * -- w00t
204 		 */
205 		ConfigTagList permchannels = ServerInstance->Config->ConfTags("permchannels");
206 		for (ConfigIter i = permchannels.first; i != permchannels.second; ++i)
207 		{
208 			ConfigTag* tag = i->second;
209 			std::string channel = tag->getString("channel");
210 
211 			if (!ServerInstance->IsChannel(channel))
212 			{
213 				ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring permchannels tag with invalid channel name (\"" + channel + "\")");
214 				continue;
215 			}
216 
217 			Channel *c = ServerInstance->FindChan(channel);
218 
219 			if (!c)
220 			{
221 				time_t TS = tag->getInt("ts", ServerInstance->Time(), 1);
222 				c = new Channel(channel, TS);
223 
224 				time_t topicset = tag->getInt("topicts", 0);
225 				std::string topic = tag->getString("topic");
226 
227 				if ((topicset != 0) || (!topic.empty()))
228 				{
229 					if (topicset == 0)
230 						topicset = ServerInstance->Time();
231 					std::string topicsetby = tag->getString("topicsetby");
232 					if (topicsetby.empty())
233 						topicsetby = ServerInstance->Config->GetServerName();
234 					c->SetTopic(ServerInstance->FakeClient, topic, topicset, &topicsetby);
235 				}
236 
237 				ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Added %s with topic %s", channel.c_str(), c->topic.c_str());
238 
239 				std::string modes = tag->getString("modes");
240 				if (modes.empty())
241 					continue;
242 
243 				irc::spacesepstream list(modes);
244 				std::string modeseq;
245 				std::string par;
246 
247 				list.GetToken(modeseq);
248 
249 				// XXX bleh, should we pass this to the mode parser instead? ugly. --w00t
250 				for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
251 				{
252 					ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
253 					if (mode)
254 					{
255 						if (mode->NeedsParam(true))
256 							list.GetToken(par);
257 						else
258 							par.clear();
259 
260 						mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
261 					}
262 				}
263 
264 				// We always apply the permchannels mode to permanent channels.
265 				par.clear();
266 				p.OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
267 			}
268 		}
269 	}
270 
OnRawMode(User * user,Channel * chan,ModeHandler * mh,const std::string & param,bool adding)271 	ModResult OnRawMode(User* user, Channel* chan, ModeHandler* mh, const std::string& param, bool adding) CXX11_OVERRIDE
272 	{
273 		if (chan && (chan->IsModeSet(p) || mh == &p))
274 			dirty = true;
275 
276 		return MOD_RES_PASSTHRU;
277 	}
278 
OnPostTopicChange(User *,Channel * c,const std::string &)279 	void OnPostTopicChange(User*, Channel *c, const std::string&) CXX11_OVERRIDE
280 	{
281 		if (c->IsModeSet(p))
282 			dirty = true;
283 	}
284 
Tick(time_t)285 	bool Tick(time_t) CXX11_OVERRIDE
286 	{
287 		if (dirty)
288 			WriteDatabase(p, this, save_listmodes);
289 		dirty = false;
290 		return true;
291 	}
292 
Prioritize()293 	void Prioritize() CXX11_OVERRIDE
294 	{
295 		// XXX: Load the DB here because the order in which modules are init()ed at boot is
296 		// alphabetical, this means we must wait until all modules have done their init()
297 		// to be able to set the modes they provide (e.g.: m_stripcolor is inited after us)
298 		// Prioritize() is called after all module initialization is complete, consequently
299 		// all modes are available now
300 		if (loaded)
301 			return;
302 
303 		loaded = true;
304 
305 		// Load only when there are no linked servers - we set the TS of the channels we
306 		// create to the current time, this can lead to desync because spanningtree has
307 		// no way of knowing what we do
308 		ProtocolInterface::ServerList serverlist;
309 		ServerInstance->PI->GetServerList(serverlist);
310 		if (serverlist.size() < 2)
311 		{
312 			try
313 			{
314 				LoadDatabase();
315 			}
316 			catch (CoreException& e)
317 			{
318 				ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error loading permchannels database: " + std::string(e.GetReason()));
319 			}
320 		}
321 	}
322 
GetVersion()323 	Version GetVersion() CXX11_OVERRIDE
324 	{
325 		return Version("Adds channel mode P (permanent) which prevents the channel from being deleted when the last user leaves.", VF_VENDOR);
326 	}
327 
OnChannelPreDelete(Channel * c)328 	ModResult OnChannelPreDelete(Channel *c) CXX11_OVERRIDE
329 	{
330 		if (c->IsModeSet(p))
331 			return MOD_RES_DENY;
332 
333 		return MOD_RES_PASSTHRU;
334 	}
335 };
336 
337 MODULE_INIT(ModulePermanentChannels)
338