blob: 50827acbd8e98fdb844a1089a0bc530275d9dac8 [file] [log] [blame]
[email protected]e7b3a612012-01-05 02:18:181// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]5199d742010-08-19 10:35:462// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]493c8002011-04-14 16:56:015#include "base/files/file_path_watcher.h"
[email protected]5199d742010-08-19 10:35:466
7#include <errno.h>
8#include <string.h>
9#include <sys/inotify.h>
10#include <sys/ioctl.h>
11#include <sys/select.h>
12#include <unistd.h>
13
14#include <algorithm>
[email protected]f8d025c2014-05-13 19:31:3015#include <map>
[email protected]5199d742010-08-19 10:35:4616#include <set>
17#include <utility>
18#include <vector>
19
[email protected]f4412a882011-10-05 16:58:2020#include "base/bind.h"
[email protected]14c1c232013-06-11 17:52:4421#include "base/containers/hash_tables.h"
[email protected]f8d025c2014-05-13 19:31:3022#include "base/files/file_enumerator.h"
[email protected]57999812013-02-24 05:40:5223#include "base/files/file_path.h"
[email protected]e3177dd52014-08-13 20:22:1424#include "base/files/file_util.h"
[email protected]fee46a82010-12-09 16:42:1525#include "base/lazy_instance.h"
[email protected]c62dd9d2011-09-21 18:05:4126#include "base/location.h"
[email protected]5199d742010-08-19 10:35:4627#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1528#include "base/memory/scoped_ptr.h"
[email protected]2025d002012-11-14 20:54:3529#include "base/posix/eintr_wrapper.h"
skyostil054861d2015-04-30 19:06:1530#include "base/single_thread_task_runner.h"
[email protected]20305ec2011-01-21 04:55:5231#include "base/synchronization/lock.h"
skyostil054861d2015-04-30 19:06:1532#include "base/thread_task_runner_handle.h"
[email protected]34b99632011-01-01 01:01:0633#include "base/threading/thread.h"
primianoa7b8dcb2015-01-31 18:21:1434#include "base/trace_event/trace_event.h"
[email protected]5199d742010-08-19 10:35:4635
[email protected]493c8002011-04-14 16:56:0136namespace base {
[email protected]493c8002011-04-14 16:56:0137
[email protected]5199d742010-08-19 10:35:4638namespace {
39
40class FilePathWatcherImpl;
41
42// Singleton to manage all inotify watches.
43// TODO(tony): It would be nice if this wasn't a singleton.
44// http://crbug.com/38174
45class InotifyReader {
46 public:
47 typedef int Watch; // Watch descriptor used by AddWatch and RemoveWatch.
48 static const Watch kInvalidWatch = -1;
49
50 // Watch directory |path| for changes. |watcher| will be notified on each
51 // change. Returns kInvalidWatch on failure.
52 Watch AddWatch(const FilePath& path, FilePathWatcherImpl* watcher);
53
[email protected]dae3f532014-04-26 22:26:3854 // Remove |watch| if it's valid.
55 void RemoveWatch(Watch watch, FilePathWatcherImpl* watcher);
[email protected]5199d742010-08-19 10:35:4656
57 // Callback for InotifyReaderTask.
58 void OnInotifyEvent(const inotify_event* event);
59
60 private:
[email protected]b264eab2013-11-27 23:22:0861 friend struct DefaultLazyInstanceTraits<InotifyReader>;
[email protected]5199d742010-08-19 10:35:4662
63 typedef std::set<FilePathWatcherImpl*> WatcherSet;
64
65 InotifyReader();
66 ~InotifyReader();
67
68 // We keep track of which delegates want to be notified on which watches.
[email protected]b264eab2013-11-27 23:22:0869 hash_map<Watch, WatcherSet> watchers_;
[email protected]5199d742010-08-19 10:35:4670
71 // Lock to protect watchers_.
[email protected]b264eab2013-11-27 23:22:0872 Lock lock_;
[email protected]5199d742010-08-19 10:35:4673
74 // Separate thread on which we run blocking read for inotify events.
[email protected]b264eab2013-11-27 23:22:0875 Thread thread_;
[email protected]5199d742010-08-19 10:35:4676
77 // File descriptor returned by inotify_init.
78 const int inotify_fd_;
79
80 // Use self-pipe trick to unblock select during shutdown.
81 int shutdown_pipe_[2];
82
83 // Flag set to true when startup was successful.
84 bool valid_;
85
86 DISALLOW_COPY_AND_ASSIGN(InotifyReader);
87};
88
[email protected]d64abe12011-03-22 20:14:0689class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate,
90 public MessageLoop::DestructionObserver {
[email protected]5199d742010-08-19 10:35:4691 public:
92 FilePathWatcherImpl();
[email protected]5199d742010-08-19 10:35:4693
94 // Called for each event coming from the watch. |fired_watch| identifies the
95 // watch that fired, |child| indicates what has changed, and is relative to
[email protected]f8d025c2014-05-13 19:31:3096 // the currently watched path for |fired_watch|.
97 //
98 // |created| is true if the object appears.
99 // |deleted| is true if the object disappears.
100 // |is_dir| is true if the object is a directory.
[email protected]5199d742010-08-19 10:35:46101 void OnFilePathChanged(InotifyReader::Watch fired_watch,
102 const FilePath::StringType& child,
[email protected]f8d025c2014-05-13 19:31:30103 bool created,
104 bool deleted,
105 bool is_dir);
[email protected]5199d742010-08-19 10:35:46106
[email protected]dae3f532014-04-26 22:26:38107 protected:
viettrungluub9f1b812014-10-22 01:48:30108 ~FilePathWatcherImpl() override {}
[email protected]dae3f532014-04-26 22:26:38109
110 private:
[email protected]5199d742010-08-19 10:35:46111 // Start watching |path| for changes and notify |delegate| on each change.
112 // Returns true if watch for |path| has been added successfully.
viettrungluub9f1b812014-10-22 01:48:30113 bool Watch(const FilePath& path,
114 bool recursive,
115 const FilePathWatcher::Callback& callback) override;
[email protected]5199d742010-08-19 10:35:46116
117 // Cancel the watch. This unregisters the instance with InotifyReader.
viettrungluub9f1b812014-10-22 01:48:30118 void Cancel() override;
[email protected]5199d742010-08-19 10:35:46119
[email protected]dae3f532014-04-26 22:26:38120 // Cleans up and stops observing the message_loop() thread.
viettrungluub9f1b812014-10-22 01:48:30121 void CancelOnMessageLoopThread() override;
[email protected]dae3f532014-04-26 22:26:38122
[email protected]d64abe12011-03-22 20:14:06123 // Deletion of the FilePathWatcher will call Cancel() to dispose of this
124 // object in the right thread. This also observes destruction of the required
125 // cleanup thread, in case it quits before Cancel() is called.
viettrungluub9f1b812014-10-22 01:48:30126 void WillDestroyCurrentMessageLoop() override;
[email protected]d64abe12011-03-22 20:14:06127
thestigbd265f9692014-12-19 22:51:16128 // Inotify watches are installed for all directory components of |target_|.
129 // A WatchEntry instance holds:
130 // - |watch|: the watch descriptor for a component.
131 // - |subdir|: the subdirectory that identifies the next component.
132 // - For the last component, there is no next component, so it is empty.
133 // - |linkname|: the target of the symlink.
134 // - Only if the target being watched is a symbolic link.
[email protected]5199d742010-08-19 10:35:46135 struct WatchEntry {
[email protected]dae3f532014-04-26 22:26:38136 explicit WatchEntry(const FilePath::StringType& dirname)
137 : watch(InotifyReader::kInvalidWatch),
138 subdir(dirname) {}
[email protected]5199d742010-08-19 10:35:46139
[email protected]dae3f532014-04-26 22:26:38140 InotifyReader::Watch watch;
141 FilePath::StringType subdir;
142 FilePath::StringType linkname;
[email protected]5199d742010-08-19 10:35:46143 };
144 typedef std::vector<WatchEntry> WatchVector;
145
146 // Reconfigure to watch for the most specific parent directory of |target_|
[email protected]f8d025c2014-05-13 19:31:30147 // that exists. Also calls UpdateRecursiveWatches() below.
148 void UpdateWatches();
149
150 // Reconfigure to recursively watch |target_| and all its sub-directories.
151 // - This is a no-op if the watch is not recursive.
152 // - If |target_| does not exist, then clear all the recursive watches.
153 // - Assuming |target_| exists, passing kInvalidWatch as |fired_watch| forces
154 // addition of recursive watches for |target_|.
155 // - Otherwise, only the directory associated with |fired_watch| and its
156 // sub-directories will be reconfigured.
157 void UpdateRecursiveWatches(InotifyReader::Watch fired_watch, bool is_dir);
158
159 // Enumerate recursively through |path| and add / update watches.
160 void UpdateRecursiveWatchesForPath(const FilePath& path);
161
162 // Do internal bookkeeping to update mappings between |watch| and its
163 // associated full path |path|.
164 void TrackWatchForRecursion(InotifyReader::Watch watch, const FilePath& path);
165
166 // Remove all the recursive watches.
167 void RemoveRecursiveWatches();
[email protected]5199d742010-08-19 10:35:46168
[email protected]dae3f532014-04-26 22:26:38169 // |path| is a symlink to a non-existent target. Attempt to add a watch to
jbudorick93e97412015-07-23 15:26:25170 // the link target's parent directory. Update |watch_entry| on success.
171 void AddWatchForBrokenSymlink(const FilePath& path, WatchEntry* watch_entry);
[email protected]dae3f532014-04-26 22:26:38172
173 bool HasValidWatchVector() const;
174
[email protected]6b5d0022013-01-15 00:37:47175 // Callback to notify upon changes.
176 FilePathWatcher::Callback callback_;
[email protected]5199d742010-08-19 10:35:46177
178 // The file or directory we're supposed to watch.
179 FilePath target_;
180
[email protected]f8d025c2014-05-13 19:31:30181 bool recursive_;
182
[email protected]5199d742010-08-19 10:35:46183 // The vector of watches and next component names for all path components,
184 // starting at the root directory. The last entry corresponds to the watch for
[email protected]dae3f532014-04-26 22:26:38185 // |target_| and always stores an empty next component name in |subdir|.
[email protected]5199d742010-08-19 10:35:46186 WatchVector watches_;
187
[email protected]f8d025c2014-05-13 19:31:30188 hash_map<InotifyReader::Watch, FilePath> recursive_paths_by_watch_;
189 std::map<FilePath, InotifyReader::Watch> recursive_watches_by_path_;
190
[email protected]5199d742010-08-19 10:35:46191 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
192};
193
[email protected]e7b3a612012-01-05 02:18:18194void InotifyReaderCallback(InotifyReader* reader, int inotify_fd,
195 int shutdown_fd) {
196 // Make sure the file descriptors are good for use with select().
197 CHECK_LE(0, inotify_fd);
198 CHECK_GT(FD_SETSIZE, inotify_fd);
199 CHECK_LE(0, shutdown_fd);
200 CHECK_GT(FD_SETSIZE, shutdown_fd);
[email protected]5199d742010-08-19 10:35:46201
ssid759dd8c2015-02-09 21:25:39202 trace_event::TraceLog::GetInstance()->SetCurrentThreadBlocksMessageLoop();
[email protected]14040a02013-10-22 02:16:58203
[email protected]e7b3a612012-01-05 02:18:18204 while (true) {
205 fd_set rfds;
206 FD_ZERO(&rfds);
207 FD_SET(inotify_fd, &rfds);
208 FD_SET(shutdown_fd, &rfds);
[email protected]5199d742010-08-19 10:35:46209
[email protected]e7b3a612012-01-05 02:18:18210 // Wait until some inotify events are available.
211 int select_result =
212 HANDLE_EINTR(select(std::max(inotify_fd, shutdown_fd) + 1,
213 &rfds, NULL, NULL, NULL));
214 if (select_result < 0) {
215 DPLOG(WARNING) << "select failed";
216 return;
217 }
[email protected]5199d742010-08-19 10:35:46218
[email protected]e7b3a612012-01-05 02:18:18219 if (FD_ISSET(shutdown_fd, &rfds))
220 return;
[email protected]5199d742010-08-19 10:35:46221
[email protected]e7b3a612012-01-05 02:18:18222 // Adjust buffer size to current event queue size.
223 int buffer_size;
224 int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd, FIONREAD,
225 &buffer_size));
[email protected]5199d742010-08-19 10:35:46226
[email protected]e7b3a612012-01-05 02:18:18227 if (ioctl_result != 0) {
228 DPLOG(WARNING) << "ioctl failed";
229 return;
230 }
[email protected]5199d742010-08-19 10:35:46231
[email protected]e7b3a612012-01-05 02:18:18232 std::vector<char> buffer(buffer_size);
[email protected]5199d742010-08-19 10:35:46233
[email protected]e7b3a612012-01-05 02:18:18234 ssize_t bytes_read = HANDLE_EINTR(read(inotify_fd, &buffer[0],
235 buffer_size));
[email protected]5199d742010-08-19 10:35:46236
[email protected]e7b3a612012-01-05 02:18:18237 if (bytes_read < 0) {
238 DPLOG(WARNING) << "read from inotify fd failed";
239 return;
240 }
[email protected]5199d742010-08-19 10:35:46241
[email protected]e7b3a612012-01-05 02:18:18242 ssize_t i = 0;
243 while (i < bytes_read) {
244 inotify_event* event = reinterpret_cast<inotify_event*>(&buffer[i]);
245 size_t event_size = sizeof(inotify_event) + event->len;
246 DCHECK(i + event_size <= static_cast<size_t>(bytes_read));
247 reader->OnInotifyEvent(event);
248 i += event_size;
[email protected]5199d742010-08-19 10:35:46249 }
250 }
[email protected]e7b3a612012-01-05 02:18:18251}
[email protected]5199d742010-08-19 10:35:46252
[email protected]b264eab2013-11-27 23:22:08253static LazyInstance<InotifyReader>::Leaky g_inotify_reader =
[email protected]6de0fd1d2011-11-15 13:31:49254 LAZY_INSTANCE_INITIALIZER;
[email protected]fee46a82010-12-09 16:42:15255
[email protected]5199d742010-08-19 10:35:46256InotifyReader::InotifyReader()
257 : thread_("inotify_reader"),
258 inotify_fd_(inotify_init()),
259 valid_(false) {
[email protected]de85c522013-11-26 03:41:58260 if (inotify_fd_ < 0)
261 PLOG(ERROR) << "inotify_init() failed";
262
[email protected]5199d742010-08-19 10:35:46263 shutdown_pipe_[0] = -1;
264 shutdown_pipe_[1] = -1;
265 if (inotify_fd_ >= 0 && pipe(shutdown_pipe_) == 0 && thread_.Start()) {
skyostil054861d2015-04-30 19:06:15266 thread_.task_runner()->PostTask(
[email protected]dae3f532014-04-26 22:26:38267 FROM_HERE,
268 Bind(&InotifyReaderCallback, this, inotify_fd_, shutdown_pipe_[0]));
[email protected]5199d742010-08-19 10:35:46269 valid_ = true;
270 }
271}
272
273InotifyReader::~InotifyReader() {
274 if (valid_) {
275 // Write to the self-pipe so that the select call in InotifyReaderTask
276 // returns.
277 ssize_t ret = HANDLE_EINTR(write(shutdown_pipe_[1], "", 1));
278 DPCHECK(ret > 0);
279 DCHECK_EQ(ret, 1);
280 thread_.Stop();
281 }
282 if (inotify_fd_ >= 0)
283 close(inotify_fd_);
284 if (shutdown_pipe_[0] >= 0)
285 close(shutdown_pipe_[0]);
286 if (shutdown_pipe_[1] >= 0)
287 close(shutdown_pipe_[1]);
288}
289
290InotifyReader::Watch InotifyReader::AddWatch(
291 const FilePath& path, FilePathWatcherImpl* watcher) {
292 if (!valid_)
293 return kInvalidWatch;
294
[email protected]b264eab2013-11-27 23:22:08295 AutoLock auto_lock(lock_);
[email protected]5199d742010-08-19 10:35:46296
297 Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(),
[email protected]f8d025c2014-05-13 19:31:30298 IN_ATTRIB | IN_CREATE | IN_DELETE |
[email protected]5199d742010-08-19 10:35:46299 IN_CLOSE_WRITE | IN_MOVE |
300 IN_ONLYDIR);
301
302 if (watch == kInvalidWatch)
303 return kInvalidWatch;
304
305 watchers_[watch].insert(watcher);
306
307 return watch;
308}
309
[email protected]dae3f532014-04-26 22:26:38310void InotifyReader::RemoveWatch(Watch watch, FilePathWatcherImpl* watcher) {
311 if (!valid_ || (watch == kInvalidWatch))
312 return;
[email protected]5199d742010-08-19 10:35:46313
[email protected]b264eab2013-11-27 23:22:08314 AutoLock auto_lock(lock_);
[email protected]5199d742010-08-19 10:35:46315
316 watchers_[watch].erase(watcher);
317
318 if (watchers_[watch].empty()) {
319 watchers_.erase(watch);
[email protected]dae3f532014-04-26 22:26:38320 inotify_rm_watch(inotify_fd_, watch);
[email protected]5199d742010-08-19 10:35:46321 }
[email protected]5199d742010-08-19 10:35:46322}
323
324void InotifyReader::OnInotifyEvent(const inotify_event* event) {
325 if (event->mask & IN_IGNORED)
326 return;
327
328 FilePath::StringType child(event->len ? event->name : FILE_PATH_LITERAL(""));
[email protected]b264eab2013-11-27 23:22:08329 AutoLock auto_lock(lock_);
[email protected]5199d742010-08-19 10:35:46330
331 for (WatcherSet::iterator watcher = watchers_[event->wd].begin();
332 watcher != watchers_[event->wd].end();
333 ++watcher) {
[email protected]b8ca91f2011-03-18 04:11:49334 (*watcher)->OnFilePathChanged(event->wd,
335 child,
[email protected]f8d025c2014-05-13 19:31:30336 event->mask & (IN_CREATE | IN_MOVED_TO),
337 event->mask & (IN_DELETE | IN_MOVED_FROM),
338 event->mask & IN_ISDIR);
[email protected]5199d742010-08-19 10:35:46339 }
340}
341
[email protected]f8d025c2014-05-13 19:31:30342FilePathWatcherImpl::FilePathWatcherImpl()
343 : recursive_(false) {
[email protected]5199d742010-08-19 10:35:46344}
345
[email protected]aa8946b2012-03-13 08:33:59346void FilePathWatcherImpl::OnFilePathChanged(InotifyReader::Watch fired_watch,
347 const FilePath::StringType& child,
[email protected]f8d025c2014-05-13 19:31:30348 bool created,
349 bool deleted,
350 bool is_dir) {
skyostil054861d2015-04-30 19:06:15351 if (!task_runner()->BelongsToCurrentThread()) {
352 // Switch to task_runner() to access |watches_| safely.
353 task_runner()->PostTask(FROM_HERE,
354 Bind(&FilePathWatcherImpl::OnFilePathChanged, this,
355 fired_watch, child, created, deleted, is_dir));
[email protected]dae3f532014-04-26 22:26:38356 return;
357 }
358
359 // Check to see if CancelOnMessageLoopThread() has already been called.
360 // May happen when code flow reaches here from the PostTask() above.
361 if (watches_.empty()) {
362 DCHECK(target_.empty());
[email protected]b8ca91f2011-03-18 04:11:49363 return;
364 }
365
366 DCHECK(MessageLoopForIO::current());
[email protected]dae3f532014-04-26 22:26:38367 DCHECK(HasValidWatchVector());
[email protected]5199d742010-08-19 10:35:46368
[email protected]f8d025c2014-05-13 19:31:30369 // Used below to avoid multiple recursive updates.
370 bool did_update = false;
371
[email protected]5199d742010-08-19 10:35:46372 // Find the entry in |watches_| that corresponds to |fired_watch|.
[email protected]dae3f532014-04-26 22:26:38373 for (size_t i = 0; i < watches_.size(); ++i) {
374 const WatchEntry& watch_entry = watches_[i];
375 if (fired_watch != watch_entry.watch)
376 continue;
[email protected]9a2ab282011-09-05 15:02:12377
[email protected]dae3f532014-04-26 22:26:38378 // Check whether a path component of |target_| changed.
379 bool change_on_target_path =
380 child.empty() ||
381 (child == watch_entry.linkname) ||
382 (child == watch_entry.subdir);
[email protected]9a2ab282011-09-05 15:02:12383
[email protected]dae3f532014-04-26 22:26:38384 // Check if the change references |target_| or a direct child of |target_|.
thestigbd265f9692014-12-19 22:51:16385 bool target_changed;
386 if (watch_entry.subdir.empty()) {
387 // The fired watch is for a WatchEntry without a subdir. Thus for a given
388 // |target_| = "/path/to/foo", this is for "foo". Here, check either:
389 // - the target has no symlink: it is the target and it changed.
390 // - the target has a symlink, and it matches |child|.
391 target_changed = (watch_entry.linkname.empty() ||
392 child == watch_entry.linkname);
393 } else {
394 // The fired watch is for a WatchEntry with a subdir. Thus for a given
395 // |target_| = "/path/to/foo", this is for {"/", "/path", "/path/to"}.
396 // So we can safely access the next WatchEntry since we have not reached
397 // the end yet. Check |watch_entry| is for "/path/to", i.e. the next
398 // element is "foo".
399 bool next_watch_may_be_for_target = watches_[i + 1].subdir.empty();
400 if (next_watch_may_be_for_target) {
401 // The current |watch_entry| is for "/path/to", so check if the |child|
402 // that changed is "foo".
403 target_changed = watch_entry.subdir == child;
404 } else {
405 // The current |watch_entry| is not for "/path/to", so the next entry
406 // cannot be "foo". Thus |target_| has not changed.
407 target_changed = false;
408 }
409 }
[email protected]9a2ab282011-09-05 15:02:12410
[email protected]dae3f532014-04-26 22:26:38411 // Update watches if a directory component of the |target_| path
412 // (dis)appears. Note that we don't add the additional restriction of
413 // checking the event mask to see if it is for a directory here as changes
414 // to symlinks on the target path will not have IN_ISDIR set in the event
415 // masks. As a result we may sometimes call UpdateWatches() unnecessarily.
[email protected]f8d025c2014-05-13 19:31:30416 if (change_on_target_path && (created || deleted) && !did_update) {
417 UpdateWatches();
418 did_update = true;
[email protected]dae3f532014-04-26 22:26:38419 }
420
421 // Report the following events:
422 // - The target or a direct child of the target got changed (in case the
423 // watched path refers to a directory).
424 // - One of the parent directories got moved or deleted, since the target
425 // disappears in this case.
426 // - One of the parent directories appears. The event corresponding to
427 // the target appearing might have been missed in this case, so recheck.
428 if (target_changed ||
[email protected]f8d025c2014-05-13 19:31:30429 (change_on_target_path && deleted) ||
430 (change_on_target_path && created && PathExists(target_))) {
431 if (!did_update) {
432 UpdateRecursiveWatches(fired_watch, is_dir);
433 did_update = true;
434 }
[email protected]dae3f532014-04-26 22:26:38435 callback_.Run(target_, false /* error */);
436 return;
[email protected]9a2ab282011-09-05 15:02:12437 }
[email protected]5199d742010-08-19 10:35:46438 }
[email protected]f8d025c2014-05-13 19:31:30439
440 if (ContainsKey(recursive_paths_by_watch_, fired_watch)) {
441 if (!did_update)
442 UpdateRecursiveWatches(fired_watch, is_dir);
443 callback_.Run(target_, false /* error */);
444 }
[email protected]5199d742010-08-19 10:35:46445}
446
447bool FilePathWatcherImpl::Watch(const FilePath& path,
[email protected]66a59402012-12-05 00:36:39448 bool recursive,
[email protected]6b5d0022013-01-15 00:37:47449 const FilePathWatcher::Callback& callback) {
[email protected]5199d742010-08-19 10:35:46450 DCHECK(target_.empty());
[email protected]b8ca91f2011-03-18 04:11:49451 DCHECK(MessageLoopForIO::current());
[email protected]5199d742010-08-19 10:35:46452
skyostil054861d2015-04-30 19:06:15453 set_task_runner(ThreadTaskRunnerHandle::Get());
[email protected]6b5d0022013-01-15 00:37:47454 callback_ = callback;
[email protected]5199d742010-08-19 10:35:46455 target_ = path;
[email protected]f8d025c2014-05-13 19:31:30456 recursive_ = recursive;
[email protected]d64abe12011-03-22 20:14:06457 MessageLoop::current()->AddDestructionObserver(this);
458
[email protected]5199d742010-08-19 10:35:46459 std::vector<FilePath::StringType> comps;
460 target_.GetComponents(&comps);
461 DCHECK(!comps.empty());
[email protected]dae3f532014-04-26 22:26:38462 for (size_t i = 1; i < comps.size(); ++i)
463 watches_.push_back(WatchEntry(comps[i]));
464 watches_.push_back(WatchEntry(FilePath::StringType()));
[email protected]f8d025c2014-05-13 19:31:30465 UpdateWatches();
466 return true;
[email protected]5199d742010-08-19 10:35:46467}
468
469void FilePathWatcherImpl::Cancel() {
[email protected]6b5d0022013-01-15 00:37:47470 if (callback_.is_null()) {
[email protected]dae3f532014-04-26 22:26:38471 // Watch was never called, or the message_loop() thread is already gone.
[email protected]d64abe12011-03-22 20:14:06472 set_cancelled();
[email protected]b8ca91f2011-03-18 04:11:49473 return;
474 }
475
[email protected]dae3f532014-04-26 22:26:38476 // Switch to the message_loop() if necessary so we can access |watches_|.
skyostil054861d2015-04-30 19:06:15477 if (!task_runner()->BelongsToCurrentThread()) {
478 task_runner()->PostTask(FROM_HERE, Bind(&FilePathWatcher::CancelWatch,
479 make_scoped_refptr(this)));
[email protected]d64abe12011-03-22 20:14:06480 } else {
481 CancelOnMessageLoopThread();
[email protected]5199d742010-08-19 10:35:46482 }
[email protected]d64abe12011-03-22 20:14:06483}
[email protected]5199d742010-08-19 10:35:46484
[email protected]d64abe12011-03-22 20:14:06485void FilePathWatcherImpl::CancelOnMessageLoopThread() {
skyostil054861d2015-04-30 19:06:15486 DCHECK(task_runner()->BelongsToCurrentThread());
[email protected]dae3f532014-04-26 22:26:38487 set_cancelled();
[email protected]d64abe12011-03-22 20:14:06488
[email protected]6b5d0022013-01-15 00:37:47489 if (!callback_.is_null()) {
[email protected]f8a3f1372011-08-18 00:26:25490 MessageLoop::current()->RemoveDestructionObserver(this);
[email protected]6b5d0022013-01-15 00:37:47491 callback_.Reset();
[email protected]5199d742010-08-19 10:35:46492 }
[email protected]f8a3f1372011-08-18 00:26:25493
[email protected]dae3f532014-04-26 22:26:38494 for (size_t i = 0; i < watches_.size(); ++i)
495 g_inotify_reader.Get().RemoveWatch(watches_[i].watch, this);
[email protected]f8a3f1372011-08-18 00:26:25496 watches_.clear();
497 target_.clear();
[email protected]f8d025c2014-05-13 19:31:30498
499 if (recursive_)
500 RemoveRecursiveWatches();
[email protected]d64abe12011-03-22 20:14:06501}
502
503void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() {
504 CancelOnMessageLoopThread();
[email protected]5199d742010-08-19 10:35:46505}
506
[email protected]f8d025c2014-05-13 19:31:30507void FilePathWatcherImpl::UpdateWatches() {
[email protected]dae3f532014-04-26 22:26:38508 // Ensure this runs on the message_loop() exclusively in order to avoid
[email protected]5199d742010-08-19 10:35:46509 // concurrency issues.
skyostil054861d2015-04-30 19:06:15510 DCHECK(task_runner()->BelongsToCurrentThread());
[email protected]dae3f532014-04-26 22:26:38511 DCHECK(HasValidWatchVector());
[email protected]5199d742010-08-19 10:35:46512
513 // Walk the list of watches and update them as we go.
514 FilePath path(FILE_PATH_LITERAL("/"));
[email protected]dae3f532014-04-26 22:26:38515 for (size_t i = 0; i < watches_.size(); ++i) {
516 WatchEntry& watch_entry = watches_[i];
517 InotifyReader::Watch old_watch = watch_entry.watch;
518 watch_entry.watch = InotifyReader::kInvalidWatch;
519 watch_entry.linkname.clear();
jbudorick93e97412015-07-23 15:26:25520 watch_entry.watch = g_inotify_reader.Get().AddWatch(path, this);
521 if (watch_entry.watch == InotifyReader::kInvalidWatch) {
522 // Ignore the error code (beyond symlink handling) to attempt to add
523 // watches on accessible children of unreadable directories. Note that
524 // this is a best-effort attempt; we may not catch events in this
525 // scenario.
526 if (IsLink(path))
527 AddWatchForBrokenSymlink(path, &watch_entry);
[email protected]5199d742010-08-19 10:35:46528 }
[email protected]dae3f532014-04-26 22:26:38529 if (old_watch != watch_entry.watch)
[email protected]fee46a82010-12-09 16:42:15530 g_inotify_reader.Get().RemoveWatch(old_watch, this);
[email protected]dae3f532014-04-26 22:26:38531 path = path.Append(watch_entry.subdir);
[email protected]5199d742010-08-19 10:35:46532 }
533
[email protected]f8d025c2014-05-13 19:31:30534 UpdateRecursiveWatches(InotifyReader::kInvalidWatch,
535 false /* is directory? */);
536}
537
538void FilePathWatcherImpl::UpdateRecursiveWatches(
539 InotifyReader::Watch fired_watch,
540 bool is_dir) {
541 if (!recursive_)
542 return;
543
544 if (!DirectoryExists(target_)) {
545 RemoveRecursiveWatches();
546 return;
547 }
548
549 // Check to see if this is a forced update or if some component of |target_|
550 // has changed. For these cases, redo the watches for |target_| and below.
551 if (!ContainsKey(recursive_paths_by_watch_, fired_watch)) {
552 UpdateRecursiveWatchesForPath(target_);
553 return;
554 }
555
556 // Underneath |target_|, only directory changes trigger watch updates.
557 if (!is_dir)
558 return;
559
560 const FilePath& changed_dir = recursive_paths_by_watch_[fired_watch];
561
562 std::map<FilePath, InotifyReader::Watch>::iterator start_it =
563 recursive_watches_by_path_.lower_bound(changed_dir);
564 std::map<FilePath, InotifyReader::Watch>::iterator end_it = start_it;
565 for (; end_it != recursive_watches_by_path_.end(); ++end_it) {
566 const FilePath& cur_path = end_it->first;
567 if (!changed_dir.IsParent(cur_path))
568 break;
569 if (!DirectoryExists(cur_path))
570 g_inotify_reader.Get().RemoveWatch(end_it->second, this);
571 }
572 recursive_watches_by_path_.erase(start_it, end_it);
573 UpdateRecursiveWatchesForPath(changed_dir);
574}
575
576void FilePathWatcherImpl::UpdateRecursiveWatchesForPath(const FilePath& path) {
577 DCHECK(recursive_);
578 DCHECK(!path.empty());
579 DCHECK(DirectoryExists(path));
580
581 // Note: SHOW_SYM_LINKS exposes symlinks as symlinks, so they are ignored
582 // rather than followed. Following symlinks can easily lead to the undesirable
583 // situation where the entire file system is being watched.
584 FileEnumerator enumerator(
585 path,
586 true /* recursive enumeration */,
587 FileEnumerator::DIRECTORIES | FileEnumerator::SHOW_SYM_LINKS);
588 for (FilePath current = enumerator.Next();
589 !current.empty();
590 current = enumerator.Next()) {
591 DCHECK(enumerator.GetInfo().IsDirectory());
592
593 if (!ContainsKey(recursive_watches_by_path_, current)) {
594 // Add new watches.
595 InotifyReader::Watch watch =
596 g_inotify_reader.Get().AddWatch(current, this);
597 TrackWatchForRecursion(watch, current);
598 } else {
599 // Update existing watches.
600 InotifyReader::Watch old_watch = recursive_watches_by_path_[current];
601 DCHECK_NE(InotifyReader::kInvalidWatch, old_watch);
602 InotifyReader::Watch watch =
603 g_inotify_reader.Get().AddWatch(current, this);
604 if (watch != old_watch) {
605 g_inotify_reader.Get().RemoveWatch(old_watch, this);
606 recursive_paths_by_watch_.erase(old_watch);
607 recursive_watches_by_path_.erase(current);
608 TrackWatchForRecursion(watch, current);
609 }
610 }
611 }
612}
613
614void FilePathWatcherImpl::TrackWatchForRecursion(InotifyReader::Watch watch,
615 const FilePath& path) {
616 DCHECK(recursive_);
617 DCHECK(!path.empty());
618 DCHECK(target_.IsParent(path));
619
620 if (watch == InotifyReader::kInvalidWatch)
621 return;
622
623 DCHECK(!ContainsKey(recursive_paths_by_watch_, watch));
624 DCHECK(!ContainsKey(recursive_watches_by_path_, path));
625 recursive_paths_by_watch_[watch] = path;
626 recursive_watches_by_path_[path] = watch;
627}
628
629void FilePathWatcherImpl::RemoveRecursiveWatches() {
630 if (!recursive_)
631 return;
632
633 for (hash_map<InotifyReader::Watch, FilePath>::const_iterator it =
634 recursive_paths_by_watch_.begin();
635 it != recursive_paths_by_watch_.end();
636 ++it) {
637 g_inotify_reader.Get().RemoveWatch(it->first, this);
638 }
639 recursive_paths_by_watch_.clear();
640 recursive_watches_by_path_.clear();
[email protected]5199d742010-08-19 10:35:46641}
642
jbudorick93e97412015-07-23 15:26:25643void FilePathWatcherImpl::AddWatchForBrokenSymlink(const FilePath& path,
[email protected]dae3f532014-04-26 22:26:38644 WatchEntry* watch_entry) {
645 DCHECK_EQ(InotifyReader::kInvalidWatch, watch_entry->watch);
646 FilePath link;
647 if (!ReadSymbolicLink(path, &link))
jbudorick93e97412015-07-23 15:26:25648 return;
[email protected]dae3f532014-04-26 22:26:38649
650 if (!link.IsAbsolute())
651 link = path.DirName().Append(link);
652
653 // Try watching symlink target directory. If the link target is "/", then we
654 // shouldn't get here in normal situations and if we do, we'd watch "/" for
655 // changes to a component "/" which is harmless so no special treatment of
656 // this case is required.
657 InotifyReader::Watch watch =
658 g_inotify_reader.Get().AddWatch(link.DirName(), this);
659 if (watch == InotifyReader::kInvalidWatch) {
660 // TODO(craig) Symlinks only work if the parent directory for the target
661 // exist. Ideally we should make sure we've watched all the components of
662 // the symlink path for changes. See crbug.com/91561 for details.
663 DPLOG(WARNING) << "Watch failed for " << link.DirName().value();
jbudorick93e97412015-07-23 15:26:25664 return;
[email protected]dae3f532014-04-26 22:26:38665 }
666 watch_entry->watch = watch;
667 watch_entry->linkname = link.BaseName().value();
[email protected]dae3f532014-04-26 22:26:38668}
669
670bool FilePathWatcherImpl::HasValidWatchVector() const {
671 if (watches_.empty())
672 return false;
673 for (size_t i = 0; i < watches_.size() - 1; ++i) {
674 if (watches_[i].subdir.empty())
675 return false;
676 }
677 return watches_[watches_.size() - 1].subdir.empty();
678}
679
[email protected]5199d742010-08-19 10:35:46680} // namespace
681
682FilePathWatcher::FilePathWatcher() {
683 impl_ = new FilePathWatcherImpl();
684}
[email protected]493c8002011-04-14 16:56:01685
[email protected]493c8002011-04-14 16:56:01686} // namespace base