Walk.cxx 11.9 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
#include "util/Alloc.hxx"
40
#include "util/StringCompare.hxx"
Max Kellermann's avatar
Max Kellermann committed
41
#include "util/UriUtil.hxx"
42
#include "Log.hxx"
43

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

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

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

	follow_outside_symlinks =
64
		config_get_bool(ConfigOption::FOLLOW_OUTSIDE_SYMLINKS,
65 66 67 68 69
				DEFAULT_FOLLOW_OUTSIDE_SYMLINKS);
#endif
}

static void
70
directory_set_stat(Directory &dir, const StorageFileInfo &info)
71
{
72 73
	dir.inode = info.inode;
	dir.device = info.device;
74 75
}

76 77
inline void
UpdateWalk::RemoveExcludedFromDirectory(Directory &directory,
78
					const ExcludeList &exclude_list) noexcept
79
{
80
	const ScopeDatabaseLock protect;
81

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
	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;
			}
		});
101 102
}

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

110
			editor.LockDeleteDirectory(&child);
111

112 113
			modified = true;
		});
114

115 116 117 118
	directory.ForEachSongSafe([&](Song &song){
			if (!directory_child_is_regular(storage, directory,
							song.uri)) {
				editor.LockDeleteSong(directory, &song);
119

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

124 125
	for (auto i = directory.playlists.begin(),
		     end = directory.playlists.end();
126
	     i != end;) {
127 128
		if (!directory_child_is_regular(storage, directory,
						i->name.c_str())) {
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 189
inline bool
UpdateWalk::UpdatePlaylistFile(Directory &directory,
			       const char *name, const char *suffix,
190
			       const StorageFileInfo &info) noexcept
191 192 193 194
{
	if (!playlist_suffix_supported(suffix))
		return false;

195
	PlaylistInfo pi(name, info.mtime);
196

197
	const ScopeDatabaseLock protect;
198
	if (directory.playlists.UpdateOrInsert(std::move(pi)))
199 200 201 202
		modified = true;
	return true;
}

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

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

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

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

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

237
		assert(&directory == subdir->parent);
238

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

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

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

269
	const auto target = ReadLink(path_fs);
270
	if (target.IsNull())
271 272 273 274 275 276 277 278 279 280 281
		/* 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;
	}

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

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

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

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

336
	directory_set_stat(directory, info);
337

338 339 340
	std::unique_ptr<StorageDirectoryReader> reader;

	try {
341
		reader = storage.OpenDirectory(directory.GetPath());
342 343
	} catch (...) {
		LogError(std::current_exception());
344 345 346
		return false;
	}

347
	ExcludeList child_exclude_list(exclude_list);
348 349 350 351 352

	{
		const auto exclude_path_fs =
			storage.MapChildFS(directory.GetPath(), ".mpdignore");
		if (!exclude_path_fs.IsNull())
353
			child_exclude_list.LoadFile(exclude_path_fs);
354
	}
355

356 357
	if (!child_exclude_list.IsEmpty())
		RemoveExcludedFromDirectory(directory, child_exclude_list);
358

359
	PurgeDeletedFromDirectory(directory);
360

361
	const char *name_utf8;
362
	while (!cancel && (name_utf8 = reader->Read()) != nullptr) {
363
		if (skip_path(name_utf8))
364 365
			continue;

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

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

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

383
		UpdateDirectoryChild(directory, child_exclude_list, name_utf8, info2);
384 385
	}

386
	directory.mtime = info.mtime;
387 388 389 390

	return true;
}

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

Max Kellermann's avatar
Max Kellermann committed
402 403 404 405
	if (directory != nullptr) {
		if (directory->IsMount())
			directory = nullptr;

406
		return directory;
Max Kellermann's avatar
Max Kellermann committed
407
	}
408

409
	StorageFileInfo info;
410
	if (!GetInfo(storage, uri_utf8, info) ||
411
	    FindAncestorLoop(storage, &parent, info.inode, info.device))
412
		return nullptr;
413

414
	if (SkipSymlink(&parent, name_utf8))
415
		return nullptr;
416

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

425 426
		directory = parent.CreateChild(name_utf8);
	}
427

428
	directory_set_stat(*directory, info);
429 430 431
	return directory;
}

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

440
	while ((slash = strchr(name_utf8, '/')) != nullptr) {
441 442
		*slash = 0;

443
		if (StringIsEmpty(name_utf8))
444 445
			continue;

446
		directory = DirectoryMakeChildChecked(*directory,
447
						      duplicated,
448
						      name_utf8);
449
		if (directory == nullptr)
450 451
			break;

452
		name_utf8 = slash + 1;
453 454
	}

455
	free(duplicated);
456 457 458
	return directory;
}

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

466
	const char *name = PathTraitsUTF8::GetBase(uri);
467

468
	if (SkipSymlink(parent, name)) {
469
		modified |= editor.DeleteNameIn(*parent, name);
470 471 472
		return;
	}

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

479 480 481
	ExcludeList exclude_list;

	UpdateDirectoryChild(*parent, exclude_list, name, info);
482 483
} catch (const std::exception &e) {
	LogError(e);
484 485 486
}

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

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

499 500 501
		ExcludeList exclude_list;

		UpdateDirectory(root, exclude_list, info);
502 503 504 505
	}

	return modified;
}