Home | History | Annotate | Download | only in files
      1 // Copyright (c) 2011 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/eintr_wrapper.h"
     20 #include "base/file_path.h"
     21 #include "base/file_util.h"
     22 #include "base/hash_tables.h"
     23 #include "base/lazy_instance.h"
     24 #include "base/logging.h"
     25 #include "base/memory/scoped_ptr.h"
     26 #include "base/message_loop.h"
     27 #include "base/message_loop_proxy.h"
     28 #include "base/synchronization/lock.h"
     29 #include "base/task.h"
     30 #include "base/threading/thread.h"
     31 
     32 namespace base {
     33 namespace files {
     34 
     35 namespace {
     36 
     37 class FilePathWatcherImpl;
     38 
     39 // Singleton to manage all inotify watches.
     40 // TODO(tony): It would be nice if this wasn't a singleton.
     41 // http://crbug.com/38174
     42 class InotifyReader {
     43  public:
     44   typedef int Watch;  // Watch descriptor used by AddWatch and RemoveWatch.
     45   static const Watch kInvalidWatch = -1;
     46 
     47   // Watch directory |path| for changes. |watcher| will be notified on each
     48   // change. Returns kInvalidWatch on failure.
     49   Watch AddWatch(const FilePath& path, FilePathWatcherImpl* watcher);
     50 
     51   // Remove |watch|. Returns true on success.
     52   bool RemoveWatch(Watch watch, FilePathWatcherImpl* watcher);
     53 
     54   // Callback for InotifyReaderTask.
     55   void OnInotifyEvent(const inotify_event* event);
     56 
     57  private:
     58   friend struct ::base::DefaultLazyInstanceTraits<InotifyReader>;
     59 
     60   typedef std::set<FilePathWatcherImpl*> WatcherSet;
     61 
     62   InotifyReader();
     63   ~InotifyReader();
     64 
     65   // We keep track of which delegates want to be notified on which watches.
     66   base::hash_map<Watch, WatcherSet> watchers_;
     67 
     68   // Lock to protect watchers_.
     69   base::Lock lock_;
     70 
     71   // Separate thread on which we run blocking read for inotify events.
     72   base::Thread thread_;
     73 
     74   // File descriptor returned by inotify_init.
     75   const int inotify_fd_;
     76 
     77   // Use self-pipe trick to unblock select during shutdown.
     78   int shutdown_pipe_[2];
     79 
     80   // Flag set to true when startup was successful.
     81   bool valid_;
     82 
     83   DISALLOW_COPY_AND_ASSIGN(InotifyReader);
     84 };
     85 
     86 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate,
     87                             public MessageLoop::DestructionObserver {
     88  public:
     89   FilePathWatcherImpl();
     90 
     91   // Called for each event coming from the watch. |fired_watch| identifies the
     92   // watch that fired, |child| indicates what has changed, and is relative to
     93   // the currently watched path for |fired_watch|. The flag |created| is true if
     94   // the object appears, and |is_directory| is set when the event refers to a
     95   // directory.
     96   void OnFilePathChanged(InotifyReader::Watch fired_watch,
     97                          const FilePath::StringType& child,
     98                          bool created,
     99                          bool is_directory);
    100 
    101   // Start watching |path| for changes and notify |delegate| on each change.
    102   // Returns true if watch for |path| has been added successfully.
    103   virtual bool Watch(const FilePath& path,
    104                      FilePathWatcher::Delegate* delegate) OVERRIDE;
    105 
    106   // Cancel the watch. This unregisters the instance with InotifyReader.
    107   virtual void Cancel() OVERRIDE;
    108 
    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;
    113 
    114  private:
    115   virtual ~FilePathWatcherImpl() {}
    116 
    117   // Cleans up and stops observing the |message_loop_| thread.
    118   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.
    123   struct WatchEntry {
    124     WatchEntry(InotifyReader::Watch watch, const FilePath::StringType& subdir)
    125         : watch_(watch),
    126           subdir_(subdir) {}
    127 
    128     InotifyReader::Watch watch_;
    129     FilePath::StringType subdir_;
    130   };
    131   typedef std::vector<WatchEntry> WatchVector;
    132 
    133   // Reconfigure to watch for the most specific parent directory of |target_|
    134   // that exists. Updates |watched_path_|. Returns true on success.
    135   bool UpdateWatches() WARN_UNUSED_RESULT;
    136 
    137   // Delegate to notify upon changes.
    138   scoped_refptr<FilePathWatcher::Delegate> delegate_;
    139 
    140   // The file or directory we're supposed to watch.
    141   FilePath target_;
    142 
    143   // The vector of watches and next component names for all path components,
    144   // starting at the root directory. The last entry corresponds to the watch for
    145   // |target_| and always stores an empty next component name in |subdir_|.
    146   WatchVector watches_;
    147 
    148   DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
    149 };
    150 
    151 class InotifyReaderTask : public Task {
    152  public:
    153   InotifyReaderTask(InotifyReader* reader, int inotify_fd, int shutdown_fd)
    154       : reader_(reader),
    155         inotify_fd_(inotify_fd),
    156         shutdown_fd_(shutdown_fd) {
    157   }
    158 
    159   virtual void Run() {
    160     while (true) {
    161       fd_set rfds;
    162       FD_ZERO(&rfds);
    163       FD_SET(inotify_fd_, &rfds);
    164       FD_SET(shutdown_fd_, &rfds);
    165 
    166       // Wait until some inotify events are available.
    167       int select_result =
    168         HANDLE_EINTR(select(std::max(inotify_fd_, shutdown_fd_) + 1,
    169                             &rfds, NULL, NULL, NULL));
    170       if (select_result < 0) {
    171         DPLOG(WARNING) << "select failed";
    172         return;
    173       }
    174 
    175       if (FD_ISSET(shutdown_fd_, &rfds))
    176         return;
    177 
    178       // Adjust buffer size to current event queue size.
    179       int buffer_size;
    180       int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd_, FIONREAD,
    181                                             &buffer_size));
    182 
    183       if (ioctl_result != 0) {
    184         DPLOG(WARNING) << "ioctl failed";
    185         return;
    186       }
    187 
    188       std::vector<char> buffer(buffer_size);
    189 
    190       ssize_t bytes_read = HANDLE_EINTR(read(inotify_fd_, &buffer[0],
    191                                              buffer_size));
    192 
    193       if (bytes_read < 0) {
    194         DPLOG(WARNING) << "read from inotify fd failed";
    195         return;
    196       }
    197 
    198       ssize_t i = 0;
    199       while (i < bytes_read) {
    200         inotify_event* event = reinterpret_cast<inotify_event*>(&buffer[i]);
    201         size_t event_size = sizeof(inotify_event) + event->len;
    202         DCHECK(i + event_size <= static_cast<size_t>(bytes_read));
    203         reader_->OnInotifyEvent(event);
    204         i += event_size;
    205       }
    206     }
    207   }
    208 
    209  private:
    210   InotifyReader* reader_;
    211   int inotify_fd_;
    212   int shutdown_fd_;
    213 
    214   DISALLOW_COPY_AND_ASSIGN(InotifyReaderTask);
    215 };
    216 
    217 static base::LazyInstance<InotifyReader> g_inotify_reader(
    218     base::LINKER_INITIALIZED);
    219 
    220 InotifyReader::InotifyReader()
    221     : thread_("inotify_reader"),
    222       inotify_fd_(inotify_init()),
    223       valid_(false) {
    224   shutdown_pipe_[0] = -1;
    225   shutdown_pipe_[1] = -1;
    226   if (inotify_fd_ >= 0 && pipe(shutdown_pipe_) == 0 && thread_.Start()) {
    227     thread_.message_loop()->PostTask(
    228         FROM_HERE, new InotifyReaderTask(this, inotify_fd_, shutdown_pipe_[0]));
    229     valid_ = true;
    230   }
    231 }
    232 
    233 InotifyReader::~InotifyReader() {
    234   if (valid_) {
    235     // Write to the self-pipe so that the select call in InotifyReaderTask
    236     // returns.
    237     ssize_t ret = HANDLE_EINTR(write(shutdown_pipe_[1], "", 1));
    238     DPCHECK(ret > 0);
    239     DCHECK_EQ(ret, 1);
    240     thread_.Stop();
    241   }
    242   if (inotify_fd_ >= 0)
    243     close(inotify_fd_);
    244   if (shutdown_pipe_[0] >= 0)
    245     close(shutdown_pipe_[0]);
    246   if (shutdown_pipe_[1] >= 0)
    247     close(shutdown_pipe_[1]);
    248 }
    249 
    250 InotifyReader::Watch InotifyReader::AddWatch(
    251     const FilePath& path, FilePathWatcherImpl* watcher) {
    252   if (!valid_)
    253     return kInvalidWatch;
    254 
    255   base::AutoLock auto_lock(lock_);
    256 
    257   Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(),
    258                                   IN_CREATE | IN_DELETE |
    259                                   IN_CLOSE_WRITE | IN_MOVE |
    260                                   IN_ONLYDIR);
    261 
    262   if (watch == kInvalidWatch)
    263     return kInvalidWatch;
    264 
    265   watchers_[watch].insert(watcher);
    266 
    267   return watch;
    268 }
    269 
    270 bool InotifyReader::RemoveWatch(Watch watch,
    271                                 FilePathWatcherImpl* watcher) {
    272   if (!valid_)
    273     return false;
    274 
    275   base::AutoLock auto_lock(lock_);
    276 
    277   watchers_[watch].erase(watcher);
    278 
    279   if (watchers_[watch].empty()) {
    280     watchers_.erase(watch);
    281     return (inotify_rm_watch(inotify_fd_, watch) == 0);
    282   }
    283 
    284   return true;
    285 }
    286 
    287 void InotifyReader::OnInotifyEvent(const inotify_event* event) {
    288   if (event->mask & IN_IGNORED)
    289     return;
    290 
    291   FilePath::StringType child(event->len ? event->name : FILE_PATH_LITERAL(""));
    292   base::AutoLock auto_lock(lock_);
    293 
    294   for (WatcherSet::iterator watcher = watchers_[event->wd].begin();
    295        watcher != watchers_[event->wd].end();
    296        ++watcher) {
    297     (*watcher)->OnFilePathChanged(event->wd,
    298                                   child,
    299                                   event->mask & (IN_CREATE | IN_MOVED_TO),
    300                                   event->mask & IN_ISDIR);
    301   }
    302 }
    303 
    304 FilePathWatcherImpl::FilePathWatcherImpl()
    305     : delegate_(NULL) {
    306 }
    307 
    308 void FilePathWatcherImpl::OnFilePathChanged(
    309     InotifyReader::Watch fired_watch,
    310     const FilePath::StringType& child,
    311     bool created,
    312     bool is_directory) {
    313 
    314   if (!message_loop()->BelongsToCurrentThread()) {
    315     // Switch to message_loop_ to access watches_ safely.
    316     message_loop()->PostTask(FROM_HERE,
    317         NewRunnableMethod(this,
    318                           &FilePathWatcherImpl::OnFilePathChanged,
    319                           fired_watch,
    320                           child,
    321                           created,
    322                           is_directory));
    323     return;
    324   }
    325 
    326   DCHECK(MessageLoopForIO::current());
    327 
    328   // Find the entry in |watches_| that corresponds to |fired_watch|.
    329   WatchVector::const_iterator watch_entry(watches_.begin());
    330   for ( ; watch_entry != watches_.end(); ++watch_entry) {
    331     if (fired_watch == watch_entry->watch_)
    332       break;
    333   }
    334 
    335   // If this notification is from a previous generation of watches or the watch
    336   // has been cancelled (|watches_| is empty then), bail out.
    337   if (watch_entry == watches_.end())
    338     return;
    339 
    340   // Check whether a path component of |target_| changed.
    341   bool change_on_target_path = child.empty() || child == watch_entry->subdir_;
    342 
    343   // Check whether the change references |target_| or a direct child.
    344   DCHECK(watch_entry->subdir_.empty() || (watch_entry + 1) != watches_.end());
    345   bool target_changed = watch_entry->subdir_.empty() ||
    346       (watch_entry->subdir_ == child && (++watch_entry)->subdir_.empty());
    347 
    348   // Update watches if a directory component of the |target_| path (dis)appears.
    349   if (is_directory && change_on_target_path && !UpdateWatches()) {
    350     delegate_->OnFilePathError(target_);
    351     return;
    352   }
    353 
    354   // Report the following events:
    355   //  - The target or a direct child of the target got changed (in case the
    356   //    watched path refers to a directory).
    357   //  - One of the parent directories got moved or deleted, since the target
    358   //    disappears in this case.
    359   //  - One of the parent directories appears. The event corresponding to the
    360   //    target appearing might have been missed in this case, so recheck.
    361   if (target_changed ||
    362       (change_on_target_path && !created) ||
    363       (change_on_target_path && file_util::PathExists(target_))) {
    364     delegate_->OnFilePathChanged(target_);
    365   }
    366 }
    367 
    368 bool FilePathWatcherImpl::Watch(const FilePath& path,
    369                                 FilePathWatcher::Delegate* delegate) {
    370   DCHECK(target_.empty());
    371   DCHECK(MessageLoopForIO::current());
    372 
    373   set_message_loop(base::MessageLoopProxy::CreateForCurrentThread());
    374   delegate_ = delegate;
    375   target_ = path;
    376   MessageLoop::current()->AddDestructionObserver(this);
    377 
    378   std::vector<FilePath::StringType> comps;
    379   target_.GetComponents(&comps);
    380   DCHECK(!comps.empty());
    381   for (std::vector<FilePath::StringType>::const_iterator comp(++comps.begin());
    382        comp != comps.end(); ++comp) {
    383     watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch, *comp));
    384   }
    385   watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch,
    386                                 FilePath::StringType()));
    387   return UpdateWatches();
    388 }
    389 
    390 void FilePathWatcherImpl::Cancel() {
    391   if (!delegate_) {
    392     // Watch was never called, or the |message_loop_| thread is already gone.
    393     set_cancelled();
    394     return;
    395   }
    396 
    397   // Switch to the message_loop_ if necessary so we can access |watches_|.
    398   if (!message_loop()->BelongsToCurrentThread()) {
    399     message_loop()->PostTask(FROM_HERE,
    400                              new FilePathWatcher::CancelTask(this));
    401   } else {
    402     CancelOnMessageLoopThread();
    403   }
    404 }
    405 
    406 void FilePathWatcherImpl::CancelOnMessageLoopThread() {
    407   if (!is_cancelled()) {
    408     set_cancelled();
    409     MessageLoop::current()->RemoveDestructionObserver(this);
    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     delegate_ = NULL;
    418     target_.clear();
    419   }
    420 }
    421 
    422 void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() {
    423   CancelOnMessageLoopThread();
    424 }
    425 
    426 bool FilePathWatcherImpl::UpdateWatches() {
    427   // Ensure this runs on the message_loop_ exclusively in order to avoid
    428   // concurrency issues.
    429   DCHECK(message_loop()->BelongsToCurrentThread());
    430 
    431   // Walk the list of watches and update them as we go.
    432   FilePath path(FILE_PATH_LITERAL("/"));
    433   bool path_valid = true;
    434   for (WatchVector::iterator watch_entry(watches_.begin());
    435        watch_entry != watches_.end(); ++watch_entry) {
    436     InotifyReader::Watch old_watch = watch_entry->watch_;
    437     if (path_valid) {
    438       watch_entry->watch_ = g_inotify_reader.Get().AddWatch(path, this);
    439       if (watch_entry->watch_ == InotifyReader::kInvalidWatch) {
    440         path_valid = false;
    441       }
    442     } else {
    443       watch_entry->watch_ = InotifyReader::kInvalidWatch;
    444     }
    445     if (old_watch != InotifyReader::kInvalidWatch &&
    446         old_watch != watch_entry->watch_) {
    447       g_inotify_reader.Get().RemoveWatch(old_watch, this);
    448     }
    449     path = path.Append(watch_entry->subdir_);
    450   }
    451 
    452   return true;
    453 }
    454 
    455 }  // namespace
    456 
    457 FilePathWatcher::FilePathWatcher() {
    458   impl_ = new FilePathWatcherImpl();
    459 }
    460 
    461 }  // namespace files
    462 }  // namespace base
    463