InotifyUpdate.cxx 7.84 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2015 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 */
Max Kellermann's avatar
Max Kellermann committed
21 22 23
#include "InotifyUpdate.hxx"
#include "InotifySource.hxx"
#include "InotifyQueue.hxx"
24
#include "InotifyDomain.hxx"
25
#include "storage/StorageInterface.hxx"
26
#include "fs/AllocatedPath.hxx"
27
#include "fs/FileInfo.hxx"
28
#include "util/Error.hxx"
29
#include "Log.hxx"
30

31
#include <string>
32
#include <map>
33
#include <forward_list>
34

35 36 37 38 39 40
#include <assert.h>
#include <sys/inotify.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>

41
static constexpr unsigned IN_MASK =
42
#ifdef IN_ONLYDIR
43
	IN_ONLYDIR|
44
#endif
45 46
	IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_DELETE_SELF
	|IN_MOVE|IN_MOVE_SELF;
47

48 49
struct WatchDirectory {
	WatchDirectory *parent;
50

51
	AllocatedPath name;
52 53 54

	int descriptor;

55
	std::forward_list<WatchDirectory> children;
56

57 58
	template<typename N>
	WatchDirectory(WatchDirectory *_parent, N &&_name,
59
		       int _descriptor)
60
		:parent(_parent), name(std::forward<N>(_name)),
61 62 63 64
		 descriptor(_descriptor) {}

	WatchDirectory(const WatchDirectory &) = delete;
	WatchDirectory &operator=(const WatchDirectory &) = delete;
65 66 67 68 69 70

	gcc_pure
	unsigned GetDepth() const;

	gcc_pure
	AllocatedPath GetUriFS() const;
71 72
};

73
static InotifySource *inotify_source;
74
static InotifyQueue *inotify_queue;
75

76
static unsigned inotify_max_depth;
77
static WatchDirectory *inotify_root;
78
static std::map<int, WatchDirectory *> inotify_directories;
79 80

static void
81
tree_add_watch_directory(WatchDirectory *directory)
82
{
83 84
	inotify_directories.insert(std::make_pair(directory->descriptor,
						  directory));
85 86 87
}

static void
88
tree_remove_watch_directory(WatchDirectory *directory)
89
{
90 91 92
	auto i = inotify_directories.find(directory->descriptor);
	assert(i != inotify_directories.end());
	inotify_directories.erase(i);
93 94
}

95
static WatchDirectory *
96 97
tree_find_watch_directory(int wd)
{
98 99 100 101 102
	auto i = inotify_directories.find(wd);
	if (i == inotify_directories.end())
		return nullptr;

	return i->second;
103 104
}

105 106 107 108 109 110 111 112 113 114 115
static void
disable_watch_directory(WatchDirectory &directory)
{
	tree_remove_watch_directory(&directory);

	for (WatchDirectory &child : directory.children)
		disable_watch_directory(child);

	inotify_source->Remove(directory.descriptor);
}

116
static void
117
remove_watch_directory(WatchDirectory *directory)
118
{
119
	assert(directory != nullptr);
120

121
	if (directory->parent == nullptr) {
122 123 124
		LogWarning(inotify_domain,
			   "music directory was removed - "
			   "cannot continue to watch it");
125 126 127
		return;
	}

128
	disable_watch_directory(*directory);
129

130 131 132 133
	/* remove it from the parent, which effectively deletes it */
	directory->parent->children.remove_if([directory](const WatchDirectory &child){
			return &child == directory;
		});
134 135
}

136 137
AllocatedPath
WatchDirectory::GetUriFS() const
138
{
139
	if (parent == nullptr)
140
		return AllocatedPath::Null();
141

142
	const auto uri = parent->GetUriFS();
143
	if (uri.IsNull())
144
		return name;
145

146
	return AllocatedPath::Build(uri, name);
147 148 149 150 151 152 153
}

/* we don't look at "." / ".." nor files with newlines in their name */
static bool skip_path(const char *path)
{
	return (path[0] == '.' && path[1] == 0) ||
		(path[0] == '.' && path[1] == '.' && path[2] == 0) ||
154
		strchr(path, '\n') != nullptr;
155 156 157
}

static void
158
recursive_watch_subdirectories(WatchDirectory *directory,
159
			       const AllocatedPath &path_fs, unsigned depth)
