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 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <aclapi.h>
10 #elif defined(OS_POSIX)
11 #include <sys/stat.h>
12 #endif
13
14 #include <set>
15
16 #include "base/bind.h"
17 #include "base/bind_helpers.h"
18 #include "base/compiler_specific.h"
19 #include "base/files/file_path.h"
20 #include "base/files/file_util.h"
21 #include "base/files/scoped_temp_dir.h"
22 #include "base/location.h"
23 #include "base/macros.h"
24 #include "base/message_loop/message_loop.h"
25 #include "base/run_loop.h"
26 #include "base/single_thread_task_runner.h"
27 #include "base/stl_util.h"
28 #include "base/strings/stringprintf.h"
29 #include "base/synchronization/waitable_event.h"
30 #include "base/test/test_file_util.h"
31 #include "base/test/test_timeouts.h"
32 #include "base/threading/thread_task_runner_handle.h"
33 #include "build/build_config.h"
34 #include "testing/gtest/include/gtest/gtest.h"
35
36 #if defined(OS_ANDROID)
37 #include "base/android/path_utils.h"
38 #endif // defined(OS_ANDROID)
39
40 #if defined(OS_POSIX)
41 #include "base/files/file_descriptor_watcher_posix.h"
42 #endif // defined(OS_POSIX)
43
44 namespace base {
45
46 namespace {
47
48 class TestDelegate;
49
50 // Aggregates notifications from the test delegates and breaks the message loop
51 // the test thread is waiting on once they all came in.
52 class NotificationCollector
53 : public base::RefCountedThreadSafe<NotificationCollector> {
54 public:
NotificationCollector()55 NotificationCollector() : task_runner_(base::ThreadTaskRunnerHandle::Get()) {}
56
57 // Called from the file thread by the delegates.
OnChange(TestDelegate * delegate)58 void OnChange(TestDelegate* delegate) {
59 task_runner_->PostTask(
60 FROM_HERE, base::BindOnce(&NotificationCollector::RecordChange, this,
61 base::Unretained(delegate)));
62 }
63
Register(TestDelegate * delegate)64 void Register(TestDelegate* delegate) {
65 delegates_.insert(delegate);
66 }
67
Reset(base::OnceClosure signal_closure)68 void Reset(base::OnceClosure signal_closure) {
69 signal_closure_ = std::move(signal_closure);
70 signaled_.clear();
71 }
72
Success()73 bool Success() {
74 return signaled_ == delegates_;
75 }
76
77 private:
78 friend class base::RefCountedThreadSafe<NotificationCollector>;
79 ~NotificationCollector() = default;
80
RecordChange(TestDelegate * delegate)81 void RecordChange(TestDelegate* delegate) {
82 // Warning: |delegate| is Unretained. Do not dereference.
83 ASSERT_TRUE(task_runner_->BelongsToCurrentThread());
84 ASSERT_TRUE(delegates_.count(delegate));
85 signaled_.insert(delegate);
86
87 // Check whether all delegates have been signaled.
88 if (signal_closure_ && signaled_ == delegates_)
89 std::move(signal_closure_).Run();
90 }
91
92 // Set of registered delegates.
93 std::set<TestDelegate*> delegates_;
94
95 // Set of signaled delegates.
96 std::set<TestDelegate*> signaled_;
97
98 // The loop we should break after all delegates signaled.
99 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
100
101 // Closure to run when all delegates have signaled.
102 base::OnceClosure signal_closure_;
103 };
104
105 class TestDelegateBase : public SupportsWeakPtr<TestDelegateBase> {
106 public:
107 TestDelegateBase() = default;
108 virtual ~TestDelegateBase() = default;
109
110 virtual void OnFileChanged(const FilePath& path, bool error) = 0;
111
112 private:
113 DISALLOW_COPY_AND_ASSIGN(TestDelegateBase);
114 };
115
116 // A mock class for testing. Gmock is not appropriate because it is not
117 // thread-safe for setting expectations. Thus the test code cannot safely
118 // reset expectations while the file watcher is running.
119 // Instead, TestDelegate gets the notifications from FilePathWatcher and uses
120 // NotificationCollector to aggregate the results.
121 class TestDelegate : public TestDelegateBase {
122 public:
TestDelegate(NotificationCollector * collector)123 explicit TestDelegate(NotificationCollector* collector)
124 : collector_(collector) {
125 collector_->Register(this);
126 }
127 ~TestDelegate() override = default;
128
OnFileChanged(const FilePath & path,bool error)129 void OnFileChanged(const FilePath& path, bool error) override {
130 if (error)
131 ADD_FAILURE() << "Error " << path.value();
132 else
133 collector_->OnChange(this);
134 }
135
136 private:
137 scoped_refptr<NotificationCollector> collector_;
138
139 DISALLOW_COPY_AND_ASSIGN(TestDelegate);
140 };
141
142 class FilePathWatcherTest : public testing::Test {
143 public:
FilePathWatcherTest()144 FilePathWatcherTest()
145 #if defined(OS_POSIX)
146 : file_descriptor_watcher_(&loop_)
147 #endif
148 {
149 }
150
151 ~FilePathWatcherTest() override = default;
152
153 protected:
SetUp()154 void SetUp() override {
155 #if defined(OS_ANDROID)
156 // Watching files is only permitted when all parent directories are
157 // accessible, which is not the case for the default temp directory
158 // on Android which is under /data/data. Use /sdcard instead.
159 // TODO(pauljensen): Remove this when crbug.com/475568 is fixed.
160 FilePath parent_dir;
161 ASSERT_TRUE(android::GetExternalStorageDirectory(&parent_dir));
162 ASSERT_TRUE(temp_dir_.CreateUniqueTempDirUnderPath(parent_dir));
163 #else // defined(OS_ANDROID)
164 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
165 #endif // defined(OS_ANDROID)
166 collector_ = new NotificationCollector();
167 }
168
TearDown()169 void TearDown() override { RunLoop().RunUntilIdle(); }
170
test_file()171 FilePath test_file() {
172 return temp_dir_.GetPath().AppendASCII("FilePathWatcherTest");
173 }
174
test_link()175 FilePath test_link() {
176 return temp_dir_.GetPath().AppendASCII("FilePathWatcherTest.lnk");
177 }
178
179 // Write |content| to |file|. Returns true on success.
WriteFile(const FilePath & file,const std::string & content)180 bool WriteFile(const FilePath& file, const std::string& content) {
181 int write_size = ::base::WriteFile(file, content.c_str(), content.length());
182 return write_size == static_cast<int>(content.length());
183 }
184
185 bool SetupWatch(const FilePath& target,
186 FilePathWatcher* watcher,
187 TestDelegateBase* delegate,
188 bool recursive_watch) WARN_UNUSED_RESULT;
189
WaitForEvents()190 bool WaitForEvents() WARN_UNUSED_RESULT {
191 return WaitForEventsWithTimeout(TestTimeouts::action_timeout());
192 }
193
WaitForEventsWithTimeout(TimeDelta timeout)194 bool WaitForEventsWithTimeout(TimeDelta timeout) WARN_UNUSED_RESULT {
195 RunLoop run_loop;
196 collector_->Reset(run_loop.QuitClosure());
197
198 // Make sure we timeout if we don't get notified.
199 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
200 FROM_HERE, run_loop.QuitClosure(), timeout);
201 run_loop.Run();
202 return collector_->Success();
203 }
204
collector()205 NotificationCollector* collector() { return collector_.get(); }
206
207 MessageLoopForIO loop_;
208 #if defined(OS_POSIX)
209 FileDescriptorWatcher file_descriptor_watcher_;
210 #endif
211
212 ScopedTempDir temp_dir_;
213 scoped_refptr<NotificationCollector> collector_;
214
215 private:
216 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherTest);
217 };
218
SetupWatch(const FilePath & target,FilePathWatcher * watcher,TestDelegateBase * delegate,bool recursive_watch)219 bool FilePathWatcherTest::SetupWatch(const FilePath& target,
220 FilePathWatcher* watcher,
221 TestDelegateBase* delegate,
222 bool recursive_watch) {
223 return watcher->Watch(
224 target, recursive_watch,
225 base::Bind(&TestDelegateBase::OnFileChanged, delegate->AsWeakPtr()));
226 }
227
228 // Basic test: Create the file and verify that we notice.
TEST_F(FilePathWatcherTest,NewFile)229 TEST_F(FilePathWatcherTest, NewFile) {
230 FilePathWatcher watcher;
231 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
232 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
233
234 ASSERT_TRUE(WriteFile(test_file(), "content"));
235 ASSERT_TRUE(WaitForEvents());
236 }
237
238 // Verify that modifying the file is caught.
TEST_F(FilePathWatcherTest,ModifiedFile)239 TEST_F(FilePathWatcherTest, ModifiedFile) {
240 ASSERT_TRUE(WriteFile(test_file(), "content"));
241
242 FilePathWatcher watcher;
243 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
244 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
245
246 // Now make sure we get notified if the file is modified.
247 ASSERT_TRUE(WriteFile(test_file(), "new content"));
248 ASSERT_TRUE(WaitForEvents());
249 }
250
251 // Verify that moving the file into place is caught.
TEST_F(FilePathWatcherTest,MovedFile)252 TEST_F(FilePathWatcherTest, MovedFile) {
253 FilePath source_file(temp_dir_.GetPath().AppendASCII("source"));
254 ASSERT_TRUE(WriteFile(source_file, "content"));
255
256 FilePathWatcher watcher;
257 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
258 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
259
260 // Now make sure we get notified if the file is modified.
261 ASSERT_TRUE(base::Move(source_file, test_file()));
262 ASSERT_TRUE(WaitForEvents());
263 }
264
TEST_F(FilePathWatcherTest,DeletedFile)265 TEST_F(FilePathWatcherTest, DeletedFile) {
266 ASSERT_TRUE(WriteFile(test_file(), "content"));
267
268 FilePathWatcher watcher;
269 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
270 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
271
272 // Now make sure we get notified if the file is deleted.
273 base::DeleteFile(test_file(), false);
274 ASSERT_TRUE(WaitForEvents());
275 }
276
277 // Used by the DeleteDuringNotify test below.
278 // Deletes the FilePathWatcher when it's notified.
279 class Deleter : public TestDelegateBase {
280 public:
Deleter(base::OnceClosure done_closure)281 explicit Deleter(base::OnceClosure done_closure)
282 : watcher_(std::make_unique<FilePathWatcher>()),
283 done_closure_(std::move(done_closure)) {}
284 ~Deleter() override = default;
285
OnFileChanged(const FilePath &,bool)286 void OnFileChanged(const FilePath&, bool) override {
287 watcher_.reset();
288 std::move(done_closure_).Run();
289 }
290
watcher() const291 FilePathWatcher* watcher() const { return watcher_.get(); }
292
293 private:
294 std::unique_ptr<FilePathWatcher> watcher_;
295 base::OnceClosure done_closure_;
296
297 DISALLOW_COPY_AND_ASSIGN(Deleter);
298 };
299
300 // Verify that deleting a watcher during the callback doesn't crash.
TEST_F(FilePathWatcherTest,DeleteDuringNotify)301 TEST_F(FilePathWatcherTest, DeleteDuringNotify) {
302 base::RunLoop run_loop;
303 Deleter deleter(run_loop.QuitClosure());
304 ASSERT_TRUE(SetupWatch(test_file(), deleter.watcher(), &deleter, false));
305
306 ASSERT_TRUE(WriteFile(test_file(), "content"));
307 run_loop.Run();
308
309 // We win if we haven't crashed yet.
310 // Might as well double-check it got deleted, too.
311 ASSERT_TRUE(deleter.watcher() == nullptr);
312 }
313
314 // Verify that deleting the watcher works even if there is a pending
315 // notification.
316 // Flaky on MacOS (and ARM linux): http://crbug.com/85930
TEST_F(FilePathWatcherTest,DISABLED_DestroyWithPendingNotification)317 TEST_F(FilePathWatcherTest, DISABLED_DestroyWithPendingNotification) {
318 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
319 FilePathWatcher watcher;
320 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
321 ASSERT_TRUE(WriteFile(test_file(), "content"));
322 }
323
TEST_F(FilePathWatcherTest,MultipleWatchersSingleFile)324 TEST_F(FilePathWatcherTest, MultipleWatchersSingleFile) {
325 FilePathWatcher watcher1, watcher2;
326 std::unique_ptr<TestDelegate> delegate1(new TestDelegate(collector()));
327 std::unique_ptr<TestDelegate> delegate2(new TestDelegate(collector()));
328 ASSERT_TRUE(SetupWatch(test_file(), &watcher1, delegate1.get(), false));
329 ASSERT_TRUE(SetupWatch(test_file(), &watcher2, delegate2.get(), false));
330
331 ASSERT_TRUE(WriteFile(test_file(), "content"));
332 ASSERT_TRUE(WaitForEvents());
333 }
334
335 // Verify that watching a file whose parent directory doesn't exist yet works if
336 // the directory and file are created eventually.
TEST_F(FilePathWatcherTest,NonExistentDirectory)337 TEST_F(FilePathWatcherTest, NonExistentDirectory) {
338 FilePathWatcher watcher;
339 FilePath dir(temp_dir_.GetPath().AppendASCII("dir"));
340 FilePath file(dir.AppendASCII("file"));
341 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
342 ASSERT_TRUE(SetupWatch(file, &watcher, delegate.get(), false));
343
344 ASSERT_TRUE(base::CreateDirectory(dir));
345
346 ASSERT_TRUE(WriteFile(file, "content"));
347
348 VLOG(1) << "Waiting for file creation";
349 ASSERT_TRUE(WaitForEvents());
350
351 ASSERT_TRUE(WriteFile(file, "content v2"));
352 VLOG(1) << "Waiting for file change";
353 ASSERT_TRUE(WaitForEvents());
354
355 ASSERT_TRUE(base::DeleteFile(file, false));
356 VLOG(1) << "Waiting for file deletion";
357 ASSERT_TRUE(WaitForEvents());
358 }
359
360 // Exercises watch reconfiguration for the case that directories on the path
361 // are rapidly created.
TEST_F(FilePathWatcherTest,DirectoryChain)362 TEST_F(FilePathWatcherTest, DirectoryChain) {
363 FilePath path(temp_dir_.GetPath());
364 std::vector<std::string> dir_names;
365 for (int i = 0; i < 20; i++) {
366 std::string dir(base::StringPrintf("d%d", i));
367 dir_names.push_back(dir);
368 path = path.AppendASCII(dir);
369 }
370
371 FilePathWatcher watcher;
372 FilePath file(path.AppendASCII("file"));
373 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
374 ASSERT_TRUE(SetupWatch(file, &watcher, delegate.get(), false));
375
376 FilePath sub_path(temp_dir_.GetPath());
377 for (std::vector<std::string>::const_iterator d(dir_names.begin());
378 d != dir_names.end(); ++d) {
379 sub_path = sub_path.AppendASCII(*d);
380 ASSERT_TRUE(base::CreateDirectory(sub_path));
381 }
382 VLOG(1) << "Create File";
383 ASSERT_TRUE(WriteFile(file, "content"));
384 VLOG(1) << "Waiting for file creation";
385 ASSERT_TRUE(WaitForEvents());
386
387 ASSERT_TRUE(WriteFile(file, "content v2"));
388 VLOG(1) << "Waiting for file modification";
389 ASSERT_TRUE(WaitForEvents());
390 }
391
392 #if defined(OS_MACOSX)
393 // http://crbug.com/85930
394 #define DisappearingDirectory DISABLED_DisappearingDirectory
395 #endif
TEST_F(FilePathWatcherTest,DisappearingDirectory)396 TEST_F(FilePathWatcherTest, DisappearingDirectory) {
397 FilePathWatcher watcher;
398 FilePath dir(temp_dir_.GetPath().AppendASCII("dir"));
399 FilePath file(dir.AppendASCII("file"));
400 ASSERT_TRUE(base::CreateDirectory(dir));
401 ASSERT_TRUE(WriteFile(file, "content"));
402 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
403 ASSERT_TRUE(SetupWatch(file, &watcher, delegate.get(), false));
404
405 ASSERT_TRUE(base::DeleteFile(dir, true));
406 ASSERT_TRUE(WaitForEvents());
407 }
408
409 // Tests that a file that is deleted and reappears is tracked correctly.
TEST_F(FilePathWatcherTest,DeleteAndRecreate)410 TEST_F(FilePathWatcherTest, DeleteAndRecreate) {
411 ASSERT_TRUE(WriteFile(test_file(), "content"));
412 FilePathWatcher watcher;
413 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
414 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
415
416 ASSERT_TRUE(base::DeleteFile(test_file(), false));
417 VLOG(1) << "Waiting for file deletion";
418 ASSERT_TRUE(WaitForEvents());
419
420 ASSERT_TRUE(WriteFile(test_file(), "content"));
421 VLOG(1) << "Waiting for file creation";
422 ASSERT_TRUE(WaitForEvents());
423 }
424
TEST_F(FilePathWatcherTest,WatchDirectory)425 TEST_F(FilePathWatcherTest, WatchDirectory) {
426 FilePathWatcher watcher;
427 FilePath dir(temp_dir_.GetPath().AppendASCII("dir"));
428 FilePath file1(dir.AppendASCII("file1"));
429 FilePath file2(dir.AppendASCII("file2"));
430 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
431 ASSERT_TRUE(SetupWatch(dir, &watcher, delegate.get(), false));
432
433 ASSERT_TRUE(base::CreateDirectory(dir));
434 VLOG(1) << "Waiting for directory creation";
435 ASSERT_TRUE(WaitForEvents());
436
437 ASSERT_TRUE(WriteFile(file1, "content"));
438 VLOG(1) << "Waiting for file1 creation";
439 ASSERT_TRUE(WaitForEvents());
440
441 #if !defined(OS_MACOSX)
442 // Mac implementation does not detect files modified in a directory.
443 ASSERT_TRUE(WriteFile(file1, "content v2"));
444 VLOG(1) << "Waiting for file1 modification";
445 ASSERT_TRUE(WaitForEvents());
446 #endif // !OS_MACOSX
447
448 ASSERT_TRUE(base::DeleteFile(file1, false));
449 VLOG(1) << "Waiting for file1 deletion";
450 ASSERT_TRUE(WaitForEvents());
451
452 ASSERT_TRUE(WriteFile(file2, "content"));
453 VLOG(1) << "Waiting for file2 creation";
454 ASSERT_TRUE(WaitForEvents());
455 }
456
TEST_F(FilePathWatcherTest,MoveParent)457 TEST_F(FilePathWatcherTest, MoveParent) {
458 FilePathWatcher file_watcher;
459 FilePathWatcher subdir_watcher;
460 FilePath dir(temp_dir_.GetPath().AppendASCII("dir"));
461 FilePath dest(temp_dir_.GetPath().AppendASCII("dest"));
462 FilePath subdir(dir.AppendASCII("subdir"));
463 FilePath file(subdir.AppendASCII("file"));
464 std::unique_ptr<TestDelegate> file_delegate(new TestDelegate(collector()));
465 ASSERT_TRUE(SetupWatch(file, &file_watcher, file_delegate.get(), false));
466 std::unique_ptr<TestDelegate> subdir_delegate(new TestDelegate(collector()));
467 ASSERT_TRUE(SetupWatch(subdir, &subdir_watcher, subdir_delegate.get(),
468 false));
469
470 // Setup a directory hierarchy.
471 ASSERT_TRUE(base::CreateDirectory(subdir));
472 ASSERT_TRUE(WriteFile(file, "content"));
473 VLOG(1) << "Waiting for file creation";
474 ASSERT_TRUE(WaitForEvents());
475
476 // Move the parent directory.
477 base::Move(dir, dest);
478 VLOG(1) << "Waiting for directory move";
479 ASSERT_TRUE(WaitForEvents());
480 }
481
TEST_F(FilePathWatcherTest,RecursiveWatch)482 TEST_F(FilePathWatcherTest, RecursiveWatch) {
483 FilePathWatcher watcher;
484 FilePath dir(temp_dir_.GetPath().AppendASCII("dir"));
485 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
486 bool setup_result = SetupWatch(dir, &watcher, delegate.get(), true);
487 if (!FilePathWatcher::RecursiveWatchAvailable()) {
488 ASSERT_FALSE(setup_result);
489 return;
490 }
491 ASSERT_TRUE(setup_result);
492
493 // Main directory("dir") creation.
494 ASSERT_TRUE(base::CreateDirectory(dir));
495 ASSERT_TRUE(WaitForEvents());
496
497 // Create "$dir/file1".
498 FilePath file1(dir.AppendASCII("file1"));
499 ASSERT_TRUE(WriteFile(file1, "content"));
500 ASSERT_TRUE(WaitForEvents());
501
502 // Create "$dir/subdir".
503 FilePath subdir(dir.AppendASCII("subdir"));
504 ASSERT_TRUE(base::CreateDirectory(subdir));
505 ASSERT_TRUE(WaitForEvents());
506
507 // Create "$dir/subdir/subdir_file1".
508 FilePath subdir_file1(subdir.AppendASCII("subdir_file1"));
509 ASSERT_TRUE(WriteFile(subdir_file1, "content"));
510 ASSERT_TRUE(WaitForEvents());
511
512 // Create "$dir/subdir/subdir_child_dir".
513 FilePath subdir_child_dir(subdir.AppendASCII("subdir_child_dir"));
514 ASSERT_TRUE(base::CreateDirectory(subdir_child_dir));
515 ASSERT_TRUE(WaitForEvents());
516
517 // Create "$dir/subdir/subdir_child_dir/child_dir_file1".
518 FilePath child_dir_file1(subdir_child_dir.AppendASCII("child_dir_file1"));
519 ASSERT_TRUE(WriteFile(child_dir_file1, "content v2"));
520 ASSERT_TRUE(WaitForEvents());
521
522 // Write into "$dir/subdir/subdir_child_dir/child_dir_file1".
523 ASSERT_TRUE(WriteFile(child_dir_file1, "content"));
524 ASSERT_TRUE(WaitForEvents());
525
526 // Apps cannot change file attributes on Android in /sdcard as /sdcard uses the
527 // "fuse" file system, while /data uses "ext4". Running these tests in /data
528 // would be preferable and allow testing file attributes and symlinks.
529 // TODO(pauljensen): Re-enable when crbug.com/475568 is fixed and SetUp() places
530 // the |temp_dir_| in /data.
531 #if !defined(OS_ANDROID)
532 // Modify "$dir/subdir/subdir_child_dir/child_dir_file1" attributes.
533 ASSERT_TRUE(base::MakeFileUnreadable(child_dir_file1));
534 ASSERT_TRUE(WaitForEvents());
535 #endif
536
537 // Delete "$dir/subdir/subdir_file1".
538 ASSERT_TRUE(base::DeleteFile(subdir_file1, false));
539 ASSERT_TRUE(WaitForEvents());
540
541 // Delete "$dir/subdir/subdir_child_dir/child_dir_file1".
542 ASSERT_TRUE(base::DeleteFile(child_dir_file1, false));
543 ASSERT_TRUE(WaitForEvents());
544 }
545
546 #if defined(OS_POSIX) && !defined(OS_ANDROID)
547 // Apps cannot create symlinks on Android in /sdcard as /sdcard uses the
548 // "fuse" file system, while /data uses "ext4". Running these tests in /data
549 // would be preferable and allow testing file attributes and symlinks.
550 // TODO(pauljensen): Re-enable when crbug.com/475568 is fixed and SetUp() places
551 // the |temp_dir_| in /data.
552 //
553 // This test is disabled on Fuchsia since it doesn't support symlinking.
TEST_F(FilePathWatcherTest,RecursiveWithSymLink)554 TEST_F(FilePathWatcherTest, RecursiveWithSymLink) {
555 if (!FilePathWatcher::RecursiveWatchAvailable())
556 return;
557
558 FilePathWatcher watcher;
559 FilePath test_dir(temp_dir_.GetPath().AppendASCII("test_dir"));
560 ASSERT_TRUE(base::CreateDirectory(test_dir));
561 FilePath symlink(test_dir.AppendASCII("symlink"));
562 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
563 ASSERT_TRUE(SetupWatch(symlink, &watcher, delegate.get(), true));
564
565 // Link creation.
566 FilePath target1(temp_dir_.GetPath().AppendASCII("target1"));
567 ASSERT_TRUE(base::CreateSymbolicLink(target1, symlink));
568 ASSERT_TRUE(WaitForEvents());
569
570 // Target1 creation.
571 ASSERT_TRUE(base::CreateDirectory(target1));
572 ASSERT_TRUE(WaitForEvents());
573
574 // Create a file in target1.
575 FilePath target1_file(target1.AppendASCII("file"));
576 ASSERT_TRUE(WriteFile(target1_file, "content"));
577 ASSERT_TRUE(WaitForEvents());
578
579 // Link change.
580 FilePath target2(temp_dir_.GetPath().AppendASCII("target2"));
581 ASSERT_TRUE(base::CreateDirectory(target2));
582 ASSERT_TRUE(base::DeleteFile(symlink, false));
583 ASSERT_TRUE(base::CreateSymbolicLink(target2, symlink));
584 ASSERT_TRUE(WaitForEvents());
585
586 // Create a file in target2.
587 FilePath target2_file(target2.AppendASCII("file"));
588 ASSERT_TRUE(WriteFile(target2_file, "content"));
589 ASSERT_TRUE(WaitForEvents());
590 }
591 #endif // defined(OS_POSIX) && !defined(OS_ANDROID)
592
TEST_F(FilePathWatcherTest,MoveChild)593 TEST_F(FilePathWatcherTest, MoveChild) {
594 FilePathWatcher file_watcher;
595 FilePathWatcher subdir_watcher;
596 FilePath source_dir(temp_dir_.GetPath().AppendASCII("source"));
597 FilePath source_subdir(source_dir.AppendASCII("subdir"));
598 FilePath source_file(source_subdir.AppendASCII("file"));
599 FilePath dest_dir(temp_dir_.GetPath().AppendASCII("dest"));
600 FilePath dest_subdir(dest_dir.AppendASCII("subdir"));
601 FilePath dest_file(dest_subdir.AppendASCII("file"));
602
603 // Setup a directory hierarchy.
604 ASSERT_TRUE(base::CreateDirectory(source_subdir));
605 ASSERT_TRUE(WriteFile(source_file, "content"));
606
607 std::unique_ptr<TestDelegate> file_delegate(new TestDelegate(collector()));
608 ASSERT_TRUE(SetupWatch(dest_file, &file_watcher, file_delegate.get(), false));
609 std::unique_ptr<TestDelegate> subdir_delegate(new TestDelegate(collector()));
610 ASSERT_TRUE(SetupWatch(dest_subdir, &subdir_watcher, subdir_delegate.get(),
611 false));
612
613 // Move the directory into place, s.t. the watched file appears.
614 ASSERT_TRUE(base::Move(source_dir, dest_dir));
615 ASSERT_TRUE(WaitForEvents());
616 }
617
618 // Verify that changing attributes on a file is caught
619 #if defined(OS_ANDROID)
620 // Apps cannot change file attributes on Android in /sdcard as /sdcard uses the
621 // "fuse" file system, while /data uses "ext4". Running these tests in /data
622 // would be preferable and allow testing file attributes and symlinks.
623 // TODO(pauljensen): Re-enable when crbug.com/475568 is fixed and SetUp() places
624 // the |temp_dir_| in /data.
625 #define FileAttributesChanged DISABLED_FileAttributesChanged
626 #endif // defined(OS_ANDROID
TEST_F(FilePathWatcherTest,FileAttributesChanged)627 TEST_F(FilePathWatcherTest, FileAttributesChanged) {
628 ASSERT_TRUE(WriteFile(test_file(), "content"));
629 FilePathWatcher watcher;
630 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
631 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
632
633 // Now make sure we get notified if the file is modified.
634 ASSERT_TRUE(base::MakeFileUnreadable(test_file()));
635 ASSERT_TRUE(WaitForEvents());
636 }
637
638 #if defined(OS_LINUX)
639
640 // Verify that creating a symlink is caught.
TEST_F(FilePathWatcherTest,CreateLink)641 TEST_F(FilePathWatcherTest, CreateLink) {
642 FilePathWatcher watcher;
643 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
644 // Note that we are watching the symlink
645 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
646
647 // Now make sure we get notified if the link is created.
648 // Note that test_file() doesn't have to exist.
649 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
650 ASSERT_TRUE(WaitForEvents());
651 }
652
653 // Verify that deleting a symlink is caught.
TEST_F(FilePathWatcherTest,DeleteLink)654 TEST_F(FilePathWatcherTest, DeleteLink) {
655 // Unfortunately this test case only works if the link target exists.
656 // TODO(craig) fix this as part of crbug.com/91561.
657 ASSERT_TRUE(WriteFile(test_file(), "content"));
658 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
659 FilePathWatcher watcher;
660 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
661 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
662
663 // Now make sure we get notified if the link is deleted.
664 ASSERT_TRUE(base::DeleteFile(test_link(), false));
665 ASSERT_TRUE(WaitForEvents());
666 }
667
668 // Verify that modifying a target file that a link is pointing to
669 // when we are watching the link is caught.
TEST_F(FilePathWatcherTest,ModifiedLinkedFile)670 TEST_F(FilePathWatcherTest, ModifiedLinkedFile) {
671 ASSERT_TRUE(WriteFile(test_file(), "content"));
672 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
673 FilePathWatcher watcher;
674 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
675 // Note that we are watching the symlink.
676 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
677
678 // Now make sure we get notified if the file is modified.
679 ASSERT_TRUE(WriteFile(test_file(), "new content"));
680 ASSERT_TRUE(WaitForEvents());
681 }
682
683 // Verify that creating a target file that a link is pointing to
684 // when we are watching the link is caught.
TEST_F(FilePathWatcherTest,CreateTargetLinkedFile)685 TEST_F(FilePathWatcherTest, CreateTargetLinkedFile) {
686 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
687 FilePathWatcher watcher;
688 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
689 // Note that we are watching the symlink.
690 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
691
692 // Now make sure we get notified if the target file is created.
693 ASSERT_TRUE(WriteFile(test_file(), "content"));
694 ASSERT_TRUE(WaitForEvents());
695 }
696
697 // Verify that deleting a target file that a link is pointing to
698 // when we are watching the link is caught.
TEST_F(FilePathWatcherTest,DeleteTargetLinkedFile)699 TEST_F(FilePathWatcherTest, DeleteTargetLinkedFile) {
700 ASSERT_TRUE(WriteFile(test_file(), "content"));
701 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
702 FilePathWatcher watcher;
703 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
704 // Note that we are watching the symlink.
705 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
706
707 // Now make sure we get notified if the target file is deleted.
708 ASSERT_TRUE(base::DeleteFile(test_file(), false));
709 ASSERT_TRUE(WaitForEvents());
710 }
711
712 // Verify that watching a file whose parent directory is a link that
713 // doesn't exist yet works if the symlink is created eventually.
TEST_F(FilePathWatcherTest,LinkedDirectoryPart1)714 TEST_F(FilePathWatcherTest, LinkedDirectoryPart1) {
715 FilePathWatcher watcher;
716 FilePath dir(temp_dir_.GetPath().AppendASCII("dir"));
717 FilePath link_dir(temp_dir_.GetPath().AppendASCII("dir.lnk"));
718 FilePath file(dir.AppendASCII("file"));
719 FilePath linkfile(link_dir.AppendASCII("file"));
720 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
721 // dir/file should exist.
722 ASSERT_TRUE(base::CreateDirectory(dir));
723 ASSERT_TRUE(WriteFile(file, "content"));
724 // Note that we are watching dir.lnk/file which doesn't exist yet.
725 ASSERT_TRUE(SetupWatch(linkfile, &watcher, delegate.get(), false));
726
727 ASSERT_TRUE(CreateSymbolicLink(dir, link_dir));
728 VLOG(1) << "Waiting for link creation";
729 ASSERT_TRUE(WaitForEvents());
730
731 ASSERT_TRUE(WriteFile(file, "content v2"));
732 VLOG(1) << "Waiting for file change";
733 ASSERT_TRUE(WaitForEvents());
734
735 ASSERT_TRUE(base::DeleteFile(file, false));
736 VLOG(1) << "Waiting for file deletion";
737 ASSERT_TRUE(WaitForEvents());
738 }
739
740 // Verify that watching a file whose parent directory is a
741 // dangling symlink works if the directory is created eventually.
TEST_F(FilePathWatcherTest,LinkedDirectoryPart2)742 TEST_F(FilePathWatcherTest, LinkedDirectoryPart2) {
743 FilePathWatcher watcher;
744 FilePath dir(temp_dir_.GetPath().AppendASCII("dir"));
745 FilePath link_dir(temp_dir_.GetPath().AppendASCII("dir.lnk"));
746 FilePath file(dir.AppendASCII("file"));
747 FilePath linkfile(link_dir.AppendASCII("file"));
748 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
749 // Now create the link from dir.lnk pointing to dir but
750 // neither dir nor dir/file exist yet.
751 ASSERT_TRUE(CreateSymbolicLink(dir, link_dir));
752 // Note that we are watching dir.lnk/file.
753 ASSERT_TRUE(SetupWatch(linkfile, &watcher, delegate.get(), false));
754
755 ASSERT_TRUE(base::CreateDirectory(dir));
756 ASSERT_TRUE(WriteFile(file, "content"));
757 VLOG(1) << "Waiting for dir/file creation";
758 ASSERT_TRUE(WaitForEvents());
759
760 ASSERT_TRUE(WriteFile(file, "content v2"));
761 VLOG(1) << "Waiting for file change";
762 ASSERT_TRUE(WaitForEvents());
763
764 ASSERT_TRUE(base::DeleteFile(file, false));
765 VLOG(1) << "Waiting for file deletion";
766 ASSERT_TRUE(WaitForEvents());
767 }
768
769 // Verify that watching a file with a symlink on the path
770 // to the file works.
TEST_F(FilePathWatcherTest,LinkedDirectoryPart3)771 TEST_F(FilePathWatcherTest, LinkedDirectoryPart3) {
772 FilePathWatcher watcher;
773 FilePath dir(temp_dir_.GetPath().AppendASCII("dir"));
774 FilePath link_dir(temp_dir_.GetPath().AppendASCII("dir.lnk"));
775 FilePath file(dir.AppendASCII("file"));
776 FilePath linkfile(link_dir.AppendASCII("file"));
777 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
778 ASSERT_TRUE(base::CreateDirectory(dir));
779 ASSERT_TRUE(CreateSymbolicLink(dir, link_dir));
780 // Note that we are watching dir.lnk/file but the file doesn't exist yet.
781 ASSERT_TRUE(SetupWatch(linkfile, &watcher, delegate.get(), false));
782
783 ASSERT_TRUE(WriteFile(file, "content"));
784 VLOG(1) << "Waiting for file creation";
785 ASSERT_TRUE(WaitForEvents());
786
787 ASSERT_TRUE(WriteFile(file, "content v2"));
788 VLOG(1) << "Waiting for file change";
789 ASSERT_TRUE(WaitForEvents());
790
791 ASSERT_TRUE(base::DeleteFile(file, false));
792 VLOG(1) << "Waiting for file deletion";
793 ASSERT_TRUE(WaitForEvents());
794 }
795
796 #endif // OS_LINUX
797
798 enum Permission {
799 Read,
800 Write,
801 Execute
802 };
803
804 #if defined(OS_MACOSX)
ChangeFilePermissions(const FilePath & path,Permission perm,bool allow)805 bool ChangeFilePermissions(const FilePath& path, Permission perm, bool allow) {
806 struct stat stat_buf;
807
808 if (stat(path.value().c_str(), &stat_buf) != 0)
809 return false;
810
811 mode_t mode = 0;
812 switch (perm) {
813 case Read:
814 mode = S_IRUSR | S_IRGRP | S_IROTH;
815 break;
816 case Write:
817 mode = S_IWUSR | S_IWGRP | S_IWOTH;
818 break;
819 case Execute:
820 mode = S_IXUSR | S_IXGRP | S_IXOTH;
821 break;
822 default:
823 ADD_FAILURE() << "unknown perm " << perm;
824 return false;
825 }
826 if (allow) {
827 stat_buf.st_mode |= mode;
828 } else {
829 stat_buf.st_mode &= ~mode;
830 }
831 return chmod(path.value().c_str(), stat_buf.st_mode) == 0;
832 }
833 #endif // defined(OS_MACOSX)
834
835 #if defined(OS_MACOSX)
836 // Linux implementation of FilePathWatcher doesn't catch attribute changes.
837 // http://crbug.com/78043
838 // Windows implementation of FilePathWatcher catches attribute changes that
839 // don't affect the path being watched.
840 // http://crbug.com/78045
841
842 // Verify that changing attributes on a directory works.
TEST_F(FilePathWatcherTest,DirAttributesChanged)843 TEST_F(FilePathWatcherTest, DirAttributesChanged) {
844 FilePath test_dir1(
845 temp_dir_.GetPath().AppendASCII("DirAttributesChangedDir1"));
846 FilePath test_dir2(test_dir1.AppendASCII("DirAttributesChangedDir2"));
847 FilePath test_file(test_dir2.AppendASCII("DirAttributesChangedFile"));
848 // Setup a directory hierarchy.
849 ASSERT_TRUE(base::CreateDirectory(test_dir1));
850 ASSERT_TRUE(base::CreateDirectory(test_dir2));
851 ASSERT_TRUE(WriteFile(test_file, "content"));
852
853 FilePathWatcher watcher;
854 std::unique_ptr<TestDelegate> delegate(new TestDelegate(collector()));
855 ASSERT_TRUE(SetupWatch(test_file, &watcher, delegate.get(), false));
856
857 // We should not get notified in this case as it hasn't affected our ability
858 // to access the file.
859 ASSERT_TRUE(ChangeFilePermissions(test_dir1, Read, false));
860 ASSERT_FALSE(WaitForEventsWithTimeout(TestTimeouts::tiny_timeout()));
861 ASSERT_TRUE(ChangeFilePermissions(test_dir1, Read, true));
862
863 // We should get notified in this case because filepathwatcher can no
864 // longer access the file
865 ASSERT_TRUE(ChangeFilePermissions(test_dir1, Execute, false));
866 ASSERT_TRUE(WaitForEvents());
867 ASSERT_TRUE(ChangeFilePermissions(test_dir1, Execute, true));
868 }
869
870 #endif // OS_MACOSX
871 } // namespace
872
873 } // namespace base
874