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