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