file_path_watcher_linux.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
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 <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> 15#include <set> 16#include <utility> 17#include <vector> 18 19#include "base/bind.h" 20#include "base/eintr_wrapper.h" 21#include "base/file_path.h" 22#include "base/file_util.h" 23#include "base/hash_tables.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.h" 29#include "base/message_loop_proxy.h" 30#include "base/synchronization/lock.h" 31#include "base/threading/thread.h" 32 33namespace base { 34namespace files { 35 36namespace { 37 38class FilePathWatcherImpl; 39 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 43class InotifyReader { 44 public: 45 typedef int Watch; // Watch descriptor used by AddWatch and RemoveWatch. 46 static const Watch kInvalidWatch = -1; 47 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); 51 52 // Remove |watch|. Returns true on success. 53 bool RemoveWatch(Watch watch, FilePathWatcherImpl* watcher); 54 55 // Callback for InotifyReaderTask. 56 void OnInotifyEvent(const inotify_event* event); 57 58 private: 59 friend struct ::base::DefaultLazyInstanceTraits<InotifyReader>; 60 61 typedef std::set<FilePathWatcherImpl*> WatcherSet; 62 63 InotifyReader(); 64 ~InotifyReader(); 65 66 // We keep track of which delegates want to be notified on which watches. 67 base::hash_map<Watch, WatcherSet> watchers_; 68 69 // Lock to protect watchers_. 70 base::Lock lock_; 71 72 // Separate thread on which we run blocking read for inotify events. 73 base::Thread thread_; 74 75 // File descriptor returned by inotify_init. 76 const int inotify_fd_; 77 78 // Use self-pipe trick to unblock select during shutdown. 79 int shutdown_pipe_[2]; 80 81 // Flag set to true when startup was successful. 82 bool valid_; 83 84 DISALLOW_COPY_AND_ASSIGN(InotifyReader); 85}; 86 87class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate, 88 public MessageLoop::DestructionObserver { 89 public: 90 FilePathWatcherImpl(); 91 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, 98 bool created); 99 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, 103 FilePathWatcher::Delegate* delegate) OVERRIDE; 104 105 // Cancel the watch. This unregisters the instance with InotifyReader. 106 virtual void Cancel() OVERRIDE; 107 108 // Deletion of the FilePathWatcher will call Cancel() to dispose of this 109 // object in the right thread. This also observes destruction of the required 110 // cleanup thread, in case it quits before Cancel() is called. 111 virtual void WillDestroyCurrentMessageLoop() OVERRIDE; 112 113 protected: 114 virtual ~FilePathWatcherImpl() {} 115 116 private: 117 // Cleans up and stops observing the |message_loop_| thread. 118 virtual void CancelOnMessageLoopThread() OVERRIDE; 119 120 // Inotify watches are installed for all directory components of |target_|. A 121 // WatchEntry instance holds the watch descriptor for a component and the 122 // subdirectory for that identifies the next component. If a symbolic link 123 // is being watched, the target of the link is also kept. 124 struct WatchEntry { 125 WatchEntry(InotifyReader::Watch watch, const FilePath::StringType& subdir) 126 : watch_(watch), 127 subdir_(subdir) {} 128 129 InotifyReader::Watch watch_; 130 FilePath::StringType subdir_; 131 FilePath::StringType linkname_; 132 }; 133 typedef std::vector<WatchEntry> WatchVector; 134 135 // Reconfigure to watch for the most specific parent directory of |target_| 136 // that exists. Updates |watched_path_|. Returns true on success. 137 bool UpdateWatches() WARN_UNUSED_RESULT; 138 139 // Delegate to notify upon changes. 140 scoped_refptr<FilePathWatcher::Delegate> delegate_; 141 142 // The file or directory we're supposed to watch. 143 FilePath target_; 144 145 // The vector of watches and next component names for all path components, 146 // starting at the root directory. The last entry corresponds to the watch for 147 // |target_| and always stores an empty next component name in |subdir_|. 148 WatchVector watches_; 149 150 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); 151}; 152 153void InotifyReaderCallback(InotifyReader* reader, int inotify_fd, 154 int shutdown_fd) { 155 // Make sure the file descriptors are good for use with select(). 156 CHECK_LE(0, inotify_fd); 157 CHECK_GT(FD_SETSIZE, inotify_fd); 158 CHECK_LE(0, shutdown_fd); 159 CHECK_GT(FD_SETSIZE, shutdown_fd); 160 161 while (true) { 162 fd_set rfds; 163 FD_ZERO(&rfds); 164 FD_SET(inotify_fd, &rfds); 165 FD_SET(shutdown_fd, &rfds); 166 167 // Wait until some inotify events are available. 168 int select_result = 169 HANDLE_EINTR(select(std::max(inotify_fd, shutdown_fd) + 1, 170 &rfds, NULL, NULL, NULL)); 171 if (select_result < 0) { 172 DPLOG(WARNING) << "select failed"; 173 return; 174 } 175 176 if (FD_ISSET(shutdown_fd, &rfds)) 177 return; 178 179 // Adjust buffer size to current event queue size. 180 int buffer_size; 181 int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd, FIONREAD, 182 &buffer_size)); 183 184 if (ioctl_result != 0) { 185 DPLOG(WARNING) << "ioctl failed"; 186 return; 187 } 188 189 std::vector<char> buffer(buffer_size); 190 191 ssize_t bytes_read = HANDLE_EINTR(read(inotify_fd, &buffer[0], 192 buffer_size)); 193 194 if (bytes_read < 0) { 195 DPLOG(WARNING) << "read from inotify fd failed"; 196 return; 197 } 198 199 ssize_t i = 0; 200 while (i < bytes_read) { 201 inotify_event* event = reinterpret_cast<inotify_event*>(&buffer[i]); 202 size_t event_size = sizeof(inotify_event) + event->len; 203 DCHECK(i + event_size <= static_cast<size_t>(bytes_read)); 204 reader->OnInotifyEvent(event); 205 i += event_size; 206 } 207 } 208} 209 210static base::LazyInstance<InotifyReader>::Leaky g_inotify_reader = 211 LAZY_INSTANCE_INITIALIZER; 212 213InotifyReader::InotifyReader() 214 : thread_("inotify_reader"), 215 inotify_fd_(inotify_init()), 216 valid_(false) { 217 shutdown_pipe_[0] = -1; 218 shutdown_pipe_[1] = -1; 219 if (inotify_fd_ >= 0 && pipe(shutdown_pipe_) == 0 && thread_.Start()) { 220 thread_.message_loop()->PostTask( 221 FROM_HERE, base::Bind(&InotifyReaderCallback, this, inotify_fd_, 222 shutdown_pipe_[0])); 223 valid_ = true; 224 } 225} 226 227InotifyReader::~InotifyReader() { 228 if (valid_) { 229 // Write to the self-pipe so that the select call in InotifyReaderTask 230 // returns. 231 ssize_t ret = HANDLE_EINTR(write(shutdown_pipe_[1], "", 1)); 232 DPCHECK(ret > 0); 233 DCHECK_EQ(ret, 1); 234 thread_.Stop(); 235 } 236 if (inotify_fd_ >= 0) 237 close(inotify_fd_); 238 if (shutdown_pipe_[0] >= 0) 239 close(shutdown_pipe_[0]); 240 if (shutdown_pipe_[1] >= 0) 241 close(shutdown_pipe_[1]); 242} 243 244InotifyReader::Watch InotifyReader::AddWatch( 245 const FilePath& path, FilePathWatcherImpl* watcher) { 246 if (!valid_) 247 return kInvalidWatch; 248 249 base::AutoLock auto_lock(lock_); 250 251 Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(), 252 IN_CREATE | IN_DELETE | 253 IN_CLOSE_WRITE | IN_MOVE | 254 IN_ONLYDIR); 255 256 if (watch == kInvalidWatch) 257 return kInvalidWatch; 258 259 watchers_[watch].insert(watcher); 260 261 return watch; 262} 263 264bool InotifyReader::RemoveWatch(Watch watch, 265 FilePathWatcherImpl* watcher) { 266 if (!valid_) 267 return false; 268 269 base::AutoLock auto_lock(lock_); 270 271 watchers_[watch].erase(watcher); 272 273 if (watchers_[watch].empty()) { 274 watchers_.erase(watch); 275 return (inotify_rm_watch(inotify_fd_, watch) == 0); 276 } 277 278 return true; 279} 280 281void InotifyReader::OnInotifyEvent(const inotify_event* event) { 282 if (event->mask & IN_IGNORED) 283 return; 284 285 FilePath::StringType child(event->len ? event->name : FILE_PATH_LITERAL("")); 286 base::AutoLock auto_lock(lock_); 287 288 for (WatcherSet::iterator watcher = watchers_[event->wd].begin(); 289 watcher != watchers_[event->wd].end(); 290 ++watcher) { 291 (*watcher)->OnFilePathChanged(event->wd, 292 child, 293 event->mask & (IN_CREATE | IN_MOVED_TO)); 294 } 295} 296 297FilePathWatcherImpl::FilePathWatcherImpl() 298 : delegate_(NULL) { 299} 300 301void FilePathWatcherImpl::OnFilePathChanged(InotifyReader::Watch fired_watch, 302 const FilePath::StringType& child, 303 bool created) { 304 if (!message_loop()->BelongsToCurrentThread()) { 305 // Switch to message_loop_ to access watches_ safely. 306 message_loop()->PostTask(FROM_HERE, 307 base::Bind(&FilePathWatcherImpl::OnFilePathChanged, 308 this, 309 fired_watch, 310 child, 311 created)); 312 return; 313 } 314 315 DCHECK(MessageLoopForIO::current()); 316 317 // Find the entry in |watches_| that corresponds to |fired_watch|. 318 WatchVector::const_iterator watch_entry(watches_.begin()); 319 for ( ; watch_entry != watches_.end(); ++watch_entry) { 320 if (fired_watch == watch_entry->watch_) { 321 // Check whether a path component of |target_| changed. 322 bool change_on_target_path = child.empty() || 323 ((child == watch_entry->subdir_) && watch_entry->linkname_.empty()) || 324 (child == watch_entry->linkname_); 325 326 // Check whether the change references |target_| or a direct child. 327 DCHECK(watch_entry->subdir_.empty() || 328 (watch_entry + 1) != watches_.end()); 329 bool target_changed = 330 (watch_entry->subdir_.empty() && (child == watch_entry->linkname_)) || 331 (watch_entry->subdir_.empty() && watch_entry->linkname_.empty()) || 332 (watch_entry->subdir_ == child && (watch_entry + 1)->subdir_.empty()); 333 334 // Update watches if a directory component of the |target_| path 335 // (dis)appears. Note that we don't add the additional restriction 336 // of checking the event mask to see if it is for a directory here 337 // as changes to symlinks on the target path will not have 338 // IN_ISDIR set in the event masks. As a result we may sometimes 339 // call UpdateWatches() unnecessarily. 340 if (change_on_target_path && !UpdateWatches()) { 341 delegate_->OnFilePathError(target_); 342 return; 343 } 344 345 // Report the following events: 346 // - The target or a direct child of the target got changed (in case the 347 // watched path refers to a directory). 348 // - One of the parent directories got moved or deleted, since the target 349 // disappears in this case. 350 // - One of the parent directories appears. The event corresponding to 351 // the target appearing might have been missed in this case, so 352 // recheck. 353 if (target_changed || 354 (change_on_target_path && !created) || 355 (change_on_target_path && file_util::PathExists(target_))) { 356 delegate_->OnFilePathChanged(target_); 357 return; 358 } 359 } 360 } 361} 362 363bool FilePathWatcherImpl::Watch(const FilePath& path, 364 FilePathWatcher::Delegate* delegate) { 365 DCHECK(target_.empty()); 366 DCHECK(MessageLoopForIO::current()); 367 368 set_message_loop(base::MessageLoopProxy::current()); 369 delegate_ = delegate; 370 target_ = path; 371 MessageLoop::current()->AddDestructionObserver(this); 372 373 std::vector<FilePath::StringType> comps; 374 target_.GetComponents(&comps); 375 DCHECK(!comps.empty()); 376 std::vector<FilePath::StringType>::const_iterator comp = comps.begin(); 377 for (++comp; comp != comps.end(); ++comp) 378 watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch, *comp)); 379 380 watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch, 381 FilePath::StringType())); 382 return UpdateWatches(); 383} 384 385void FilePathWatcherImpl::Cancel() { 386 if (!delegate_) { 387 // Watch was never called, or the |message_loop_| thread is already gone. 388 set_cancelled(); 389 return; 390 } 391 392 // Switch to the message_loop_ if necessary so we can access |watches_|. 393 if (!message_loop()->BelongsToCurrentThread()) { 394 message_loop()->PostTask(FROM_HERE, 395 base::Bind(&FilePathWatcher::CancelWatch, 396 make_scoped_refptr(this))); 397 } else { 398 CancelOnMessageLoopThread(); 399 } 400} 401 402void FilePathWatcherImpl::CancelOnMessageLoopThread() { 403 if (!is_cancelled()) 404 set_cancelled(); 405 406 if (delegate_) { 407 MessageLoop::current()->RemoveDestructionObserver(this); 408 delegate_ = NULL; 409 } 410 411 for (WatchVector::iterator watch_entry(watches_.begin()); 412 watch_entry != watches_.end(); ++watch_entry) { 413 if (watch_entry->watch_ != InotifyReader::kInvalidWatch) 414 g_inotify_reader.Get().RemoveWatch(watch_entry->watch_, this); 415 } 416 watches_.clear(); 417 target_.clear(); 418} 419 420void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() { 421 CancelOnMessageLoopThread(); 422} 423 424bool FilePathWatcherImpl::UpdateWatches() { 425 // Ensure this runs on the |message_loop_| exclusively in order to avoid 426 // concurrency issues. 427 DCHECK(message_loop()->BelongsToCurrentThread()); 428 429 // Walk the list of watches and update them as we go. 430 FilePath path(FILE_PATH_LITERAL("/")); 431 bool path_valid = true; 432 for (WatchVector::iterator watch_entry(watches_.begin()); 433 watch_entry != watches_.end(); ++watch_entry) { 434 InotifyReader::Watch old_watch = watch_entry->watch_; 435 if (path_valid) { 436 watch_entry->watch_ = g_inotify_reader.Get().AddWatch(path, this); 437 if ((watch_entry->watch_ == InotifyReader::kInvalidWatch) && 438 file_util::IsLink(path)) { 439 FilePath link; 440 if (file_util::ReadSymbolicLink(path, &link)) { 441 if (!link.IsAbsolute()) 442 link = path.DirName().Append(link); 443 // Try watching symlink target directory. If the link target is "/", 444 // then we shouldn't get here in normal situations and if we do, we'd 445 // watch "/" for changes to a component "/" which is harmless so no 446 // special treatment of this case is required. 447 watch_entry->watch_ = 448 g_inotify_reader.Get().AddWatch(link.DirName(), this); 449 if (watch_entry->watch_ != InotifyReader::kInvalidWatch) { 450 watch_entry->linkname_ = link.BaseName().value(); 451 } else { 452 DPLOG(WARNING) << "Watch failed for " << link.DirName().value(); 453 // TODO(craig) Symlinks only work if the parent directory 454 // for the target exist. Ideally we should make sure we've 455 // watched all the components of the symlink path for 456 // changes. See crbug.com/91561 for details. 457 } 458 } 459 } 460 if (watch_entry->watch_ == InotifyReader::kInvalidWatch) { 461 path_valid = false; 462 } 463 } else { 464 watch_entry->watch_ = InotifyReader::kInvalidWatch; 465 } 466 if (old_watch != InotifyReader::kInvalidWatch && 467 old_watch != watch_entry->watch_) { 468 g_inotify_reader.Get().RemoveWatch(old_watch, this); 469 } 470 path = path.Append(watch_entry->subdir_); 471 } 472 473 return true; 474} 475 476} // namespace 477 478FilePathWatcher::FilePathWatcher() { 479 impl_ = new FilePathWatcherImpl(); 480} 481 482} // namespace files 483} // namespace base 484