Walk.cxx 12.7 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * 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.
 */

20
#include "Walk.hxx"
Max Kellermann's avatar
Max Kellermann committed
21
#include "UpdateIO.hxx"
22
#include "Editor.hxx"
23
#include "UpdateDomain.hxx"
Max Kellermann's avatar
Max Kellermann committed
24
#include "db/DatabaseLock.hxx"
25
#include "db/Uri.hxx"
26 27
#include "db/plugins/simple/Directory.hxx"
#include "db/plugins/simple/Song.hxx"
28
#include "storage/StorageInterface.hxx"
Max Kellermann's avatar
Max Kellermann committed
29
#include "ExcludeList.hxx"
30
#include "fs/AllocatedPath.hxx"
31
#include "fs/Traits.hxx"
32
#include "fs/FileSystem.hxx"
33
#include "storage/FileInfo.hxx"
34 35
#include "input/InputStream.hxx"
#include "input/Error.hxx"
36
#include "util/StringCompare.hxx"
Max Kellermann's avatar
Max Kellermann committed
37
#include "util/UriExtract.hxx"
38
#include "Log.hxx"
39

40
#include <cassert>
Rosen Penev's avatar
Rosen Penev committed
41
#include <cerrno>
42
#include <exception>
43 44
#include <memory>

45
#include <string.h>
46
#include <stdlib.h>
47

48 49
UpdateWalk::UpdateWalk(const UpdateConfig &_config,
		       EventLoop &_loop, DatabaseListener &_listener,
50
		       Storage &_storage) noexcept
51
	:config(_config), cancel(false),
52
	 storage(_storage),
53
	 editor(_loop, _listener)
54 55 56 57
{
}

static void
58
directory_set_stat(Directory &dir, const StorageFileInfo &info)
59
{
60 61
	dir.inode = info.inode;
	dir.device = info.device;
62 63
}

64 65
inline void
UpdateWalk::RemoveExcludedFromDirectory(Directory &directory,
66
					const ExcludeList &exclude_list) noexcept
67
{
68
	const ScopeDatabaseLock protect;
69

70
	directory.ForEachChildSafe([&](Directory &child){
71 72
		const auto name_fs =
			AllocatedPath::FromUTF8(child.GetName());
73

74 75 76 77 78
		if (name_fs.IsNull() || exclude_list.Check(name_fs)) {
			editor.DeleteDirectory(&child);
			modified = true;
		}
	});
79 80

	directory.ForEachSongSafe([&](Song &song){
81 82 83 84 85 86 87 88
		assert(&song.parent == &directory);

		const auto name_fs = AllocatedPath::FromUTF8(song.filename);
		if (name_fs.IsNull() || exclude_list.Check(name_fs)) {
			editor.DeleteSong(directory, &song);
			modified = true;
		}
	});
89 90
}

91
inline void
92
UpdateWalk::PurgeDeletedFromDirectory(Directory &directory) noexcept
93
{
94
	directory.ForEachChildSafe([&](Directory &child){
95
		if (child.IsMount())
96
			/* mount points are always preserved */
97 98 99 100
			return;

		if (DirectoryExists(storage, child) &&
		    child.IsPluginAvailable())
101
			return;
102

103 104 105
		/* the directory was deleted (or the plugin which
		   handles this "virtual" directory is unavailable) */

106
		editor.LockDeleteDirectory(&child);
107

108 109
		modified = true;
	});
110

111
	directory.ForEachSongSafe([&](Song &song){
112
		if (!directory_child_is_regular(storage, directory,
113 114 115 116 117
						song.filename) ||
		    !song.IsPluginAvailable()) {
			/* the song file was deleted (or the decoder
			   plugin is unavailable) */

118
			editor.LockDeleteSong(directory, &song);
119

120 121 122
			modified = true;
		}
	});
123

124 125
	for (auto i = directory.playlists.begin(),
		     end = directory.playlists.end();
126
	     i != end;) {
127
		if (!directory_child_is_regular(storage, directory, i->name)) {
128
			const ScopeDatabaseLock protect;
129
			i = directory.playlists.erase(i);
130 131
		} else
			++i;
132
	}
133 134
}

