Walk.cxx 11.7 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 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 "util/Error.hxx"
43
#include "Log.hxx"
44 45 46

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

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

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

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

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

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

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

109
			editor.LockDeleteDirectory(&child);
110

111 112
			modified = true;
		});
113

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

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

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

135
#ifndef WIN32
136
static bool
137
update_directory_stat(Storage &storage, Directory &directory)
138
{
139
	StorageFileInfo info;
140 141
	if (!GetInfo(storage, directory.GetPath(), info))
		return false;
142

143 144
	directory_set_stat(directory, info);
	return true;
145
}
146
#endif
147

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

164
	while (parent) {
165
		if (parent->device == 0 && parent->inode == 0 &&
166
		    !update_directory_stat(storage, *parent))
167
			return -1;
168

169
		if (parent->inode == inode && parent->device == device) {
170
			LogDebug(update_domain, "recursive directory found");
171 172
			return 1;
		}
173

174 175
		parent = parent->parent;
	}
176
#else
177
	(void)storage;
178 179 180 181
	(void)parent;
	(void)inode;
	(void)device;
#endif
182 183 184 185

	return 0;
}

186 187 188
inline bool
UpdateWalk::UpdatePlaylistFile(Directory &directory,
			       const char *name, const char *suffix,
189
			       const StorageFileInfo &info)
190 191 192 193
{
	if (!playlist_suffix_supported(suffix))
		return false;

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

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

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

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

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

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

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

235
		assert(&directory == subdir->parent);
236

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

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

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

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

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

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

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

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

334
	directory_set_stat(directory, info);
335

336
	Error error;
337
	const std::unique_ptr<StorageDirectoryReader> reader(storage.OpenDirectory(directory.GetPath(), error));
338
	if (reader.get() == nullptr) {
339
		LogError(error);
340 341 342
		return false;
	}

343
	ExcludeList child_exclude_list(exclude_list);
344 345 346 347 348

	{
		const auto exclude_path_fs =
			storage.MapChildFS(directory.GetPath(), ".mpdignore");
		if (!exclude_path_fs.IsNull())
349
			child_exclude_list.LoadFile(exclude_path_fs);
350
	}
351

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

355
	PurgeDeletedFromDirectory(directory);
356

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

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

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

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

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

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

	return true;
}

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

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

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

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

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

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

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

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

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

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

438
		if (StringIsEmpty(name_utf8))
439 440
			continue;

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

447
		name_utf8 = slash + 1;
448 449
	}

450
	free(duplicated);
451 452 453
	return directory;
}

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

461
	const char *name = PathTraitsUTF8::GetBase(uri);
462

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

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

474 475 476
	ExcludeList exclude_list;

	UpdateDirectoryChild(*parent, exclude_list, name, info);
477 478
} catch (const std::exception &e) {
	LogError(e);
479 480 481
}

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

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

494 495 496
		ExcludeList exclude_list;

		UpdateDirectory(root, exclude_list, info);
497 498 499 500
	}

	return modified;
}