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