135
#ifndef _WIN32
136
static bool
137
update_directory_stat(Storage &storage, Directory &directory) noexcept
138
{
139
	StorageFileInfo info;
140 141
	if (!GetInfo(storage, directory.GetPath(), info))
		return false;
142

143 144
	directory_set_stat(directory, info);
	return true;
145
}
146
#endif
147

148 149 150 151 152 153
/**
 * Check the ancestors of the given #Directory and see if there's one
 * with the same device/inode number, building a loop.
 *
 * @return 1 if a loop was found, 0 if not, -1 on I/O error
 */
154
static int
155
FindAncestorLoop(Storage &storage, Directory *parent,
156
		 unsigned inode, unsigned device) noexcept
157
{
158
#ifndef _WIN32
159 160 161 162 163
	if (device == 0 && inode == 0)
		/* can't detect loops if the Storage does not support
		   these numbers */
		return 0;

164
	while (parent) {
165
		if (parent->device == 0 && parent->inode == 0 &&
166
		    !update_directory_stat(storage, *parent))
167
			return -1;
168

169
		if (parent->inode == inode && parent->device == device) {
170
			LogDebug(update_domain, "recursive directory found");
171 172
			return 1;
		}
173

174 175
		parent = parent->parent;
	}
176
#else
177
	(void)storage;
178 179 180 181
	(void)parent;
	(void)inode;
	(void)device;
#endif
182 183 184 185

	return 0;
}

186 187
inline bool
UpdateWalk::UpdateRegularFile(Directory &directory,
188 189
			      const char *name,
			      const StorageFileInfo &info) noexcept
190
{
191 192
	const auto suffix = uri_get_suffix(name);
	if (suffix.empty())
193
		return false;
194

195 196 197
	return UpdateSongFile(directory, name, suffix, info) ||
		UpdateArchiveFile(directory, name, suffix, info) ||
		UpdatePlaylistFile(directory, name, suffix, info);
198 199
}

200 201
void
UpdateWalk::UpdateDirectoryChild(Directory &directory,
202
				 const ExcludeList &exclude_list,
203
				 const char *name, const StorageFileInfo &info) noexcept
204
try {
Rosen Penev's avatar
Rosen Penev committed
205
	assert(std::strchr(name, '/') == nullptr);
206

207 208 209
	if (info.IsRegular()) {
		UpdateRegularFile(directory, name, info);
	} else if (info.IsDirectory()) {
210
		if (FindAncestorLoop(storage, &directory,
211
					info.inode, info.device))
212 213
			return;

214 215 216 217 218
		Directory *subdir;
		{
			const ScopeDatabaseLock protect;
			subdir = directory.MakeChild(name);
		}
219

220
		assert(&directory == subdir->parent);
221

222
		if (!UpdateDirectory(*subdir, exclude_list, info))
223
			editor.LockDeleteDirectory(subdir);
224
	} else {
225 226
		FmtDebug(update_domain,
			 "{} is not a directory, archive or music", name);
227
	}
228 229
} catch (...) {
	LogError(std::current_exception());
230 231
}

232
/* we don't look at files with newlines in their name */
233
gcc_pure
234
static bool
235
skip_path(const char *name_utf8) noexcept
236
{
Rosen Penev's avatar
Rosen Penev committed
237
	return std::strchr(name_utf8, '\n') != nullptr;
238 239
}

240
gcc_pure
241 242
bool
UpdateWalk::SkipSymlink(const Directory *directory,
243
			std::string_view utf8_name) const noexcept
