Walk.cxx 11.8 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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/PlaylistVector.hxx"
26
#include "db/Uri.hxx"
27 28
#include "db/plugins/simple/Directory.hxx"
#include "db/plugins/simple/Song.hxx"
29
#include "storage/StorageInterface.hxx"
30
#include "playlist/PlaylistRegistry.hxx"
Max Kellermann's avatar
Max Kellermann committed
31
#include "ExcludeList.hxx"
32
#include "fs/AllocatedPath.hxx"
33
#include "fs/Traits.hxx"
34
#include "fs/FileSystem.hxx"
35
#include "storage/FileInfo.hxx"
36 37
#include "input/InputStream.hxx"
#include "input/Error.hxx"
38
#include "util/Alloc.hxx"
39
#include "util/StringCompare.hxx"
Max Kellermann's avatar
Max Kellermann committed
40
#include "util/UriUtil.hxx"
41
#include "Log.hxx"
42

43 44 45
#include <stdexcept>
#include <memory>

46 47
#include <assert.h>
#include <string.h>
48
#include <stdlib.h>
49 50
#include <errno.h>

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

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

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

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	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;
			}
		});
92 93
}

94
inline void
95
UpdateWalk::PurgeDeletedFromDirectory(Directory &directory) noexcept
96
{
97
	directory.ForEachChildSafe([&](Directory &child){
98
			if (child.IsMount() || DirectoryExists(storage, child))
99
				return;
100

101
			editor.LockDeleteDirectory(&child);
102

103 104
			modified = true;
		});
105

106 107 108 109
	directory.ForEachSongSafe([&](Song &song){
			if (!directory_child_is_regular(storage, directory,
							song.uri)) {
				editor.LockDeleteSong(directory, &song);
110

111 112 113
				modified = true;
			}
		});
114

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

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

135 136
	directory_set_stat(directory, info);
	return true;
137
}
138
#endif
139

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

156
	while (parent) {
157
		if (parent->device == 0 && parent->inode == 0 &&
158
		    !update_directory_stat(storage, *parent))
159
			return -1;
160

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

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

	return 0;
}

178 179 180
inline bool
UpdateWalk::UpdatePlaylistFile(Directory &directory,
			       const char *name, const char *suffix,
181
			       const StorageFileInfo &info) noexcept
182 183 184 185
{
	if (!playlist_suffix_supported(suffix))
		return false;

186
	PlaylistInfo pi(name, info.mtime);
187

188
	const ScopeDatabaseLock protect;
189
	if (directory.playlists.UpdateOrInsert(std::move(pi)))
190 191 192 193
		modified = true;
	return true;
}

194 195
inline bool
UpdateWalk::UpdateRegularFile(Directory &directory,
196 197
			      const char *name,
			      const StorageFileInfo &info) noexcept
198 199
{
	const char *suffix = uri_get_suffix(name);
200
	if (suffix == nullptr)
201
		return false;
202

203 204 205
	return UpdateSongFile(directory, name, suffix, info) ||
		UpdateArchiveFile(directory, name, suffix, info) ||
		UpdatePlaylistFile(directory, name, suffix, info);
206 207
}

208 209
void
UpdateWalk::UpdateDirectoryChild(Directory &directory,
210
				 const ExcludeList &exclude_list,
211
				 const char *name, const StorageFileInfo &info) noexcept
212
try {
213
	assert(strchr(name, '/') == nullptr);
214

215 216 217
	if (info.IsRegular()) {
		UpdateRegularFile(directory, name, info);
	} else if (info.IsDirectory()) {
218
		if (FindAncestorLoop(storage, &directory,
219
					info.inode, info.device))
220 221
			return;

222 223 224 225 226
		Directory *subdir;
		{
			const ScopeDatabaseLock protect;
			subdir = directory.MakeChild(name);
		}
227

228
		assert(&directory == subdir->parent);
229

230
		if (!UpdateDirectory(*subdir, exclude_list, info))
231
			editor.LockDeleteDirectory(subdir);
232
	} else {
233 234
		FormatDebug(update_domain,
			    "%s is not a directory, archive or music", name);
235
	}
236 237
} catch (...) {
	LogError(std::current_exception());
238 239 240
}

/* we don't look at "." / ".." nor files with newlines in their name */
241
gcc_pure
242
static bool
243
skip_path(const char *name_utf8) noexcept
244
{
245
	return strchr(name_utf8, '\n') != nullptr;
246 247
}

248
gcc_pure
249 250
bool
UpdateWalk::SkipSymlink(const Directory *directory,
251
			const char *utf8_name) const noexcept
252
{
253
#ifndef _WIN32
254 255
	const auto path_fs = storage.MapChildFS(directory->GetPath(),
						utf8_name);
256
	if (path_fs.IsNull())
257 258
		/* not a local file: don't skip */
		return false;
259

260
	const auto target = ReadLink(path_fs);
261
	if (target.IsNull())
262 263 264
		/* don't skip if this is not a symlink */
		return errno != EINVAL;

265 266
	if (!config.follow_inside_symlinks &&
	    !config.follow_outside_symlinks) {
267 268
		/* ignore all symlinks */
		return true;
269 270
	} else if (config.follow_inside_symlinks &&
		   config.follow_outside_symlinks) {
271 272 273 274
		/* consider all symlinks */
		return false;
	}

275
	if (target.IsAbsolute()) {
276 277
		/* if the symlink points to an absolute path, see if
		   that path is inside the music directory */
278
		const auto target_utf8 = target.ToUTF8();
279 280 281 282 283 284
		if (target_utf8.empty())
			return true;

		const char *relative =
			storage.MapToRelativeUTF8(target_utf8.c_str());
		return relative != nullptr
285 286
			? !config.follow_inside_symlinks
			: !config.follow_outside_symlinks;
287
	}
288

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

	(void)directory;
	(void)utf8_name;

	return false;
#endif
}

