]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_permchannels.cpp
0f3ac001ddb79e3d78fdae96f42346cf9ca229df
[user/henk/code/inspircd.git] / src / modules / m_permchannels.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2014 Justin Crawford <Justasic@Gmail.com>
5  *   Copyright (C) 2013-2014, 2017-2020 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:
38         PermChannel(Module* Creator)
39                 : ModeHandler(Creator, "permanent", 'P', PARAM_NONE, MODETYPE_CHANNEL)
40         {
41                 oper = true;
42         }
43
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;
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 << "# This file is automatically generated by m_permchannels. Any changes will be overwritten." << std::endl
81                 << "<config format=\"xml\">" << std::endl;
82
83         const chan_hash& chans = ServerInstance->GetChans();
84         for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); ++i)
85         {
86                 Channel* chan = i->second;
87                 if (!chan->IsModeSet(permchanmode))
88                         continue;
89
90                 std::string chanmodes = chan->ChanModes(true);
91                 if (save_listmodes)
92                 {
93                         std::string modes;
94                         std::string params;
95
96                         const ModeParser::ListModeList& listmodes = ServerInstance->Modes->GetListModes();
97                         for (ModeParser::ListModeList::const_iterator j = listmodes.begin(); j != listmodes.end(); ++j)
98                         {
99                                 ListModeBase* lm = *j;
100                                 ListModeBase::ModeList* list = lm->GetList(chan);
101                                 if (!list || list->empty())
102                                         continue;
103
104                                 size_t n = 0;
105                                 // Append the parameters
106                                 for (ListModeBase::ModeList::const_iterator k = list->begin(); k != list->end(); ++k, n++)
107                                 {
108                                         params += k->mask;
109                                         params += ' ';
110                                 }
111
112                                 // Append the mode letters (for example "IIII", "gg")
113                                 modes.append(n, lm->GetModeChar());
114                         }
115
116                         if (!params.empty())
117                         {
118                                 // Remove the last space
119                                 params.erase(params.end()-1);
120
121                                 // If there is at least a space in chanmodes (that is, a non-listmode has a parameter)
122                                 // insert the listmode mode letters before the space. Otherwise just append them.
123                                 std::string::size_type p = chanmodes.find(' ');
124                                 if (p == std::string::npos)
125                                         chanmodes += modes;
126                                 else
127                                         chanmodes.insert(p, modes);
128
129                                 // Append the listmode parameters (the masks themselves)
130                                 chanmodes += ' ';
131                                 chanmodes += params;
132                         }
133                 }
134
135                 stream << "<permchannels channel=\"" << ServerConfig::Escape(chan->name)
136                         << "\" ts=\"" << chan->age
137                         << "\" topic=\"" << ServerConfig::Escape(chan->topic)
138                         << "\" topicts=\"" << chan->topicset
139                         << "\" topicsetby=\"" << ServerConfig::Escape(chan->setby)
140                         << "\" modes=\"" << ServerConfig::Escape(chanmodes)
141                         << "\">" << std::endl;
142         }
143
144         if (stream.fail())
145         {
146                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot write to new database \"%s\"! %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno);
147                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new permchan db \"%s\": %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno);
148                 return false;
149         }
150         stream.close();
151
152 #ifdef _WIN32
153         remove(permchannelsconf.c_str());
154 #endif
155         // Use rename to move temporary to new db - this is guaranteed not to fuck up, even in case of a crash.
156         if (rename(permchannelsnewconf.c_str(), permchannelsconf.c_str()) < 0)
157         {
158                 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);
159                 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);
160                 return false;
161         }
162
163         return true;
164 }
165
166 class ModulePermanentChannels
167         : public Module
168         , public Timer
169
170 {
171         PermChannel p;
172         bool dirty;
173         bool loaded;
174         bool save_listmodes;
175 public:
176
177         ModulePermanentChannels()
178                 : Timer(0, true)
179                 , p(this)
180                 , dirty(false)
181                 , loaded(false)
182         {
183         }
184
185         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
186         {
187                 ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb");
188                 permchannelsconf = tag->getString("filename");
189                 save_listmodes = tag->getBool("listmodes");
190                 SetInterval(tag->getDuration("saveperiod", 5));
191
192                 if (!permchannelsconf.empty())
193                         permchannelsconf = ServerInstance->Config->Paths.PrependConfig(permchannelsconf);
194         }
195
196         void LoadDatabase()
197         {
198                 /*
199                  * Process config-defined list of permanent channels.
200                  * -- w00t
201                  */
202                 ConfigTagList permchannels = ServerInstance->Config->ConfTags("permchannels");
203                 for (ConfigIter i = permchannels.first; i != permchannels.second; ++i)
204                 {
205                         ConfigTag* tag = i->second;
206                         std::string channel = tag->getString("channel");
207                         std::string modes = tag->getString("modes");
208
209                         if (!ServerInstance->IsChannel(channel))
210                         {
211                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring permchannels tag with invalid channel name (\"" + channel + "\")");
212                                 continue;
213                         }
214
215                         Channel *c = ServerInstance->FindChan(channel);
216
217                         if (!c)
218                         {
219                                 time_t TS = tag->getInt("ts", ServerInstance->Time(), 1);
220                                 c = new Channel(channel, TS);
221
222                                 time_t topicset = tag->getInt("topicts", 0);
223                                 std::string topic = tag->getString("topic");
224
225                                 if ((topicset != 0) || (!topic.empty()))
226                                 {
227                                         if (topicset == 0)
228                                                 topicset = ServerInstance->Time();
229                                         std::string topicsetby = tag->getString("topicsetby");
230                                         if (topicsetby.empty())
231                                                 topicsetby = ServerInstance->Config->GetServerName();
232                                         c->SetTopic(ServerInstance->FakeClient, topic, topicset, &topicsetby);
233                                 }
234
235                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Added %s with topic %s", channel.c_str(), c->topic.c_str());
236
237                                 if (modes.empty())
238                                         continue;
239
240                                 irc::spacesepstream list(modes);
241                                 std::string modeseq;
242                                 std::string par;
243
244                                 list.GetToken(modeseq);
245
246                                 // XXX bleh, should we pass this to the mode parser instead? ugly. --w00t
247                                 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
248                                 {
249                                         ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
250                                         if (mode)
251                                         {
252                                                 if (mode->NeedsParam(true))
253                                                         list.GetToken(par);
254                                                 else
255                                                         par.clear();
256
257                                                 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
258                                         }
259                                 }
260
261                                 // We always apply the permchannels mode to permanent channels.
262                                 par.clear();
263                                 p.OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
264                         }
265                 }
266         }
267
268         ModResult OnRawMode(User* user, Channel* chan, ModeHandler* mh, const std::string& param, bool adding) CXX11_OVERRIDE
269         {
270                 if (chan && (chan->IsModeSet(p) || mh == &p))
271                         dirty = true;
272
273                 return MOD_RES_PASSTHRU;
274         }
275
276         void OnPostTopicChange(User*, Channel *c, const std::string&) CXX11_OVERRIDE
277         {
278                 if (c->IsModeSet(p))
279                         dirty = true;
280         }
281
282         bool Tick(time_t) CXX11_OVERRIDE
283         {
284                 if (dirty)
285                         WriteDatabase(p, this, save_listmodes);
286                 dirty = false;
287                 return true;
288         }
289
290         void Prioritize() CXX11_OVERRIDE
291         {
292                 // XXX: Load the DB here because the order in which modules are init()ed at boot is
293                 // alphabetical, this means we must wait until all modules have done their init()
294                 // to be able to set the modes they provide (e.g.: m_stripcolor is inited after us)
295                 // Prioritize() is called after all module initialization is complete, consequently
296                 // all modes are available now
297                 if (loaded)
298                         return;
299
300                 loaded = true;
301
302                 // Load only when there are no linked servers - we set the TS of the channels we
303                 // create to the current time, this can lead to desync because spanningtree has
304                 // no way of knowing what we do
305                 ProtocolInterface::ServerList serverlist;
306                 ServerInstance->PI->GetServerList(serverlist);
307                 if (serverlist.size() < 2)
308                 {
309                         try
310                         {
311                                 LoadDatabase();
312                         }
313                         catch (CoreException& e)
314                         {
315                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error loading permchannels database: " + std::string(e.GetReason()));
316                         }
317                 }
318         }
319
320         Version GetVersion() CXX11_OVERRIDE
321         {
322                 return Version("Adds channel mode P (permanent) which prevents the channel from being deleted when the last user leaves.", VF_VENDOR);
323         }
324
325         ModResult OnChannelPreDelete(Channel *c) CXX11_OVERRIDE
326         {
327                 if (c->IsModeSet(p))
328                         return MOD_RES_DENY;
329
330                 return MOD_RES_PASSTHRU;
331         }
332 };
333
334 MODULE_INIT(ModulePermanentChannels)