244
{
245
#ifndef _WIN32
246 247
	const auto path_fs = storage.MapChildFS(directory->GetPath(),
						utf8_name);
248
	if (path_fs.IsNull())
249 250
		/* not a local file: don't skip */
		return false;
251

252
	const auto target = ReadLink(path_fs);
253
	if (target.IsNull())
254 255 256
		/* don't skip if this is not a symlink */
		return errno != EINVAL;

257 258
	if (!config.follow_inside_symlinks &&
	    !config.follow_outside_symlinks) {
259 260
		/* ignore all symlinks */
		return true;
261 262
	} else if (config.follow_inside_symlinks &&
		   config.follow_outside_symlinks) {
263 264 265 266
		/* consider all symlinks */
		return false;
	}

267
	if (target.IsAbsolute()) {
268 269
		/* if the symlink points to an absolute path, see if
		   that path is inside the music directory */
270
		const auto target_utf8 = target.ToUTF8();
271 272 273
		if (target_utf8.empty())
			return true;

274
		auto relative =
275
			storage.MapToRelativeUTF8(target_utf8.c_str());
276
		return relative.data() != nullptr
277 278
			? !config.follow_inside_symlinks
			: !config.follow_outside_symlinks;
279
	}
280

281
	const char *p = target.c_str();
282
	while (*p == '.') {
283
		if (p[1] == '.' && PathTraitsFS::IsSeparator(p[2])) {
284 285
			/* "../" moves to parent directory */
			directory = directory->parent;
286
			if (directory == nullptr) {
287 288 289
				/* we have moved outside the music
				   directory - skip this symlink
				   if such symlinks are not allowed */
290
				return !config.follow_outside_symlinks;
291 292
			}
			p += 3;
293
		} else if (PathTraitsFS::IsSeparator(p[1]))
294 295 296 297 298 299 300 301 302
			/* eliminate "./" */
			p += 2;
		else
			break;
	}

	/* we are still in the music directory, so this symlink points
	   to a song which is already in the database - skip according
	   to the follow_inside_symlinks param*/
303
	return !config.follow_inside_symlinks;
304 305 306 307 308 309 310 311 312 313
#else
	/* no symlink checking on WIN32 */

	(void)directory;
	(void)utf8_name;

	return false;
#endif
}

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
static void
LoadExcludeListOrThrow(const Storage &storage, const Directory &directory,
		       ExcludeList &exclude_list)
{
	Mutex mutex;
	auto is = InputStream::OpenReady(storage.MapUTF8(PathTraitsUTF8::Build(directory.GetPath(),
									       ".mpdignore")).c_str(),
					 mutex);
	exclude_list.Load(std::move(is));
}

static void
LoadExcludeListOrLog(const Storage &storage, const Directory &directory,
		     ExcludeList &exclude_list) noexcept
{
	try {
		LoadExcludeListOrThrow(storage, directory, exclude_list);
	} catch (...) {
		if (!IsFileNotFound(std::current_exception()))
			LogError(std::current_exception());
	}
}

337
bool
338 339
UpdateWalk::UpdateDirectory(Directory &directory,
			    const ExcludeList &exclude_list,
340
			    const StorageFileInfo &info) noexcept
341
{
342
	assert(info.IsDirectory());
343

344
	directory_set_stat(directory, info);
345

346 347 348
	std::unique_ptr<StorageDirectoryReader> reader;

	try {
349
		reader = storage.OpenDirectory(directory.GetPath());
350 351
	} catch (...) {
		LogError(std::current_exception());
352 353 354
		return false;
	}

355
	ExcludeList child_exclude_list(exclude_list);
356
	LoadExcludeListOrLog(storage, directory, child_exclude_list);
357

358 359
	if (!child_exclude_list.IsEmpty())
		RemoveExcludedFromDirectory(directory, child_exclude_list);
360

361
	PurgeDeletedFromDirectory(directory);
362

363
	const char *name_utf8;
364
	while (!cancel && (name_utf8 = reader->Read()) != nullptr) {
365
		if (skip_path(name_utf8))
366 367
			continue;

368 369
		{
			const auto name_fs = AllocatedPath::FromUTF8(name_utf8);
370
			if (name_fs.IsNull() || child_exclude_list.Check(name_fs))
371 372 373 374 375
				continue;
		}

		if (SkipSymlink(&directory, name_utf8)) {
			modified |= editor.DeleteNameIn(directory, name_utf8);
Max Kellermann's avatar
Max Kellermann committed
376
			continue;
377
		}
Max Kellermann's avatar
Max Kellermann committed
378

379
		StorageFileInfo info2;
380 381
		if (!GetInfo(*reader, info2)) {
			modified |= editor.DeleteNameIn(directory, name_utf8);
382 383 384
			continue;
		}

385
		UpdateDirectoryChild(directory, child_exclude_list, name_utf8, info2);
386 387
	}

388
	directory.mtime = info.mtime;
389 390 391 392

	return true;
}

393
inline Directory *
394 395
UpdateWalk::DirectoryMakeChildChecked(Directory &parent,
				      const char *uri_utf8,
396
				      std::string_view name_utf8) noexcept
