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