Walk.cxx 12 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
 * 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 "config.h" /* must be first for large file support */
21
#include "Walk.hxx"
Max Kellermann's avatar
Max Kellermann committed
22
#include "UpdateIO.hxx"
23
#include "Editor.hxx"
24
#include "UpdateDomain.hxx"
Max Kellermann's avatar
Max Kellermann committed
25
#include "db/DatabaseLock.hxx"
26
#include "db/PlaylistVector.hxx"
27
#include "db/Uri.hxx"
28 29
#include "db/plugins/simple/Directory.hxx"
#include "db/plugins/simple/Song.hxx"
30
#include "storage/StorageInterface.hxx"
31
#include "playlist/PlaylistRegistry.hxx"
Max Kellermann's avatar
Max Kellermann committed
32
#include "ExcludeList.hxx"
33 34
#include "config/ConfigGlobal.hxx"
#include "config/ConfigOption.hxx"
35
#include "fs/AllocatedPath.hxx"
36
#include "fs/Traits.hxx"
37
#include "fs/FileSystem.hxx"
38
#include "storage/FileInfo.hxx"
39 40 41
#include "input/InputStream.hxx"
#include "input/Error.hxx"
#include "thread/Cond.hxx"
42
#include "util/Alloc.hxx"
43
#include "util/StringCompare.hxx"
Max Kellermann's avatar
Max Kellermann committed
44
#include "util/UriUtil.hxx"
45
#include "Log.hxx"
46

47 48 49
#include <stdexcept>
#include <memory>

50 51
#include <assert.h>
#include <string.h>
52
#include <stdlib.h>
53 54
#include <errno.h>

55
UpdateWalk::UpdateWalk(EventLoop &_loop, DatabaseListener &_listener,
56
		       Storage &_storage)
57 58
	:cancel(false),
	 storage(_storage),
59
	 editor(_loop, _listener)
60
{
61
#ifndef _WIN32
62
	follow_inside_symlinks =
63
		config_get_bool(ConfigOption::FOLLOW_INSIDE_SYMLINKS,
64 65 66
				DEFAULT_FOLLOW_INSIDE_SYMLINKS);

	follow_outside_symlinks =
67
		config_get_bool(ConfigOption::FOLLOW_OUTSIDE_SYMLINKS,
68 69 70 71 72
				DEFAULT_FOLLOW_OUTSIDE_SYMLINKS);
#endif
}

static void
73
directory_set_stat(Directory &dir, const StorageFileInfo &info)
74
{
75 76
	dir.inode = info.inode;
	dir.device = info.device;
77 78
}

79 80 81
inline void
UpdateWalk::RemoveExcludedFromDirectory(Directory &directory,
					const ExcludeList &exclude_list)