397
{
398 399 400 401 402
	Directory *directory;
	{
		const ScopeDatabaseLock protect;
		directory = parent.FindChild(name_utf8);
	}
403

Max Kellermann's avatar
Max Kellermann committed
404 405 406 407
	if (directory != nullptr) {
		if (directory->IsMount())
			directory = nullptr;

408
		return directory;
Max Kellermann's avatar
Max Kellermann committed
409
	}
410

411
	StorageFileInfo info;
412
	if (!GetInfo(storage, uri_utf8, info) ||
413
	    FindAncestorLoop(storage, &parent, info.inode, info.device))
414
		return nullptr;
415

416
	if (SkipSymlink(&parent, name_utf8))
417
		return nullptr;
418

419 420
	/* if we're adding directory paths, make sure to delete filenames
	   with potentially the same name */
421 422 423 424 425
	{
		const ScopeDatabaseLock protect;
		Song *conflicting = parent.FindSong(name_utf8);
		if (conflicting)
			editor.DeleteSong(parent, conflicting);
426

427 428
		directory = parent.CreateChild(name_utf8);
	}
429

430
	directory_set_stat(*directory, info);
431 432 433
	return directory;
}

434
inline Directory *
435
UpdateWalk::DirectoryMakeUriParentChecked(Directory &root,
436
					  std::string_view _uri) noexcept
437
{
438
	Directory *directory = &root;
439
	StringView uri(_uri);
440

441
	while (true) {
442
		auto [name, rest] = uri.Split('/');
443
		if (rest == nullptr)
444 445
			break;

446 447 448
		if (!name.empty()) {
			directory = DirectoryMakeChildChecked(*directory,
							      std::string(name).c_str(),
449
							      name);
450 451 452 453
			if (directory == nullptr)
				break;
		}

454
		uri = rest;
455 456 457 458 459
	}

	return directory;
}

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
static void
LoadExcludeLists(std::forward_list<ExcludeList> &lists,
		 const Storage &storage, const Directory &directory) noexcept
{
	assert(!lists.empty());

	if (!directory.IsRoot())
		LoadExcludeLists(lists, storage, *directory.parent);

	lists.emplace_front();
	LoadExcludeListOrLog(storage, directory, lists.front());
}

static auto
LoadExcludeLists(const Storage &storage, const Directory &directory) noexcept
{
	std::forward_list<ExcludeList> lists;
	lists.emplace_front();
	LoadExcludeLists(lists, storage, directory);
	return lists;
}

482
inline void
483
UpdateWalk::UpdateUri(Directory &root, const char *uri) noexcept
484
try {
485
	Directory *parent = DirectoryMakeUriParentChecked(root, uri);
486
	if (parent == nullptr)
487 488
		return;

489
	const char *name = PathTraitsUTF8::GetBase(uri);
490

491
	if (SkipSymlink(parent, name)) {
492
		modified |= editor.DeleteNameIn(*parent, name);
493 494 495
		return;
	}

496
	StorageFileInfo info;
497 498 499 500 501
	if (!GetInfo(storage, uri, info)) {
		modified |= editor.DeleteNameIn(*parent, name);
		return;
	}

502 503
	const auto exclude_lists = LoadExcludeLists(storage, *parent);
	UpdateDirectoryChild(*parent, exclude_lists.front(), name, info);
504 505
} catch (...) {
	LogError(std::current_exception());
506 507 508
}

bool
509
UpdateWalk::Walk(Directory &root, const char *path, bool discard) noexcept
510
{
511
	walk_discard = discard;
512 513
	modified = false;

514
	if (path != nullptr && !isRootDirectory(path)) {
515
		UpdateUri(root, path);
516
	} else {
517
		StorageFileInfo info;
518 519
		if (!GetInfo(storage, "", info))
			return false;
520

521
		if (!info.IsDirectory()) {
522 523
			FmtError(update_domain, "Not a directory: {}",
				 storage.MapUTF8(""));
524 525 526
			return false;
		}

527 528 529
		ExcludeList exclude_list;

		UpdateDirectory(root, exclude_list, info);
530 531
	}

532 533 534 535 536
	{
		const ScopeDatabaseLock protect;
		PurgeDanglingFromPlaylists(root);
	}

537 538
	return modified;
}