Walk.cxx 11.7 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)
54 55
	:cancel(false),
	 storage(_storage),
56
	 editor(_loop, _listener)
57 58 59
{
#ifndef WIN32
	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 78
inline void
UpdateWalk::RemoveExcludedFromDirectory(Directory &directory,
					const ExcludeList &exclude_list)
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 104
inline void
UpdateWalk::PurgeDeletedFromDirectory(Directory &directory)
105
{
106 107 108
	directory.ForEachChildSafe([&](Directory &child){
			if (DirectoryExists(storage, child))
				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)
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 157
FindAncestorLoop(Storage &storage, Directory *parent,
		 unsigned inode, unsigned device)
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)
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
			      const char *name, const StorageFileInfo &info)
206 207
{
	const char *suffix = uri_get_suffix(name);
208
	if (suffix == nullptr)
209
		return false;
210

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

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

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

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

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

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

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

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

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

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

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

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

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

335
	directory_set_stat(directory, info);
336

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

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

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

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

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

358
	PurgeDeletedFromDirectory(directory);
359

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

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

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

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

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

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

	return true;
}

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

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

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

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

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

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

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

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

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

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

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

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

450
		name_utf8 = slash + 1;
451 452
	}

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

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

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

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

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

477 478 479
	ExcludeList exclude_list;

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

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

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

497 498 499
		ExcludeList exclude_list;

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

	return modified;
}