Walk.cxx 11.5 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 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 72 73 74 75 76 77 78 79 80 81
	directory.ForEachChildSafe([&](Directory &child){
			const auto name_fs =
				AllocatedPath::FromUTF8(child.GetName());

			if (name_fs.IsNull() || exclude_list.Check(name_fs)) {
				editor.DeleteDirectory(&child);
				modified = true;
			}
		});

	directory.ForEachSongSafe([&](Song &song){
82
			assert(&song.parent == &directory);
83

84
			const auto name_fs = AllocatedPath::FromUTF8(song.filename);
85 86 87 88 89
			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() || DirectoryExists(storage, child))
97
				return;
98

99
			editor.LockDeleteDirectory(&child);
100

101 102
			modified = true;
		});
103

104 105
	directory.ForEachSongSafe([&](Song &song){
			if (!directory_child_is_regular(storage, directory,
106
							song.filename)) {
107
				editor.LockDeleteSong(directory, &song);
108

109 110 111
				modified = true;
			}
		});
112

113 114
	for (auto i = directory.playlists.begin(),
		     end = directory.playlists.end();
115
	     i != end;) {
116
		if (!directory_child_is_regular(storage, directory, i->name)) {
117
			const ScopeDatabaseLock protect;
118
			i = directory.playlists.erase(i);
119 120
		} else
			++i;
121
	}
122 123
}

124
#ifndef _WIN32
125
static bool
126
update_directory_stat(Storage &storage, Directory &directory) noexcept
127
{
128
	StorageFileInfo info;
129 130
	if (!GetInfo(storage, directory.GetPath(), info))
		return false;
131

132 133
	directory_set_stat(directory, info);
	return true;
134
}
135
#endif
136

137 138 139 140 141 142
/**
 * 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
 */
143
static int
144
FindAncestorLoop(Storage &storage, Directory *parent,
145
		 unsigned inode, unsigned device) noexcept
146
{
147
#ifndef _WIN32
148 149 150 151 152
	if (device == 0 && inode == 0)
		/* can't detect loops if the Storage does not support
		   these numbers */
		return 0;

153
	while (parent) {
154
		if (parent->device == 0 && parent->inode == 0 &&
155
		    !update_directory_stat(storage, *parent))
156
			return -1;
157

158
		if (parent->inode == inode && parent->device == device) {
159
			LogDebug(update_domain, "recursive directory found");
160 161
			return 1;
		}
162

163 164
		parent = parent->parent;
	}
165
#else
166
	(void)storage;
167 168 169 170
	(void)parent;
	(void)inode;
	(void)device;
#endif
171 172 173 174

	return 0;
}

175 176
inline bool
UpdateWalk::UpdateRegularFile(Directory &directory,
177 178
			      const char *name,
			      const StorageFileInfo &info) noexcept
179 180
{
	const char *suffix = uri_get_suffix(name);
181
	if (suffix == nullptr)
182
		return false;
183

184 185 186
	return UpdateSongFile(directory, name, suffix, info) ||
		UpdateArchiveFile(directory, name, suffix, info) ||
		UpdatePlaylistFile(directory, name, suffix, info);
187 188
}

189 190
void
UpdateWalk::UpdateDirectoryChild(Directory &directory,
191
				 const ExcludeList &exclude_list,
192
				 const char *name, const StorageFileInfo &info) noexcept
193
try {
Rosen Penev's avatar
Rosen Penev committed
194
	assert(std::strchr(name, '/') == nullptr);
195

196 197 198
	if (info.IsRegular()) {
		UpdateRegularFile(directory, name, info);
	} else if (info.IsDirectory()) {
199
		if (FindAncestorLoop(storage, &directory,
200
					info.inode, info.device))
201 202
			return;

203 204 205 206 207
		Directory *subdir;
		{
			const ScopeDatabaseLock protect;
			subdir = directory.MakeChild(name);
		}
208

209
		assert(&directory == subdir->parent);
210

211
		if (!UpdateDirectory(*subdir, exclude_list, info))
212
			editor.LockDeleteDirectory(subdir);
213
	} else {
214 215
		FormatDebug(update_domain,
			    "%s is not a directory, archive or music", name);
216
	}
217 218
} catch (...) {
	LogError(std::current_exception());
219 220
}