322
bool
323 324
UpdateWalk::UpdateDirectory(Directory &directory,
			    const ExcludeList &exclude_list,
325
			    const StorageFileInfo &info) noexcept
326
{
327
	assert(info.IsDirectory());
328

329
	directory_set_stat(directory, info);
330

331 332 333
	std::unique_ptr<StorageDirectoryReader> reader;

	try {
334
		reader = storage.OpenDirectory(directory.GetPath());
335 336
	} catch (...) {
		LogError(std::current_exception());
337 338 339
		return false;
	}

340
	ExcludeList child_exclude_list(exclude_list);
341

342 343 344 345
	try {
		Mutex mutex;
		auto is = InputStream::OpenReady(PathTraitsUTF8::Build(storage.MapUTF8(directory.GetPath()).c_str(),
								       ".mpdignore").c_str(),
346
						 mutex);
347 348 349 350
		child_exclude_list.Load(std::move(is));
	} catch (...) {
		if (!IsFileNotFound(std::current_exception()))
			LogError(std::current_exception());
351
	}
352

353 354
	if (!child_exclude_list.IsEmpty())
		RemoveExcludedFromDirectory(directory, child_exclude_list);
355

356
	PurgeDeletedFromDirectory(directory);
357

358
	const char *name_utf8;
359
	while (!cancel && (name_utf8 = reader->Read()) != nullptr) {
360
		if (skip_path(name_utf8))
361 362
			continue;

363 364
		{
			const auto name_fs = AllocatedPath::FromUTF8(name_utf8);
365
			if (name_fs.IsNull() || child_exclude_list.Check(name_fs))
366 367 368 369 370
				continue;
		}

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

374
		StorageFileInfo info2;
375 376
		if (!GetInfo(*reader, info2)) {
			modified |= editor.DeleteNameIn(directory, name_utf8);
377 378 379
			continue;
		}

380
		UpdateDirectoryChild(directory, child_exclude_list, name_utf8, info2);
381 382
	}

383
	directory.mtime = info.mtime;
384 385 386 387

	return true;
}

388
inline Directory *
389 390
UpdateWalk::DirectoryMakeChildChecked(Directory &parent,
				      const char *uri_utf8,
391
				      const char *name_utf8) noexcept
392
{
393 394 395 396 397
	Directory *directory;
	{
		const ScopeDatabaseLock protect;
		directory = parent.FindChild(name_utf8);
	}
398

Max Kellermann's avatar
Max Kellermann committed
399 400 401 402
	if (directory != nullptr) {
		if (directory->IsMount())
			directory = nullptr;

403
		return directory;
Max Kellermann's avatar
Max Kellermann committed
404
	}
405

406
	StorageFileInfo info;
407
	if (!GetInfo(storage, uri_utf8, info) ||
408
	    FindAncestorLoop(storage, &parent, info.inode, info.device))
409
		return nullptr;
410

411
	if (SkipSymlink(&parent, name_utf8))
412
		return nullptr;
413

414 415
	/* if we're adding directory paths, make sure to delete filenames
	   with potentially the same name */
416 417 418 419 420
	{
		const ScopeDatabaseLock protect;
		Song *conflicting = parent.FindSong(name_utf8);
		if (conflicting)
			editor.DeleteSong(parent, conflicting);
421

422 423
		directory = parent.CreateChild(name_utf8);
	}
424

425
	directory_set_stat(*directory, info);
426 427 428
	return directory;
}

429
inline Directory *
430 431
UpdateWalk::DirectoryMakeUriParentChecked(Directory &root,
					  const char *uri) noexcept
432
{
433
	Directory *directory = &root;
434
	char *duplicated = xstrdup(uri);
435
	char *name_utf8 = duplicated, *slash;
436

437
	while ((slash = strchr(name_utf8, '/')) != nullptr) {
438 439
		*slash = 0;

440
		if (StringIsEmpty(name_utf8))
441 442
			continue;

443
		directory = DirectoryMakeChildChecked(*directory,
444
						      duplicated,
445
						      name_utf8);
446
		if (directory == nullptr)
447 448
			break;

449
		name_utf8 = slash + 1;
450 451
	}

452
	free(duplicated);
453 454 455
	return directory;
}

456
inline void
457
UpdateWalk::UpdateUri(Directory &root, const char *uri) noexcept
458
try {
459
	Directory *parent = DirectoryMakeUriParentChecked(root, uri);
460
	if (parent == nullptr)
461 462
		return;

463
	const char *name = PathTraitsUTF8::GetBase(uri);
464

465
	if (SkipSymlink(parent, name)) {
466
		modified |= editor.DeleteNameIn(*parent, name);
467 468 469
		return;
	}

470
	StorageFileInfo info;
471 472 473 474 475
	if (!GetInfo(storage, uri, info)) {
		modified |= editor.DeleteNameIn(*parent, name);
		return;
	}

476 477 478
	ExcludeList exclude_list;

	UpdateDirectoryChild(*parent, exclude_list, name, info);
479 480
} catch (...) {
	LogError(std::current_exception());
481 482 483
}

bool
484
UpdateWalk::Walk(Directory &root, const char *path, bool discard) noexcept
485
{
486
	walk_discard = discard;
487 488
	modified = false;

489
	if (path != nullptr && !isRootDirectory(path)) {
490
		UpdateUri(root, path);
491
	} else {
492
		StorageFileInfo info;
493 494
		if (!GetInfo(storage, "", info))
			return false;
495

496 497 498
		ExcludeList exclude_list;

		UpdateDirectory(root, exclude_list, info);
499 500 501 502
	}

	return modified;
}