2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2008-2009 Robin Burchell <robin+git@viroteck.net>
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.
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
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/>.
23 /* $ModDesc: Provides support for channel mode +P to provide permanent channels */
31 // Not in a class due to circular dependancy hell.
32 static std::string permchannelsconf;
33 static bool WriteDatabase(Module* mod, bool save_listmodes)
37 if (permchannelsconf.empty())
43 std::string tempname = permchannelsconf + ".tmp";
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..
50 f = fopen(tempname.c_str(), "w");
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);
58 fputs("# Permchannels DB\n# This file is autogenerated; any changes will be overwritten!\n<config format=\"compat\">\n", f);
61 for (chan_hash::const_iterator i = ServerInstance->chanlist->begin(); i != ServerInstance->chanlist->end(); i++)
63 Channel* chan = i->second;
64 if (!chan->IsModeSet('P'))
67 std::string chanmodes = chan->ChanModes(true);
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)
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));
86 if (!lm.modes.empty())
88 // Remove the last space
89 lm.params.erase(lm.params.end()-1);
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;
97 chanmodes.insert(p, lm.modes);
99 // Append the listmode parameters (the masks themselves)
101 chanmodes += lm.params;
105 std::string chants = ConvToStr(chan->age);
106 std::string topicts = ConvToStr(chan->topicset);
107 const char* items[] =
109 "<permchannels channel=",
125 int item = 0, ipos = 0;
128 char c = items[item][ipos++];
131 // end of this string; hop to next string, insert a quote
136 else if (c == '\\' || c == '"')
144 line.erase(line.end()-1);
145 fputs(line.c_str(), f);
149 write_error = ferror(f);
150 write_error |= fclose(f);
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);
159 remove(permchannelsconf.c_str());
161 // Use rename to move temporary to new db - this is guarenteed not to fuck up, even in case of a crash.
162 if (rename(tempname.c_str(), permchannelsconf.c_str()) < 0)
164 ServerInstance->Logs->Log("m_permchannels",DEFAULT, "permchannels: Cannot move new to old database! %s (%d)", strerror(errno), errno);
165 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno);
174 /** Handles the +P channel mode
176 class PermChannel : public ModeHandler
179 PermChannel(Module* Creator) : ModeHandler(Creator, "permanent", 'P', PARAM_NONE, MODETYPE_CHANNEL) { oper = true; }
181 ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding)
185 if (!channel->IsModeSet('P'))
187 channel->SetMode('P',true);
188 return MODEACTION_ALLOW;
193 if (channel->IsModeSet('P'))
195 channel->SetMode(this,false);
196 if (channel->GetUserCounter() == 0)
198 channel->DelUser(ServerInstance->FakeClient);
200 return MODEACTION_ALLOW;
204 return MODEACTION_DENY;
208 class ModulePermanentChannels : public Module
216 ModulePermanentChannels()
217 : p(this), dirty(false), loaded(false)
223 ServerInstance->Modules->AddService(p);
224 Implementation eventlist[] = { I_OnChannelPreDelete, I_OnPostTopicChange, I_OnRawMode, I_OnRehash, I_OnBackgroundTimer };
225 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
233 * DelMode can't remove the +P mode on empty channels, or it will break
234 * merging modes with remote servers. Remove the empty channels now as
235 * we know this is not the case.
237 chan_hash::iterator iter = ServerInstance->chanlist->begin();
238 while (iter != ServerInstance->chanlist->end())
240 Channel* c = iter->second;
241 if (c->GetUserCounter() == 0)
243 chan_hash::iterator at = iter;
245 FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(c));
246 ServerInstance->chanlist->erase(at);
247 ServerInstance->GlobalCulls.AddItem(c);
252 ServerInstance->Modes->DelMode(&p);
253 return Module::cull();
256 virtual void OnRehash(User *user)
258 ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb");
259 permchannelsconf = tag->getString("filename");
260 save_listmodes = tag->getBool("listmodes");
266 * Process config-defined list of permanent channels.
269 ConfigTagList permchannels = ServerInstance->Config->ConfTags("permchannels");
270 for (ConfigIter i = permchannels.first; i != permchannels.second; ++i)
272 ConfigTag* tag = i->second;
273 std::string channel = tag->getString("channel");
274 std::string topic = tag->getString("topic");
275 std::string modes = tag->getString("modes");
277 if ((channel.empty()) || (channel.length() > ServerInstance->Config->Limits.ChanMax))
279 ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Ignoring permchannels tag with empty or too long channel name (\"" + channel + "\")");
283 Channel *c = ServerInstance->FindChan(channel);
287 time_t TS = tag->getInt("ts");
288 c = new Channel(channel, ((TS > 0) ? TS : ServerInstance->Time()));
290 c->SetTopic(NULL, topic, true);
291 c->setby = tag->getString("topicsetby");
292 if (c->setby.empty())
293 c->setby = ServerInstance->Config->ServerName;
294 unsigned int topicset = tag->getInt("topicts");
295 // SetTopic() sets the topic TS to now, if there was no topicts saved then don't overwrite that with a 0
297 c->topicset = topicset;
299 ServerInstance->Logs->Log("m_permchannels", DEBUG, "Added %s with topic %s", channel.c_str(), topic.c_str());
304 irc::spacesepstream list(modes);
308 list.GetToken(modeseq);
310 // XXX bleh, should we pass this to the mode parser instead? ugly. --w00t
311 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
313 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
316 if (mode->GetNumParams(true))
321 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
328 virtual ModResult OnRawMode(User* user, Channel* chan, const char mode, const std::string ¶m, bool adding, int pcnt)
330 if (chan && (chan->IsModeSet('P') || mode == 'P'))
333 return MOD_RES_PASSTHRU;
336 virtual void OnPostTopicChange(User*, Channel *c, const std::string&)
338 if (c->IsModeSet('P'))
342 void OnBackgroundTimer(time_t)
345 WriteDatabase(this, save_listmodes);
351 // XXX: Load the DB here because the order in which modules are init()ed at boot is
352 // alphabetical, this means we must wait until all modules have done their init()
353 // to be able to set the modes they provide (e.g.: m_stripcolor is inited after us)
354 // Prioritize() is called after all module initialization is complete, consequently
355 // all modes are available now
361 // Load only when there are no linked servers - we set the TS of the channels we
362 // create to the current time, this can lead to desync because spanningtree has
363 // no way of knowing what we do
364 ProtoServerList serverlist;
365 ServerInstance->PI->GetServerList(serverlist);
366 if (serverlist.size() < 2)
372 catch (CoreException& e)
374 ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Error loading permchannels database: " + std::string(e.GetReason()));
379 void ProtoSendMode(void* opaque, TargetTypeFlags type, void* target, const std::vector<std::string>& modes, const std::vector<TranslateType>& translate)
381 // We never pass an empty modelist but better be sure
385 ListModeData* lm = static_cast<ListModeData*>(opaque);
387 // Append the mode letters without the trailing '+' (for example "IIII", "gg")
388 lm->modes.append(modes[0].begin()+1, modes[0].end());
390 // Append the parameters
391 for (std::vector<std::string>::const_iterator i = modes.begin()+1; i != modes.end(); ++i)
398 virtual Version GetVersion()
400 return Version("Provides support for channel mode +P to provide permanent channels",VF_VENDOR);
403 virtual ModResult OnChannelPreDelete(Channel *c)
405 if (c->IsModeSet('P'))
408 return MOD_RES_PASSTHRU;
412 MODULE_INIT(ModulePermanentChannels)