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