160
{
161
	Error error;
162 163 164
	DIR *dir;
	struct dirent *ent;

165
	assert(directory != nullptr);
166
	assert(depth <= inotify_max_depth);
167
	assert(!path_fs.IsNull());
168

169 170 171 172 173
	++depth;

	if (depth > inotify_max_depth)
		return;

174
	dir = opendir(path_fs.c_str());
175
	if (dir == nullptr) {
176
		FormatErrno(inotify_domain,
177
			    "Failed to open directory %s", path_fs.c_str());
178 179 180 181 182 183 184 185 186
		return;
	}

	while ((ent = readdir(dir))) {
		int ret;

		if (skip_path(ent->d_name))
			continue;

187 188
		const auto child_path_fs =
			AllocatedPath::Build(path_fs, ent->d_name);
189 190 191 192 193

		FileInfo fi;
		if (!GetFileInfo(child_path_fs, fi, error)) {
			LogError(error);
			error.Clear();
194 195 196
			continue;
		}

197
		if (!fi.IsDirectory())
198 199
			continue;

200 201
		ret = inotify_source->Add(child_path_fs.c_str(), IN_MASK,
					  error);
202
		if (ret < 0) {
203
			FormatError(error,
204 205
				    "Failed to register %s",
				    child_path_fs.c_str());
206
			error.Clear();
207 208 209
			continue;
		}

210
		WatchDirectory *child = tree_find_watch_directory(ret);
211
		if (child != nullptr)
212 213 214
			/* already being watched */
			continue;

215
		directory->children.emplace_front(directory,
216
						  AllocatedPath::FromFS(ent->d_name),
217
						  ret);
218
		child = &directory->children.front();
219 220 221

		tree_add_watch_directory(child);

222
		recursive_watch_subdirectories(child, child_path_fs, depth);
223 224 225 226 227
	}

	closedir(dir);
}

228
gcc_pure
229 230
unsigned
WatchDirectory::GetDepth() const
231
{
232
	const WatchDirectory *d = this;
233
	unsigned depth = 0;
234
	while ((d = d->parent) != nullptr)
235 236 237 238 239
		++depth;

	return depth;
}

240 241
static void
mpd_inotify_callback(int wd, unsigned mask,
242
		     gcc_unused const char *name, gcc_unused void *ctx)
243
{
244
	WatchDirectory *directory;
245

246
	/*FormatDebug(inotify_domain, "wd=%d mask=0x%x name='%s'", wd, mask, name);*/
247 248

	directory = tree_find_watch_directory(wd);
249
	if (directory == nullptr)
250 251
		return;

252
	const auto uri_fs = directory->GetUriFS();
253 254 255 256 257 258 259 260 261 262

	if ((mask & (IN_DELETE_SELF|IN_MOVE_SELF)) != 0) {
		remove_watch_directory(directory);
		return;
	}

	if ((mask & (IN_ATTRIB|IN_CREATE|IN_MOVE)) != 0 &&
	    (mask & IN_ISDIR) != 0) {
		/* a sub directory was changed: register those in
		   inotify */
263
		const auto &root = inotify_root->name;
264

265
		const auto path_fs = uri_fs.IsNull()
266
			? root
267
			: AllocatedPath::Build(root, uri_fs.c_str());
268

269
		recursive_watch_subdirectories(directory, path_fs,
270
					       directory->GetDepth());
271 272
	}

273 274 275
	if ((mask & (IN_CLOSE_WRITE|IN_MOVE|IN_DELETE)) != 0 ||
	    /* at the maximum depth, we watch out for newly created
	       directories */
276
	    (directory->GetDepth() == inotify_max_depth &&
277 278
	     (mask & (IN_CREATE|IN_ISDIR)) == (IN_CREATE|IN_ISDIR))) {
		/* a file was changed, or a directory was
279 280
		   moved/deleted: queue a database update */

281 282
		if (!uri_fs.IsNull()) {
			const std::string uri_utf8 = uri_fs.ToUTF8();
283 284
			if (!uri_utf8.empty())
				inotify_queue->Enqueue(uri_utf8.c_str());
285
		}
286 287
		else
			inotify_queue->Enqueue("");
288 289 290 291
	}
}

void
292 293
mpd_inotify_init(EventLoop &loop, Storage &storage, UpdateService &update,
		 unsigned max_depth)
294
{
295
	LogDebug(inotify_domain, "initializing inotify");
296

297
	const auto path = storage.MapFS("");
298
	if (path.IsNull()) {
299
		LogDebug(inotify_domain, "no music directory configured");
300 301 302
		return;
	}

303
	Error error;
304
	inotify_source = InotifySource::Create(loop,
305
					       mpd_inotify_callback, nullptr,
306
					       error);
307
	if (inotify_source == nullptr) {
308
		LogError(error);
309 310 311
		return;
	}

312 313
	inotify_max_depth = max_depth;

314
	int descriptor = inotify_source->Add(path.c_str(), IN_MASK, error);
315
	if (descriptor < 0) {
316
		LogError(error);
317
		delete inotify_source;
318
		inotify_source = nullptr;
319 320 321
		return;
	}

322
	inotify_root = new WatchDirectory(nullptr, path, descriptor);
323

324 325
	tree_add_watch_directory(inotify_root);

326
	recursive_watch_subdirectories(inotify_root, path, 0);
327

328
	inotify_queue = new InotifyQueue(loop, update);
329

330
	LogDebug(inotify_domain, "watching music directory");
331 332 333 334 335
}

void
mpd_inotify_finish(void)
{
336
	if (inotify_source == nullptr)
337 338
		return;

339
	delete inotify_queue;
340
	delete inotify_source;
341
	delete inotify_root;
342
	inotify_directories.clear();
343
}