SimpleDatabasePlugin.cxx 10.1 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "config.h"
21
#include "SimpleDatabasePlugin.hxx"
Max Kellermann's avatar
Max Kellermann committed
22
#include "PrefixedLightSong.hxx"
23
#include "db/DatabasePlugin.hxx"
Max Kellermann's avatar
Max Kellermann committed
24 25
#include "db/Selection.hxx"
#include "db/Helpers.hxx"
26
#include "db/Stats.hxx"
27
#include "db/UniqueTags.hxx"
Max Kellermann's avatar
Max Kellermann committed
28
#include "db/LightDirectory.hxx"
29 30 31
#include "Directory.hxx"
#include "Song.hxx"
#include "DatabaseSave.hxx"
Max Kellermann's avatar
Max Kellermann committed
32 33
#include "db/DatabaseLock.hxx"
#include "db/DatabaseError.hxx"
34
#include "tag/Mask.hxx"
35 36 37
#include "fs/io/TextFile.hxx"
#include "fs/io/BufferedOutputStream.hxx"
#include "fs/io/FileOutputStream.hxx"
38
#include "fs/FileInfo.hxx"
39
#include "config/Block.hxx"
40
#include "fs/FileSystem.hxx"
Max Kellermann's avatar
Max Kellermann committed
41
#include "util/CharUtil.hxx"
42
#include "util/Domain.hxx"
43
#include "Log.hxx"
44

45
#ifdef ENABLE_ZLIB
46 47 48
#include "fs/io/GzipOutputStream.hxx"
#endif

49 50
#include <memory>

51 52
#include <errno.h>

53
static constexpr Domain simple_db_domain("simple_db");
54

55
inline SimpleDatabase::SimpleDatabase(const ConfigBlock &block)
56
	:Database(simple_db_plugin),
57
	 path(block.GetPath("path")),
58
#ifdef ENABLE_ZLIB
59
	 compress(block.GetBlockValue("compress", true)),
60
#endif
61 62 63 64 65 66 67 68
	 cache_path(block.GetPath("cache_directory")),
	 prefixed_light_song(nullptr)
{
	if (path.IsNull())
		throw std::runtime_error("No \"path\" parameter specified");

	path_utf8 = path.ToUTF8();
}
Max Kellermann's avatar
Max Kellermann committed
69

70
inline SimpleDatabase::SimpleDatabase(AllocatedPath &&_path,
71
#ifndef ENABLE_ZLIB
72 73 74
				      gcc_unused
#endif
				      bool _compress)
Max Kellermann's avatar
Max Kellermann committed
75 76 77
	:Database(simple_db_plugin),
	 path(std::move(_path)),
	 path_utf8(path.ToUTF8()),
78
#ifdef ENABLE_ZLIB
79 80
	 compress(_compress),
#endif
Max Kellermann's avatar
Max Kellermann committed
81 82 83
	 cache_path(AllocatedPath::Null()),
	 prefixed_light_song(nullptr) {
}
84

85
Database *
86
SimpleDatabase::Create(EventLoop &, EventLoop &,
87
		       gcc_unused DatabaseListener &listener,
88
		       const ConfigBlock &block)
89
{
90
	return new SimpleDatabase(block);
91 92
}

93 94
void
SimpleDatabase::Check() const
95
{
96
	assert(!path.IsNull());
97 98

	/* Check if the file exists */
99
	if (!PathExists(path)) {
100 101 102
		/* If the file doesn't exist, we can't check if we can write
		 * it, so we are going to try to get the directory path, and
		 * see if we can write a file in that */
103
		const auto dirPath = path.GetDirectoryName();
104 105

		/* Check that the parent part of the path is a directory */
106
		FileInfo fi;
107

108 109 110 111
		try {
			fi = FileInfo(dirPath);
		} catch (...) {
			std::throw_with_nested(std::runtime_error("On parent directory of db file"));
112 113
		}

114 115 116 117 118
		if (!fi.IsDirectory())
			throw std::runtime_error("Couldn't create db file \"" +
						 path_utf8 + "\" because the "
						 "parent path is not a directory");

119
#ifndef WIN32
120
		/* Check if we can write to the directory */
121
		if (!CheckAccess(dirPath, X_OK | W_OK)) {
122
			const int e = errno;
123
			const std::string dirPath_utf8 = dirPath.ToUTF8();
124
			throw FormatErrno(e, "Can't create db file in \"%s\"",
125
					  dirPath_utf8.c_str());
126
		}
127
#endif
128 129

		return;
130 131 132
	}

	/* Path exists, now check if it's a regular file */
133
	const FileInfo fi(path);
134

135 136
	if (!fi.IsRegular())
		throw std::runtime_error("db file \"" + path_utf8 + "\" is not a regular file");
137

138
#ifndef WIN32
139
	/* And check that we can write to it */
140 141
	if (!CheckAccess(path, R_OK | W_OK))
		throw FormatErrno("Can't open db file \"%s\" for reading/writing",
142
				  path_utf8.c_str());
143
#endif
144 145
}

