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