InotifyUpdate.cxx 7.94 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2013 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"
Max Kellermann's avatar
Max Kellermann committed
25
#include "Mapper.hxx"
26
#include "Main.hxx"
27
#include "fs/AllocatedPath.hxx"
28
#include "fs/FileSystem.hxx"
29
#include "util/Error.hxx"
30
#include "Log.hxx"
31

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

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

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

49 50
struct WatchDirectory {
	WatchDirectory *parent;
51

52
	AllocatedPath name;
53 54 55

	int descriptor;

56
	std::forward_list<WatchDirectory> children;
57

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

	WatchDirectory(const WatchDirectory &) = delete;
	WatchDirectory &operator=(const WatchDirectory &) = delete;
66 67
};

68
static InotifySource *inotify_source;
69
static InotifyQueue *inotify_queue;
70

71
static unsigned inotify_max_depth;
72
static WatchDirectory *inotify_root;
73
static std::map<int, WatchDirectory *> inotify_directories;
74 75

static void
76
tree_add_watch_directory(WatchDirectory *directory)
77
{
78 79
	inotify_directories.insert(std::make_pair(directory->descriptor,
						  directory));
80 81 82
}

static void
83
tree_remove_watch_directory(WatchDirectory *directory)
84
{
85 86 87
	auto i = inotify_directories.find(directory->descriptor);
	assert(i != inotify_directories.end());
	inotify_directories.erase(i);
88 89
}

90
static WatchDirectory *
91 92
tree_find_watch_directory(int wd)
{
93 94 95 96 97
	auto i = inotify_directories.find(wd);
	if (i == inotify_directories.end())
		return nullptr;

	return i->second;
98 99
}

100 101 102 103 104 105 106 107 108 109 110
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);
}

111
static void
112
remove_watch_directory(WatchDirectory *directory)
113
{
114
	assert(directory != nullptr);
115

116
	if (directory->parent == nullptr) {
117 118 119
		LogWarning(inotify_domain,
			   "music directory was removed - "
			   "cannot continue to watch it");
120 121 122
		return;
	}

123
	disable_watch_directory(*directory);
124

125 126 127 128
	/* remove it from the parent, which effectively deletes it */
	directory->parent->children.remove_if([directory](const WatchDirectory &child){
			return &child == directory;
		});
129 130
}

131
static AllocatedPath
132
watch_directory_get_uri_fs(const WatchDirectory *directory)
133
{
134
	if (directory->parent == nullptr)
135
		return AllocatedPath::Null();
136

137
	const auto uri = watch_directory_get_uri_fs(directory->parent);
138 139
	if (uri.IsNull())
		return directory->name;
140

141
	return AllocatedPath::Build(uri, directory->name);
142 143 144 145 146 147 148
}

/* 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) ||
149
		strchr(path, '\n') != nullptr;
150 151 152
}

static void
153
recursive_watch_subdirectories(WatchDirectory *directory,
154
			       const AllocatedPath &path_fs, unsigned depth)
155
{
156
	Error error;
157 158 159
	DIR *dir;
	struct dirent *ent;

160
	assert(directory != nullptr);
161
	assert(depth <= inotify_max_depth);
162
	assert(!path_fs.IsNull());
163

164 165 166 167 168
	++depth;

	if (depth > inotify_max_depth)
		return;

169
	dir = opendir(path_fs.c_str());
170
	if (dir == nullptr) {
171
		FormatErrno(inotify_domain,
172
			    "Failed to open directory %s", path_fs.c_str());
173 174 175 176 177 178 179 180 181 182
		return;
	}

	while ((ent = readdir(dir))) {
		struct stat st;
		int ret;

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

183 184
		const auto child_path_fs =
			AllocatedPath::Build(path_fs, ent->d_name);
185
		ret = StatFile(child_path_fs, st);
186
		if (ret < 0) {
187 188
			FormatErrno(inotify_domain,
				    "Failed to stat %s",
189
				    child_path_fs.c_str());
190 191 192
			continue;
		}

193
		if (!S_ISDIR(st.st_mode))
194 195
			continue;

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

206
		WatchDirectory *child = tree_find_watch_directory(ret);
207
		if (child != nullptr)
208 209 210
			/* already being watched */
			continue;

211
		directory->children.emplace_front(directory,
212
						  AllocatedPath::FromFS(ent->d_name),
213
						  ret);
214
		child = &directory->children.front();
215 216 217

		tree_add_watch_directory(child);

218
		recursive_watch_subdirectories(child, child_path_fs, depth);
219 220 221 222 223
	}

	closedir(dir);
}

224
gcc_pure
225
static unsigned
226
watch_directory_depth(const WatchDirectory *d)
227
{
228
	assert(d != nullptr);
229 230

	unsigned depth = 0;
231
	while ((d = d->parent) != nullptr)
232 233 234 235 236
		++depth;

	return depth;
}

237 238
static void
mpd_inotify_callback(int wd, unsigned mask,
239
		     gcc_unused const char *name, gcc_unused void *ctx)
240
{
241
	WatchDirectory *directory;
242

243
	/*FormatDebug(inotify_domain, "wd=%d mask=0x%x name='%s'", wd, mask, name);*/
244 245

	directory = tree_find_watch_directory(wd);
246
	if (directory == nullptr)
247 248
		return;

249
	const auto uri_fs = watch_directory_get_uri_fs(directory);
250 251 252 253 254 255 256 257 258 259

	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 */
260
		const auto &root = mapper_get_music_directory_fs();
261

262
		const auto path_fs = uri_fs.IsNull()
263
			? root
264
			: AllocatedPath::Build(root, uri_fs.c_str());
265

266 267
		recursive_watch_subdirectories(directory, path_fs,
					       watch_directory_depth(directory));
268 269
	}

270 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 */
	    (watch_directory_depth(directory) == inotify_max_depth &&
	     (mask & (IN_CREATE|IN_ISDIR)) == (IN_CREATE|IN_ISDIR))) {
		/* a file was changed, or a directory was
276 277
		   moved/deleted: queue a database update */

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

void
289
mpd_inotify_init(unsigned max_depth)
290
{
291
	LogDebug(inotify_domain, "initializing inotify");
292

293
	const auto &path = mapper_get_music_directory_fs();
294
	if (path.IsNull()) {
295
		LogDebug(inotify_domain, "no music directory configured");
296 297 298
		return;
	}

299
	Error error;
300 301
	inotify_source = InotifySource::Create(*main_loop,
					       mpd_inotify_callback, nullptr,
302
					       error);
303
	if (inotify_source == nullptr) {
304
		LogError(error);
305 306 307
		return;
	}

308 309
	inotify_max_depth = max_depth;

310
	int descriptor = inotify_source->Add(path.c_str(), IN_MASK, error);
311
	if (descriptor < 0) {
312
		LogError(error);
313
		delete inotify_source;
314
		inotify_source = nullptr;
315 316 317
		return;
	}

318
	inotify_root = new WatchDirectory(nullptr, path, descriptor);
319

320 321
	tree_add_watch_directory(inotify_root);

322
	recursive_watch_subdirectories(inotify_root, path, 0);
323

324
	inotify_queue = new InotifyQueue(*main_loop);
325

326
	LogDebug(inotify_domain, "watching music directory");
327 328 329 330 331
}

void
mpd_inotify_finish(void)
{
332
	if (inotify_source == nullptr)
333 334
		return;

335
	delete inotify_queue;
336
	delete inotify_source;
337
	delete inotify_root;
338
	inotify_directories.clear();
339
}