82
{
83
	const ScopeDatabaseLock protect;
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
	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){
			assert(song.parent == &directory);

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

106 107
inline void
UpdateWalk::PurgeDeletedFromDirectory(Directory &directory)
108
{
109
	directory.ForEachChildSafe([&](Directory &child){
110
			if (child.IsMount() || DirectoryExists(storage, child))
111
				return;
112

113
			editor.LockDeleteDirectory(&child);
114

115 116
			modified = true;
		});
117

118 119 120 121
	directory.ForEachSongSafe([&](Song &song){
			if (!directory_child_is_regular(storage, directory,
							song.uri)) {
				editor.LockDeleteSong(directory, &song);
122

123 124 125
				modified = true;
			}
		});
126

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

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

147 148
	directory_set_stat(directory, info);
	return true;
149
}
150
#endif
151

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

168
	while (parent) {
169
		if (parent->device == 0 && parent->inode == 0 &&
170
		    !update_directory_stat(storage, *parent))
171
			return -1;
172

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

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

	return 0;
}

190 191 192
inline bool
UpdateWalk::UpdatePlaylistFile(Directory &directory,
			       const char *name, const char *suffix,
193
			       const StorageFileInfo &info)
194 195 196 197
{
	if (!playlist_suffix_supported(suffix))
		return false;

198
	PlaylistInfo pi(name, info.mtime);
199

200
	const ScopeDatabaseLock protect;
201
	if (directory.playlists.UpdateOrInsert(std::move(pi)))
202 203 204 205
		modified = true;
	return true;
}

206 207
inline bool
UpdateWalk::UpdateRegularFile(Directory &directory,
208
			      const char *name, const StorageFileInfo &info)
209 210
{
	const char *suffix = uri_get_suffix(name);
211
	if (suffix == nullptr)
212
		return false;
213

214 215 216
	return UpdateSongFile(directory, name, suffix, info) ||
		UpdateArchiveFile(directory, name, suffix, info) ||
		UpdatePlaylistFile(directory, name, suffix, info);
217 218
}

219 220
void
UpdateWalk::UpdateDirectoryChild(Directory &directory,
221
				 const ExcludeList &exclude_list,
222
				 const char *name, const StorageFileInfo &info)
223
try {
224
	assert(strchr(name, '/') == nullptr);
225

226 227 228
	if (info.IsRegular()) {
		UpdateRegularFile(directory, name, info);
	} else if (info.IsDirectory()) {
229
		if (FindAncestorLoop(storage, &directory,
230
					info.inode, info.device))
231 232
			return;

233 234 235 236 237
		Directory *subdir;
		{
			const ScopeDatabaseLock protect;
			subdir = directory.MakeChild(name);
		}
238

239
		assert(&directory == subdir->parent);
240

241
		if (!UpdateDirectory(*subdir, exclude_list, info))
242
			editor.LockDeleteDirectory(subdir);
243
	} else {
244 245
		FormatDebug(update_domain,
			    "%s is not a directory, archive or music", name);
246
	}
247 248
} catch (const std::exception &e) {
	LogError(e);
249 250 251
}

/* we don't look at "." / ".." nor files with newlines in their name */
252
gcc_pure
253
static bool
254
skip_path(const char *name_utf8) noexcept
255
{
256
	return strchr(name_utf8, '\n') != nullptr;
257 258
}

259
gcc_pure
260 261
bool
UpdateWalk::SkipSymlink(const Directory *directory,
262
			const char *utf8_name) const noexcept
263
{
264
#ifndef _WIN32
265 266
	const auto path_fs = storage.MapChildFS(directory->GetPath(),
						utf8_name);
267
	if (path_fs.IsNull())
268 269
		/* not a local file: don't skip */
		return false;
270

271
	const auto target = ReadLink(path_fs);
272
	if (target.IsNull())
273 274 275 276 277 278 279 280 281 282 283
		/* don't skip if this is not a symlink */
		return errno != EINVAL;

	if (!follow_inside_symlinks && !follow_outside_symlinks) {
		/* ignore all symlinks */
		return true;
	} else if (follow_inside_symlinks && follow_outside_symlinks) {
		/* consider all symlinks */
		return false;
	}

284
	if (target.IsAbsolute()) {
285 286
		/* if the symlink points to an absolute path, see if
		   that path is inside the music directory */
287
		const auto target_utf8 = target.ToUTF8();
288 289 290 291 292 293
		if (target_utf8.empty())
			return true;

		const char *relative =
			storage.MapToRelativeUTF8(target_utf8.c_str());
		return relative != nullptr
294 295 296
			? !follow_inside_symlinks
			: !follow_outside_symlinks;
	}
297

298
	const char *p = target.c_str();
299
	while (*p == '.') {
300
		if (p[1] == '.' && PathTraitsFS::IsSeparator(p[2])) {
301 302
			/* "../" moves to parent directory */
			directory = directory->parent;
303
			if (directory == nullptr) {
304 305 306 307 308 309
				/* we have moved outside the music
				   directory - skip this symlink
				   if such symlinks are not allowed */
				return !follow_outside_symlinks;
			}
			p += 3;
310
		} else if (PathTraitsFS::IsSeparator(p[1]))
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
			/* 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*/
	return !follow_inside_symlinks;
#else
	/* no symlink checking on WIN32 */

	(void)directory;
	(void)utf8_name;

	return false;
#endif
}

331
bool
332 333 334
UpdateWalk::UpdateDirectory(Directory &directory,
			    const ExcludeList &exclude_list,
			    const StorageFileInfo &info)
335
{
336
	assert(info.IsDirectory());
337

338
	directory_set_stat(directory, info);
339

340 341 342
	std::unique_ptr<StorageDirectoryReader> reader;

	try {
343
		reader.reset(storage.OpenDirectory(directory.GetPath()));
344 345
	} catch (const std::runtime_error &e) {
		LogError(e);
346 347 348
		return false;
	}

349
	ExcludeList child_exclude_list(exclude_list);
350

351 352 353 354 355 356 357 358 359 360
	try {
		Mutex mutex;
		Cond cond;
		auto is = InputStream::OpenReady(PathTraitsUTF8::Build(storage.MapUTF8(directory.GetPath()).c_str(),
								       ".mpdignore").c_str(),
						 mutex, cond);
		child_exclude_list.Load(std::move(is));
	} catch (...) {
		if (!IsFileNotFound(std::current_exception()))
			LogError(std::current_exception());
361
	}
362

363 364
	if (!child_exclude_list.IsEmpty())
		RemoveExcludedFromDirectory(directory, child_exclude_list);
365

366
	PurgeDeletedFromDirectory(directory);
367

368
	const char *name_utf8;
369
	while (!cancel && (name_utf8 = reader->Read()) != nullptr) {
370
		if (skip_path(name_utf8))
371 372
			continue;

373 374
		{
			const auto name_fs = AllocatedPath::FromUTF8(name_utf8);
375
			if (name_fs.IsNull() || child_exclude_list.Check(name_fs))
376 377 378 379 380
				continue;
		}

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

384
		StorageFileInfo info2;
385 386
		if (!GetInfo(*reader, info2)) {
			modified |= editor.DeleteNameIn(directory, name_utf8);
387 388 389
			continue;
		}

390
		UpdateDirectoryChild(directory, child_exclude_list, name_utf8, info2);
391 392
	}

393
	directory.mtime = info.mtime;
394 395 396 397

	return true;
}

398
inline Directory *
399 400 401
UpdateWalk::DirectoryMakeChildChecked(Directory &parent,
				      const char *uri_utf8,
				      const char *name_utf8)
402
{
403 404 405 406 407
	Directory *directory;
	{
		const ScopeDatabaseLock protect;
		directory = parent.FindChild(name_utf8);
	}
408

Max Kellermann's avatar
Max Kellermann committed
409 410 411 412
	if (directory != nullptr) {
		if (directory->IsMount())
			directory = nullptr;

413
		return directory;
Max Kellermann's avatar
Max Kellermann committed
414
	}
415

416
	StorageFileInfo info;
417
	if (!GetInfo(storage, uri_utf8, info) ||
418
	    FindAncestorLoop(storage, &parent, info.inode, info.device))
419
		return nullptr;
420

421
	if (SkipSymlink(&parent, name_utf8))
422
		return nullptr;
423

424 425
	/* if we're adding directory paths, make sure to delete filenames
	   with potentially the same name */
426 427 428 429 430
	{
		const ScopeDatabaseLock protect;
		Song *conflicting = parent.FindSong(name_utf8);
		if (conflicting)
			editor.DeleteSong(parent, conflicting);
431

432 433
		directory = parent.CreateChild(name_utf8);
	}
434

435
	directory_set_stat(*directory, info);
436 437 438
	return directory;
}

439
inline Directory *
440
UpdateWalk::DirectoryMakeUriParentChecked(Directory &root, const char *uri)
441
{
442
	Directory *directory = &root;
443
	char *duplicated = xstrdup(uri);
444
	char *name_utf8 = duplicated, *slash;
445

446
	while ((slash = strchr(name_utf8, '/')) != nullptr) {
447 448
		*slash = 0;

449
		if (StringIsEmpty(name_utf8))
450 451
			continue;

452
		directory = DirectoryMakeChildChecked(*directory,
453
						      duplicated,
454
						      name_utf8);
455
		if (directory == nullptr)
456 457
			break;

458
		name_utf8 = slash + 1;
459 460
	}

461
	free(duplicated);
462 463 464
	return directory;
}

465
inline void
466
UpdateWalk::UpdateUri(Directory &root, const char *uri)
467
try {
468
	Directory *parent = DirectoryMakeUriParentChecked(root, uri);
469
	if (parent == nullptr)
470 471
		return;

472
	const char *name = PathTraitsUTF8::GetBase(uri);
473

474
	if (SkipSymlink(parent, name)) {
475
		modified |= editor.DeleteNameIn(*parent, name);
476 477 478
		return;
	}

479
	StorageFileInfo info;
480 481 482 483 484
	if (!GetInfo(storage, uri, info)) {
		modified |= editor.DeleteNameIn(*parent, name);
		return;
	}

485 486 487
	ExcludeList exclude_list;

	UpdateDirectoryChild(*parent, exclude_list, name, info);
488 489
} catch (const std::exception &e) {
	LogError(e);
490 491 492
}

bool
493
UpdateWalk::Walk(Directory &root, const char *path, bool discard)
494
{
495
	walk_discard = discard;
496 497
	modified = false;

498
	if (path != nullptr && !isRootDirectory(path)) {
499
		UpdateUri(root, path);
500
	} else {
501
		StorageFileInfo info;
502 503
		if (!GetInfo(storage, "", info))
			return false;
504

505 506 507
		ExcludeList exclude_list;

		UpdateDirectory(root, exclude_list, info);
508 509 510 511
	}

	return modified;
}