]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_permchannels.cpp
Fix m_permchannels not prepending the path when reading the config.
[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)
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 (%d)", strerror(errno), errno);
70                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new db: %s (%d)", 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         for (chan_hash::const_iterator i = ServerInstance->chanlist->begin(); i != ServerInstance->chanlist->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 (%d)", strerror(errno), errno);
140                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new db: %s (%d)", strerror(errno), errno);
141                 return false;
142         }
143         stream.close();
144
145 #ifdef _WIN32
146         if (remove(permchannelsconf.c_str()))
147         {
148                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot remove old database! %s (%d)", strerror(errno), errno);
149                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot remove old database: %s (%d)", strerror(errno), errno);
150                 return false;
151         }
152 #endif
153         // Use rename to move temporary to new db - this is guarenteed not to fuck up, even in case of a crash.
154         if (rename(permchannelsnewconf.c_str(), permchannelsconf.c_str()) < 0)
155         {
156                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot move new to old database! %s (%d)", strerror(errno), errno);
157                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno);
158                 return false;
159         }
160
161         return true;
162 }
163
164 class ModulePermanentChannels : public Module
165 {
166         PermChannel p;
167         bool dirty;
168         bool loaded;
169         bool save_listmodes;
170 public:
171
172         ModulePermanentChannels()
173                 : p(this), dirty(false), loaded(false)
174         {
175         }
176
177         CullResult cull()
178         {
179                 /*
180                  * DelMode can't remove the +P mode on empty channels, or it will break
181                  * merging modes with remote servers. Remove the empty channels now as
182                  * we know this is not the case.
183                  */
184                 chan_hash::iterator iter = ServerInstance->chanlist->begin();
185                 while (iter != ServerInstance->chanlist->end())
186                 {
187                         Channel* c = iter->second;
188                         if (c->GetUserCounter() == 0)
189                         {
190                                 chan_hash::iterator at = iter;
191                                 iter++;
192                                 FOREACH_MOD(OnChannelDelete, (c));
193                                 ServerInstance->chanlist->erase(at);
194                                 ServerInstance->GlobalCulls.AddItem(c);
195                         }
196                         else
197                                 iter++;
198                 }
199                 ServerInstance->Modes->DelMode(&p);
200                 return Module::cull();
201         }
202
203         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
204         {
205                 ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb");
206                 permchannelsconf = tag->getString("filename");
207                 save_listmodes = tag->getBool("listmodes");
208
209                 if (!permchannelsconf.empty())
210                         permchannelsconf = ServerInstance->Config->Paths.PrependConfig(permchannelsconf);
211         }
212
213         void LoadDatabase()
214         {
215                 /*
216                  * Process config-defined list of permanent channels.
217                  * -- w00t
218                  */
219                 ConfigTagList permchannels = ServerInstance->Config->ConfTags("permchannels");
220                 for (ConfigIter i = permchannels.first; i != permchannels.second; ++i)
221                 {
222                         ConfigTag* tag = i->second;
223                         std::string channel = tag->getString("channel");
224                         std::string modes = tag->getString("modes");
225
226                         if ((channel.empty()) || (channel.length() > ServerInstance->Config->Limits.ChanMax))
227                         {
228                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring permchannels tag with empty or too long channel name (\"" + channel + "\")");
229                                 continue;
230                         }
231
232                         Channel *c = ServerInstance->FindChan(channel);
233
234                         if (!c)
235                         {
236                                 time_t TS = tag->getInt("ts", ServerInstance->Time(), 1);
237                                 c = new Channel(channel, TS);
238
239                                 unsigned int topicset = tag->getInt("topicts");
240                                 c->topic = tag->getString("topic");
241
242                                 if ((topicset != 0) || (!c->topic.empty()))
243                                 {
244                                         if (topicset == 0)
245                                                 topicset = ServerInstance->Time();
246                                         c->topicset = topicset;
247                                         c->setby = tag->getString("topicsetby");
248                                         if (c->setby.empty())
249                                                 c->setby = ServerInstance->Config->ServerName;
250                                 }
251
252                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Added %s with topic %s", channel.c_str(), c->topic.c_str());
253
254                                 if (modes.empty())
255                                         continue;
256
257                                 irc::spacesepstream list(modes);
258                                 std::string modeseq;
259                                 std::string par;
260
261                                 list.GetToken(modeseq);
262
263                                 // XXX bleh, should we pass this to the mode parser instead? ugly. --w00t
264                                 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
265                                 {
266                                         ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
267                                         if (mode)
268                                         {
269                                                 if (mode->GetNumParams(true))
270                                                         list.GetToken(par);
271                                                 else
272                                                         par.clear();
273
274                                                 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
275                                         }
276                                 }
277                         }
278                 }
279         }
280
281         ModResult OnRawMode(User* user, Channel* chan, ModeHandler* mh, const std::string& param, bool adding) CXX11_OVERRIDE
282         {
283                 if (chan && (chan->IsModeSet(p) || mh == &p))
284                         dirty = true;
285
286                 return MOD_RES_PASSTHRU;
287         }
288
289         void OnPostTopicChange(User*, Channel *c, const std::string&) CXX11_OVERRIDE
290         {
291                 if (c->IsModeSet(p))
292                         dirty = true;
293         }
294
295         void OnBackgroundTimer(time_t) CXX11_OVERRIDE
296         {
297                 if (dirty)
298                         WriteDatabase(p, this, save_listmodes);
299                 dirty = false;
300         }
301
302         void Prioritize()
303         {
304                 // XXX: Load the DB here because the order in which modules are init()ed at boot is
305                 // alphabetical, this means we must wait until all modules have done their init()
306                 // to be able to set the modes they provide (e.g.: m_stripcolor is inited after us)
307                 // Prioritize() is called after all module initialization is complete, consequently
308                 // all modes are available now
309                 if (loaded)
310                         return;
311
312                 loaded = true;
313
314                 // Load only when there are no linked servers - we set the TS of the channels we
315                 // create to the current time, this can lead to desync because spanningtree has
316                 // no way of knowing what we do
317                 ProtocolInterface::ServerList serverlist;
318                 ServerInstance->PI->GetServerList(serverlist);
319                 if (serverlist.size() < 2)
320                 {
321                         try
322                         {
323                                 LoadDatabase();
324                         }
325                         catch (CoreException& e)
326                         {
327                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error loading permchannels database: " + std::string(e.GetReason()));
328                         }
329                 }
330         }
331
332         Version GetVersion() CXX11_OVERRIDE
333         {
334                 return Version("Provides support for channel mode +P to provide permanent channels",VF_VENDOR);
335         }
336
337         ModResult OnChannelPreDelete(Channel *c) CXX11_OVERRIDE
338         {
339                 if (c->IsModeSet(p))
340                         return MOD_RES_DENY;
341
342                 return MOD_RES_PASSTHRU;
343         }
344 };
345
346 MODULE_INIT(ModulePermanentChannels)