]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_xline_db.cpp
1c51258053928563b7ac3ae0c2fadb9408fac3ba
[user/henk/code/inspircd.git] / src / modules / m_xline_db.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
5  *   Copyright (C) 2008 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 #include "xline.h"
23
24 /* $ModConfig: <xlinedb filename="data/xline.db">
25  *  Specify the filename for the xline database here*/
26 /* $ModDesc: Keeps a dynamic log of all XLines created, and stores them in a seperate conf file (xline.db). */
27
28 class ModuleXLineDB : public Module
29 {
30         bool dirty;
31         std::string xlinedbpath;
32  public:
33         void init()
34         {
35                 /* Load the configuration
36                  * Note:
37                  *              this is on purpose not in the OnRehash() method. It would be non-trivial to change the database on-the-fly.
38                  *              Imagine a scenario where the new file already exists. Merging the current XLines with the existing database is likely a bad idea
39                  *              ...and so is discarding all current in-memory XLines for the ones in the database.
40                  */
41                 ConfigTag* Conf = ServerInstance->Config->ConfValue("xlinedb");
42                 xlinedbpath = Conf->getString("filename", DATA_PATH "/xline.db");
43
44                 // Read xlines before attaching to events
45                 ReadDatabase();
46
47                 Implementation eventlist[] = { I_OnAddLine, I_OnDelLine, I_OnExpireLine, I_OnBackgroundTimer };
48                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
49                 dirty = false;
50         }
51
52         virtual ~ModuleXLineDB()
53         {
54         }
55
56         /** Called whenever an xline is added by a local user.
57          * This method is triggered after the line is added.
58          * @param source The sender of the line or NULL for local server
59          * @param line The xline being added
60          */
61         void OnAddLine(User* source, XLine* line)
62         {
63                 dirty = true;
64         }
65
66         /** Called whenever an xline is deleted.
67          * This method is triggered after the line is deleted.
68          * @param source The user removing the line or NULL for local server
69          * @param line the line being deleted
70          */
71         void OnDelLine(User* source, XLine* line)
72         {
73                 dirty = true;
74         }
75
76         void OnExpireLine(XLine *line)
77         {
78                 dirty = true;
79         }
80
81         void OnBackgroundTimer(time_t now)
82         {
83                 if (dirty)
84                 {
85                         if (WriteDatabase())
86                                 dirty = false;
87                 }
88         }
89
90         bool WriteDatabase()
91         {
92                 FILE *f;
93
94                 /*
95                  * We need to perform an atomic write so as not to fuck things up.
96                  * So, let's write to a temporary file, flush and sync the FD, then rename the file..
97                  * Technically, that means that this can block, but I have *never* seen that.
98                  *              -- w00t
99                  */
100                 ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Opening temporary database");
101                 std::string xlinenewdbpath = xlinedbpath + ".new";
102                 f = fopen(xlinenewdbpath.c_str(), "w");
103                 if (!f)
104                 {
105                         ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Cannot create database! %s (%d)", strerror(errno), errno);
106                         ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new db: %s (%d)", strerror(errno), errno);
107                         return false;
108                 }
109
110                 ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Opened. Writing..");
111
112                 /*
113                  * Now, much as I hate writing semi-unportable formats, additional
114                  * xline types may not have a conf tag, so let's just write them.
115                  * In addition, let's use a file version, so we can maintain some
116                  * semblance of backwards compatibility for reading on startup..
117                  *              -- w00t
118                  */
119                 fprintf(f, "VERSION 1\n");
120
121                 // Now, let's write.
122                 std::vector<std::string> types = ServerInstance->XLines->GetAllTypes();
123                 for (std::vector<std::string>::const_iterator it = types.begin(); it != types.end(); ++it)
124                 {
125                         XLineLookup* lookup = ServerInstance->XLines->GetAll(*it);
126                         if (!lookup)
127                                 continue; // Not possible as we just obtained the list from XLineManager
128
129                         for (LookupIter i = lookup->begin(); i != lookup->end(); ++i)
130                         {
131                                 XLine* line = i->second;
132                                 fprintf(f, "LINE %s %s %s %lu %lu :%s\n", line->type.c_str(), line->Displayable(),
133                                         ServerInstance->Config->ServerName.c_str(), (unsigned long)line->set_time, (unsigned long)line->duration, line->reason.c_str());
134                         }
135                 }
136
137                 ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Finished writing XLines. Checking for error..");
138
139                 int write_error = 0;
140                 write_error = ferror(f);
141                 write_error |= fclose(f);
142                 if (write_error)
143                 {
144                         ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Cannot write to new database! %s (%d)", strerror(errno), errno);
145                         ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new db: %s (%d)", strerror(errno), errno);
146                         return false;
147                 }
148
149 #ifdef _WIN32
150                 if (remove(xlinedbpath.c_str()))
151                 {
152                         ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Cannot remove old database! %s (%d)", strerror(errno), errno);
153                         ServerInstance->SNO->WriteToSnoMask('a', "database: cannot remove old database: %s (%d)", strerror(errno), errno);
154                         return false;
155                 }
156 #endif
157                 // Use rename to move temporary to new db - this is guarenteed not to fuck up, even in case of a crash.
158                 if (rename(xlinenewdbpath.c_str(), xlinedbpath.c_str()) < 0)
159                 {
160                         ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Cannot move new to old database! %s (%d)", strerror(errno), errno);
161                         ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno);
162                         return false;
163                 }
164
165                 return true;
166         }
167
168         bool ReadDatabase()
169         {
170                 FILE *f;
171                 char linebuf[MAXBUF];
172                 unsigned int lineno = 0;
173
174                 f = fopen(xlinedbpath.c_str(), "r");
175                 if (!f)
176                 {
177                         if (errno == ENOENT)
178                         {
179                                 /* xline.db doesn't exist, fake good return value (we don't care about this) */
180                                 return true;
181                         }
182                         else
183                         {
184                                 /* this might be slightly more problematic. */
185                                 ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Cannot read database! %s (%d)", strerror(errno), errno);
186                                 ServerInstance->SNO->WriteToSnoMask('a', "database: cannot read db: %s (%d)", strerror(errno), errno);
187                                 return false;
188                         }
189                 }
190
191                 while (fgets(linebuf, MAXBUF, f))
192                 {
193                         char *c = linebuf;
194
195                         while (c && *c)
196                         {
197                                 if (*c == '\n')
198                                 {
199                                         *c = '\0';
200                                 }
201
202                                 c++;
203                         }
204                         // Smart man might think of initing to 1, and moving this to the bottom. Don't. We use continue in this loop.
205                         lineno++;
206
207                         // Inspired by the command parser. :)
208                         irc::tokenstream tokens(linebuf);
209                         int items = 0;
210                         std::string command_p[MAXPARAMETERS];
211                         std::string tmp;
212
213                         while (tokens.GetToken(tmp) && (items < MAXPARAMETERS))
214                         {
215                                 command_p[items] = tmp;
216                                 items++;
217                         }
218
219                         ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Processing %s", linebuf);
220
221                         if (command_p[0] == "VERSION")
222                         {
223                                 if (command_p[1] == "1")
224                                 {
225                                         ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Reading db version %s", command_p[1].c_str());
226                                 }
227                                 else
228                                 {
229                                         fclose(f);
230                                         ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: I got database version %s - I don't understand it", command_p[1].c_str());
231                                         ServerInstance->SNO->WriteToSnoMask('a', "database: I got a database version (%s) I don't understand", command_p[1].c_str());
232                                         return false;
233                                 }
234                         }
235                         else if (command_p[0] == "LINE")
236                         {
237                                 // Mercilessly stolen from spanningtree
238                                 XLineFactory* xlf = ServerInstance->XLines->GetFactory(command_p[1]);
239
240                                 if (!xlf)
241                                 {
242                                         ServerInstance->SNO->WriteToSnoMask('a', "database: Unknown line type (%s).", command_p[1].c_str());
243                                         continue;
244                                 }
245
246                                 XLine* xl = xlf->Generate(ServerInstance->Time(), atoi(command_p[5].c_str()), command_p[3], command_p[6], command_p[2]);
247                                 xl->SetCreateTime(atoi(command_p[4].c_str()));
248
249                                 if (ServerInstance->XLines->AddLine(xl, NULL))
250                                 {
251                                         ServerInstance->SNO->WriteToSnoMask('x', "database: Added a line of type %s", command_p[1].c_str());
252                                 }
253                                 else
254                                         delete xl;
255                         }
256                 }
257
258                 fclose(f);
259                 return true;
260         }
261
262
263
264         virtual Version GetVersion()
265         {
266                 return Version("Keeps a dynamic log of all XLines created, and stores them in a separate conf file (xline.db).", VF_VENDOR);
267         }
268 };
269
270 MODULE_INIT(ModuleXLineDB)
271