Canonicalise path before extracting relative path

This helps us make accurate access checks on the given path.

Bug: 228833816
Bug: 228450832
Test: atest FileUtilsTest
Test: atest LegacyStorageHostTest
Change-Id: Id620644ffdfe20e9281773e2e23851c56732dd11
Merged-In: Id620644ffdfe20e9281773e2e23851c56732dd11
(cherry picked from commit 93f5186e4b4a044e00a168c55e05fd3835033221)
diff --git a/src/com/android/providers/media/util/FileUtils.java b/src/com/android/providers/media/util/FileUtils.java
index a19d1a9..72880bd 100644
--- a/src/com/android/providers/media/util/FileUtils.java
+++ b/src/com/android/providers/media/util/FileUtils.java
@@ -1101,7 +1101,9 @@
     }
 
     public static @Nullable String extractRelativePath(@Nullable String data) {
+        data = getCanonicalPath(data);
         if (data == null) return null;
+
         final Matcher matcher = PATTERN_RELATIVE_PATH.matcher(data);
         if (matcher.find()) {
             final int lastSlash = data.lastIndexOf('/');
@@ -1656,4 +1658,16 @@
 
         return null;
     }
+
+    @Nullable
+    private static String getCanonicalPath(@Nullable String path) {
+        if (path == null) return null;
+
+        try {
+            return new File(path).getCanonicalPath();
+        } catch (IOException e) {
+            Log.d(TAG, "Unable to get canonical path from invalid data path: " + path, e);
+            return null;
+        }
+    }
 }
diff --git a/tests/src/com/android/providers/media/util/FileUtilsTest.java b/tests/src/com/android/providers/media/util/FileUtilsTest.java
index ed0f5b6..41e9b00 100644
--- a/tests/src/com/android/providers/media/util/FileUtilsTest.java
+++ b/tests/src/com/android/providers/media/util/FileUtilsTest.java
@@ -542,7 +542,15 @@
                     extractRelativePath(prefix + "DCIM/foo.jpg"));
             assertEquals("DCIM/My Vacation/",
                     extractRelativePath(prefix + "DCIM/My Vacation/foo.jpg"));
+            assertEquals("Pictures/",
+                    extractRelativePath(prefix + "DCIM/../Pictures/.//foo.jpg"));
+            assertEquals("/",
+                    extractRelativePath(prefix + "DCIM/Pictures/./..//..////foo.jpg"));
+            assertEquals("Android/data/",
+                    extractRelativePath(prefix + "DCIM/foo.jpg/.//../../Android/data/poc"));
         }
+
+        assertEquals(null, extractRelativePath("/sdcard/\\\u0000"));
     }
 
     @Test