Walk.cxx 11.8 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/Alloc.hxx"
37
#include "util/StringCompare.hxx"
Max Kellermann's avatar
Max Kellermann committed
38
#include "util/UriExtract.hxx"
39
#include "Log.hxx"
40

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

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

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

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

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

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

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

	directory.ForEachSongSafe([&](Song &song){
82 83 84 85 86 87 88 89
		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;
		}
	});
90 91
}

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

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

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

107
		editor.LockDeleteDirectory(&child);
108

109 110
		modified = true;
	});
111

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

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

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

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

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

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

149 150 151 152 153 154
/**
 * 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
 */
155
static int
156
FindAncestorLoop(Storage &storage, Directory *parent,
157
		 unsigned inode, unsigned device) noexcept
158
{
159
#ifndef _WIN32
160 161 162 163 164
	if (device == 0 && inode == 0)
		/* can't detect loops if the Storage does not support
		   these numbers */
		return 0;

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

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

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

	return 0;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

282
	const char *p = target.c_str();
283
	while (*p == '.') {
284
		if (p[1] == '.' && PathTraitsFS::IsSeparator(p[2])) {
285 286
			/* "../" moves to parent directory */
			directory = directory->parent;
287
			if (directory == nullptr) {
288 289 290
				/* we have moved outside the music
				   directory - skip this symlink
				   if such symlinks are not allowed */
291
				return !config.follow_outside_symlinks;
292 293
			}
			p += 3;
294
		} else if (PathTraitsFS::IsSeparator(p[1]))
295 296 297 298 299 300 301 302 303
			/* 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*/
304
	return !config.follow_inside_symlinks;
305 306 307 308 309 310 311 312 313 314
#else
	/* no symlink checking on WIN32 */

	(void)directory;
	(void)utf8_name;

	return false;
#endif
}

315
bool
316 317
UpdateWalk::UpdateDirectory(Directory &directory,
			    const ExcludeList &exclude_list,
318
			    const StorageFileInfo &info) noexcept
319
{
320
	assert(info.IsDirectory());
321

322
	directory_set_stat(directory, info);
323

324 325 326
	std::unique_ptr<StorageDirectoryReader> reader;

	try {
327
		reader = storage.OpenDirectory(directory.GetPath());
328 329
	} catch (...) {
		LogError(std::current_exception());
330 331 332
		return false;
	}

333
	ExcludeList child_exclude_list(exclude_list);
334

335 336
	try {
		Mutex mutex;
337
		auto is = InputStream::OpenReady(storage.MapUTF8(PathTraitsUTF8::Build(directory.GetPath(),
338
										       ".mpdignore")).c_str(),
339
						 mutex);
340 341 342 343
		child_exclude_list.Load(std::move(is));
	} catch (...) {
		if (!IsFileNotFound(std::current_exception()))
			LogError(std::current_exception());
344
	}
345

346 347
	if (!child_exclude_list.IsEmpty())
		RemoveExcludedFromDirectory(directory, child_exclude_list);
348

349
	PurgeDeletedFromDirectory(directory);
350

351
	const char *name_utf8;
352
	while (!cancel && (name_utf8 = reader->Read()) != nullptr) {
353
		if (skip_path(name_utf8))
354 355
			continue;

356 357
		{
			const auto name_fs = AllocatedPath::FromUTF8(name_utf8);
358
			if (name_fs.IsNull() || child_exclude_list.Check(name_fs))
359 360 361 362 363
				continue;
		}

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

367
		StorageFileInfo info2;
368 369
		if (!GetInfo(*reader, info2)) {
			modified |= editor.DeleteNameIn(directory, name_utf8);
370 371 372
			continue;
		}

373
		UpdateDirectoryChild(directory, child_exclude_list, name_utf8, info2);
374 375
	}

376
	directory.mtime = info.mtime;
377 378 379 380

	return true;
}

381
inline Directory *
382 383
UpdateWalk::DirectoryMakeChildChecked(Directory &parent,
				      const char *uri_utf8,
384
				      std::string_view name_utf8) noexcept
385
{
386 387 388 389 390
	Directory *directory;
	{
		const ScopeDatabaseLock protect;
		directory = parent.FindChild(name_utf8);
	}
391

Max Kellermann's avatar
Max Kellermann committed
392 393 394 395
	if (directory != nullptr) {
		if (directory->IsMount())
			directory = nullptr;

396
		return directory;
Max Kellermann's avatar
Max Kellermann committed
397
	}
398

399
	StorageFileInfo info;
400
	if (!GetInfo(storage, uri_utf8, info) ||
401
	    FindAncestorLoop(storage, &parent, info.inode, info.device))
402
		return nullptr;
403

404
	if (SkipSymlink(&parent, name_utf8))
405
		return nullptr;
406

407 408
	/* if we're adding directory paths, make sure to delete filenames
	   with potentially the same name */
409 410 411 412 413
	{
		const ScopeDatabaseLock protect;
		Song *conflicting = parent.FindSong(name_utf8);
		if (conflicting)
			editor.DeleteSong(parent, conflicting);
414

415 416
		directory = parent.CreateChild(name_utf8);
	}
417

418
	directory_set_stat(*directory, info);
419 420 421
	return directory;
}

422
inline Directory *
423
UpdateWalk::DirectoryMakeUriParentChecked(Directory &root,
424
					  std::string_view _uri) noexcept
425
{
426
	Directory *directory = &root;
427
	StringView uri(_uri);
428

429
	while (true) {
430
		auto [name, rest] = uri.Split('/');
431
		if (rest == nullptr)
432 433
			break;

434 435 436
		if (!name.empty()) {
			directory = DirectoryMakeChildChecked(*directory,
							      std::string(name).c_str(),
437
							      name);
438 439 440 441
			if (directory == nullptr)
				break;
		}

442
		uri = rest;
443 444 445 446 447
	}

	return directory;
}

448
inline void
449
UpdateWalk::UpdateUri(Directory &root, const char *uri) noexcept
450
try {
451
	Directory *parent = DirectoryMakeUriParentChecked(root, uri);
452
	if (parent == nullptr)
453 454
		return;

455
	const char *name = PathTraitsUTF8::GetBase(uri);
456

457
	if (SkipSymlink(parent, name)) {
458
		modified |= editor.DeleteNameIn(*parent, name);
459 460 461
		return;
	}

462
	StorageFileInfo info;
463 464 465 466 467
	if (!GetInfo(storage, uri, info)) {
		modified |= editor.DeleteNameIn(*parent, name);
		return;
	}

468 469 470
	ExcludeList exclude_list;

	UpdateDirectoryChild(*parent, exclude_list, name, info);
471 472
} catch (...) {
	LogError(std::current_exception());
473 474 475
}

bool
476
UpdateWalk::Walk(Directory &root, const char *path, bool discard) noexcept
477
{
478
	walk_discard = discard;
479 480
	modified = false;

481
	if (path != nullptr && !isRootDirectory(path)) {
482
		UpdateUri(root, path);
483
	} else {
484
		StorageFileInfo info;
485 486
		if (!GetInfo(storage, "", info))
			return false;
487

488 489 490 491 492 493
		if (!info.IsDirectory()) {
			FormatError(update_domain, "Not a directory: %s",
				    storage.MapUTF8("").c_str());
			return false;
		}

494 495 496
		ExcludeList exclude_list;

		UpdateDirectory(root, exclude_list, info);
497 498 499 500
	}

	return modified;
}