]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_permchannels.cpp
Fix m_permchannels and m_xline_db on Windows
[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         remove(permchannelsconf.c_str());
160 #endif
161         // Use rename to move temporary to new db - this is guarenteed not to fuck up, even in case of a crash.
162         if (rename(tempname.c_str(), permchannelsconf.c_str()) < 0)
163         {
164                 ServerInstance->Logs->Log("m_permchannels",DEFAULT, "permchannels: Cannot move new to old database! %s (%d)", strerror(errno), errno);
165                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno);
166                 return false;
167         }
168
169         return true;
170 }
171
172
173
174 /** Handles the +P channel mode
175  */
176 class PermChannel : public ModeHandler
177 {
178  public:
179         PermChannel(Module* Creator) : ModeHandler(Creator, "permanent", 'P', PARAM_NONE, MODETYPE_CHANNEL) { oper = true; }
180
181         ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string &parameter, bool adding)
182         {
183                 if (adding)
184                 {
185                         if (!channel->IsModeSet('P'))
186                         {
187                                 channel->SetMode('P',true);
188                                 return MODEACTION_ALLOW;
189                         }
190                 }
191                 else
192                 {
193                         if (channel->IsModeSet('P'))
194                         {
195                                 channel->SetMode(this,false);
196                                 if (channel->GetUserCounter() == 0)
197                                 {
198                                         channel->DelUser(ServerInstance->FakeClient);
199                                 }
200                                 return MODEACTION_ALLOW;
201                         }
202                 }
203
204                 return MODEACTION_DENY;
205         }
206 };
207
208 class ModulePermanentChannels : public Module
209 {
210         PermChannel p;
211         bool dirty;
212         bool loaded;
213         bool save_listmodes;
214 public:
215
216         ModulePermanentChannels()
217                 : p(this), dirty(false), loaded(false)
218         {
219         }
220
221         void init()
222         {
223                 ServerInstance->Modules->AddService(p);
224                 Implementation eventlist[] = { I_OnChannelPreDelete, I_OnPostTopicChange, I_OnRawMode, I_OnRehash, I_OnBackgroundTimer };
225                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
226
227                 OnRehash(NULL);
228         }
229
230         CullResult cull()
231         {
232                 /*
233                  * DelMode can't remove the +P mode on empty channels, or it will break
234                  * merging modes with remote servers. Remove the empty channels now as
235                  * we know this is not the case.
236                  */
237                 chan_hash::iterator iter = ServerInstance->chanlist->begin();
238                 while (iter != ServerInstance->chanlist->end())
239                 {
240                         Channel* c = iter->second;
241                         if (c->GetUserCounter() == 0)
242                         {
243                                 chan_hash::iterator at = iter;
244                                 iter++;
245                                 FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(c));
246                                 ServerInstance->chanlist->erase(at);
247                                 ServerInstance->GlobalCulls.AddItem(c);
248                         }
249                         else
250                                 iter++;
251                 }
252                 ServerInstance->Modes->DelMode(&p);
253                 return Module::cull();
254         }
255
256         virtual void OnRehash(User *user)
257         {
258                 ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb");
259                 permchannelsconf = tag->getString("filename");
260                 save_listmodes = tag->getBool("listmodes");
261         }
262
263         void LoadDatabase()
264         {
265                 /*
266                  * Process config-defined list of permanent channels.
267                  * -- w00t
268                  */
269                 ConfigTagList permchannels = ServerInstance->Config->ConfTags("permchannels");
270                 for (ConfigIter i = permchannels.first; i != permchannels.second; ++i)
271                 {
272                         ConfigTag* tag = i->second;
273                         std::string channel = tag->getString("channel");
274                         std::string topic = tag->getString("topic");
275                         std::string modes = tag->getString("modes");
276
277                         if ((channel.empty()) || (channel.length() > ServerInstance->Config->Limits.ChanMax))
278                         {
279                                 ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Ignoring permchannels tag with empty or too long channel name (\"" + channel + "\")");
280                                 continue;
281                         }
282
283                         Channel *c = ServerInstance->FindChan(channel);
284
285                         if (!c)
286                         {
287                                 time_t TS = tag->getInt("ts");
288                                 c = new Channel(channel, ((TS > 0) ? TS : ServerInstance->Time()));
289
290                                 c->SetTopic(NULL, topic, true);
291                                 c->setby = tag->getString("topicsetby");
292                                 if (c->setby.empty())
293                                         c->setby = ServerInstance->Config->ServerName;
294                                 unsigned int topicset = tag->getInt("topicts");
295                                 // SetTopic() sets the topic TS to now, if there was no topicts saved then don't overwrite that with a 0
296                                 if (topicset > 0)
297                                         c->topicset = topicset;
298
299                                 ServerInstance->Logs->Log("m_permchannels", DEBUG, "Added %s with topic %s", channel.c_str(), topic.c_str());
300
301                                 if (modes.empty())
302                                         continue;
303
304                                 irc::spacesepstream list(modes);
305                                 std::string modeseq;
306                                 std::string par;
307
308                                 list.GetToken(modeseq);
309
310                                 // XXX bleh, should we pass this to the mode parser instead? ugly. --w00t
311                                 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
312                                 {
313                                         ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
314                                         if (mode)
315                                         {
316                                                 if (mode->GetNumParams(true))
317                                                         list.GetToken(par);
318                                                 else
319                                                         par.clear();
320
321                                                 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, c, par, true);
322                                         }
323                                 }
324                         }
325                 }
326         }
327
328         virtual ModResult OnRawMode(User* user, Channel* chan, const char mode, const std::string &param, bool adding, int pcnt)
329         {
330                 if (chan && (chan->IsModeSet('P') || mode == 'P'))
331                         dirty = true;
332
333                 return MOD_RES_PASSTHRU;
334         }
335
336         virtual void OnPostTopicChange(User*, Channel *c, const std::string&)
337         {
338                 if (c->IsModeSet('P'))
339                         dirty = true;
340         }
341
342         void OnBackgroundTimer(time_t)
343         {
344                 if (dirty)
345                         WriteDatabase(this, save_listmodes);
346                 dirty = false;
347         }
348
349         void Prioritize()
350         {
351                 // XXX: Load the DB here because the order in which modules are init()ed at boot is
352                 // alphabetical, this means we must wait until all modules have done their init()
353                 // to be able to set the modes they provide (e.g.: m_stripcolor is inited after us)
354                 // Prioritize() is called after all module initialization is complete, consequently
355                 // all modes are available now
356                 if (loaded)
357                         return;
358
359                 loaded = true;
360
361                 // Load only when there are no linked servers - we set the TS of the channels we
362                 // create to the current time, this can lead to desync because spanningtree has
363                 // no way of knowing what we do
364                 ProtoServerList serverlist;
365                 ServerInstance->PI->GetServerList(serverlist);
366                 if (serverlist.size() < 2)
367                 {
368                         try
369                         {
370                                 LoadDatabase();
371                         }
372                         catch (CoreException& e)
373                         {
374                                 ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Error loading permchannels database: " + std::string(e.GetReason()));
375                         }
376                 }
377         }
378
379         void ProtoSendMode(void* opaque, TargetTypeFlags type, void* target, const std::vector<std::string>& modes, const std::vector<TranslateType>& translate)
380         {
381                 // We never pass an empty modelist but better be sure
382                 if (modes.empty())
383                         return;
384
385                 ListModeData* lm = static_cast<ListModeData*>(opaque);
386
387                 // Append the mode letters without the trailing '+' (for example "IIII", "gg")
388                 lm->modes.append(modes[0].begin()+1, modes[0].end());
389
390                 // Append the parameters
391                 for (std::vector<std::string>::const_iterator i = modes.begin()+1; i != modes.end(); ++i)
392                 {
393                         lm->params += *i;
394                         lm->params += ' ';
395                 }
396         }
397
398         virtual Version GetVersion()
399         {
400                 return Version("Provides support for channel mode +P to provide permanent channels",VF_VENDOR);
401         }
402
403         virtual ModResult OnChannelPreDelete(Channel *c)
404         {
405                 if (c->IsModeSet('P'))
406                         return MOD_RES_DENY;
407
408                 return MOD_RES_PASSTHRU;
409         }
410 };
411
412 MODULE_INIT(ModulePermanentChannels)