]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_xline_db.cpp
00605f259373898a2fe890ee54db10017d7ada58
[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 #include <fstream>
24
25 class ModuleXLineDB
26         : public Module
27         , public Timer
28 {
29  private:
30         bool dirty;
31         std::string xlinedbpath;
32
33  public:
34         ModuleXLineDB()
35                 : Timer(0, true)
36         {
37         }
38
39         void init() CXX11_OVERRIDE
40         {
41                 /* Load the configuration
42                  * Note:
43                  *              This is on purpose not changed on a rehash. It would be non-trivial to change the database on-the-fly.
44                  *              Imagine a scenario where the new file already exists. Merging the current XLines with the existing database is likely a bad idea
45                  *              ...and so is discarding all current in-memory XLines for the ones in the database.
46                  */
47                 ConfigTag* Conf = ServerInstance->Config->ConfValue("xlinedb");
48                 xlinedbpath = ServerInstance->Config->Paths.PrependData(Conf->getString("filename", "xline.db"));
49                 SetInterval(Conf->getDuration("saveperiod", 5));
50
51                 // Read xlines before attaching to events
52                 ReadDatabase();
53
54                 dirty = false;
55         }
56
57         /** Called whenever an xline is added by a local user.
58          * This method is triggered after the line is added.
59          * @param source The sender of the line or NULL for local server
60          * @param line The xline being added
61          */
62         void OnAddLine(User* source, XLine* line) CXX11_OVERRIDE
63         {
64                 if (!line->from_config)
65                         dirty = true;
66         }
67
68         /** Called whenever an xline is deleted.
69          * This method is triggered after the line is deleted.
70          * @param source The user removing the line or NULL for local server
71          * @param line the line being deleted
72          */
73         void OnDelLine(User* source, XLine* line) CXX11_OVERRIDE
74         {
75                 if (!line->from_config)
76                         dirty = true;
77         }
78
79         bool Tick(time_t) CXX11_OVERRIDE
80         {
81                 if (dirty)
82                 {
83                         if (WriteDatabase())
84                                 dirty = false;
85                 }
86                 return true;
87         }
88
89         bool WriteDatabase()
90         {
91                 /*
92                  * We need to perform an atomic write so as not to fuck things up.
93                  * So, let's write to a temporary file, flush it, then rename the file..
94                  * Technically, that means that this can block, but I have *never* seen that.
95                  *     -- w00t
96                  */
97                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Opening temporary database");
98                 std::string xlinenewdbpath = xlinedbpath + ".new";
99                 std::ofstream stream(xlinenewdbpath.c_str());
100                 if (!stream.is_open())
101                 {
102                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot create database \"%s\"! %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno);
103                         ServerInstance->SNO->WriteToSnoMask('x', "database: cannot create new xline db \"%s\": %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno);
104                         return false;
105                 }
106
107                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Opened. Writing..");
108
109                 /*
110                  * Now, much as I hate writing semi-unportable formats, additional
111                  * xline types may not have a conf tag, so let's just write them.
112                  * In addition, let's use a file version, so we can maintain some
113                  * semblance of backwards compatibility for reading on startup..
114                  *              -- w00t
115                  */
116                 stream << "VERSION 1" << std::endl;
117
118                 // Now, let's write.
119                 std::vector<std::string> types = ServerInstance->XLines->GetAllTypes();
120                 for (std::vector<std::string>::const_iterator it = types.begin(); it != types.end(); ++it)
121                 {
122                         XLineLookup* lookup = ServerInstance->XLines->GetAll(*it);
123                         if (!lookup)
124                                 continue; // Not possible as we just obtained the list from XLineManager
125
126                         for (LookupIter i = lookup->begin(); i != lookup->end(); ++i)
127                         {
128                                 XLine* line = i->second;
129                                 if (line->from_config)
130                                         continue;
131
132                                 stream << "LINE " << line->type << " " << line->Displayable() << " "
133                                         << line->source << " " << line->set_time << " "
134                                         << line->duration << " :" << line->reason << std::endl;
135                         }
136                 }
137
138                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Finished writing XLines. Checking for error..");
139
140                 if (stream.fail())
141                 {
142                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot write to new database \"%s\"! %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno);
143                         ServerInstance->SNO->WriteToSnoMask('x', "database: cannot write to new xline db \"%s\": %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno);
144                         return false;
145                 }
146                 stream.close();
147
148 #ifdef _WIN32
149                 remove(xlinedbpath.c_str());
150 #endif
151                 // Use rename to move temporary to new db - this is guarenteed not to fuck up, even in case of a crash.
152                 if (rename(xlinenewdbpath.c_str(), xlinedbpath.c_str()) < 0)
153                 {
154                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot replace old database \"%s\" with new database \"%s\"! %s (%d)", xlinedbpath.c_str(), xlinenewdbpath.c_str(), strerror(errno), errno);
155                         ServerInstance->SNO->WriteToSnoMask('x', "database: cannot replace old xline db \"%s\" with new db \"%s\": %s (%d)", xlinedbpath.c_str(), xlinenewdbpath.c_str(), strerror(errno), errno);
156                         return false;
157                 }
158
159                 return true;
160         }
161
162         bool ReadDatabase()
163         {
164                 // If the xline database doesn't exist then we don't need to load it.
165                 if (!FileSystem::FileExists(xlinedbpath))
166                         return true;
167
168                 std::ifstream stream(xlinedbpath.c_str());
169                 if (!stream.is_open())
170                 {
171                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot read database \"%s\"! %s (%d)", xlinedbpath.c_str(), strerror(errno), errno);
172                         ServerInstance->SNO->WriteToSnoMask('x', "database: cannot read xline db \"%s\": %s (%d)", xlinedbpath.c_str(), strerror(errno), errno);
173                         return false;
174                 }
175
176                 std::string line;
177                 while (std::getline(stream, line))
178                 {
179                         // Inspired by the command parser. :)
180                         irc::tokenstream tokens(line);
181                         int items = 0;
182                         std::string command_p[7];
183                         std::string tmp;
184
185                         while (tokens.GetTrailing(tmp) && (items < 7))
186                         {
187                                 command_p[items] = tmp;
188                                 items++;
189                         }
190
191                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing %s", line.c_str());
192
193                         if (command_p[0] == "VERSION")
194                         {
195                                 if (command_p[1] != "1")
196                                 {
197                                         stream.close();
198                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "I got database version %s - I don't understand it", command_p[1].c_str());
199                                         ServerInstance->SNO->WriteToSnoMask('x', "database: I got a database version (%s) I don't understand", command_p[1].c_str());
200                                         return false;
201                                 }
202                         }
203                         else if (command_p[0] == "LINE")
204                         {
205                                 // Mercilessly stolen from spanningtree
206                                 XLineFactory* xlf = ServerInstance->XLines->GetFactory(command_p[1]);
207
208                                 if (!xlf)
209                                 {
210                                         ServerInstance->SNO->WriteToSnoMask('x', "database: Unknown line type (%s).", command_p[1].c_str());
211                                         continue;
212                                 }
213
214                                 XLine* xl = xlf->Generate(ServerInstance->Time(), atoi(command_p[5].c_str()), command_p[3], command_p[6], command_p[2]);
215                                 xl->SetCreateTime(atoi(command_p[4].c_str()));
216
217                                 if (ServerInstance->XLines->AddLine(xl, NULL))
218                                 {
219                                         ServerInstance->SNO->WriteToSnoMask('x', "database: Added a line of type %s", command_p[1].c_str());
220                                 }
221                                 else
222                                         delete xl;
223                         }
224                 }
225                 stream.close();
226                 return true;
227         }
228
229         Version GetVersion() CXX11_OVERRIDE
230         {
231                 return Version("Provides the ability to store X-lines in a database file", VF_VENDOR);
232         }
233 };
234
235 MODULE_INIT(ModuleXLineDB)