1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9
10 #include "base/files/file_path_watcher_fsevents.h"
11
12 #include <dispatch/dispatch.h>
13
14 #include <algorithm>
15 #include <list>
16
17 #include "base/apple/foundation_util.h"
18 #include "base/apple/scoped_cftyperef.h"
19 #include "base/check.h"
20 #include "base/files/file_util.h"
21 #include "base/functional/bind.h"
22 #include "base/lazy_instance.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/task/sequenced_task_runner.h"
25 #include "base/threading/scoped_blocking_call.h"
26
27 namespace base {
28
29 namespace {
30
31 // The latency parameter passed to FSEventsStreamCreate().
32 const CFAbsoluteTime kEventLatencySeconds = 0.3;
33
34 // Resolve any symlinks in the path.
ResolvePath(const FilePath & path)35 FilePath ResolvePath(const FilePath& path) {
36 const unsigned kMaxLinksToResolve = 255;
37
38 std::vector<FilePath::StringType> component_vector = path.GetComponents();
39 std::list<FilePath::StringType>
40 components(component_vector.begin(), component_vector.end());
41
42 FilePath result;
43 unsigned resolve_count = 0;
44 while (resolve_count < kMaxLinksToResolve && !components.empty()) {
45 FilePath component(*components.begin());
46 components.pop_front();
47
48 FilePath current;
49 if (component.IsAbsolute()) {
50 current = component;
51 } else {
52 current = result.Append(component);
53 }
54
55 FilePath target;
56 if (ReadSymbolicLink(current, &target)) {
57 if (target.IsAbsolute())
58 result.clear();
59 std::vector<FilePath::StringType> target_components =
60 target.GetComponents();
61 components.insert(components.begin(), target_components.begin(),
62 target_components.end());
63 resolve_count++;
64 } else {
65 result = current;
66 }
67 }
68
69 if (resolve_count >= kMaxLinksToResolve)
70 result.clear();
71 return result;
72 }
73
74 } // namespace
75
FilePathWatcherFSEvents()76 FilePathWatcherFSEvents::FilePathWatcherFSEvents()
77 : queue_(dispatch_queue_create(
78 base::StringPrintf("org.chromium.base.FilePathWatcher.%p", this)
79 .c_str(),
80 DISPATCH_QUEUE_SERIAL)) {}
81
~FilePathWatcherFSEvents()82 FilePathWatcherFSEvents::~FilePathWatcherFSEvents() {
83 DCHECK(!task_runner() || task_runner()->RunsTasksInCurrentSequence());
84 DCHECK(callback_.is_null())
85 << "Cancel() must be called before FilePathWatcher is destroyed.";
86 }
87
Watch(const FilePath & path,Type type,const FilePathWatcher::Callback & callback)88 bool FilePathWatcherFSEvents::Watch(const FilePath& path,
89 Type type,
90 const FilePathWatcher::Callback& callback) {
91 DCHECK(!callback.is_null());
92 DCHECK(callback_.is_null());
93
94 // This class could support non-recursive watches, but that is currently
95 // left to FilePathWatcherKQueue.
96 if (type != Type::kRecursive)
97 return false;
98
99 set_task_runner(SequencedTaskRunner::GetCurrentDefault());
100 callback_ = callback;
101
102 FSEventStreamEventId start_event = FSEventsGetCurrentEventId();
103 // The block runtime would implicitly capture the reference, not the object
104 // it's referencing. Copy the path into a local, so that the value is
105 // captured by the block's scope.
106 const FilePath path_copy(path);
107
108 dispatch_async(queue_.get(), ^{
109 StartEventStream(start_event, path_copy);
110 });
111 return true;
112 }
113
Cancel()114 void FilePathWatcherFSEvents::Cancel() {
115 set_cancelled();
116 callback_.Reset();
117
118 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
119 // Switch to the dispatch queue to tear down the event stream. As the queue is
120 // owned by |this|, and this method is called from the destructor, execute the
121 // block synchronously.
122 dispatch_sync(queue_.get(), ^{
123 if (fsevent_stream_) {
124 DestroyEventStream();
125 target_.clear();
126 resolved_target_.clear();
127 }
128 });
129 }
130
131 // static
FSEventsCallback(ConstFSEventStreamRef stream,void * event_watcher,size_t num_events,void * event_paths,const FSEventStreamEventFlags flags[],const FSEventStreamEventId event_ids[])132 void FilePathWatcherFSEvents::FSEventsCallback(
133 ConstFSEventStreamRef stream,
134 void* event_watcher,
135 size_t num_events,
136 void* event_paths,
137 const FSEventStreamEventFlags flags[],
138 const FSEventStreamEventId event_ids[]) {
139 FilePathWatcherFSEvents* watcher =
140 reinterpret_cast<FilePathWatcherFSEvents*>(event_watcher);
141 bool root_changed = watcher->ResolveTargetPath();
142 std::vector<FilePath> paths;
143 FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream);
144 for (size_t i = 0; i < num_events; i++) {
145 if (flags[i] & kFSEventStreamEventFlagRootChanged)
146 root_changed = true;
147 if (event_ids[i])
148 root_change_at = std::min(root_change_at, event_ids[i]);
149 paths.push_back(FilePath(
150 reinterpret_cast<char**>(event_paths)[i]).StripTrailingSeparators());
151 }
152
153 // Reinitialize the event stream if we find changes to the root. This is
154 // necessary since FSEvents doesn't report any events for the subtree after
155 // the directory to be watched gets created.
156 if (root_changed) {
157 // Resetting the event stream from within the callback fails (FSEvents spews
158 // bad file descriptor errors), so do the reset asynchronously.
159 //
160 // We can't dispatch_async a call to UpdateEventStream() directly because
161 // there would be no guarantee that |watcher| still exists when it runs.
162 //
163 // Instead, bounce on task_runner() and use a WeakPtr to verify that
164 // |watcher| still exists. If it does, dispatch_async a call to
165 // UpdateEventStream(). Because the destructor of |watcher| runs on
166 // task_runner() and calls dispatch_sync, it is guaranteed that |watcher|
167 // still exists when UpdateEventStream() runs.
168 watcher->task_runner()->PostTask(
169 FROM_HERE, BindOnce(
170 [](WeakPtr<FilePathWatcherFSEvents> weak_watcher,
171 FSEventStreamEventId root_change_at) {
172 if (!weak_watcher)
173 return;
174 FilePathWatcherFSEvents* watcher = weak_watcher.get();
175 dispatch_async(watcher->queue_.get(), ^{
176 watcher->UpdateEventStream(root_change_at);
177 });
178 },
179 watcher->weak_factory_.GetWeakPtr(), root_change_at));
180 }
181
182 watcher->OnFilePathsChanged(paths);
183 }
184
OnFilePathsChanged(const std::vector<FilePath> & paths)185 void FilePathWatcherFSEvents::OnFilePathsChanged(
186 const std::vector<FilePath>& paths) {
187 DCHECK(!resolved_target_.empty());
188 task_runner()->PostTask(
189 FROM_HERE,
190 BindOnce(&FilePathWatcherFSEvents::DispatchEvents,
191 weak_factory_.GetWeakPtr(), paths, target_, resolved_target_));
192 }
193
DispatchEvents(const std::vector<FilePath> & paths,const FilePath & target,const FilePath & resolved_target)194 void FilePathWatcherFSEvents::DispatchEvents(const std::vector<FilePath>& paths,
195 const FilePath& target,
196 const FilePath& resolved_target) {
197 DCHECK(task_runner()->RunsTasksInCurrentSequence());
198
199 // Don't issue callbacks after Cancel() has been called.
200 if (is_cancelled() || callback_.is_null()) {
201 return;
202 }
203
204 for (const FilePath& path : paths) {
205 if (resolved_target.IsParent(path) || resolved_target == path) {
206 callback_.Run(target, false);
207 return;
208 }
209 }
210 }
211
UpdateEventStream(FSEventStreamEventId start_event)212 void FilePathWatcherFSEvents::UpdateEventStream(
213 FSEventStreamEventId start_event) {
214 // It can happen that the watcher gets canceled while tasks that call this
215 // function are still in flight, so abort if this situation is detected.
216 if (resolved_target_.empty()) {
217 return;
218 }
219
220 if (fsevent_stream_) {
221 DestroyEventStream();
222 }
223
224 apple::ScopedCFTypeRef<CFStringRef> cf_path =
225 apple::FilePathToCFString(resolved_target_);
226 apple::ScopedCFTypeRef<CFStringRef> cf_dir_path =
227 apple::FilePathToCFString(resolved_target_.DirName());
228 CFStringRef paths_array[] = {cf_path.get(), cf_dir_path.get()};
229 apple::ScopedCFTypeRef<CFArrayRef> watched_paths(
230 CFArrayCreate(NULL, reinterpret_cast<const void**>(paths_array),
231 std::size(paths_array), &kCFTypeArrayCallBacks));
232
233 FSEventStreamContext context;
234 context.version = 0;
235 context.info = this;
236 context.retain = NULL;
237 context.release = NULL;
238 context.copyDescription = NULL;
239
240 fsevent_stream_ = FSEventStreamCreate(
241 NULL, &FSEventsCallback, &context, watched_paths.get(), start_event,
242 kEventLatencySeconds, kFSEventStreamCreateFlagWatchRoot);
243 FSEventStreamSetDispatchQueue(fsevent_stream_, queue_.get());
244
245 if (!FSEventStreamStart(fsevent_stream_)) {
246 task_runner()->PostTask(FROM_HERE,
247 BindOnce(&FilePathWatcherFSEvents::ReportError,
248 weak_factory_.GetWeakPtr(), target_));
249 }
250 }
251
ResolveTargetPath()252 bool FilePathWatcherFSEvents::ResolveTargetPath() {
253 FilePath resolved = ResolvePath(target_).StripTrailingSeparators();
254 bool changed = resolved != resolved_target_;
255 resolved_target_ = resolved;
256 if (resolved_target_.empty()) {
257 task_runner()->PostTask(FROM_HERE,
258 BindOnce(&FilePathWatcherFSEvents::ReportError,
259 weak_factory_.GetWeakPtr(), target_));
260 }
261 return changed;
262 }
263
ReportError(const FilePath & target)264 void FilePathWatcherFSEvents::ReportError(const FilePath& target) {
265 DCHECK(task_runner()->RunsTasksInCurrentSequence());
266 if (!callback_.is_null()) {
267 callback_.Run(target, true);
268 }
269 }
270
DestroyEventStream()271 void FilePathWatcherFSEvents::DestroyEventStream() {
272 FSEventStreamStop(fsevent_stream_);
273 FSEventStreamInvalidate(fsevent_stream_);
274 FSEventStreamRelease(fsevent_stream_);
275 fsevent_stream_ = NULL;
276 }
277
StartEventStream(FSEventStreamEventId start_event,const FilePath & path)278 void FilePathWatcherFSEvents::StartEventStream(FSEventStreamEventId start_event,
279 const FilePath& path) {
280 DCHECK(resolved_target_.empty());
281
282 target_ = path;
283 ResolveTargetPath();
284 UpdateEventStream(start_event);
285 }
286
287 } // namespace base
288