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