summaryrefslogtreecommitdiff
path: root/modules/database/flatfile.cpp
blob: 1221349605347a39621a77458ef922bf8877419b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/*
 * (C) 2003-2014 Anope Team
 * Contact us at team@anope.org
 *
 * Please read COPYING and README for further details.
 *
 * Based on the original code of Epona by Lara.
 * Based on the original code of Services by Andy Church.
 */

#include "module.h"

class DBFlatFile : public Module
	, public EventHook<Event::LoadDatabase>
	, public EventHook<Event::SaveDatabase>
{
	/* Day the last backup was on */
	int last_day;
	/* Backup file names */
	std::map<Anope::string, std::list<Anope::string> > backups;
	bool loaded;

	void BackupDatabase()
	{
		tm *tm = localtime(&Anope::CurTime);

		if (tm->tm_mday != last_day)
		{
			last_day = tm->tm_mday;

			const std::map<Anope::string, Serialize::TypeBase *> &types = Serialize::TypeBase::GetTypes();

			std::set<Anope::string> dbs;
			dbs.insert(Config->GetModule(this)->Get<Anope::string>("database", "anope.db"));

			for (const std::pair<Anope::string, Serialize::TypeBase *> &p : types)
			{
				Serialize::TypeBase *stype = p.second;

				if (stype->GetOwner())
					dbs.insert("module_" + stype->GetOwner()->name + ".db");
			}


			for (std::set<Anope::string>::const_iterator it = dbs.begin(), it_end = dbs.end(); it != it_end; ++it)
			{
				const Anope::string &oldname = Anope::DataDir + "/" + *it;
				Anope::string newname = Anope::DataDir + "/backups/" + *it + "-" + stringify(tm->tm_year + 1900) + Anope::printf("-%02i-", tm->tm_mon + 1) + Anope::printf("%02i", tm->tm_mday);

				/* Backup already exists or no database to backup */
				if (Anope::IsFile(newname) || !Anope::IsFile(oldname))
					continue;

				Log(LOG_DEBUG) << "db_flatfile: Attempting to rename " << *it << " to " << newname;
				if (rename(oldname.c_str(), newname.c_str()))
				{
					Anope::string err = Anope::LastError();
					Log(this) << "Unable to back up database " << *it << " (" << err << ")!";

					if (!Config->GetModule(this)->Get<bool>("nobackupokay"))
					{
						Anope::Quitting = true;
						Anope::QuitReason = "Unable to back up database " + *it + " (" + err + ")";
					}

					continue;
				}

				backups[*it].push_back(newname);

				unsigned keepbackups = Config->GetModule(this)->Get<unsigned>("keepbackups");
				if (keepbackups > 0 && backups[*it].size() > keepbackups)
				{
					unlink(backups[*it].front().c_str());
					backups[*it].pop_front();
				}
			}
		}
	}

 public:
	DBFlatFile(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, DATABASE | VENDOR)
		, last_day(0)
		, loaded(false)
	{

	}

	EventReturn OnLoadDatabase() override
	{
		const Anope::string &db_name = Anope::DataDir + "/" + Config->GetModule(this)->Get<Anope::string>("database", "anope.db");

		std::fstream fd(db_name.c_str(), std::ios_base::in | std::ios_base::binary);
		if (!fd.is_open())
		{
			Log(this) << "Unable to open " << db_name << " for reading!";
			return EVENT_STOP;
		}

		Serialize::TypeBase *type = nullptr;
		Serialize::Object *obj = nullptr;
		for (Anope::string buf; std::getline(fd, buf.str());)
		{
			if (buf.find("OBJECT ") == 0)
			{
				Anope::string t = buf.substr(7);
				if (obj)
					Log(LOG_DEBUG) << "obj != null but got OBJECT";
				if (type)
					Log(LOG_DEBUG) << "type != null but got OBJECT";
				type = Serialize::TypeBase::Find(t);
				obj = nullptr;
			}
			else if (buf.find("ID ") == 0)
			{
				if (!type || obj)
					continue;

				try
				{
					Serialize::ID id = convertTo<Serialize::ID>(buf.substr(3));
					obj = type->Require(id);
				}
				catch (const ConvertException &)
				{
					Log(LOG_DEBUG) << "Unable to parse object id " << buf.substr(3);
				}
			}
			else if (buf.find("DATA ") == 0)
			{
				if (!type)
					continue;

				if (!obj)
					obj = type->Create();

				size_t sp = buf.find(' ', 5); // Skip DATA
				if (sp == Anope::string::npos)
					continue;

				Anope::string key = buf.substr(5, sp - 5), value = buf.substr(sp + 1);

				Serialize::FieldBase *field = type->GetField(key);
				if (field)
					field->UnserializeFromString(obj, value);
			}
			else if (buf.find("END") == 0)
			{
				type = nullptr;
				obj = nullptr;
			}
		}

		fd.close();

		loaded = true;
		return EVENT_STOP;
	}


	void OnSaveDatabase() override
	{
		BackupDatabase();

		Anope::string db_name = Anope::DataDir + "/" + Config->GetModule(this)->Get<Anope::string>("database", "anope.db");

		if (Anope::IsFile(db_name))
			rename(db_name.c_str(), (db_name + ".tmp").c_str());

		std::fstream f(db_name.c_str(), std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);

		if (!f.is_open())
		{
			Log(this) << "Unable to open " << db_name << " for writing";
		}
		else
		{
			for (std::pair<Serialize::ID, Serialize::Object *> p : Serialize::objects)
			{
				Serialize::Object *object = p.second;
				Serialize::TypeBase *s_type = object->GetSerializableType();

				f << "OBJECT " << s_type->GetName() << "\n";
				f << "ID " << object->id << "\n";
				for (Serialize::FieldBase *field : s_type->fields)
					f << "DATA " << field->GetName() << " " << field->SerializeToString(object) << "\n";
				f << "END\n";
			}
		}

		if (!f.is_open() || !f.good())
		{
			f.close();
			rename((db_name + ".tmp").c_str(), db_name.c_str());
		}
		else
		{
			f.close();
			unlink((db_name + ".tmp").c_str());
		}
	}
};

MODULE_INIT(DBFlatFile)