221
/* we don't look at files with newlines in their name */
222
gcc_pure
223
static bool
224
skip_path(const char *name_utf8) noexcept
225
{
Rosen Penev's avatar
Rosen Penev committed
226
	return std::strchr(name_utf8, '\n') != nullptr;
227 228
}

229
gcc_pure
230 231
bool
UpdateWalk::SkipSymlink(const Directory *directory,
232
			std::string_view utf8_name) const noexcept
233
{
234
#ifndef _WIN32
235 236
	const auto path_fs = storage.MapChildFS(directory->GetPath(),
						utf8_name);
237
	if (path_fs.IsNull())
238 239
		/* not a local file: don't skip */
		return false;
240

241
	const auto target = ReadLink(path_fs);
242
	if (target.IsNull())
243 244 245
		/* don't skip if this is not a symlink */
		return errno != EINVAL;

246 247
	if (!config.follow_inside_symlinks &&
	    !config.follow_outside_symlinks) {
248 249
		/* ignore all symlinks */
		return true;
250 251
	} else if (config.follow_inside_symlinks &&
		   config.follow_outside_symlinks) {
252 253 254 255
		/* consider all symlinks */
		return false;
	}

256
	if (target.IsAbsolute()) {
257 258
		/* if the symlink points to an absolute path, see if
		   that path is inside the music directory */
259
		const auto target_utf8 = target.ToUTF8();
260 261 262
		if (target_utf8.empty())
			return true;

263
		auto relative =
264
			storage.MapToRelativeUTF8(target_utf8.c_str());
265
		return relative.data() != nullptr
266 267
			? !config.follow_inside_symlinks
			: !config.follow_outside_symlinks;
268
	}
269

270
	const char *p = target.c_str();
271
	while (*p == '.') {
272
		if (p[1] == '.' && PathTraitsFS::IsSeparator(p[2])) {
273 274
			/* "../" moves to parent directory */
			directory = directory->parent;
275
			if (directory == nullptr) {
276 277 278
				/* we have moved outside the music
				   directory - skip this symlink
				   if such symlinks are not allowed */
279
				return !config.follow_outside_symlinks;
280 281
			}
			p += 3;
282
		} else if (PathTraitsFS::IsSeparator(p[1]))
283 284 285 286 287 288 289 290 291
			/* 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*/
292
	return !config.follow_inside_symlinks;
293 294 295 296 297 298 299 300 301 302
#else
	/* no symlink checking on WIN32 */

	(void)directory;
	(void)utf8_name;

	return false;
#endif
}

303
bool
304 305
UpdateWalk::UpdateDirectory(Directory &directory,
			    const ExcludeList &exclude_list,
306
			    const StorageFileInfo &info) noexcept
307
{
308
	assert(info.IsDirectory());
309

310
	directory_set_stat(directory, info);
311

312 313 314
	std::unique_ptr<StorageDirectoryReader> reader;

	try {
315
		reader = storage.OpenDirectory(directory.GetPath());
316 317
	} catch (...) {
		LogError(std::current_exception());
318 319 320
		return false;
	}

321
	ExcludeList child_exclude_list(exclude_list);
322

323 324
	try {
		Mutex mutex;
325
		auto is = InputStream::OpenReady(storage.MapUTF8(PathTraitsUTF8::Build(directory.GetPath(),
326
										       ".mpdignore")).c_str(),
327
						 mutex);
328 329 330 331
		child_exclude_list.Load(std::move(is));
	} catch (...) {
		if (!IsFileNotFound(std::current_exception()))
			LogError(std::current_exception());
332
	}
333

334 335
	if (!child_exclude_list.IsEmpty())
		RemoveExcludedFromDirectory(directory, child_exclude_list);
336

337
	PurgeDeletedFromDirectory(directory);
338

339
	const char *name_utf8;
340
	while (!cancel && (name_utf8 = reader->Read()) != nullptr) {
341
		if (skip_path(name_utf8))
342 343
			continue;

344 345
		{
			const auto name_fs = AllocatedPath::FromUTF8(name_utf8);
346
			if (name_fs.IsNull() || child_exclude_list.Check(name_fs))
347 348 349 350 351
				continue;
		}

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

355
		StorageFileInfo info2;
356 357
		if (!GetInfo(*reader, info2)) {
			modified |= editor.DeleteNameIn(directory, name_utf8);
358 359 360
			continue;
		}

361
		UpdateDirectoryChild(directory, child_exclude_list, name_utf8, info2);
362 363
	}

364
	directory.mtime = info.mtime;
365 366 367 368

	return true;
}

369
inline Directory *
370 371
UpdateWalk::DirectoryMakeChildChecked(Directory &parent,
				      const char *uri_utf8,
372
				      std::string_view name_utf8) noexcept
373
{
374 375 376 377 378
	Directory *directory;
	{
		const ScopeDatabaseLock protect;
		directory = parent.FindChild(name_utf8);
	}
379

Max Kellermann's avatar
Max Kellermann committed
380 381 382 383
	if (directory != nullptr) {
		if (directory->IsMount())
			directory = nullptr;

384
		return directory;
Max Kellermann's avatar
Max Kellermann committed
385
	}
386

387
	StorageFileInfo info;
388
	if (!GetInfo(storage, uri_utf8, info) ||
389
	    FindAncestorLoop(storage, &parent, info.inode, info.device))
390
		return nullptr;
391

392
	if (SkipSymlink(&parent, name_utf8))
393
		return nullptr;
394

395 396
	/* if we're adding directory paths, make sure to delete filenames
	   with potentially the same name */
397 398 399 400 401
	{
		const ScopeDatabaseLock protect;
		Song *conflicting = parent.FindSong(name_utf8);
		if (conflicting)
			editor.DeleteSong(parent, conflicting);
402

403 404
		directory = parent.CreateChild(name_utf8);
	}
405

406
	directory_set_stat(*directory, info);
407 408 409
	return directory;
}

410
inline Directory *
411
UpdateWalk::DirectoryMakeUriParentChecked(Directory &root,
412
					  std::string_view _uri) noexcept
413
{
414
	Directory *directory = &root;
415
	StringView uri(_uri);
416

417 418 419 420 421
	while (true) {
		auto s = uri.Split('/');
		const std::string_view name = s.first;
		const auto rest = s.second;
		if (rest == nullptr)
422 423
			break;

424 425 426 427 428 429 430 431 432
		if (!name.empty()) {
			directory = DirectoryMakeChildChecked(*directory,
							      std::string(name).c_str(),
							      s.first);
			if (directory == nullptr)
				break;
		}

		uri = s.second;
433 434 435 436 437
	}

	return directory;
}

438
inline void
439
UpdateWalk::UpdateUri(Directory &root, const char *uri) noexcept
440
try {
441
	Directory *parent = DirectoryMakeUriParentChecked(root, uri);
442
	if (parent == nullptr)
443 444
		return;

445
	const char *name = PathTraitsUTF8::GetBase(uri);
446

447
	if (SkipSymlink(parent, name)) {
448
		modified |= editor.DeleteNameIn(*parent, name);
449 450 451
		return;
	}

452
	StorageFileInfo info;
453 454 455 456 457
	if (!GetInfo(storage, uri, info)) {
		modified |= editor.DeleteNameIn(*parent, name);
		return;
	}

458 459 460
	ExcludeList exclude_list;

	UpdateDirectoryChild(*parent, exclude_list, name, info);
461 462
} catch (...) {
	LogError(std::current_exception());
463 464 465
}

bool
466
UpdateWalk::Walk(Directory &root, const char *path, bool discard) noexcept
467
{
468
	walk_discard = discard;
469 470
	modified = false;

471
	if (path != nullptr && !isRootDirectory(path)) {
472
		UpdateUri(root, path);
473
	} else {
474
		StorageFileInfo info;
475 476
		if (!GetInfo(storage, "", info))
			return false;
477

478 479 480 481 482 483
		if (!info.IsDirectory()) {
			FormatError(update_domain, "Not a directory: %s",
				    storage.MapUTF8("").c_str());
			return false;
		}

484 485 486
		ExcludeList exclude_list;

		UpdateDirectory(root, exclude_list, info);
487 488 489 490
	}

	return modified;
}