Walk.cxx 11.6 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.c_str());
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.c_str())) {
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 117
		if (!directory_child_is_regular(storage, directory,
						i->name.c_str())) {
118
			const ScopeDatabaseLock protect;
119
			i = directory.playlists.erase(i);
120 121
		} else
			++i;
122
	}
123 124
}

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

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

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

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

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

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

	return 0;
}

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

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

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

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

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

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

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

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

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

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

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

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

		const char *relative =
			storage.MapToRelativeUTF8(target_utf8.c_str());
		return relative != nullptr
267 268
			? !config.follow_inside_symlinks
			: !config.follow_outside_symlinks;
269
	}
270

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

	(void)directory;
	(void)utf8_name;

	return false;
#endif
}

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

311
	directory_set_stat(directory, info);
312

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

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

322
	ExcludeList child_exclude_list(exclude_list);
323

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

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

338
	PurgeDeletedFromDirectory(directory);
339

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

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

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

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

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

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

	return true;
}

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

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

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

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

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

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

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

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

411
inline Directory *
412 413
UpdateWalk::DirectoryMakeUriParentChecked(Directory &root,
					  const char *uri) noexcept
414
{
415
	Directory *directory = &root;
416
	char *duplicated = xstrdup(uri);
417
	char *name_utf8 = duplicated, *slash;
418

419
	while ((slash = strchr(name_utf8, '/')) != nullptr) {
420 421
		*slash = 0;

422
		if (StringIsEmpty(name_utf8))
423 424
			continue;

425
		directory = DirectoryMakeChildChecked(*directory,
426
						      duplicated,
427
						      name_utf8);
428
		if (directory == nullptr)
429 430
			break;

431
		name_utf8 = slash + 1;
432 433
	}

434
	free(duplicated);
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;
}