]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_permchannels.cpp
69a2826378f334ce171dfaeb551d7983dd0bcbde
[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 loaded;
218         bool save_listmodes;
219 public:
220
221         ModulePermanentChannels()
222                 : p(this), dirty(false), loaded(false)
223         {
224         }
225
226         void init()
227         {
228                 ServerInstance->Modules->AddService(p);
229                 Implementation eventlist[] = { I_OnChannelPreDelete, I_OnPostTopicChange, I_OnRawMode, I_OnRehash, I_OnBackgroundTimer };
230                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
231
232                 OnRehash(NULL);
233         }
234
235         CullResult cull()
236         {
237                 /*
238                  * DelMode can't remove the +P mode on empty channels, or it will break
239                  * merging modes with remote servers. Remove the empty channels now as
240                  * we know this is not the case.
241                  */
242                 chan_hash::iterator iter = ServerInstance->chanlist->begin();
243                 while (iter != ServerInstance->chanlist->end())
244                 {
245                         Channel* c = iter->second;
246                         if (c->GetUserCounter() == 0)
247                         {
248                                 chan_hash::iterator at = iter;
249                                 iter++;
250                                 FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(c));
251                                 ServerInstance->chanlist->erase(at);
252                                 ServerInstance->GlobalCulls.AddItem(c);
253                         }
254                         else
255                                 iter++;
256                 }
257                 ServerInstance->Modes->DelMode(&p);
258                 return Module::cull();
259         }
260
261         virtual void OnRehash(User *user)
262         {
263                 ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb");
264                 permchannelsconf = tag->getString("filename");
265                 save_listmodes = tag->getBool("listmodes");
266         }
267
268         void LoadDatabase()
269         {
270                 /*
271                  * Process config-defined list of permanent channels.
272                  * -- w00t
273                  */
274                 ConfigTagList permchannels = ServerInstance->Config->ConfTags("permchannels");
275                 for (ConfigIter i = permchannels.first; i != permchannels.second; ++i)
276                 {
277                         ConfigTag* tag = i->second;
278                         std::string channel = tag->getString("channel");
279                         std::string topic = tag->getString("topic");
280                         std::string modes = tag->getString("modes");
281
282                         if ((channel.empty()) || (channel.length() > ServerInstance->Config->Limits.ChanMax))
283                         {
284                                 ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Ignoring permchannels tag with empty or too long channel name (\"" + channel + "\")");
285                                 continue;
286                         }
287
288                         Channel *c = ServerInstance->FindChan(channel);
289
290                         if (!c)
291                         {
292                                 time_t TS = tag->getInt("ts");
293                                 c = new Channel(channel, ((TS > 0) ? TS : ServerInstance->Time()));
294
295                                 c->SetTopic(NULL, topic, true);
296                                 c->setby = tag->getString("topicsetby");
297                                 if (c->setby.empty())
298                                         c->setby = ServerInstance->Config->ServerName;
299                                 unsigned int topicset = tag->getInt("topicts");
300                                 // SetTopic() sets the topic TS to now, if there was no topicts saved then don't overwrite that with a 0
301                                 if (topicset > 0)
302                                         c->topicset = topicset;
303
304                                 ServerInstance->Logs->Log("m_permchannels", DEBUG, "Added %s with topic %s", channel.c_str(), topic.c_str());
305
306                                 if (modes.empty())
307                                         continue;
308
309                                 irc::spacesepstream list(modes);
310                                 std::string modeseq;
311                                 std::string par;
312
313                                 list.GetToken(modeseq);
314
315                                 // XXX bleh, should we pass this to the mode parser instead? ugly. --w00t
316                                 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
317                                 {
318                                         ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
319                                         if (mode)
320                                         {
321                                                 if (mode->GetNumParams(true))
322                                                         list.GetToken(par);
323                                                 else
324                                                         par.clear();
325
326                                                 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
327                                         }
328                                 }
329                         }
330                 }
331         }
332
333         virtual ModResult OnRawMode(User* user, Channel* chan, const char mode, const std::string &param, bool adding, int pcnt)
334         {
335                 if (chan && (chan->IsModeSet('P') || mode == 'P'))
336                         dirty = true;
337
338                 return MOD_RES_PASSTHRU;
339         }
340
341         virtual void OnPostTopicChange(User*, Channel *c, const std::string&)
342         {
343                 if (c->IsModeSet('P'))
344                         dirty = true;
345         }
346
347         void OnBackgroundTimer(time_t)
348         {
349                 if (dirty)
350                         WriteDatabase(this, save_listmodes);
351                 dirty = false;
352         }
353
354         void Prioritize()
355         {
356                 // XXX: Load the DB here because the order in which modules are init()ed at boot is
357                 // alphabetical, this means we must wait until all modules have done their init()
358                 // to be able to set the modes they provide (e.g.: m_stripcolor is inited after us)
359                 // Prioritize() is called after all module initialization is complete, consequently
360                 // all modes are available now
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)