146 147
void
SimpleDatabase::Load()
148
{
149
	assert(!path.IsNull());
150
	assert(root != nullptr);
151

152
	TextFile file(path);
153

154 155
	LogDebug(simple_db_domain, "reading DB");

156
	db_load_internal(file, *root);
157

158 159
	FileInfo fi;
	if (GetFileInfo(path, fi))
160
		mtime = fi.GetModificationTime();
161 162
}

163 164
void
SimpleDatabase::Open()
165
{
Max Kellermann's avatar
Max Kellermann committed
166 167
	assert(prefixed_light_song == nullptr);

168
	root = Directory::NewRoot();
169
	mtime = std::chrono::system_clock::time_point::min();
170

171 172 173 174
#ifndef NDEBUG
	borrowed_song_count = 0;
#endif

175
	try {
176
		Load();
177 178
	} catch (const std::exception &e) {
		LogError(e);
179

180
		delete root;
181

182
		Check();
183

184
		root = Directory::NewRoot();
185 186 187
	}
}

188 189
void
SimpleDatabase::Close()
190
{
191
	assert(root != nullptr);
Max Kellermann's avatar
Max Kellermann committed
192
	assert(prefixed_light_song == nullptr);
193
	assert(borrowed_song_count == 0);
194

195
	delete root;
196 197
}

198
const LightSong *
199
SimpleDatabase::GetSong(const char *uri) const
200
{
201
	assert(root != nullptr);
Max Kellermann's avatar
Max Kellermann committed
202
	assert(prefixed_light_song == nullptr);
203
	assert(borrowed_song_count == 0);
204

205
	ScopeDatabaseLock protect;
206 207

	auto r = root->LookupDirectory(uri);
Max Kellermann's avatar
Max Kellermann committed
208 209 210

	if (r.directory->IsMount()) {
		/* pass the request to the mounted database */
211
		protect.unlock();
Max Kellermann's avatar
Max Kellermann committed
212 213

		const LightSong *song =
214
			r.directory->mounted_database->GetSong(r.uri);
Max Kellermann's avatar
Max Kellermann committed
215 216 217 218 219 220 221 222
		if (song == nullptr)
			return nullptr;

		prefixed_light_song =
			new PrefixedLightSong(*song, r.directory->GetPath());
		return prefixed_light_song;
	}

223
	if (r.uri == nullptr)
224
		/* it's a directory */
225 226
		throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
				    "No such song");
227

228
	if (strchr(r.uri, '/') != nullptr)
229
		/* refers to a URI "below" the actual song */
230 231
		throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
				    "No such song");
232 233

	const Song *song = r.directory->FindSong(r.uri);
234
	protect.unlock();
235 236 237
	if (song == nullptr)
		throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
				    "No such song");
238 239 240

	light_song = song->Export();

241
#ifndef NDEBUG
242
	++borrowed_song_count;
243
#endif
244

245
	return &light_song;
246 247
}

248
void
249
SimpleDatabase::ReturnSong(gcc_unused const LightSong *song) const
250
{
Max Kellermann's avatar
Max Kellermann committed
251 252 253 254 255
	assert(song != nullptr);
	assert(song == &light_song || song == prefixed_light_song);

	delete prefixed_light_song;
	prefixed_light_song = nullptr;
256 257

#ifndef NDEBUG
Max Kellermann's avatar
Max Kellermann committed
258 259 260 261
	if (song == &light_song) {
		assert(borrowed_song_count > 0);
		--borrowed_song_count;
	}
262 263 264
#endif
}

265
void
266
SimpleDatabase::Visit(const DatabaseSelection &selection,
267 268
		      VisitDirectory visit_directory,
		      VisitSong visit_song,
269
		      VisitPlaylist visit_playlist) const
270
{
271 272
	ScopeDatabaseLock protect;

273 274 275 276
	auto r = root->LookupDirectory(selection.uri.c_str());
	if (r.uri == nullptr) {
		/* it's a directory */

277 278
		if (selection.recursive && visit_directory)
			visit_directory(r.directory->Export());
279

280 281 282 283
		r.directory->Walk(selection.recursive, selection.filter,
				  visit_directory, visit_song,
				  visit_playlist);
		return;
284 285 286
	}

	if (strchr(r.uri, '/') == nullptr) {
287
		if (visit_song) {
288
			Song *song = r.directory->FindSong(r.uri);
289 290
			if (song != nullptr) {
				const LightSong song2 = song->Export();
291 292
				if (selection.Match(song2))
					visit_song(song2);
293 294

				return;
295
			}
296
		}
297 298
	}

299 300
	throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
			    "No such directory");
301 302
}

303
void
304
SimpleDatabase::VisitUniqueTags(const DatabaseSelection &selection,
305
				TagType tag_type, TagMask group_mask,
306
				VisitTag visit_tag) const
307
{
308
	::VisitUniqueTags(*this, selection, tag_type, group_mask, visit_tag);
309 310
}

