1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/files/file_path_watcher.h"
6
7 #include <errno.h>
8 #include <stddef.h>
9 #include <string.h>
10 #include <sys/inotify.h>
11 #include <sys/ioctl.h>
12 #include <sys/select.h>
13 #include <unistd.h>
14
15 #include <algorithm>
16 #include <map>
17 #include <memory>
18 #include <set>
19 #include <unordered_map>
20 #include <utility>
21 #include <vector>
22
23 #include "base/bind.h"
24 #include "base/files/file_enumerator.h"
25 #include "base/files/file_path.h"
26 #include "base/files/file_util.h"
27 #include "base/lazy_instance.h"
28 #include "base/location.h"
29 #include "base/logging.h"
30 #include "base/macros.h"
31 #include "base/memory/ptr_util.h"
32 #include "base/memory/weak_ptr.h"
33 #include "base/posix/eintr_wrapper.h"
34 #include "base/single_thread_task_runner.h"
35 #include "base/stl_util.h"
36 #include "base/synchronization/lock.h"
37 #include "base/threading/platform_thread.h"
38 #include "base/threading/sequenced_task_runner_handle.h"
39 #include "base/trace_event/trace_event.h"
40
41 namespace base {
42
43 namespace {
44
45 class FilePathWatcherImpl;
46 class InotifyReader;
47
48 class InotifyReaderThreadDelegate final : public PlatformThread::Delegate {
49 public:
InotifyReaderThreadDelegate(int inotify_fd)50 InotifyReaderThreadDelegate(int inotify_fd) : inotify_fd_(inotify_fd){};
51
52 ~InotifyReaderThreadDelegate() override = default;
53
54 private:
55 void ThreadMain() override;
56
57 int inotify_fd_;
58
59 DISALLOW_COPY_AND_ASSIGN(InotifyReaderThreadDelegate);
60 };
61
62 // Singleton to manage all inotify watches.
63 // TODO(tony): It would be nice if this wasn't a singleton.
64 // http://crbug.com/38174
65 class InotifyReader {
66 public:
67 typedef int Watch; // Watch descriptor used by AddWatch and RemoveWatch.
68 static const Watch kInvalidWatch = -1;
69
70 // Watch directory |path| for changes. |watcher| will be notified on each
71 // change. Returns kInvalidWatch on failure.
72 Watch AddWatch(const FilePath& path, FilePathWatcherImpl* watcher);
73
74 // Remove |watch| if it's valid.
75 void RemoveWatch(Watch watch, FilePathWatcherImpl* watcher);
76
77 // Callback for InotifyReaderTask.
78 void OnInotifyEvent(const inotify_event* event);
79
80 private:
81 friend struct LazyInstanceTraitsBase<InotifyReader>;
82
83 typedef std::set<FilePathWatcherImpl*> WatcherSet;
84
85 InotifyReader();
86 // There is no destructor because |g_inotify_reader| is a
87 // base::LazyInstace::Leaky object. Having a destructor causes build
88 // issues with GCC 6 (http://crbug.com/636346).
89
90 // Returns true on successful thread creation.
91 bool StartThread();
92
93 // We keep track of which delegates want to be notified on which watches.
94 std::unordered_map<Watch, WatcherSet> watchers_;
95
96 // Lock to protect watchers_.
97 Lock lock_;
98
99 // File descriptor returned by inotify_init.
100 const int inotify_fd_;
101
102 // Thread delegate for the Inotify thread.
103 InotifyReaderThreadDelegate thread_delegate_;
104
105 // Flag set to true when startup was successful.
106 bool valid_;
107
108 DISALLOW_COPY_AND_ASSIGN(InotifyReader);
109 };
110
111 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate {
112 public:
113 FilePathWatcherImpl();
114 ~FilePathWatcherImpl() override;
115
116 // Called for each event coming from the watch. |fired_watch| identifies the
117 // watch that fired, |child| indicates what has changed, and is relative to
118 // the currently watched path for |fired_watch|.
119 //
120 // |created| is true if the object appears.
121 // |deleted| is true if the object disappears.
122 // |is_dir| is true if the object is a directory.
123 void OnFilePathChanged(InotifyReader::Watch fired_watch,
124 const FilePath::StringType& child,
125 bool created,
126 bool deleted,
127 bool is_dir);
128
129 private:
130 void OnFilePathChangedOnOriginSequence(InotifyReader::Watch fired_watch,
131 const FilePath::StringType& child,
132 bool created,
133 bool deleted,
134 bool is_dir);
135
136 // Start watching |path| for changes and notify |delegate| on each change.
137 // Returns true if watch for |path| has been added successfully.
138 bool Watch(const FilePath& path,
139 bool recursive,
140 const FilePathWatcher::Callback& callback) override;
141
142 // Cancel the watch. This unregisters the instance with InotifyReader.
143 void Cancel() override;
144
145 // Inotify watches are installed for all directory components of |target_|.
146 // A WatchEntry instance holds:
147 // - |watch|: the watch descriptor for a component.
148 // - |subdir|: the subdirectory that identifies the next component.
149 // - For the last component, there is no next component, so it is empty.
150 // - |linkname|: the target of the symlink.
151 // - Only if the target being watched is a symbolic link.
152 struct WatchEntry {
WatchEntrybase::__anon7f9c86bd0111::FilePathWatcherImpl::WatchEntry153 explicit WatchEntry(const FilePath::StringType& dirname)
154 : watch(InotifyReader::kInvalidWatch),
155 subdir(dirname) {}
156
157 InotifyReader::Watch watch;
158 FilePath::StringType subdir;
159 FilePath::StringType linkname;
160 };
161 typedef std::vector<WatchEntry> WatchVector;
162
163 // Reconfigure to watch for the most specific parent directory of |target_|
164 // that exists. Also calls UpdateRecursiveWatches() below.
165 void UpdateWatches();
166
167 // Reconfigure to recursively watch |target_| and all its sub-directories.
168 // - This is a no-op if the watch is not recursive.
169 // - If |target_| does not exist, then clear all the recursive watches.
170 // - Assuming |target_| exists, passing kInvalidWatch as |fired_watch| forces
171 // addition of recursive watches for |target_|.
172 // - Otherwise, only the directory associated with |fired_watch| and its
173 // sub-directories will be reconfigured.
174 void UpdateRecursiveWatches(InotifyReader::Watch fired_watch, bool is_dir);
175
176 // Enumerate recursively through |path| and add / update watches.
177 void UpdateRecursiveWatchesForPath(const FilePath& path);
178
179 // Do internal bookkeeping to update mappings between |watch| and its
180 // associated full path |path|.
181 void TrackWatchForRecursion(InotifyReader::Watch watch, const FilePath& path);
182
183 // Remove all the recursive watches.
184 void RemoveRecursiveWatches();
185
186 // |path| is a symlink to a non-existent target. Attempt to add a watch to
187 // the link target's parent directory. Update |watch_entry| on success.
188 void AddWatchForBrokenSymlink(const FilePath& path, WatchEntry* watch_entry);
189
190 bool HasValidWatchVector() const;
191
192 // Callback to notify upon changes.
193 FilePathWatcher::Callback callback_;
194
195 // The file or directory we're supposed to watch.
196 FilePath target_;
197
198 bool recursive_;
199
200 // The vector of watches and next component names for all path components,
201 // starting at the root directory. The last entry corresponds to the watch for
202 // |target_| and always stores an empty next component name in |subdir|.
203 WatchVector watches_;
204
205 std::unordered_map<InotifyReader::Watch, FilePath> recursive_paths_by_watch_;
206 std::map<FilePath, InotifyReader::Watch> recursive_watches_by_path_;
207
208 // Read only while INotifyReader::lock_ is held, and used to post asynchronous
209 // notifications to the Watcher on its home task_runner(). Ideally this should
210 // be const, but since it is initialized from |weak_factory_|, which must
211 // appear after it, that is not possible.
212 WeakPtr<FilePathWatcherImpl> weak_ptr_;
213
214 WeakPtrFactory<FilePathWatcherImpl> weak_factory_;
215
216 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
217 };
218
219 LazyInstance<InotifyReader>::Leaky g_inotify_reader = LAZY_INSTANCE_INITIALIZER;
220
ThreadMain()221 void InotifyReaderThreadDelegate::ThreadMain() {
222 PlatformThread::SetName("inotify_reader");
223
224 // Make sure the file descriptors are good for use with select().
225 CHECK_LE(0, inotify_fd_);
226 CHECK_GT(FD_SETSIZE, inotify_fd_);
227
228 while (true) {
229 fd_set rfds;
230 FD_ZERO(&rfds);
231 FD_SET(inotify_fd_, &rfds);
232
233 // Wait until some inotify events are available.
234 int select_result =
235 HANDLE_EINTR(select(inotify_fd_ + 1, &rfds, nullptr, nullptr, nullptr));
236 if (select_result < 0) {
237 DPLOG(WARNING) << "select failed";
238 return;
239 }
240
241 // Adjust buffer size to current event queue size.
242 int buffer_size;
243 int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd_, FIONREAD, &buffer_size));
244
245 if (ioctl_result != 0) {
246 DPLOG(WARNING) << "ioctl failed";
247 return;
248 }
249
250 std::vector<char> buffer(buffer_size);
251
252 ssize_t bytes_read =
253 HANDLE_EINTR(read(inotify_fd_, &buffer[0], buffer_size));
254
255 if (bytes_read < 0) {
256 DPLOG(WARNING) << "read from inotify fd failed";
257 return;
258 }
259
260 ssize_t i = 0;
261 while (i < bytes_read) {
262 inotify_event* event = reinterpret_cast<inotify_event*>(&buffer[i]);
263 size_t event_size = sizeof(inotify_event) + event->len;
264 DCHECK(i + event_size <= static_cast<size_t>(bytes_read));
265 g_inotify_reader.Get().OnInotifyEvent(event);
266 i += event_size;
267 }
268 }
269 }
270
InotifyReader()271 InotifyReader::InotifyReader()
272 : inotify_fd_(inotify_init()),
273 thread_delegate_(inotify_fd_),
274 valid_(false) {
275 if (inotify_fd_ < 0) {
276 PLOG(ERROR) << "inotify_init() failed";
277 return;
278 }
279
280 if (!StartThread())
281 return;
282
283 valid_ = true;
284 }
285
StartThread()286 bool InotifyReader::StartThread() {
287 // This object is LazyInstance::Leaky, so thread_delegate_ will outlive the
288 // thread.
289 return PlatformThread::CreateNonJoinable(0, &thread_delegate_);
290 }
291
AddWatch(const FilePath & path,FilePathWatcherImpl * watcher)292 InotifyReader::Watch InotifyReader::AddWatch(
293 const FilePath& path, FilePathWatcherImpl* watcher) {
294 if (!valid_)
295 return kInvalidWatch;
296
297 AutoLock auto_lock(lock_);
298
299 Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(),
300 IN_ATTRIB | IN_CREATE | IN_DELETE |
301 IN_CLOSE_WRITE | IN_MOVE |
302 IN_ONLYDIR);
303
304 if (watch == kInvalidWatch)
305 return kInvalidWatch;
306
307 watchers_[watch].insert(watcher);
308
309 return watch;
310 }
311
RemoveWatch(Watch watch,FilePathWatcherImpl * watcher)312 void InotifyReader::RemoveWatch(Watch watch, FilePathWatcherImpl* watcher) {
313 if (!valid_ || (watch == kInvalidWatch))
314 return;
315
316 AutoLock auto_lock(lock_);
317
318 watchers_[watch].erase(watcher);
319
320 if (watchers_[watch].empty()) {
321 watchers_.erase(watch);
322 inotify_rm_watch(inotify_fd_, watch);
323 }
324 }
325
OnInotifyEvent(const inotify_event * event)326 void InotifyReader::OnInotifyEvent(const inotify_event* event) {
327 if (event->mask & IN_IGNORED)
328 return;
329
330 FilePath::StringType child(event->len ? event->name : FILE_PATH_LITERAL(""));
331 AutoLock auto_lock(lock_);
332
333 for (WatcherSet::iterator watcher = watchers_[event->wd].begin();
334 watcher != watchers_[event->wd].end();
335 ++watcher) {
336 (*watcher)->OnFilePathChanged(event->wd,
337 child,
338 event->mask & (IN_CREATE | IN_MOVED_TO),
339 event->mask & (IN_DELETE | IN_MOVED_FROM),
340 event->mask & IN_ISDIR);
341 }
342 }
343
FilePathWatcherImpl()344 FilePathWatcherImpl::FilePathWatcherImpl()
345 : recursive_(false), weak_factory_(this) {
346 weak_ptr_ = weak_factory_.GetWeakPtr();
347 }
348
~FilePathWatcherImpl()349 FilePathWatcherImpl::~FilePathWatcherImpl() {
350 DCHECK(!task_runner() || task_runner()->RunsTasksInCurrentSequence());
351 }
352
OnFilePathChanged(InotifyReader::Watch fired_watch,const FilePath::StringType & child,bool created,bool deleted,bool is_dir)353 void FilePathWatcherImpl::OnFilePathChanged(InotifyReader::Watch fired_watch,
354 const FilePath::StringType& child,
355 bool created,
356 bool deleted,
357 bool is_dir) {
358 DCHECK(!task_runner()->RunsTasksInCurrentSequence());
359
360 // This method is invoked on the Inotify thread. Switch to task_runner() to
361 // access |watches_| safely. Use a WeakPtr to prevent the callback from
362 // running after |this| is destroyed (i.e. after the watch is cancelled).
363 task_runner()->PostTask(
364 FROM_HERE,
365 BindOnce(&FilePathWatcherImpl::OnFilePathChangedOnOriginSequence,
366 weak_ptr_, fired_watch, child, created, deleted, is_dir));
367 }
368
OnFilePathChangedOnOriginSequence(InotifyReader::Watch fired_watch,const FilePath::StringType & child,bool created,bool deleted,bool is_dir)369 void FilePathWatcherImpl::OnFilePathChangedOnOriginSequence(
370 InotifyReader::Watch fired_watch,
371 const FilePath::StringType& child,
372 bool created,
373 bool deleted,
374 bool is_dir) {
375 DCHECK(task_runner()->RunsTasksInCurrentSequence());
376 DCHECK(!watches_.empty());
377 DCHECK(HasValidWatchVector());
378
379 // Used below to avoid multiple recursive updates.
380 bool did_update = false;
381
382 // Find the entry in |watches_| that corresponds to |fired_watch|.
383 for (size_t i = 0; i < watches_.size(); ++i) {
384 const WatchEntry& watch_entry = watches_[i];
385 if (fired_watch != watch_entry.watch)
386 continue;
387
388 // Check whether a path component of |target_| changed.
389 bool change_on_target_path =
390 child.empty() ||
391 (child == watch_entry.linkname) ||
392 (child == watch_entry.subdir);
393
394 // Check if the change references |target_| or a direct child of |target_|.
395 bool target_changed;
396 if (watch_entry.subdir.empty()) {
397 // The fired watch is for a WatchEntry without a subdir. Thus for a given
398 // |target_| = "/path/to/foo", this is for "foo". Here, check either:
399 // - the target has no symlink: it is the target and it changed.
400 // - the target has a symlink, and it matches |child|.
401 target_changed = (watch_entry.linkname.empty() ||
402 child == watch_entry.linkname);
403 } else {
404 // The fired watch is for a WatchEntry with a subdir. Thus for a given
405 // |target_| = "/path/to/foo", this is for {"/", "/path", "/path/to"}.
406 // So we can safely access the next WatchEntry since we have not reached
407 // the end yet. Check |watch_entry| is for "/path/to", i.e. the next
408 // element is "foo".
409 bool next_watch_may_be_for_target = watches_[i + 1].subdir.empty();
410 if (next_watch_may_be_for_target) {
411 // The current |watch_entry| is for "/path/to", so check if the |child|
412 // that changed is "foo".
413 target_changed = watch_entry.subdir == child;
414 } else {
415 // The current |watch_entry| is not for "/path/to", so the next entry
416 // cannot be "foo". Thus |target_| has not changed.
417 target_changed = false;
418 }
419 }
420
421 // Update watches if a directory component of the |target_| path
422 // (dis)appears. Note that we don't add the additional restriction of
423 // checking the event mask to see if it is for a directory here as changes
424 // to symlinks on the target path will not have IN_ISDIR set in the event
425 // masks. As a result we may sometimes call UpdateWatches() unnecessarily.
426 if (change_on_target_path && (created || deleted) && !did_update) {
427 UpdateWatches();
428 did_update = true;
429 }
430
431 // Report the following events:
432 // - The target or a direct child of the target got changed (in case the
433 // watched path refers to a directory).
434 // - One of the parent directories got moved or deleted, since the target
435 // disappears in this case.
436 // - One of the parent directories appears. The event corresponding to
437 // the target appearing might have been missed in this case, so recheck.
438 if (target_changed ||
439 (change_on_target_path && deleted) ||
440 (change_on_target_path && created && PathExists(target_))) {
441 if (!did_update) {
442 UpdateRecursiveWatches(fired_watch, is_dir);
443 did_update = true;
444 }
445 callback_.Run(target_, false /* error */);
446 return;
447 }
448 }
449
450 if (ContainsKey(recursive_paths_by_watch_, fired_watch)) {
451 if (!did_update)
452 UpdateRecursiveWatches(fired_watch, is_dir);
453 callback_.Run(target_, false /* error */);
454 }
455 }
456
Watch(const FilePath & path,bool recursive,const FilePathWatcher::Callback & callback)457 bool FilePathWatcherImpl::Watch(const FilePath& path,
458 bool recursive,
459 const FilePathWatcher::Callback& callback) {
460 DCHECK(target_.empty());
461
462 set_task_runner(SequencedTaskRunnerHandle::Get());
463 callback_ = callback;
464 target_ = path;
465 recursive_ = recursive;
466
467 std::vector<FilePath::StringType> comps;
468 target_.GetComponents(&comps);
469 DCHECK(!comps.empty());
470 for (size_t i = 1; i < comps.size(); ++i)
471 watches_.push_back(WatchEntry(comps[i]));
472 watches_.push_back(WatchEntry(FilePath::StringType()));
473 UpdateWatches();
474 return true;
475 }
476
Cancel()477 void FilePathWatcherImpl::Cancel() {
478 if (!callback_) {
479 // Watch() was never called.
480 set_cancelled();
481 return;
482 }
483
484 DCHECK(task_runner()->RunsTasksInCurrentSequence());
485 DCHECK(!is_cancelled());
486
487 set_cancelled();
488 callback_.Reset();
489
490 for (size_t i = 0; i < watches_.size(); ++i)
491 g_inotify_reader.Get().RemoveWatch(watches_[i].watch, this);
492 watches_.clear();
493 target_.clear();
494 RemoveRecursiveWatches();
495 }
496
UpdateWatches()497 void FilePathWatcherImpl::UpdateWatches() {
498 // Ensure this runs on the task_runner() exclusively in order to avoid
499 // concurrency issues.
500 DCHECK(task_runner()->RunsTasksInCurrentSequence());
501 DCHECK(HasValidWatchVector());
502
503 // Walk the list of watches and update them as we go.
504 FilePath path(FILE_PATH_LITERAL("/"));
505 for (size_t i = 0; i < watches_.size(); ++i) {
506 WatchEntry& watch_entry = watches_[i];
507 InotifyReader::Watch old_watch = watch_entry.watch;
508 watch_entry.watch = InotifyReader::kInvalidWatch;
509 watch_entry.linkname.clear();
510 watch_entry.watch = g_inotify_reader.Get().AddWatch(path, this);
511 if (watch_entry.watch == InotifyReader::kInvalidWatch) {
512 // Ignore the error code (beyond symlink handling) to attempt to add
513 // watches on accessible children of unreadable directories. Note that
514 // this is a best-effort attempt; we may not catch events in this
515 // scenario.
516 if (IsLink(path))
517 AddWatchForBrokenSymlink(path, &watch_entry);
518 }
519 if (old_watch != watch_entry.watch)
520 g_inotify_reader.Get().RemoveWatch(old_watch, this);
521 path = path.Append(watch_entry.subdir);
522 }
523
524 UpdateRecursiveWatches(InotifyReader::kInvalidWatch,
525 false /* is directory? */);
526 }
527
UpdateRecursiveWatches(InotifyReader::Watch fired_watch,bool is_dir)528 void FilePathWatcherImpl::UpdateRecursiveWatches(
529 InotifyReader::Watch fired_watch,
530 bool is_dir) {
531 DCHECK(HasValidWatchVector());
532
533 if (!recursive_)
534 return;
535
536 if (!DirectoryExists(target_)) {
537 RemoveRecursiveWatches();
538 return;
539 }
540
541 // Check to see if this is a forced update or if some component of |target_|
542 // has changed. For these cases, redo the watches for |target_| and below.
543 if (!ContainsKey(recursive_paths_by_watch_, fired_watch) &&
544 fired_watch != watches_.back().watch) {
545 UpdateRecursiveWatchesForPath(target_);
546 return;
547 }
548
549 // Underneath |target_|, only directory changes trigger watch updates.
550 if (!is_dir)
551 return;
552
553 const FilePath& changed_dir =
554 ContainsKey(recursive_paths_by_watch_, fired_watch) ?
555 recursive_paths_by_watch_[fired_watch] :
556 target_;
557
558 std::map<FilePath, InotifyReader::Watch>::iterator start_it =
559 recursive_watches_by_path_.lower_bound(changed_dir);
560 std::map<FilePath, InotifyReader::Watch>::iterator end_it = start_it;
561 for (; end_it != recursive_watches_by_path_.end(); ++end_it) {
562 const FilePath& cur_path = end_it->first;
563 if (!changed_dir.IsParent(cur_path))
564 break;
565 if (!DirectoryExists(cur_path))
566 g_inotify_reader.Get().RemoveWatch(end_it->second, this);
567 }
568 recursive_watches_by_path_.erase(start_it, end_it);
569 UpdateRecursiveWatchesForPath(changed_dir);
570 }
571
UpdateRecursiveWatchesForPath(const FilePath & path)572 void FilePathWatcherImpl::UpdateRecursiveWatchesForPath(const FilePath& path) {
573 DCHECK(recursive_);
574 DCHECK(!path.empty());
575 DCHECK(DirectoryExists(path));
576
577 // Note: SHOW_SYM_LINKS exposes symlinks as symlinks, so they are ignored
578 // rather than followed. Following symlinks can easily lead to the undesirable
579 // situation where the entire file system is being watched.
580 FileEnumerator enumerator(
581 path,
582 true /* recursive enumeration */,
583 FileEnumerator::DIRECTORIES | FileEnumerator::SHOW_SYM_LINKS);
584 for (FilePath current = enumerator.Next();
585 !current.empty();
586 current = enumerator.Next()) {
587 DCHECK(enumerator.GetInfo().IsDirectory());
588
589 if (!ContainsKey(recursive_watches_by_path_, current)) {
590 // Add new watches.
591 InotifyReader::Watch watch =
592 g_inotify_reader.Get().AddWatch(current, this);
593 TrackWatchForRecursion(watch, current);
594 } else {
595 // Update existing watches.
596 InotifyReader::Watch old_watch = recursive_watches_by_path_[current];
597 DCHECK_NE(InotifyReader::kInvalidWatch, old_watch);
598 InotifyReader::Watch watch =
599 g_inotify_reader.Get().AddWatch(current, this);
600 if (watch != old_watch) {
601 g_inotify_reader.Get().RemoveWatch(old_watch, this);
602 recursive_paths_by_watch_.erase(old_watch);
603 recursive_watches_by_path_.erase(current);
604 TrackWatchForRecursion(watch, current);
605 }
606 }
607 }
608 }
609
TrackWatchForRecursion(InotifyReader::Watch watch,const FilePath & path)610 void FilePathWatcherImpl::TrackWatchForRecursion(InotifyReader::Watch watch,
611 const FilePath& path) {
612 DCHECK(recursive_);
613 DCHECK(!path.empty());
614 DCHECK(target_.IsParent(path));
615
616 if (watch == InotifyReader::kInvalidWatch)
617 return;
618
619 DCHECK(!ContainsKey(recursive_paths_by_watch_, watch));
620 DCHECK(!ContainsKey(recursive_watches_by_path_, path));
621 recursive_paths_by_watch_[watch] = path;
622 recursive_watches_by_path_[path] = watch;
623 }
624
RemoveRecursiveWatches()625 void FilePathWatcherImpl::RemoveRecursiveWatches() {
626 if (!recursive_)
627 return;
628
629 for (const auto& it : recursive_paths_by_watch_)
630 g_inotify_reader.Get().RemoveWatch(it.first, this);
631
632 recursive_paths_by_watch_.clear();
633 recursive_watches_by_path_.clear();
634 }
635
AddWatchForBrokenSymlink(const FilePath & path,WatchEntry * watch_entry)636 void FilePathWatcherImpl::AddWatchForBrokenSymlink(const FilePath& path,
637 WatchEntry* watch_entry) {
638 DCHECK_EQ(InotifyReader::kInvalidWatch, watch_entry->watch);
639 FilePath link;
640 if (!ReadSymbolicLink(path, &link))
641 return;
642
643 if (!link.IsAbsolute())
644 link = path.DirName().Append(link);
645
646 // Try watching symlink target directory. If the link target is "/", then we
647 // shouldn't get here in normal situations and if we do, we'd watch "/" for
648 // changes to a component "/" which is harmless so no special treatment of
649 // this case is required.
650 InotifyReader::Watch watch =
651 g_inotify_reader.Get().AddWatch(link.DirName(), this);
652 if (watch == InotifyReader::kInvalidWatch) {
653 // TODO(craig) Symlinks only work if the parent directory for the target
654 // exist. Ideally we should make sure we've watched all the components of
655 // the symlink path for changes. See crbug.com/91561 for details.
656 DPLOG(WARNING) << "Watch failed for " << link.DirName().value();
657 return;
658 }
659 watch_entry->watch = watch;
660 watch_entry->linkname = link.BaseName().value();
661 }
662
HasValidWatchVector() const663 bool FilePathWatcherImpl::HasValidWatchVector() const {
664 if (watches_.empty())
665 return false;
666 for (size_t i = 0; i < watches_.size() - 1; ++i) {
667 if (watches_[i].subdir.empty())
668 return false;
669 }
670 return watches_.back().subdir.empty();
671 }
672
673 } // namespace
674
FilePathWatcher()675 FilePathWatcher::FilePathWatcher() {
676 sequence_checker_.DetachFromSequence();
677 impl_ = std::make_unique<FilePathWatcherImpl>();
678 }
679
680 } // namespace base
681