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.
5 #include "base/files/file_path_watcher.h"
9 #include <sys/inotify.h>
10 #include <sys/ioctl.h>
11 #include <sys/select.h>
19 #include "base/bind.h"
20 #include "base/containers/hash_tables.h"
21 #include "base/debug/trace_event.h"
22 #include "base/file_util.h"
23 #include "base/files/file_path.h"
24 #include "base/lazy_instance.h"
25 #include "base/location.h"
26 #include "base/logging.h"
27 #include "base/memory/scoped_ptr.h"
28 #include "base/message_loop/message_loop.h"
29 #include "base/message_loop/message_loop_proxy.h"
30 #include "base/posix/eintr_wrapper.h"
31 #include "base/synchronization/lock.h"
32 #include "base/threading/thread.h"
38 class FilePathWatcherImpl
;
40 // Singleton to manage all inotify watches.
41 // TODO(tony): It would be nice if this wasn't a singleton.
42 // http://crbug.com/38174
45 typedef int Watch
; // Watch descriptor used by AddWatch and RemoveWatch.
46 static const Watch kInvalidWatch
= -1;
48 // Watch directory |path| for changes. |watcher| will be notified on each
49 // change. Returns kInvalidWatch on failure.
50 Watch
AddWatch(const FilePath
& path
, FilePathWatcherImpl
* watcher
);
52 // Remove |watch|. Returns true on success.
53 bool RemoveWatch(Watch watch
, FilePathWatcherImpl
* watcher
);
55 // Callback for InotifyReaderTask.
56 void OnInotifyEvent(const inotify_event
* event
);
59 friend struct ::base::DefaultLazyInstanceTraits
<InotifyReader
>;
61 typedef std::set
<FilePathWatcherImpl
*> WatcherSet
;
66 // We keep track of which delegates want to be notified on which watches.
67 base::hash_map
<Watch
, WatcherSet
> watchers_
;
69 // Lock to protect watchers_.
72 // Separate thread on which we run blocking read for inotify events.
75 // File descriptor returned by inotify_init.
76 const int inotify_fd_
;
78 // Use self-pipe trick to unblock select during shutdown.
79 int shutdown_pipe_
[2];
81 // Flag set to true when startup was successful.
84 DISALLOW_COPY_AND_ASSIGN(InotifyReader
);
87 class FilePathWatcherImpl
: public FilePathWatcher::PlatformDelegate
,
88 public MessageLoop::DestructionObserver
{
90 FilePathWatcherImpl();
92 // Called for each event coming from the watch. |fired_watch| identifies the
93 // watch that fired, |child| indicates what has changed, and is relative to
94 // the currently watched path for |fired_watch|. The flag |created| is true if
95 // the object appears.
96 void OnFilePathChanged(InotifyReader::Watch fired_watch
,
97 const FilePath::StringType
& child
,
100 // Start watching |path| for changes and notify |delegate| on each change.
101 // Returns true if watch for |path| has been added successfully.
102 virtual bool Watch(const FilePath
& path
,
104 const FilePathWatcher::Callback
& callback
) OVERRIDE
;
106 // Cancel the watch. This unregisters the instance with InotifyReader.
107 virtual void Cancel() OVERRIDE
;
109 // Deletion of the FilePathWatcher will call Cancel() to dispose of this
110 // object in the right thread. This also observes destruction of the required
111 // cleanup thread, in case it quits before Cancel() is called.
112 virtual void WillDestroyCurrentMessageLoop() OVERRIDE
;
115 virtual ~FilePathWatcherImpl() {}
118 // Cleans up and stops observing the |message_loop_| thread.
119 virtual void CancelOnMessageLoopThread() OVERRIDE
;
121 // Inotify watches are installed for all directory components of |target_|. A
122 // WatchEntry instance holds the watch descriptor for a component and the
123 // subdirectory for that identifies the next component. If a symbolic link
124 // is being watched, the target of the link is also kept.
126 WatchEntry(InotifyReader::Watch watch
, const FilePath::StringType
& subdir
)
130 InotifyReader::Watch watch_
;
131 FilePath::StringType subdir_
;
132 FilePath::StringType linkname_
;
134 typedef std::vector
<WatchEntry
> WatchVector
;
136 // Reconfigure to watch for the most specific parent directory of |target_|
137 // that exists. Updates |watched_path_|. Returns true on success.
138 bool UpdateWatches() WARN_UNUSED_RESULT
;
140 // Callback to notify upon changes.
141 FilePathWatcher::Callback callback_
;
143 // The file or directory we're supposed to watch.
146 // The vector of watches and next component names for all path components,
147 // starting at the root directory. The last entry corresponds to the watch for
148 // |target_| and always stores an empty next component name in |subdir_|.
149 WatchVector watches_
;
151 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl
);
154 void InotifyReaderCallback(InotifyReader
* reader
, int inotify_fd
,
156 // Make sure the file descriptors are good for use with select().
157 CHECK_LE(0, inotify_fd
);
158 CHECK_GT(FD_SETSIZE
, inotify_fd
);
159 CHECK_LE(0, shutdown_fd
);
160 CHECK_GT(FD_SETSIZE
, shutdown_fd
);
162 base::debug::TraceLog::GetInstance()->SetCurrentThreadBlocksMessageLoop();
167 FD_SET(inotify_fd
, &rfds
);
168 FD_SET(shutdown_fd
, &rfds
);
170 // Wait until some inotify events are available.
172 HANDLE_EINTR(select(std::max(inotify_fd
, shutdown_fd
) + 1,
173 &rfds
, NULL
, NULL
, NULL
));
174 if (select_result
< 0) {
175 DPLOG(WARNING
) << "select failed";
179 if (FD_ISSET(shutdown_fd
, &rfds
))
182 // Adjust buffer size to current event queue size.
184 int ioctl_result
= HANDLE_EINTR(ioctl(inotify_fd
, FIONREAD
,
187 if (ioctl_result
!= 0) {
188 DPLOG(WARNING
) << "ioctl failed";
192 std::vector
<char> buffer(buffer_size
);
194 ssize_t bytes_read
= HANDLE_EINTR(read(inotify_fd
, &buffer
[0],
197 if (bytes_read
< 0) {
198 DPLOG(WARNING
) << "read from inotify fd failed";
203 while (i
< bytes_read
) {
204 inotify_event
* event
= reinterpret_cast<inotify_event
*>(&buffer
[i
]);
205 size_t event_size
= sizeof(inotify_event
) + event
->len
;
206 DCHECK(i
+ event_size
<= static_cast<size_t>(bytes_read
));
207 reader
->OnInotifyEvent(event
);
213 static base::LazyInstance
<InotifyReader
>::Leaky g_inotify_reader
=
214 LAZY_INSTANCE_INITIALIZER
;
216 InotifyReader::InotifyReader()
217 : thread_("inotify_reader"),
218 inotify_fd_(inotify_init()),
220 shutdown_pipe_
[0] = -1;
221 shutdown_pipe_
[1] = -1;
222 if (inotify_fd_
>= 0 && pipe(shutdown_pipe_
) == 0 && thread_
.Start()) {
223 thread_
.message_loop()->PostTask(
224 FROM_HERE
, base::Bind(&InotifyReaderCallback
, this, inotify_fd_
,
230 InotifyReader::~InotifyReader() {
232 // Write to the self-pipe so that the select call in InotifyReaderTask
234 ssize_t ret
= HANDLE_EINTR(write(shutdown_pipe_
[1], "", 1));
239 if (inotify_fd_
>= 0)
241 if (shutdown_pipe_
[0] >= 0)
242 close(shutdown_pipe_
[0]);
243 if (shutdown_pipe_
[1] >= 0)
244 close(shutdown_pipe_
[1]);
247 InotifyReader::Watch
InotifyReader::AddWatch(
248 const FilePath
& path
, FilePathWatcherImpl
* watcher
) {
250 return kInvalidWatch
;
252 base::AutoLock
auto_lock(lock_
);
254 Watch watch
= inotify_add_watch(inotify_fd_
, path
.value().c_str(),
255 IN_CREATE
| IN_DELETE
|
256 IN_CLOSE_WRITE
| IN_MOVE
|
259 if (watch
== kInvalidWatch
)
260 return kInvalidWatch
;
262 watchers_
[watch
].insert(watcher
);
267 bool InotifyReader::RemoveWatch(Watch watch
,
268 FilePathWatcherImpl
* watcher
) {
272 base::AutoLock
auto_lock(lock_
);
274 watchers_
[watch
].erase(watcher
);
276 if (watchers_
[watch
].empty()) {
277 watchers_
.erase(watch
);
278 return (inotify_rm_watch(inotify_fd_
, watch
) == 0);
284 void InotifyReader::OnInotifyEvent(const inotify_event
* event
) {
285 if (event
->mask
& IN_IGNORED
)
288 FilePath::StringType
child(event
->len
? event
->name
: FILE_PATH_LITERAL(""));
289 base::AutoLock
auto_lock(lock_
);
291 for (WatcherSet::iterator watcher
= watchers_
[event
->wd
].begin();
292 watcher
!= watchers_
[event
->wd
].end();
294 (*watcher
)->OnFilePathChanged(event
->wd
,
296 event
->mask
& (IN_CREATE
| IN_MOVED_TO
));
300 FilePathWatcherImpl::FilePathWatcherImpl() {
303 void FilePathWatcherImpl::OnFilePathChanged(InotifyReader::Watch fired_watch
,
304 const FilePath::StringType
& child
,
306 if (!message_loop()->BelongsToCurrentThread()) {
307 // Switch to message_loop_ to access watches_ safely.
308 message_loop()->PostTask(FROM_HERE
,
309 base::Bind(&FilePathWatcherImpl::OnFilePathChanged
,
317 DCHECK(MessageLoopForIO::current());
319 // Find the entry in |watches_| that corresponds to |fired_watch|.
320 WatchVector::const_iterator
watch_entry(watches_
.begin());
321 for ( ; watch_entry
!= watches_
.end(); ++watch_entry
) {
322 if (fired_watch
== watch_entry
->watch_
) {
323 // Check whether a path component of |target_| changed.
324 bool change_on_target_path
= child
.empty() ||
325 ((child
== watch_entry
->subdir_
) && watch_entry
->linkname_
.empty()) ||
326 (child
== watch_entry
->linkname_
);
328 // Check whether the change references |target_| or a direct child.
329 DCHECK(watch_entry
->subdir_
.empty() ||
330 (watch_entry
+ 1) != watches_
.end());
331 bool target_changed
=
332 (watch_entry
->subdir_
.empty() && (child
== watch_entry
->linkname_
)) ||
333 (watch_entry
->subdir_
.empty() && watch_entry
->linkname_
.empty()) ||
334 (watch_entry
->subdir_
== child
&& (watch_entry
+ 1)->subdir_
.empty());
336 // Update watches if a directory component of the |target_| path
337 // (dis)appears. Note that we don't add the additional restriction
338 // of checking the event mask to see if it is for a directory here
339 // as changes to symlinks on the target path will not have
340 // IN_ISDIR set in the event masks. As a result we may sometimes
341 // call UpdateWatches() unnecessarily.
342 if (change_on_target_path
&& !UpdateWatches()) {
343 callback_
.Run(target_
, true /* error */);
347 // Report the following events:
348 // - The target or a direct child of the target got changed (in case the
349 // watched path refers to a directory).
350 // - One of the parent directories got moved or deleted, since the target
351 // disappears in this case.
352 // - One of the parent directories appears. The event corresponding to
353 // the target appearing might have been missed in this case, so
355 if (target_changed
||
356 (change_on_target_path
&& !created
) ||
357 (change_on_target_path
&& PathExists(target_
))) {
358 callback_
.Run(target_
, false);
365 bool FilePathWatcherImpl::Watch(const FilePath
& path
,
367 const FilePathWatcher::Callback
& callback
) {
368 DCHECK(target_
.empty());
369 DCHECK(MessageLoopForIO::current());
371 // Recursive watch is not supported on this platform.
376 set_message_loop(base::MessageLoopProxy::current().get());
377 callback_
= callback
;
379 MessageLoop::current()->AddDestructionObserver(this);
381 std::vector
<FilePath::StringType
> comps
;
382 target_
.GetComponents(&comps
);
383 DCHECK(!comps
.empty());
384 std::vector
<FilePath::StringType
>::const_iterator comp
= comps
.begin();
385 for (++comp
; comp
!= comps
.end(); ++comp
)
386 watches_
.push_back(WatchEntry(InotifyReader::kInvalidWatch
, *comp
));
388 watches_
.push_back(WatchEntry(InotifyReader::kInvalidWatch
,
389 FilePath::StringType()));
390 return UpdateWatches();
393 void FilePathWatcherImpl::Cancel() {
394 if (callback_
.is_null()) {
395 // Watch was never called, or the |message_loop_| thread is already gone.
400 // Switch to the message_loop_ if necessary so we can access |watches_|.
401 if (!message_loop()->BelongsToCurrentThread()) {
402 message_loop()->PostTask(FROM_HERE
,
403 base::Bind(&FilePathWatcher::CancelWatch
,
404 make_scoped_refptr(this)));
406 CancelOnMessageLoopThread();
410 void FilePathWatcherImpl::CancelOnMessageLoopThread() {
414 if (!callback_
.is_null()) {
415 MessageLoop::current()->RemoveDestructionObserver(this);
419 for (WatchVector::iterator
watch_entry(watches_
.begin());
420 watch_entry
!= watches_
.end(); ++watch_entry
) {
421 if (watch_entry
->watch_
!= InotifyReader::kInvalidWatch
)
422 g_inotify_reader
.Get().RemoveWatch(watch_entry
->watch_
, this);
428 void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() {
429 CancelOnMessageLoopThread();
432 bool FilePathWatcherImpl::UpdateWatches() {
433 // Ensure this runs on the |message_loop_| exclusively in order to avoid
434 // concurrency issues.
435 DCHECK(message_loop()->BelongsToCurrentThread());
437 // Walk the list of watches and update them as we go.
438 FilePath
path(FILE_PATH_LITERAL("/"));
439 bool path_valid
= true;
440 for (WatchVector::iterator
watch_entry(watches_
.begin());
441 watch_entry
!= watches_
.end(); ++watch_entry
) {
442 InotifyReader::Watch old_watch
= watch_entry
->watch_
;
444 watch_entry
->watch_
= g_inotify_reader
.Get().AddWatch(path
, this);
445 if ((watch_entry
->watch_
== InotifyReader::kInvalidWatch
) &&
446 file_util::IsLink(path
)) {
448 if (file_util::ReadSymbolicLink(path
, &link
)) {
449 if (!link
.IsAbsolute())
450 link
= path
.DirName().Append(link
);
451 // Try watching symlink target directory. If the link target is "/",
452 // then we shouldn't get here in normal situations and if we do, we'd
453 // watch "/" for changes to a component "/" which is harmless so no
454 // special treatment of this case is required.
455 watch_entry
->watch_
=
456 g_inotify_reader
.Get().AddWatch(link
.DirName(), this);
457 if (watch_entry
->watch_
!= InotifyReader::kInvalidWatch
) {
458 watch_entry
->linkname_
= link
.BaseName().value();
460 DPLOG(WARNING
) << "Watch failed for " << link
.DirName().value();
461 // TODO(craig) Symlinks only work if the parent directory
462 // for the target exist. Ideally we should make sure we've
463 // watched all the components of the symlink path for
464 // changes. See crbug.com/91561 for details.
468 if (watch_entry
->watch_
== InotifyReader::kInvalidWatch
) {
472 watch_entry
->watch_
= InotifyReader::kInvalidWatch
;
474 if (old_watch
!= InotifyReader::kInvalidWatch
&&
475 old_watch
!= watch_entry
->watch_
) {
476 g_inotify_reader
.Get().RemoveWatch(old_watch
, this);
478 path
= path
.Append(watch_entry
->subdir_
);
486 FilePathWatcher::FilePathWatcher() {
487 impl_
= new FilePathWatcherImpl();