OLD | NEW |
(Empty) | |
| 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 "content/common/file_path_watcher/file_path_watcher.h" |
| 6 |
| 7 #include <fcntl.h> |
| 8 #include <sys/event.h> |
| 9 #include <sys/param.h> |
| 10 |
| 11 #include <vector> |
| 12 |
| 13 #include "base/file_util.h" |
| 14 #include "base/message_loop.h" |
| 15 #include "base/message_loop_proxy.h" |
| 16 #include "base/stringprintf.h" |
| 17 |
| 18 namespace { |
| 19 |
| 20 // Mac-specific file watcher implementation based on kqueue. |
| 21 // Originally it was based on FSEvents so that the semantics were equivalent |
| 22 // on Linux, OSX and Windows where it was able to detect: |
| 23 // - file creation/deletion/modification in a watched directory |
| 24 // - file creation/deletion/modification for a watched file |
| 25 // - modifications to the paths to a watched object that would affect the |
| 26 // object such as renaming/attibute changes etc. |
| 27 // The FSEvents version did all of the above except handling attribute changes |
| 28 // to path components. Unfortunately FSEvents appears to have an issue where the |
| 29 // current implementation (Mac OS X 10.6.7) sometimes drops events and doesn't |
| 30 // send notifications. See |
| 31 // http://code.google.com/p/chromium/issues/detail?id=54822#c31 for source that |
| 32 // will reproduce the problem. FSEvents also required having a CFRunLoop |
| 33 // backing the thread that it was running on, that caused added complexity |
| 34 // in the interfaces. |
| 35 // The kqueue implementation will handle all of the items in the list above |
| 36 // except for detecting modifications to files in a watched directory. It will |
| 37 // detect the creation and deletion of files, just not the modification of |
| 38 // files. It does however detect the attribute changes that the FSEvents impl |
| 39 // would miss. |
| 40 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate, |
| 41 public MessageLoopForIO::Watcher, |
| 42 public MessageLoop::DestructionObserver { |
| 43 public: |
| 44 FilePathWatcherImpl() : kqueue_(-1) {} |
| 45 virtual ~FilePathWatcherImpl() {} |
| 46 |
| 47 // MessageLoopForIO::Watcher overrides. |
| 48 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE; |
| 49 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE; |
| 50 |
| 51 // MessageLoop::DestructionObserver overrides. |
| 52 virtual void WillDestroyCurrentMessageLoop() OVERRIDE; |
| 53 |
| 54 // FilePathWatcher::PlatformDelegate overrides. |
| 55 virtual bool Watch(const FilePath& path, |
| 56 FilePathWatcher::Delegate* delegate) OVERRIDE; |
| 57 virtual void Cancel() OVERRIDE; |
| 58 |
| 59 private: |
| 60 class EventData { |
| 61 public: |
| 62 EventData(const FilePath& path, const FilePath::StringType& subdir) |
| 63 : path_(path), subdir_(subdir) { } |
| 64 FilePath path_; // Full path to this item. |
| 65 FilePath::StringType subdir_; // Path to any sub item. |
| 66 }; |
| 67 typedef std::vector<struct kevent> EventVector; |
| 68 |
| 69 // Can only be called on |io_message_loop_|'s thread. |
| 70 virtual void CancelOnMessageLoopThread() OVERRIDE; |
| 71 |
| 72 // Returns true if the kevent values are error free. |
| 73 bool AreKeventValuesValid(struct kevent* kevents, int count); |
| 74 |
| 75 // Respond to a change of attributes of the path component represented by |
| 76 // |event|. Sets |target_file_affected| to true if |target_| is affected. |
| 77 // Sets |update_watches| to true if |events_| need to be updated. |
| 78 void HandleAttributesChange(const EventVector::iterator& event, |
| 79 bool* target_file_affected, |
| 80 bool* update_watches); |
| 81 |
| 82 // Respond to a move of deletion of the path component represented by |
| 83 // |event|. Sets |target_file_affected| to true if |target_| is affected. |
| 84 // Sets |update_watches| to true if |events_| need to be updated. |
| 85 void HandleDeleteOrMoveChange(const EventVector::iterator& event, |
| 86 bool* target_file_affected, |
| 87 bool* update_watches); |
| 88 |
| 89 // Respond to a creation of an item in the path component represented by |
| 90 // |event|. Sets |target_file_affected| to true if |target_| is affected. |
| 91 // Sets |update_watches| to true if |events_| need to be updated. |
| 92 void HandleCreateItemChange(const EventVector::iterator& event, |
| 93 bool* target_file_affected, |
| 94 bool* update_watches); |
| 95 |
| 96 // Update |events_| with the current status of the system. |
| 97 // Sets |target_file_affected| to true if |target_| is affected. |
| 98 // Returns false if an error occurs. |
| 99 bool UpdateWatches(bool* target_file_affected); |
| 100 |
| 101 // Fills |events| with one kevent per component in |path|. |
| 102 // Returns the number of valid events created where a valid event is |
| 103 // defined as one that has a ident (file descriptor) field != -1. |
| 104 static int EventsForPath(FilePath path, EventVector *events); |
| 105 |
| 106 // Release a kevent generated by EventsForPath. |
| 107 static void ReleaseEvent(struct kevent& event); |
| 108 |
| 109 // Returns a file descriptor that will not block the system from deleting |
| 110 // the file it references. |
| 111 static int FileDescriptorForPath(const FilePath& path); |
| 112 |
| 113 // Closes |*fd| and sets |*fd| to -1. |
| 114 static void CloseFileDescriptor(int* fd); |
| 115 |
| 116 // Returns true if kevent has open file descriptor. |
| 117 static bool IsKeventFileDescriptorOpen(const struct kevent& event) { |
| 118 return event.ident != static_cast<uintptr_t>(-1); |
| 119 } |
| 120 |
| 121 static EventData* EventDataForKevent(const struct kevent& event) { |
| 122 return reinterpret_cast<EventData*>(event.udata); |
| 123 } |
| 124 |
| 125 EventVector events_; |
| 126 scoped_refptr<base::MessageLoopProxy> io_message_loop_; |
| 127 MessageLoopForIO::FileDescriptorWatcher kqueue_watcher_; |
| 128 scoped_refptr<FilePathWatcher::Delegate> delegate_; |
| 129 FilePath target_; |
| 130 int kqueue_; |
| 131 |
| 132 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); |
| 133 }; |
| 134 |
| 135 void FilePathWatcherImpl::ReleaseEvent(struct kevent& event) { |
| 136 CloseFileDescriptor(reinterpret_cast<int*>(&event.ident)); |
| 137 EventData* entry = EventDataForKevent(event); |
| 138 delete entry; |
| 139 event.udata = NULL; |
| 140 } |
| 141 |
| 142 int FilePathWatcherImpl::EventsForPath(FilePath path, EventVector* events) { |
| 143 DCHECK(MessageLoopForIO::current()); |
| 144 // Make sure that we are working with a clean slate. |
| 145 DCHECK(events->empty()); |
| 146 |
| 147 std::vector<FilePath::StringType> components; |
| 148 path.GetComponents(&components); |
| 149 |
| 150 if (components.size() < 1) { |
| 151 return -1; |
| 152 } |
| 153 |
| 154 int last_existing_entry = 0; |
| 155 FilePath built_path; |
| 156 bool path_still_exists = true; |
| 157 for(std::vector<FilePath::StringType>::iterator i = components.begin(); |
| 158 i != components.end(); ++i) { |
| 159 if (i == components.begin()) { |
| 160 built_path = FilePath(*i); |
| 161 } else { |
| 162 built_path = built_path.Append(*i); |
| 163 } |
| 164 int fd = -1; |
| 165 if (path_still_exists) { |
| 166 fd = FileDescriptorForPath(built_path); |
| 167 if (fd == -1) { |
| 168 path_still_exists = false; |
| 169 } else { |
| 170 ++last_existing_entry; |
| 171 } |
| 172 } |
| 173 FilePath::StringType subdir = (i != (components.end() - 1)) ? *(i + 1) : ""; |
| 174 EventData* data = new EventData(built_path, subdir); |
| 175 struct kevent event; |
| 176 EV_SET(&event, fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR | EV_RECEIPT), |
| 177 (NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB | |
| 178 NOTE_RENAME | NOTE_REVOKE | NOTE_EXTEND), 0, data); |
| 179 events->push_back(event); |
| 180 } |
| 181 return last_existing_entry; |
| 182 } |
| 183 |
| 184 int FilePathWatcherImpl::FileDescriptorForPath(const FilePath& path) { |
| 185 return HANDLE_EINTR(open(path.value().c_str(), O_EVTONLY)); |
| 186 } |
| 187 |
| 188 void FilePathWatcherImpl::CloseFileDescriptor(int *fd) { |
| 189 if (*fd == -1) { |
| 190 return; |
| 191 } |
| 192 |
| 193 if (HANDLE_EINTR(close(*fd)) != 0) { |
| 194 PLOG(ERROR) << "close"; |
| 195 } |
| 196 *fd = -1; |
| 197 } |
| 198 |
| 199 bool FilePathWatcherImpl::AreKeventValuesValid(struct kevent* kevents, |
| 200 int count) { |
| 201 if (count < 0) { |
| 202 PLOG(ERROR) << "kevent"; |
| 203 return false; |
| 204 } |
| 205 bool valid = true; |
| 206 for (int i = 0; i < count; ++i) { |
| 207 if (kevents[i].flags & EV_ERROR && kevents[i].data) { |
| 208 // Find the kevent in |events_| that matches the kevent with the error. |
| 209 EventVector::iterator event = events_.begin(); |
| 210 for (; event != events_.end(); ++event) { |
| 211 if (event->ident == kevents[i].ident) { |
| 212 break; |
| 213 } |
| 214 } |
| 215 std::string path_name; |
| 216 if (event != events_.end()) { |
| 217 EventData* event_data = EventDataForKevent(*event); |
| 218 if (event_data != NULL) { |
| 219 path_name = event_data->path_.value(); |
| 220 } |
| 221 } |
| 222 if (path_name.empty()) { |
| 223 path_name = base::StringPrintf( |
| 224 "fd %d", *reinterpret_cast<int*>(&kevents[i].ident)); |
| 225 } |
| 226 LOG(ERROR) << "Error: " << kevents[i].data << " for " << path_name; |
| 227 valid = false; |
| 228 } |
| 229 } |
| 230 return valid; |
| 231 } |
| 232 |
| 233 void FilePathWatcherImpl::HandleAttributesChange( |
| 234 const EventVector::iterator& event, |
| 235 bool* target_file_affected, |
| 236 bool* update_watches) { |
| 237 EventVector::iterator next_event = event + 1; |
| 238 EventData* next_event_data = EventDataForKevent(*next_event); |
| 239 // Check to see if the next item in path is still accessible. |
| 240 int have_access = FileDescriptorForPath(next_event_data->path_); |
| 241 if (have_access == -1) { |
| 242 *target_file_affected = true; |
| 243 *update_watches = true; |
| 244 EventVector::iterator local_event(event); |
| 245 for (; local_event != events_.end(); ++local_event) { |
| 246 // Close all nodes from the event down. This has the side effect of |
| 247 // potentially rendering other events in |updates| invalid. |
| 248 // There is no need to remove the events from |kqueue_| because this |
| 249 // happens as a side effect of closing the file descriptor. |
| 250 CloseFileDescriptor(reinterpret_cast<int*>(&local_event->ident)); |
| 251 } |
| 252 } else { |
| 253 CloseFileDescriptor(&have_access); |
| 254 } |
| 255 } |
| 256 |
| 257 void FilePathWatcherImpl::HandleDeleteOrMoveChange( |
| 258 const EventVector::iterator& event, |
| 259 bool* target_file_affected, |
| 260 bool* update_watches) { |
| 261 *target_file_affected = true; |
| 262 *update_watches = true; |
| 263 EventVector::iterator local_event(event); |
| 264 for (; local_event != events_.end(); ++local_event) { |
| 265 // Close all nodes from the event down. This has the side effect of |
| 266 // potentially rendering other events in |updates| invalid. |
| 267 // There is no need to remove the events from |kqueue_| because this |
| 268 // happens as a side effect of closing the file descriptor. |
| 269 CloseFileDescriptor(reinterpret_cast<int*>(&local_event->ident)); |
| 270 } |
| 271 } |
| 272 |
| 273 void FilePathWatcherImpl::HandleCreateItemChange( |
| 274 const EventVector::iterator& event, |
| 275 bool* target_file_affected, |
| 276 bool* update_watches) { |
| 277 // Get the next item in the path. |
| 278 EventVector::iterator next_event = event + 1; |
| 279 EventData* next_event_data = EventDataForKevent(*next_event); |
| 280 |
| 281 // Check to see if it already has a valid file descriptor. |
| 282 if (!IsKeventFileDescriptorOpen(*next_event)) { |
| 283 // If not, attempt to open a file descriptor for it. |
| 284 next_event->ident = FileDescriptorForPath(next_event_data->path_); |
| 285 if (IsKeventFileDescriptorOpen(*next_event)) { |
| 286 *update_watches = true; |
| 287 if (next_event_data->subdir_.empty()) { |
| 288 *target_file_affected = true; |
| 289 } |
| 290 } |
| 291 } |
| 292 } |
| 293 |
| 294 bool FilePathWatcherImpl::UpdateWatches(bool* target_file_affected) { |
| 295 // Iterate over events adding kevents for items that exist to the kqueue. |
| 296 // Then check to see if new components in the path have been created. |
| 297 // Repeat until no new components in the path are detected. |
| 298 // This is to get around races in directory creation in a watched path. |
| 299 bool update_watches = true; |
| 300 while (update_watches) { |
| 301 size_t valid; |
| 302 for (valid = 0; valid < events_.size(); ++valid) { |
| 303 if (!IsKeventFileDescriptorOpen(events_[valid])) { |
| 304 break; |
| 305 } |
| 306 } |
| 307 if (valid == 0) { |
| 308 // The root of the file path is inaccessible? |
| 309 return false; |
| 310 } |
| 311 |
| 312 EventVector updates(valid); |
| 313 int count = HANDLE_EINTR(kevent(kqueue_, &events_[0], valid, &updates[0], |
| 314 valid, NULL)); |
| 315 if (!AreKeventValuesValid(&updates[0], count)) { |
| 316 return false; |
| 317 } |
| 318 update_watches = false; |
| 319 for (; valid < events_.size(); ++valid) { |
| 320 EventData* event_data = EventDataForKevent(events_[valid]); |
| 321 events_[valid].ident = FileDescriptorForPath(event_data->path_); |
| 322 if (IsKeventFileDescriptorOpen(events_[valid])) { |
| 323 update_watches = true; |
| 324 if (event_data->subdir_.empty()) { |
| 325 *target_file_affected = true; |
| 326 } |
| 327 } else { |
| 328 break; |
| 329 } |
| 330 } |
| 331 } |
| 332 return true; |
| 333 } |
| 334 |
| 335 void FilePathWatcherImpl::OnFileCanReadWithoutBlocking(int fd) { |
| 336 DCHECK(MessageLoopForIO::current()); |
| 337 CHECK_EQ(fd, kqueue_); |
| 338 CHECK(events_.size()); |
| 339 |
| 340 // Request the file system update notifications that have occurred and return |
| 341 // them in |updates|. |count| will contain the number of updates that have |
| 342 // occurred. |
| 343 EventVector updates(events_.size()); |
| 344 struct timespec timeout = {0, 0}; |
| 345 int count = HANDLE_EINTR(kevent(kqueue_, NULL, 0, &updates[0], updates.size(), |
| 346 &timeout)); |
| 347 |
| 348 // Error values are stored within updates, so check to make sure that no |
| 349 // errors occurred. |
| 350 if (!AreKeventValuesValid(&updates[0], count)) { |
| 351 delegate_->OnFilePathError(target_); |
| 352 Cancel(); |
| 353 return; |
| 354 } |
| 355 |
| 356 bool update_watches = false; |
| 357 bool send_notification = false; |
| 358 |
| 359 // Iterate through each of the updates and react to them. |
| 360 for (int i = 0; i < count; ++i) { |
| 361 // Find our kevent record that matches the update notification. |
| 362 EventVector::iterator event = events_.begin(); |
| 363 for (; event != events_.end(); ++event) { |
| 364 if (!IsKeventFileDescriptorOpen(*event) || |
| 365 event->ident == updates[i].ident) { |
| 366 break; |
| 367 } |
| 368 } |
| 369 if (!IsKeventFileDescriptorOpen(*event) || event == events_.end()) { |
| 370 // The event may no longer exist in |events_| because another event |
| 371 // modified |events_| in such a way to make it invalid. For example if |
| 372 // the path is /foo/bar/bam and foo is deleted, NOTE_DELETE events for |
| 373 // foo, bar and bam will be sent. If foo is processed first, then |
| 374 // the file descriptors for bar and bam will already be closed and set |
| 375 // to -1 before they get a chance to be processed. |
| 376 continue; |
| 377 } |
| 378 |
| 379 EventData* event_data = EventDataForKevent(*event); |
| 380 |
| 381 // If the subdir is empty, this is the last item on the path and is the |
| 382 // target file. |
| 383 bool target_file_affected = event_data->subdir_.empty(); |
| 384 if ((updates[i].fflags & NOTE_ATTRIB) && !target_file_affected) { |
| 385 HandleAttributesChange(event, &target_file_affected, &update_watches); |
| 386 } |
| 387 if (updates[i].fflags & (NOTE_DELETE | NOTE_REVOKE | NOTE_RENAME)) { |
| 388 HandleDeleteOrMoveChange(event, &target_file_affected, &update_watches); |
| 389 } |
| 390 if ((updates[i].fflags & NOTE_WRITE) && !target_file_affected) { |
| 391 HandleCreateItemChange(event, &target_file_affected, &update_watches); |
| 392 } |
| 393 send_notification |= target_file_affected; |
| 394 } |
| 395 |
| 396 if (update_watches) { |
| 397 if (!UpdateWatches(&send_notification)) { |
| 398 delegate_->OnFilePathError(target_); |
| 399 Cancel(); |
| 400 } |
| 401 } |
| 402 |
| 403 if (send_notification) { |
| 404 delegate_->OnFilePathChanged(target_); |
| 405 } |
| 406 } |
| 407 |
| 408 void FilePathWatcherImpl::OnFileCanWriteWithoutBlocking(int fd) { |
| 409 NOTREACHED(); |
| 410 } |
| 411 |
| 412 void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() { |
| 413 CancelOnMessageLoopThread(); |
| 414 } |
| 415 |
| 416 bool FilePathWatcherImpl::Watch(const FilePath& path, |
| 417 FilePathWatcher::Delegate* delegate) { |
| 418 DCHECK(MessageLoopForIO::current()); |
| 419 DCHECK(target_.value().empty()); // Can only watch one path. |
| 420 DCHECK(delegate); |
| 421 DCHECK_EQ(kqueue_, -1); |
| 422 |
| 423 delegate_ = delegate; |
| 424 target_ = path; |
| 425 |
| 426 MessageLoop::current()->AddDestructionObserver(this); |
| 427 io_message_loop_ = base::MessageLoopProxy::CreateForCurrentThread(); |
| 428 |
| 429 kqueue_ = kqueue(); |
| 430 if (kqueue_ == -1) { |
| 431 PLOG(ERROR) << "kqueue"; |
| 432 return false; |
| 433 } |
| 434 |
| 435 int last_entry = EventsForPath(target_, &events_); |
| 436 CHECK_NE(last_entry, 0); |
| 437 |
| 438 EventVector responses(last_entry); |
| 439 |
| 440 int count = HANDLE_EINTR(kevent(kqueue_, &events_[0], last_entry, |
| 441 &responses[0], last_entry, NULL)); |
| 442 if (!AreKeventValuesValid(&responses[0], count)) { |
| 443 // Calling Cancel() here to close any file descriptors that were opened. |
| 444 // This would happen in the destructor anyways, but FilePathWatchers tend to |
| 445 // be long lived, and if an error has occurred, there is no reason to waste |
| 446 // the file descriptors. |
| 447 Cancel(); |
| 448 return false; |
| 449 } |
| 450 |
| 451 return MessageLoopForIO::current()->WatchFileDescriptor( |
| 452 kqueue_, true, MessageLoopForIO::WATCH_READ, &kqueue_watcher_, this); |
| 453 } |
| 454 |
| 455 void FilePathWatcherImpl::Cancel() { |
| 456 base::MessageLoopProxy* proxy = io_message_loop_.get(); |
| 457 if (!proxy) { |
| 458 set_cancelled(); |
| 459 return; |
| 460 } |
| 461 if (!proxy->BelongsToCurrentThread()) { |
| 462 proxy->PostTask(FROM_HERE, |
| 463 NewRunnableMethod(this, &FilePathWatcherImpl::Cancel)); |
| 464 return; |
| 465 } |
| 466 CancelOnMessageLoopThread(); |
| 467 } |
| 468 |
| 469 void FilePathWatcherImpl::CancelOnMessageLoopThread() { |
| 470 DCHECK(MessageLoopForIO::current()); |
| 471 if (!is_cancelled()) { |
| 472 set_cancelled(); |
| 473 kqueue_watcher_.StopWatchingFileDescriptor(); |
| 474 CloseFileDescriptor(&kqueue_); |
| 475 std::for_each(events_.begin(), events_.end(), ReleaseEvent); |
| 476 events_.clear(); |
| 477 io_message_loop_.release(); |
| 478 MessageLoop::current()->RemoveDestructionObserver(this); |
| 479 delegate_ = NULL; |
| 480 } |
| 481 } |
| 482 |
| 483 } // namespace |
| 484 |
| 485 FilePathWatcher::FilePathWatcher() { |
| 486 impl_ = new FilePathWatcherImpl(); |
| 487 } |
OLD | NEW |