Skip to content

Commit cc5b2a8

Browse files
authored
Merge pull request #138 from jackBonadies/fixFilenameValidation
There was a pattern in the repo where we would create a file / directory, the provider would sanitize it (removing reserved characters (i.e. ':'), renaming the file type (i.e. ogg -> oga), etc.), and we would later fail to find the file by name. This led to creating duplicate folders #136 and failing to properly resume an incomplete download. To fix this we sanitize the folder/file for the most common reserved characters (the same ones the document provider uses), in addition to using the previous URI whenever possible (no need to reconstruct the URI if we already have it). We also always pass the extension when creating files (since otherwise Android can take liberty in coming up with its own based on Mime type).
2 parents f08f4f7 + e7b03c5 commit cc5b2a8

14 files changed

Lines changed: 540 additions & 97 deletions

‎Common/Services/DownloadService.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,7 @@ private Task DownloadFileAsync(DownloadInfo dlInfo, out Task waitForNext)
536536
dlTask = Task.Run(() =>
537537
{
538538
fileSystemService.GetOrCreateIncompleteLocation(username, fullfilename, depth,
539+
dlInfo.TransferItemReference.IncompleteUri, dlInfo.TransferItemReference.IncompleteParentUri,
539540
out incompleteUri, out incompleteUriDirectory, out partialLength);
540541
}).ContinueWith(setupTask =>
541542
{

‎Common/Services/IFileSystemService.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ namespace Seeker.Services
66
public interface IFileSystemService
77
{
88
void GetOrCreateIncompleteLocation(string username, string fullfilename, int depth,
9+
string storedIncompleteUri, string storedParentUri,
910
out string incompleteUri, out string parentUri, out long partialLength);
1011

1112
Stream OpenIncompleteStream(string incompleteUri, long partialLength);

‎Common/SimpleHelpers.cs‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,82 @@ public static string GenerateIncompleteFolderName(string username, string fullFi
8383
{
8484
incompleteFolderName = incompleteFolderName.Replace(c, '_');
8585
}
86-
return incompleteFolderName;
86+
return ToValidFileName(incompleteFolderName);
87+
}
88+
89+
public const int MaxFileNameBytes = 255;
90+
91+
// Port of AOSP FileUtils.buildValidFatFilename
92+
// https://android.googlesource.com/platform/frameworks/base/+/HEAD/core/java/android/os/FileUtils.java
93+
// We need to transform the filename exactly how Android does, otherwise subsequent FindFile will miss
94+
// One difference: the trim never splits a surrogate pair (otherwise it will fail to be created)
95+
public static string ToValidFileName(string name)
96+
{
97+
if (string.IsNullOrEmpty(name) || name == "." || name == "..")
98+
{
99+
return "(invalid)";
100+
}
101+
var res = new System.Text.StringBuilder(name.Length);
102+
foreach (char c in name)
103+
{
104+
res.Append(IsValidFatFileNameChar(c) ? c : '_');
105+
}
106+
if (System.Text.Encoding.UTF8.GetByteCount(res.ToString()) > MaxFileNameBytes)
107+
{
108+
while (System.Text.Encoding.UTF8.GetByteCount(res.ToString()) > MaxFileNameBytes - 3)
109+
{
110+
int mid = res.Length / 2;
111+
if (IsSecondHalfOfPair(res, mid))
112+
{
113+
res.Remove(mid - 1, 2);
114+
}
115+
else if (IsSecondHalfOfPair(res, mid + 1))
116+
{
117+
res.Remove(mid, 2);
118+
}
119+
else
120+
{
121+
res.Remove(mid, 1);
122+
}
123+
}
124+
int insertAt = res.Length / 2;
125+
if (IsSecondHalfOfPair(res, insertAt))
126+
{
127+
insertAt++;
128+
}
129+
res.Insert(insertAt, "...");
130+
}
131+
return res.ToString();
132+
}
133+
134+
private static bool IsSecondHalfOfPair(System.Text.StringBuilder sb, int index)
135+
{
136+
return index > 0 && index < sb.Length && char.IsLowSurrogate(sb[index]) && char.IsHighSurrogate(sb[index - 1]);
137+
}
138+
139+
// https://android.googlesource.com/platform/frameworks/base/+/HEAD/core/java/android/os/FileUtils.java
140+
private static bool IsValidFatFileNameChar(char c)
141+
{
142+
if (c <= 0x1f)
143+
{
144+
return false;
145+
}
146+
switch (c)
147+
{
148+
case '"':
149+
case '*':
150+
case '/':
151+
case ':':
152+
case '<':
153+
case '>':
154+
case '?':
155+
case '\\':
156+
case '|':
157+
case (char)0x7F:
158+
return false;
159+
default:
160+
return true;
161+
}
87162
}
88163

89164
private static string GetLockedFileName(SearchResponse item)

‎InstrumentationTests/InstrumentationTests.csproj‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
<ProjectReference Include="..\Seeker\Soulseek.NET-master\src\Soulseek.csproj" />
2121
</ItemGroup>
2222

23+
<ItemGroup>
24+
<Compile Include="..\Seeker\Helpers\MediaMimeTypes.cs" Link="SeekerSources\MediaMimeTypes.cs" />
25+
</ItemGroup>
26+
2327
<!--
2428
To test Seeker-specific (Android) types, include individual source files:
2529
<ItemGroup>

‎InstrumentationTests/MainActivity.cs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Reflection;
55
using System.Threading.Tasks;
66
using Android.App;
7+
using Android.Content;
78
using Android.OS;
89
using Android.Util;
910
using Android.Widget;
@@ -15,6 +16,7 @@ namespace InstrumentationTests
1516
public class MainActivity : Activity
1617
{
1718
const string Tag = "SeekerTests";
19+
const int PickTreeRequest = 1;
1820
TextView _output;
1921

2022
protected override void OnCreate(Bundle savedInstanceState)
@@ -27,6 +29,32 @@ protected override void OnCreate(Bundle savedInstanceState)
2729
scrollView.AddView(_output);
2830
SetContentView(scrollView);
2931

32+
// for ProviderFileNameParityTests (needs SAF tree)
33+
if (ContentResolver.PersistedUriPermissions.Count == 0)
34+
{
35+
if (savedInstanceState == null)
36+
{
37+
AppendLine("No folder granted yet for ProviderFileNameParityTests\n");
38+
StartActivityForResult(new Intent(Intent.ActionOpenDocumentTree), PickTreeRequest);
39+
}
40+
return;
41+
}
42+
43+
_ = RunTestsAsync();
44+
}
45+
46+
protected override void OnActivityResult(int requestCode, [Android.Runtime.GeneratedEnum] Result resultCode, Intent data)
47+
{
48+
base.OnActivityResult(requestCode, resultCode, data);
49+
if (requestCode != PickTreeRequest)
50+
{
51+
return;
52+
}
53+
if (resultCode == Result.Ok && data?.Data != null)
54+
{
55+
ContentResolver.TakePersistableUriPermission(data.Data, ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission);
56+
AppendLine("Granted " + data.Data + "\n");
57+
}
3058
_ = RunTestsAsync();
3159
}
3260

Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using Android.App;
5+
using Android.Provider;
6+
using Android.Util;
7+
using Common;
8+
using Seeker;
9+
using Seeker.Helpers;
10+
using NUnit.Framework;
11+
12+
namespace InstrumentationTests
13+
{
14+
// Checks SimpleHelpers.ToValidFileName against what the real storage provider stores.
15+
[TestFixture]
16+
public class ProviderFileNameParityTests
17+
{
18+
const string Tag = "SeekerTests";
19+
20+
private Android.Net.Uri _scratchDir;
21+
22+
private static IEnumerable<(string label, string name)> Cases()
23+
{
24+
foreach (char c in "\"*/:<>?\\|")
25+
{
26+
yield return ("char " + c, "a" + c + "b");
27+
}
28+
yield return ("tab", "a\tb");
29+
yield return ("DEL", "a\u007fb");
30+
yield return (":3", ":3");
31+
yield return ("only invalid", ":");
32+
yield return ("full test", "fulltest|\\?*<\":>+[]/'~!@#$%^&*()_+/\\.,");
33+
yield return (".", ".");
34+
yield return ("..", "..");
35+
yield return ("...", "...");
36+
yield return ("empty", "");
37+
yield return ("ampersand quote", "Rock & Roll's");
38+
yield return ("japanese", "東京事変 - 教育");
39+
yield return ("ascii 300 bytes", new string('a', 150) + new string('b', 150));
40+
yield return ("cjk 300 bytes", new string('東', 50) + new string('京', 50));
41+
yield return ("ascii 254 + 3-byte char", new string('a', 254) + "東");
42+
yield return ("ascii 255", new string('a', 255));
43+
yield return ("ascii 256", new string('a', 256));
44+
// trimming deletes single UTF-16 chars from the middle, so these split surrogate pairs
45+
yield return ("emoji 300 bytes", string.Concat(Enumerable.Repeat("😀", 75)));
46+
yield return ("ascii + emoji middle", new string('a', 140) + string.Concat(Enumerable.Repeat("😀", 5)) + new string('b', 140));
47+
yield return ("ascii + emoji middle odd", new string('a', 141) + string.Concat(Enumerable.Repeat("😀", 5)) + new string('b', 140));
48+
yield return ("mixed emoji cjk", string.Concat(Enumerable.Repeat("東😀", 50)));
49+
// AOSP and a .NET byte count disagree here (a lone surrogate is 1 byte in Java, 3 in .NET)
50+
yield return ("emoji count divergence", new string('a', 101) + string.Concat(Enumerable.Repeat("😀", 9)) + new string('b', 119));
51+
}
52+
53+
private static IEnumerable<string> MediaFileNames()
54+
{
55+
foreach (string ext in new[] { "mp3", "flac", "ogg", "oga", "opus", "m4a", "aac", "ape", "wav", "aiff", "aif", "wma", "wv", "alac", "mp4", "mka", "dsf", "weirdext" })
56+
{
57+
yield return "01 Track." + ext;
58+
}
59+
yield return "cover.jpg";
60+
yield return "folder.jpeg";
61+
yield return "cover.png";
62+
yield return "album.cue";
63+
yield return "rip.log";
64+
yield return "info.nfo";
65+
yield return "playlist.m3u";
66+
yield return "readme.txt";
67+
yield return "01 Track.FLAC";
68+
yield return "01 Track.Mp3";
69+
yield return "a.b.flac";
70+
yield return "noextension";
71+
yield return "trailing.";
72+
}
73+
74+
[SetUp]
75+
public void SetUp()
76+
{
77+
var resolver = Application.Context.ContentResolver;
78+
var tree = resolver.PersistedUriPermissions.FirstOrDefault(p => p.IsWritePermission)?.Uri;
79+
if (tree == null)
80+
{
81+
throw new InvalidOperationException("no persisted tree grant: launch the Seeker Tests app once and pick a folder");
82+
}
83+
var root = DocumentsContract.BuildDocumentUriUsingTree(tree, DocumentsContract.GetTreeDocumentId(tree));
84+
_scratchDir = DocumentsContract.CreateDocument(resolver, root, DocumentsContract.Document.MimeTypeDir, "parity_" + Guid.NewGuid().ToString("N"));
85+
Assert.That(_scratchDir, Is.Not.Null, "could not create scratch dir under " + tree);
86+
}
87+
88+
[TearDown]
89+
public void TearDown()
90+
{
91+
if (_scratchDir != null)
92+
{
93+
DocumentsContract.DeleteDocument(Application.Context.ContentResolver, _scratchDir);
94+
}
95+
}
96+
97+
[Test]
98+
public void ProviderStoresToValidFileName()
99+
{
100+
Log.Info(Tag, "provider: " + _scratchDir.Authority + " api " + (int)Android.OS.Build.VERSION.SdkInt);
101+
var mismatches = new List<string>();
102+
foreach (var (label, name) in Cases())
103+
{
104+
CheckOne(label + " (dir)", name, DocumentsContract.Document.MimeTypeDir, name, mismatches, providerMayFail: true);
105+
CheckOne(label + " (file)", name + ".mp3", "audio/mpeg", name + ".mp3", mismatches, providerMayFail: true);
106+
}
107+
Assert.That(mismatches, Is.Empty, string.Join("\n", mismatches));
108+
}
109+
110+
[Test]
111+
public void SanitizedNamesRoundTrip()
112+
{
113+
Log.Info(Tag, "provider: " + _scratchDir.Authority + " api " + (int)Android.OS.Build.VERSION.SdkInt);
114+
var mismatches = new List<string>();
115+
foreach (var (label, name) in Cases())
116+
{
117+
string dirName = SimpleHelpers.ToValidFileName(name);
118+
string fileName = SimpleHelpers.ToValidFileName(name + ".mp3");
119+
CheckOne(label + " (dir, sanitized)", dirName, DocumentsContract.Document.MimeTypeDir, dirName, mismatches, providerMayFail: false);
120+
CheckOne(label + " (file, sanitized)", fileName, "audio/mpeg", fileName, mismatches, providerMayFail: false);
121+
}
122+
Assert.That(mismatches, Is.Empty, string.Join("\n", mismatches));
123+
}
124+
125+
// CommonHelpers.CreateMediaFile now passes the full name with MediaMimeTypes.GetMimeTypeForCreate.
126+
[Test]
127+
public void MediaFilesKeepTheirName()
128+
{
129+
Log.Info(Tag, "provider: " + _scratchDir.Authority + " api " + (int)Android.OS.Build.VERSION.SdkInt);
130+
var mismatches = new List<string>();
131+
foreach (string name in MediaFileNames())
132+
{
133+
string mime = MediaMimeTypes.GetMimeTypeForCreate(name);
134+
CheckOne(name + " [" + (mime ?? "null") + "]", name, mime, name, mismatches, providerMayFail: false);
135+
136+
// PREVIOUS BEHAVIOR: since we stripped the extension, Android would take the liberty or renaming
137+
// track.ogg -> track.oga
138+
// track.opus -> track.oga
139+
// noexttrack -> noexttrack.mp3
140+
string legacyMime = MediaMimeTypes.GetMimeTypeFromFilename(name);
141+
bool legacyFullName = legacyMime == null || legacyMime == MediaMimeTypes.M4A_MIME || legacyMime == MediaMimeTypes.APE_MIME;
142+
string legacyRequested = legacyFullName ? name : System.IO.Path.GetFileNameWithoutExtension(name);
143+
Log.Info(Tag, " legacy would store '" + CreateAndReadName(legacyRequested, legacyMime) + "'");
144+
}
145+
Assert.That(mismatches, Is.Empty, string.Join("\n", mismatches));
146+
}
147+
148+
private string CreateAndReadName(string requested, string mimeType)
149+
{
150+
var resolver = Application.Context.ContentResolver;
151+
Android.Net.Uri created = null;
152+
try
153+
{
154+
created = DocumentsContract.CreateDocument(resolver, _scratchDir, mimeType, requested);
155+
return created == null ? "<null>" : QueryDisplayName(created);
156+
}
157+
catch (Exception e)
158+
{
159+
Log.Warn(Tag, " create threw for '" + requested + "': " + e);
160+
return "<threw" + e.GetType().Name + ": " + e.Message + ">";
161+
}
162+
finally
163+
{
164+
if (created != null)
165+
{
166+
DocumentsContract.DeleteDocument(resolver, created);
167+
}
168+
}
169+
}
170+
171+
private void CheckOne(string label, string requested, string mimeType, string original, List<string> mismatches, bool providerMayFail)
172+
{
173+
string expected = SimpleHelpers.ToValidFileName(original);
174+
string actual = CreateAndReadName(requested, mimeType);
175+
if (providerMayFail && actual.StartsWith("<threw"))
176+
{
177+
// android cannot create this name itself (i.e. its trim left half a surrogate pair), nothing to match
178+
Log.Info(Tag, " skip " + label + ": provider cannot create it, ours '" + Escape(expected) + "'");
179+
return;
180+
}
181+
182+
bool ok = actual == expected;
183+
Log.Info(Tag, (ok ? " same " : " DIFF ") + label + ": expected '" + Escape(expected) + "' actual '" + Escape(actual) + "'");
184+
if (!ok)
185+
{
186+
mismatches.Add(label + ": expected '" + Escape(expected) + "' actual '" + Escape(actual) + "'");
187+
}
188+
}
189+
190+
private static string QueryDisplayName(Android.Net.Uri uri)
191+
{
192+
using var cursor = Application.Context.ContentResolver.Query(uri, new[] { DocumentsContract.Document.ColumnDisplayName }, null, null, null);
193+
if (cursor == null || !cursor.MoveToFirst())
194+
{
195+
return "<no row>";
196+
}
197+
return cursor.GetString(0);
198+
}
199+
200+
private static string Escape(string s)
201+
{
202+
if (s.Length > 40)
203+
{
204+
int bytes = System.Text.Encoding.UTF8.GetByteCount(s);
205+
s = s.Substring(0, 18) + "~" + s.Substring(s.Length - 18) + " [" + bytes + "B]";
206+
}
207+
return string.Concat(s.Select(c => c < 0x20 || c == 0x7f ? "\\x" + ((int)c).ToString("x2") : c.ToString()));
208+
}
209+
}
210+
}

0 commit comments

Comments
 (0)