]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_permchannels.cpp
Automatically register ServiceProviders created by modules
[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 struct ListModeData
27 {
28         std::string modes;
29         std::string params;
30 };
31
32 /** Handles the +P channel mode
33  */
34 class PermChannel : public ModeHandler
35 {
36  public:
37         PermChannel(Module* Creator)
38                 : ModeHandler(Creator, "permanent", 'P', PARAM_NONE, MODETYPE_CHANNEL)
39         {
40                 oper = true;
41         }
42
43         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string& parameter, bool adding)
44         {
45                 if (adding == channel->IsModeSet(this))
46                         return MODEACTION_DENY;
47
48                 channel->SetMode(this, adding);
49                 if (!adding)
50                         channel->CheckDestroy();
51
52                 return MODEACTION_ALLOW;
53         }
54 };
55
56 // Not in a class due to circular dependancy hell.
57 static std::string permchannelsconf;
58 static bool WriteDatabase(PermChannel& permchanmode, Module* mod, bool save_listmodes)
59 {
60         ChanModeReference ban(mod, "ban");
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 (%d)", strerror(errno), errno);
76                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new db: %s (%d)", 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         for (chan_hash::const_iterator i = ServerInstance->chanlist->begin(); i != ServerInstance->chanlist->end(); i++)
84         {
85                 Channel* chan = i->second;
86                 if (!chan->IsModeSet(permchanmode))
87                         continue;
88
89                 std::string chanmodes = chan->ChanModes(true);
90                 if (save_listmodes)
91                 {
92                         ListModeData lm;
93
94                         // Bans are managed by the core, so we have to process them separately
95                         static_cast<ListModeBase*>(*ban)->DoSyncChannel(chan, mod, &lm);
96
97                         // All other listmodes are managed by modules, so we need to ask them (call their
98                         // OnSyncChannel() handler) to give our ProtoSendMode() a list of modes that are
99                         // set on the channel. The ListModeData struct is passed as an opaque pointer
100                         // that will be passed back to us by the module handling the mode.
101                         FOREACH_MOD(OnSyncChannel, (chan, mod, &lm));
102
103                         if (!lm.modes.empty())
104                         {
105                                 // Remove the last space
106                                 lm.params.erase(lm.params.end()-1);
107
108                                 // If there is at least a space in chanmodes (that is, a non-listmode has a parameter)
109                                 // insert the listmode mode letters before the space. Otherwise just append them.
110                                 std::string::size_type p = chanmodes.find(' ');
111                                 if (p == std::string::npos)
112                                         chanmodes += lm.modes;
113                                 else
114                                         chanmodes.insert(p, lm.modes);
115
116                                 // Append the listmode parameters (the masks themselves)
117                                 chanmodes += ' ';
118                                 chanmodes += lm.params;
119                         }
120                 }
121
122                 stream << "<permchannels channel=\"" << ServerConfig::Escape(chan->name)
123                         << "\" ts=\"" << chan->age
124                         << "\" topic=\"" << ServerConfig::Escape(chan->topic)
125                         << "\" topicts=\"" << chan->topicset
126                         << "\" topicsetby=\"" << ServerConfig::Escape(chan->setby)
127                         << "\" modes=\"" << ServerConfig::Escape(chanmodes)
128                         << "\">" << std::endl;
129         }
130
131         if (stream.fail())
132         {
133                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot write to new database! %s (%d)", strerror(errno), errno);
134                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new db: %s (%d)", strerror(errno), errno);
135                 return false;
136         }
137         stream.close();
138
139 #ifdef _WIN32
140         if (remove(permchannelsconf.c_str()))
141         {
142                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot remove old database! %s (%d)", strerror(errno), errno);
143                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot remove old database: %s (%d)", strerror(errno), errno);
144                 return false;
145         }
146 #endif
147         // Use rename to move temporary to new db - this is guarenteed not to fuck up, even in case of a crash.
148         if (rename(permchannelsnewconf.c_str(), permchannelsconf.c_str()) < 0)
149         {
150                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot move new to old database! %s (%d)", strerror(errno), errno);
151                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno);
152                 return false;
153         }
154
155         return true;
156 }
157
158 class ModulePermanentChannels : public Module
159 {
160         PermChannel p;
161         bool dirty;
162         bool save_listmodes;
163 public:
164
165         ModulePermanentChannels() : p(this), dirty(false)
166         {
167         }
168
169         CullResult cull()
170         {
171                 /*
172                  * DelMode can't remove the +P mode on empty channels, or it will break
173                  * merging modes with remote servers. Remove the empty channels now as
174                  * we know this is not the case.
175                  */
176                 chan_hash::iterator iter = ServerInstance->chanlist->begin();
177                 while (iter != ServerInstance->chanlist->end())
178                 {
179                         Channel* c = iter->second;
180                         if (c->GetUserCounter() == 0)
181                         {
182                                 chan_hash::iterator at = iter;
183                                 iter++;
184                                 FOREACH_MOD(OnChannelDelete, (c));
185                                 ServerInstance->chanlist->erase(at);
186                                 ServerInstance->GlobalCulls.AddItem(c);
187                         }
188                         else
189                                 iter++;
190                 }
191                 ServerInstance->Modes->DelMode(&p);
192                 return Module::cull();
193         }
194
195         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
196         {
197                 ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb");
198                 permchannelsconf = tag->getString("filename");
199                 save_listmodes = tag->getBool("listmodes");
200         }
201
202         void LoadDatabase()
203         {
204                 /*
205                  * Process config-defined list of permanent channels.
206                  * -- w00t
207                  */
208                 ConfigTagList permchannels = ServerInstance->Config->ConfTags("permchannels");
209                 for (ConfigIter i = permchannels.first; i != permchannels.second; ++i)
210                 {
211                         ConfigTag* tag = i->second;
212                         std::string channel = tag->getString("channel");
213                         std::string modes = tag->getString("modes");
214
215                         if ((channel.empty()) || (channel.length() > ServerInstance->Config->Limits.ChanMax))
216                         {
217                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring permchannels tag with empty or too long channel name (\"" + channel + "\")");
218                                 continue;
219                         }
220
221                         Channel *c = ServerInstance->FindChan(channel);
222
223                         if (!c)
224                         {
225                                 time_t TS = tag->getInt("ts", ServerInstance->Time(), 1);
226                                 c = new Channel(channel, TS);
227
228                                 unsigned int topicset = tag->getInt("topicts");
229                                 c->topic = tag->getString("topic");
230
231                                 if ((topicset != 0) || (!c->topic.empty()))
232                                 {
233                                         if (topicset == 0)
234                                                 topicset = ServerInstance->Time();
235                                         c->topicset = topicset;
236                                         c->setby = tag->getString("topicsetby");
237                                         if (c->setby.empty())
238                                                 c->setby = ServerInstance->Config->ServerName;
239                                 }
240
241                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Added %s with topic %s", channel.c_str(), c->topic.c_str());
242
243                                 if (modes.empty())
244                                         continue;
245
246                                 irc::spacesepstream list(modes);
247                                 std::string modeseq;
248                                 std::string par;
249
250                                 list.GetToken(modeseq);
251
252                                 // XXX bleh, should we pass this to the mode parser instead? ugly. --w00t
253                                 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
254                                 {
255                                         ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
256                                         if (mode)
257                                         {
258                                                 if (mode->GetNumParams(true))
259                                                         list.GetToken(par);
260                                                 else
261                                                         par.clear();
262
263                                                 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
264                                         }
265                                 }
266                         }
267                 }
268         }
269
270         ModResult OnRawMode(User* user, Channel* chan, const char mode, const std::string &param, bool adding, int pcnt) CXX11_OVERRIDE
271         {
272                 if (chan && (chan->IsModeSet(p) || mode == p.GetModeChar()))
273                         dirty = true;
274
275                 return MOD_RES_PASSTHRU;
276         }
277
278         void OnPostTopicChange(User*, Channel *c, const std::string&) CXX11_OVERRIDE
279         {
280                 if (c->IsModeSet(p))
281                         dirty = true;
282         }
283
284         void OnBackgroundTimer(time_t) CXX11_OVERRIDE
285         {
286                 if (dirty)
287                         WriteDatabase(p, this, save_listmodes);
288                 dirty = false;
289         }
290
291         void Prioritize()
292         {
293                 // XXX: Load the DB here because the order in which modules are init()ed at boot is
294                 // alphabetical, this means we must wait until all modules have done their init()
295                 // to be able to set the modes they provide (e.g.: m_stripcolor is inited after us)
296                 // Prioritize() is called after all module initialization is complete, consequently
297                 // all modes are available now
298
299                 static bool loaded = false;
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
323         void ProtoSendMode(void* opaque, TargetTypeFlags type, void* target, const std::vector<std::string>& modes, const std::vector<TranslateType>& translate)
324         {
325                 // We never pass an empty modelist but better be sure
326                 if (modes.empty())
327                         return;
328
329                 ListModeData* lm = static_cast<ListModeData*>(opaque);
330
331                 // Append the mode letters without the trailing '+' (for example "IIII", "gg")
332                 lm->modes.append(modes[0].begin()+1, modes[0].end());
333
334                 // Append the parameters
335                 for (std::vector<std::string>::const_iterator i = modes.begin()+1; i != modes.end(); ++i)
336                 {
337                         lm->params += *i;
338                         lm->params += ' ';
339                 }
340         }
341
342         Version GetVersion() CXX11_OVERRIDE
343         {
344                 return Version("Provides support for channel mode +P to provide permanent channels",VF_VENDOR);
345         }
346
347         ModResult OnChannelPreDelete(Channel *c) CXX11_OVERRIDE
348         {
349                 if (c->IsModeSet(p))
350                         return MOD_RES_DENY;
351
352                 return MOD_RES_PASSTHRU;
353         }
354 };
355
356 MODULE_INIT(ModulePermanentChannels)