]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_permchannels.cpp
Don't CoreExport reference, fixes m_dnsbl on Windows
[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
23 /* $ModDesc: Provides support for channel mode +P to provide permanent channels */
24
25 struct ListModeData
26 {
27         std::string modes;
28         std::string params;
29 };
30
31 // Not in a class due to circular dependancy hell.
32 static std::string permchannelsconf;
33 static bool WriteDatabase(Module* mod, bool save_listmodes)
34 {
35         FILE *f;
36
37         if (permchannelsconf.empty())
38         {
39                 // Fake success.
40                 return true;
41         }
42
43         std::string tempname = permchannelsconf + ".tmp";
44
45         /*
46          * We need to perform an atomic write so as not to fuck things up.
47          * So, let's write to a temporary file, flush and sync the FD, then rename the file..
48          *              -- w00t
49          */
50         f = fopen(tempname.c_str(), "w");
51         if (!f)
52         {
53                 ServerInstance->Logs->Log("m_permchannels",DEFAULT, "permchannels: Cannot create database! %s (%d)", strerror(errno), errno);
54                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new db: %s (%d)", strerror(errno), errno);
55                 return false;
56         }
57
58         fputs("# Permchannels DB\n# This file is autogenerated; any changes will be overwritten!\n<config format=\"compat\">\n", f);
59         // Now, let's write.
60         std::string line;
61         for (chan_hash::const_iterator i = ServerInstance->chanlist->begin(); i != ServerInstance->chanlist->end(); i++)
62         {
63                 Channel* chan = i->second;
64                 if (!chan->IsModeSet('P'))
65                         continue;
66
67                 std::string chanmodes = chan->ChanModes(true);
68                 if (save_listmodes)
69                 {
70                         ListModeData lm;
71
72                         // Bans are managed by the core, so we have to process them separately
73                         lm.modes = std::string(chan->bans.size(), 'b');
74                         for (BanList::const_iterator j = chan->bans.begin(); j != chan->bans.end(); ++j)
75                         {
76                                 lm.params += j->data;
77                                 lm.params += ' ';
78                         }
79
80                         // All other listmodes are managed by modules, so we need to ask them (call their
81                         // OnSyncChannel() handler) to give our ProtoSendMode() a list of modes that are
82                         // set on the channel. The ListModeData struct is passed as an opaque pointer
83                         // that will be passed back to us by the module handling the mode.
84                         FOREACH_MOD(I_OnSyncChannel, OnSyncChannel(chan, mod, &lm));
85
86                         if (!lm.modes.empty())
87                         {
88                                 // Remove the last space
89                                 lm.params.erase(lm.params.end()-1);
90
91                                 // If there is at least a space in chanmodes (that is, a non-listmode has a parameter)
92                                 // insert the listmode mode letters before the space. Otherwise just append them.
93                                 std::string::size_type p = chanmodes.find(' ');
94                                 if (p == std::string::npos)
95                                         chanmodes += lm.modes;
96                                 else
97                                         chanmodes.insert(p, lm.modes);
98
99                                 // Append the listmode parameters (the masks themselves)
100                                 chanmodes += ' ';
101                                 chanmodes += lm.params;
102                         }
103                 }
104
105                 std::string chants = ConvToStr(chan->age);
106                 std::string topicts = ConvToStr(chan->topicset);
107                 const char* items[] =
108                 {
109                         "<permchannels channel=",
110                         chan->name.c_str(),
111                         " ts=",
112                         chants.c_str(),
113                         " topic=",
114                         chan->topic.c_str(),
115                         " topicts=",
116                         topicts.c_str(),
117                         " topicsetby=",
118                         chan->setby.c_str(),
119                         " modes=",
120                         chanmodes.c_str(),
121                         ">\n"
122                 };
123
124                 line.clear();
125                 int item = 0, ipos = 0;
126                 while (item < 13)
127                 {
128                         char c = items[item][ipos++];
129                         if (c == 0)
130                         {
131                                 // end of this string; hop to next string, insert a quote
132                                 item++;
133                                 ipos = 0;
134                                 c = '"';
135                         }
136                         else if (c == '\\' || c == '"')
137                         {
138                                 line += '\\';
139                         }
140                         line += c;
141                 }
142
143                 // Erase last '"'
144                 line.erase(line.end()-1);
145                 fputs(line.c_str(), f);
146         }
147
148         int write_error = 0;
149         write_error = ferror(f);
150         write_error |= fclose(f);
151         if (write_error)
152         {
153                 ServerInstance->Logs->Log("m_permchannels",DEFAULT, "permchannels: Cannot write to new database! %s (%d)", strerror(errno), errno);
154                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new db: %s (%d)", strerror(errno), errno);
155                 return false;
156         }
157
158 #ifdef _WIN32
159         if (remove(permchannelsconf.c_str()))
160         {
161                 ServerInstance->Logs->Log("m_permchannels",DEFAULT, "permchannels: Cannot remove old database! %s (%d)", strerror(errno), errno);
162                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot remove old database: %s (%d)", strerror(errno), errno);
163                 return false;
164         }
165 #endif
166         // Use rename to move temporary to new db - this is guarenteed not to fuck up, even in case of a crash.
167         if (rename(tempname.c_str(), permchannelsconf.c_str()) < 0)
168         {
169                 ServerInstance->Logs->Log("m_permchannels",DEFAULT, "permchannels: Cannot move new to old database! %s (%d)", strerror(errno), errno);
170                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno);
171                 return false;
172         }
173
174         return true;
175 }
176
177
178
179 /** Handles the +P channel mode
180  */
181 class PermChannel : public ModeHandler
182 {
183  public:
184         PermChannel(Module* Creator) : ModeHandler(Creator, "permanent", 'P', PARAM_NONE, MODETYPE_CHANNEL) { oper = true; }
185
186         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
187         {
188                 if (adding)
189                 {
190                         if (!channel->IsModeSet('P'))
191                         {
192                                 channel->SetMode('P',true);
193                                 return MODEACTION_ALLOW;
194                         }
195                 }
196                 else
197                 {
198                         if (channel->IsModeSet('P'))
199                         {
200                                 channel->SetMode(this,false);
201                                 if (channel->GetUserCounter() == 0)
202                                 {
203                                         channel->DelUser(ServerInstance->FakeClient);
204                                 }
205                                 return MODEACTION_ALLOW;
206                         }
207                 }
208
209                 return MODEACTION_DENY;
210         }
211 };
212
213 class ModulePermanentChannels : public Module
214 {
215         PermChannel p;
216         bool dirty;
217         bool save_listmodes;
218 public:
219
220         ModulePermanentChannels() : p(this), dirty(false)
221         {
222         }
223
224         void init()
225         {
226                 ServerInstance->Modules->AddService(p);
227                 Implementation eventlist[] = { I_OnChannelPreDelete, I_OnPostTopicChange, I_OnRawMode, I_OnRehash, I_OnBackgroundTimer };
228                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
229
230                 OnRehash(NULL);
231         }
232
233         CullResult cull()
234         {
235                 /*
236                  * DelMode can't remove the +P mode on empty channels, or it will break
237                  * merging modes with remote servers. Remove the empty channels now as
238                  * we know this is not the case.
239                  */
240                 chan_hash::iterator iter = ServerInstance->chanlist->begin();
241                 while (iter != ServerInstance->chanlist->end())
242                 {
243                         Channel* c = iter->second;
244                         if (c->GetUserCounter() == 0)
245                         {
246                                 chan_hash::iterator at = iter;
247                                 iter++;
248                                 FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(c));
249                                 ServerInstance->chanlist->erase(at);
250                                 ServerInstance->GlobalCulls.AddItem(c);
251                         }
252                         else
253                                 iter++;
254                 }
255                 ServerInstance->Modes->DelMode(&p);
256                 return Module::cull();
257         }
258
259         virtual void OnRehash(User *user)
260         {
261                 ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb");
262                 permchannelsconf = tag->getString("filename");
263                 save_listmodes = tag->getBool("listmodes");
264         }
265
266         void LoadDatabase()
267         {
268                 /*
269                  * Process config-defined list of permanent channels.
270                  * -- w00t
271                  */
272                 ConfigTagList permchannels = ServerInstance->Config->ConfTags("permchannels");
273                 for (ConfigIter i = permchannels.first; i != permchannels.second; ++i)
274                 {
275                         ConfigTag* tag = i->second;
276                         std::string channel = tag->getString("channel");
277                         std::string topic = tag->getString("topic");
278                         std::string modes = tag->getString("modes");
279
280                         if ((channel.empty()) || (channel.length() > ServerInstance->Config->Limits.ChanMax))
281                         {
282                                 ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Ignoring permchannels tag with empty or too long channel name (\"" + channel + "\")");
283                                 continue;
284                         }
285
286                         Channel *c = ServerInstance->FindChan(channel);
287
288                         if (!c)
289                         {
290                                 time_t TS = tag->getInt("ts");
291                                 c = new Channel(channel, ((TS > 0) ? TS : ServerInstance->Time()));
292
293                                 c->SetTopic(NULL, topic, true);
294                                 c->setby = tag->getString("topicsetby");
295                                 if (c->setby.empty())
296                                         c->setby = ServerInstance->Config->ServerName;
297                                 unsigned int topicset = tag->getInt("topicts");
298                                 // SetTopic() sets the topic TS to now, if there was no topicts saved then don't overwrite that with a 0
299                                 if (topicset > 0)
300                                         c->topicset = topicset;
301
302                                 ServerInstance->Logs->Log("m_permchannels", DEBUG, "Added %s with topic %s", channel.c_str(), topic.c_str());
303
304                                 if (modes.empty())
305                                         continue;
306
307                                 irc::spacesepstream list(modes);
308                                 std::string modeseq;
309                                 std::string par;
310
311                                 list.GetToken(modeseq);
312
313                                 // XXX bleh, should we pass this to the mode parser instead? ugly. --w00t
314                                 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
315                                 {
316                                         ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
317                                         if (mode)
318                                         {
319                                                 if (mode->GetNumParams(true))
320                                                         list.GetToken(par);
321                                                 else
322                                                         par.clear();
323
324                                                 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
325                                         }
326                                 }
327                         }
328                 }
329         }
330
331         virtual ModResult OnRawMode(User* user, Channel* chan, const char mode, const std::string &param, bool adding, int pcnt)
332         {
333                 if (chan && (chan->IsModeSet('P') || mode == 'P'))
334                         dirty = true;
335
336                 return MOD_RES_PASSTHRU;
337         }
338
339         virtual void OnPostTopicChange(User*, Channel *c, const std::string&)
340         {
341                 if (c->IsModeSet('P'))
342                         dirty = true;
343         }
344
345         void OnBackgroundTimer(time_t)
346         {
347                 if (dirty)
348                         WriteDatabase(this, save_listmodes);
349                 dirty = false;
350         }
351
352         void Prioritize()
353         {
354                 // XXX: Load the DB here because the order in which modules are init()ed at boot is
355                 // alphabetical, this means we must wait until all modules have done their init()
356                 // to be able to set the modes they provide (e.g.: m_stripcolor is inited after us)
357                 // Prioritize() is called after all module initialization is complete, consequently
358                 // all modes are available now
359
360                 static bool loaded = false;
361                 if (loaded)
362                         return;
363
364                 loaded = true;
365
366                 // Load only when there are no linked servers - we set the TS of the channels we
367                 // create to the current time, this can lead to desync because spanningtree has
368                 // no way of knowing what we do
369                 ProtoServerList serverlist;
370                 ServerInstance->PI->GetServerList(serverlist);
371                 if (serverlist.size() < 2)
372                 {
373                         try
374                         {
375                                 LoadDatabase();
376                         }
377                         catch (CoreException& e)
378                         {
379                                 ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Error loading permchannels database: " + std::string(e.GetReason()));
380                         }
381                 }
382         }
383
384         void ProtoSendMode(void* opaque, TargetTypeFlags type, void* target, const std::vector<std::string>& modes, const std::vector<TranslateType>& translate)
385         {
386                 // We never pass an empty modelist but better be sure
387                 if (modes.empty())
388                         return;
389
390                 ListModeData* lm = static_cast<ListModeData*>(opaque);
391
392                 // Append the mode letters without the trailing '+' (for example "IIII", "gg")
393                 lm->modes.append(modes[0].begin()+1, modes[0].end());
394
395                 // Append the parameters
396                 for (std::vector<std::string>::const_iterator i = modes.begin()+1; i != modes.end(); ++i)
397                 {
398                         lm->params += *i;
399                         lm->params += ' ';
400                 }
401         }
402
403         virtual Version GetVersion()
404         {
405                 return Version("Provides support for channel mode +P to provide permanent channels",VF_VENDOR);
406         }
407
408         virtual ModResult OnChannelPreDelete(Channel *c)
409         {
410                 if (c->IsModeSet('P'))
411                         return MOD_RES_DENY;
412
413                 return MOD_RES_PASSTHRU;
414         }
415 };
416
417 MODULE_INIT(ModulePermanentChannels)