311 312
DatabaseStats
SimpleDatabase::GetStats(const DatabaseSelection &selection) const
313
{
314
	return ::GetStats(*this, selection);
315 316
}

317 318
void
SimpleDatabase::Save()
319
{
320 321
	{
		const ScopeDatabaseLock protect;
322

323 324
		LogDebug(simple_db_domain, "removing empty directories from DB");
		root->PruneEmpty();
325

326 327 328
		LogDebug(simple_db_domain, "sorting DB");
		root->Sort();
	}
329

330
	LogDebug(simple_db_domain, "writing DB");
331

332
	FileOutputStream fos(path);
333

334 335
	OutputStream *os = &fos;

336
#ifdef ENABLE_ZLIB
337
	std::unique_ptr<GzipOutputStream> gzip;
338
	if (compress) {
339
		gzip.reset(new GzipOutputStream(*os));
340
		os = gzip.get();
341 342 343 344
	}
#endif

	BufferedOutputStream bos(*os);
345

346
	db_save_internal(bos, *root);
347

348
	bos.Flush();
349

350
#ifdef ENABLE_ZLIB
351
	if (gzip != nullptr) {
352
		gzip->Flush();
353
		gzip.reset();
354 355 356
	}
#endif

357
	fos.Commit();
358

359 360
	FileInfo fi;
	if (GetFileInfo(path, fi))
361
		mtime = fi.GetModificationTime();
362 363
}

364 365
void
SimpleDatabase::Mount(const char *uri, Database *db)
Max Kellermann's avatar
Max Kellermann committed
366
{
367 368
#if !CLANG_CHECK_VERSION(3,6)
	/* disabled on clang due to -Wtautological-pointer-compare */
Max Kellermann's avatar
Max Kellermann committed
369 370
	assert(uri != nullptr);
	assert(db != nullptr);
371 372
#endif
	assert(*uri != 0);
Max Kellermann's avatar
Max Kellermann committed
373 374 375 376

	ScopeDatabaseLock protect;

	auto r = root->LookupDirectory(uri);
377 378 379
	if (r.uri == nullptr)
		throw DatabaseError(DatabaseErrorCode::CONFLICT,
				    "Already exists");
Max Kellermann's avatar
Max Kellermann committed
380

381 382 383
	if (strchr(r.uri, '/') != nullptr)
		throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
				    "Parent not found");
Max Kellermann's avatar
Max Kellermann committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400

	Directory *mnt = r.directory->CreateChild(r.uri);
	mnt->mounted_database = db;
}

static constexpr bool
IsSafeChar(char ch)
{
	return IsAlphaNumericASCII(ch) || ch == '-' || ch == '_' || ch == '%';
}

static constexpr bool
IsUnsafeChar(char ch)
{
	return !IsSafeChar(ch);
}

401 402
void
SimpleDatabase::Mount(const char *local_uri, const char *storage_uri)
Max Kellermann's avatar
Max Kellermann committed
403
{
404 405 406
	if (cache_path.IsNull())
		throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
				    "No 'cache_directory' configured");
Max Kellermann's avatar
Max Kellermann committed
407 408 409 410

	std::string name(storage_uri);
	std::replace_if(name.begin(), name.end(), IsUnsafeChar, '_');

411
	const auto name_fs = AllocatedPath::FromUTF8Throw(name.c_str());
412

413
#ifndef ENABLE_ZLIB
414 415
	constexpr bool compress = false;
#endif
Max Kellermann's avatar
Max Kellermann committed
416
	auto db = new SimpleDatabase(AllocatedPath::Build(cache_path,
417
							  name_fs.c_str()),
418
				     compress);
419
	try {
420
		db->Open();
421
	} catch (...) {
Max Kellermann's avatar
Max Kellermann committed
422
		delete db;
423
		throw;
Max Kellermann's avatar
Max Kellermann committed
424 425 426 427
	}

	// TODO: update the new database instance?

428 429 430
	try {
		Mount(local_uri, db);
	} catch (...) {
Max Kellermann's avatar
Max Kellermann committed
431 432
		db->Close();
		delete db;
433
		throw;
Max Kellermann's avatar
Max Kellermann committed
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
	}
}

Database *
SimpleDatabase::LockUmountSteal(const char *uri)
{
	ScopeDatabaseLock protect;

	auto r = root->LookupDirectory(uri);
	if (r.uri != nullptr || !r.directory->IsMount())
		return nullptr;

	Database *db = r.directory->mounted_database;
	r.directory->mounted_database = nullptr;
	r.directory->Delete();

	return db;
}

bool
SimpleDatabase::Unmount(const char *uri)
{
	Database *db = LockUmountSteal(uri);
	if (db == nullptr)
		return false;

	db->Close();
	delete db;
	return true;
}

465 466
const DatabasePlugin simple_db_plugin = {
	"simple",
467
	DatabasePlugin::FLAG_REQUIRE_STORAGE,
468 469
	SimpleDatabase::Create,
};