]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_xline_db.cpp
0c2ceceb5354d761ba655093ae77f97c4b063383
[user/henk/code/inspircd.git] / src / modules / m_xline_db.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2014 Justin Crawford <Justasic@Gmail.com>
6  *   Copyright (C) 2013, 2015, 2018-2019 Sadie Powell <sadie@witchery.services>
7  *   Copyright (C) 2012-2013 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
9  *   Copyright (C) 2012, 2014 Adam <Adam@anope.org>
10  *   Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
11  *   Copyright (C) 2010 Craig Edwards <brain@inspircd.org>
12  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
13  *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
14  *
15  * This file is part of InspIRCd.  InspIRCd is free software: you can
16  * redistribute it and/or modify it under the terms of the GNU General Public
17  * License as published by the Free Software Foundation, version 2.
18  *
19  * This program is distributed in the hope that it will be useful, but WITHOUT
20  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  */
27
28
29 #include "inspircd.h"
30 #include "xline.h"
31 #include <fstream>
32
33 class ModuleXLineDB
34         : public Module
35         , public Timer
36 {
37  private:
38         bool dirty;
39         std::string xlinedbpath;
40
41  public:
42         ModuleXLineDB()
43                 : Timer(0, true)
44         {
45         }
46
47         void init() CXX11_OVERRIDE
48         {
49                 /* Load the configuration
50                  * Note:
51                  *              This is on purpose not changed on a rehash. It would be non-trivial to change the database on-the-fly.
52                  *              Imagine a scenario where the new file already exists. Merging the current XLines with the existing database is likely a bad idea
53                  *              ...and so is discarding all current in-memory XLines for the ones in the database.
54                  */
55                 ConfigTag* Conf = ServerInstance->Config->ConfValue("xlinedb");
56                 xlinedbpath = ServerInstance->Config->Paths.PrependData(Conf->getString("filename", "xline.db", 1));
57                 SetInterval(Conf->getDuration("saveperiod", 5));
58
59                 // Read xlines before attaching to events
60                 ReadDatabase();
61
62                 dirty = false;
63         }
64
65         /** Called whenever an xline is added by a local user.
66          * This method is triggered after the line is added.
67          * @param source The sender of the line or NULL for local server
68          * @param line The xline being added
69          */
70         void OnAddLine(User* source, XLine* line) CXX11_OVERRIDE
71         {
72                 if (!line->from_config)
73                         dirty = true;
74         }
75
76         /** Called whenever an xline is deleted.
77          * This method is triggered after the line is deleted.
78          * @param source The user removing the line or NULL for local server
79          * @param line the line being deleted
80          */
81         void OnDelLine(User* source, XLine* line) CXX11_OVERRIDE
82         {
83                 if (!line->from_config)
84                         dirty = true;
85         }
86
87         bool Tick(time_t) CXX11_OVERRIDE
88         {
89                 if (dirty)
90                 {
91                         if (WriteDatabase())
92                                 dirty = false;
93                 }
94                 return true;
95         }
96
97         bool WriteDatabase()
98         {
99                 /*
100                  * We need to perform an atomic write so as not to fuck things up.
101                  * So, let's write to a temporary file, flush it, then rename the file..
102                  * Technically, that means that this can block, but I have *never* seen that.
103                  *     -- w00t
104                  */
105                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Opening temporary database");
106                 std::string xlinenewdbpath = xlinedbpath + ".new";
107                 std::ofstream stream(xlinenewdbpath.c_str());
108                 if (!stream.is_open())
109                 {
110                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot create database \"%s\"! %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno);
111                         ServerInstance->SNO->WriteToSnoMask('x', "database: cannot create new xline db \"%s\": %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno);
112                         return false;
113                 }
114
115                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Opened. Writing..");
116
117                 /*
118                  * Now, much as I hate writing semi-unportable formats, additional
119                  * xline types may not have a conf tag, so let's just write them.
120                  * In addition, let's use a file version, so we can maintain some
121                  * semblance of backwards compatibility for reading on startup..
122                  *              -- w00t
123                  */
124                 stream << "VERSION 1" << std::endl;
125
126                 // Now, let's write.
127                 std::vector<std::string> types = ServerInstance->XLines->GetAllTypes();
128                 for (std::vector<std::string>::const_iterator it = types.begin(); it != types.end(); ++it)
129                 {
130                         XLineLookup* lookup = ServerInstance->XLines->GetAll(*it);
131                         if (!lookup)
132                                 continue; // Not possible as we just obtained the list from XLineManager
133
134                         for (LookupIter i = lookup->begin(); i != lookup->end(); ++i)
135                         {
136                                 XLine* line = i->second;
137                                 if (line->from_config)
138                                         continue;
139
140                                 stream << "LINE " << line->type << " " << line->Displayable() << " "
141                                         << line->source << " " << line->set_time << " "
142                                         << line->duration << " :" << line->reason << std::endl;
143                         }
144                 }
145
146                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Finished writing XLines. Checking for error..");
147
148                 if (stream.fail())
149                 {
150                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot write to new database \"%s\"! %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno);
151                         ServerInstance->SNO->WriteToSnoMask('x', "database: cannot write to new xline db \"%s\": %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno);
152                         return false;
153                 }
154                 stream.close();
155
156 #ifdef _WIN32
157                 remove(xlinedbpath.c_str());
158 #endif
159                 // Use rename to move temporary to new db - this is guaranteed not to fuck up, even in case of a crash.
160                 if (rename(xlinenewdbpath.c_str(), xlinedbpath.c_str()) < 0)
161                 {
162                         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);
163                         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);
164                         return false;
165                 }
166
167                 return true;
168         }
169
170         bool ReadDatabase()
171         {
172                 // If the xline database doesn't exist then we don't need to load it.
173                 if (!FileSystem::FileExists(xlinedbpath))
174                         return true;
175
176                 std::ifstream stream(xlinedbpath.c_str());
177                 if (!stream.is_open())
178                 {
179                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot read database \"%s\"! %s (%d)", xlinedbpath.c_str(), strerror(errno), errno);
180                         ServerInstance->SNO->WriteToSnoMask('x', "database: cannot read xline db \"%s\": %s (%d)", xlinedbpath.c_str(), strerror(errno), errno);
181                         return false;
182                 }
183
184                 std::string line;
185                 while (std::getline(stream, line))
186                 {
187                         // Inspired by the command parser. :)
188                         irc::tokenstream tokens(line);
189                         int items = 0;
190                         std::string command_p[7];
191                         std::string tmp;
192
193                         while (tokens.GetTrailing(tmp) && (items < 7))
194                         {
195                                 command_p[items] = tmp;
196                                 items++;
197                         }
198
199                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing %s", line.c_str());
200
201                         if (command_p[0] == "VERSION")
202                         {
203                                 if (command_p[1] != "1")
204                                 {
205                                         stream.close();
206                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "I got database version %s - I don't understand it", command_p[1].c_str());
207                                         ServerInstance->SNO->WriteToSnoMask('x', "database: I got a database version (%s) I don't understand", command_p[1].c_str());
208                                         return false;
209                                 }
210                         }
211                         else if (command_p[0] == "LINE")
212                         {
213                                 // Mercilessly stolen from spanningtree
214                                 XLineFactory* xlf = ServerInstance->XLines->GetFactory(command_p[1]);
215
216                                 if (!xlf)
217                                 {
218                                         ServerInstance->SNO->WriteToSnoMask('x', "database: Unknown line type (%s).", command_p[1].c_str());
219                                         continue;
220                                 }
221
222                                 XLine* xl = xlf->Generate(ServerInstance->Time(), ConvToNum<unsigned long>(command_p[5]), command_p[3], command_p[6], command_p[2]);
223                                 xl->SetCreateTime(ConvToNum<time_t>(command_p[4]));
224
225                                 if (ServerInstance->XLines->AddLine(xl, NULL))
226                                 {
227                                         ServerInstance->SNO->WriteToSnoMask('x', "database: Added a line of type %s", command_p[1].c_str());
228                                 }
229                                 else
230                                         delete xl;
231                         }
232                 }
233                 stream.close();
234                 return true;
235         }
236
237         Version GetVersion() CXX11_OVERRIDE
238         {
239                 return Version("Allows X-lines to be saved and reloaded on restart.", VF_VENDOR);
240         }
241 };
242
243 MODULE_INIT(ModuleXLineDB)