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