Skip to content

An open-source cross-platform alternative to AirDrop

fix: avoid directory name collisions when receiving files (#3488)

Shlomof9b0e361052d
diff --git a/packages/localsend_isolates/lib/src/task/server/file_saver.dart b/packages/localsend_isolates/lib/src/task/server/file_saver.dart
index 9eaffe8f..4c37df37 100644
--- a/packages/localsend_isolates/lib/src/task/server/file_saver.dart
+++ b/packages/localsend_isolates/lib/src/task/server/file_saver.dart
@@ -193,7 +193,7 @@ List<String> sanitizeRelativeName(String fileName) {
return components;
}
-/// If there is a file with the same name, then it appends a number to its file name
+/// If the name is already occupied, appends a number to the file name.
Future<(String, String?, String)> digestFilePathAndPrepareDirectory({
required String parentDirectory,
required String fileName,
@@ -244,7 +244,7 @@ Future<(String, String?, String)> digestFilePathAndPrepareDirectory({
do {
destinationPath = counter == 1 ? p.join(dir, actualFileName) : p.join(dir, actualFileName.withCount(counter));
counter++;
- } while (await File(destinationPath).exists());
+ } while (await FileSystemEntity.type(destinationPath, followLinks: false) != FileSystemEntityType.notFound);
return (destinationPath, null, p.basename(destinationPath));
}
diff --git a/packages/localsend_isolates/test/task/server/file_saver_test.dart b/packages/localsend_isolates/test/task/server/file_saver_test.dart
index a31dde4d..16cf4978 100644
--- a/packages/localsend_isolates/test/task/server/file_saver_test.dart
+++ b/packages/localsend_isolates/test/task/server/file_saver_test.dart
@@ -61,6 +61,20 @@ void main() {
throwsA('Path traversal detected'),
);
});
+
+ test('saves under an alternative name when a directory occupies the incoming name', () async {
+ final existingDirectory = Directory(p.join(tempDir.path, 'file.txt'))..createSync();
+ final existingContent = File(p.join(existingDirectory.path, 'keep.txt'))..writeAsStringSync('keep');
+ final existingFile = File(p.join(tempDir.path, 'file (2).txt'))..writeAsStringSync('existing');
+
+ final path = await digest(tempDir.path, 'file.txt');
+ await File(path).writeAsString('received');
+
+ expect(path, p.join(tempDir.path, 'file (3).txt'));
+ expect(File(path).readAsStringSync(), 'received');
+ expect(existingContent.readAsStringSync(), 'keep');
+ expect(existingFile.readAsStringSync(), 'existing');
+ });
}
/// The sanitizer lives in the Rust library, which is not loaded in unit tests.