From d6d1dbac3f71a292e071dd3108d8333cb5dae44d Mon Sep 17 00:00:00 2001 From: Narayan Kamath Date: Thu, 1 May 2014 14:01:44 +0100 Subject: [PATCH] Implement FileUtils#contains. Partial cherry-pick of changes 4ca728c0 and 21de56a9, which can't be cherry-picked due to their large surface area. Change-Id: Ife46e150d360cd5241dea93863141749233c1805 --- core/java/android/os/FileUtils.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java index 411783d1d0b07..3e0b54a4d2cf2 100644 --- a/core/java/android/os/FileUtils.java +++ b/core/java/android/os/FileUtils.java @@ -357,4 +357,26 @@ public class FileUtils { } } } + + /** + * Test if a file lives under the given directory, either as a direct child + * or a distant grandchild. + *

+ * Both files must have been resolved using + * {@link File#getCanonicalFile()} to avoid symlink or path traversal + * attacks. + */ + public static boolean contains(File dir, File file) { + String dirPath = dir.getAbsolutePath(); + String filePath = file.getAbsolutePath(); + + if (dirPath.equals(filePath)) { + return true; + } + + if (!dirPath.endsWith("/")) { + dirPath += "/"; + } + return filePath.startsWith(dirPath); + } }