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