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 if (remove(permchannelsconf.c_str()))
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);
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)
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);
179 /** Handles the +P channel mode
181 class PermChannel : public ModeHandler
184 PermChannel(Module* Creator) : ModeHandler(Creator, "permanent", 'P', PARAM_NONE, MODETYPE_CHANNEL) { oper = true; }
186 ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding)
190 if (!channel->IsModeSet('P'))
192 channel->SetMode('P',true);
193 return MODEACTION_ALLOW;
198 if (channel->IsModeSet('P'))
200 channel->SetMode(this,false);
201 if (channel->GetUserCounter() == 0)
203 channel->DelUser(ServerInstance->FakeClient);
205 return MODEACTION_ALLOW;
209 return MODEACTION_DENY;
213 class ModulePermanentChannels : public Module
220 ModulePermanentChannels() : p(this), dirty(false)
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));
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.
240 chan_hash::iterator iter = ServerInstance->chanlist->begin();
241 while (iter != ServerInstance->chanlist->end())
243 Channel* c = iter->second;
244 if (c->GetUserCounter() == 0)
246 chan_hash::iterator at = iter;
248 FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(c));
249 ServerInstance->chanlist->erase(at);
250 ServerInstance->GlobalCulls.AddItem(c);
255 ServerInstance->Modes->DelMode(&p);
256 return Module::cull();
259 virtual void OnRehash(User *user)
261 ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb");
262 permchannelsconf = tag->getString("filename");
263 save_listmodes = tag->getBool("listmodes");
269 * Process config-defined list of permanent channels.
272 ConfigTagList permchannels = ServerInstance->Config->ConfTags("permchannels");
273 for (ConfigIter i = permchannels.first; i != permchannels.second; ++i)
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");
280 if ((channel.empty()) || (channel.length() > ServerInstance->Config->Limits.ChanMax))
282 ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Ignoring permchannels tag with empty or too long channel name (\"" + channel + "\")");
286 Channel *c = ServerInstance->FindChan(channel);
290 time_t TS = tag->getInt("ts");
291 c = new Channel(channel, ((TS > 0) ? TS : ServerInstance->Time()));
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
300 c->topicset = topicset;
302 ServerInstance->Logs->Log("m_permchannels", DEBUG, "Added %s with topic %s", channel.c_str(), topic.c_str());
307 irc::spacesepstream list(modes);
311 list.GetToken(modeseq);
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)
316 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
319 if (mode->GetNumParams(true))
324 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
331 virtual ModResult OnRawMode(User* user, Channel* chan, const char mode, const std::string ¶m, bool adding, int pcnt)
333 if (chan && (chan->IsModeSet('P') || mode == 'P'))
336 return MOD_RES_PASSTHRU;
339 virtual void OnPostTopicChange(User*, Channel *c, const std::string&)
341 if (c->IsModeSet('P'))
345 void OnBackgroundTimer(time_t)
348 WriteDatabase(this, save_listmodes);
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
360 static bool loaded = false;
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)
377 catch (CoreException& e)
379 ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Error loading permchannels database: " + std::string(e.GetReason()));
384 void ProtoSendMode(void* opaque, TargetTypeFlags type, void* target, const std::vector<std::string>& modes, const std::vector<TranslateType>& translate)
386 // We never pass an empty modelist but better be sure
390 ListModeData* lm = static_cast<ListModeData*>(opaque);
392 // Append the mode letters without the trailing '+' (for example "IIII", "gg")
393 lm->modes.append(modes[0].begin()+1, modes[0].end());
395 // Append the parameters
396 for (std::vector<std::string>::const_iterator i = modes.begin()+1; i != modes.end(); ++i)
403 virtual Version GetVersion()
405 return Version("Provides support for channel mode +P to provide permanent channels",VF_VENDOR);
408 virtual ModResult OnChannelPreDelete(Channel *c)
410 if (c->IsModeSet('P'))
413 return MOD_RES_PASSTHRU;
417 MODULE_INIT(ModulePermanentChannels)