Skip to content

Node.js based forum software built for the modern web

fix upload of files with a -resized suffix (#14955)

Barış Uşaklı67d45996e8ee
diff --git a/src/controllers/uploads.js b/src/controllers/uploads.js
index be70dde5ea..e200bc8d38 100644
--- a/src/controllers/uploads.js
+++ b/src/controllers/uploads.js
@@ -185,7 +185,7 @@ async function saveFileToLocal(uid, folder, uploadedFile) {
const basename = extension ? name.slice(0, -extension.length) : name;
const filename = `${Date.now()}-${basename.slice(0, 255)}${extension}`;
- const upload = await file.saveFileToLocal(filename, folder, uploadedFile.path);
+ const upload = await file.saveFileToLocal(filename, folder, uploadedFile.path, { unique: true });
const storedFile = {
url: nconf.get('relative_path') + upload.url,
path: upload.path,
diff --git a/src/file.js b/src/file.js
index 9c75f768fd..d88253d9ea 100644
--- a/src/file.js
+++ b/src/file.js
@@ -16,18 +16,17 @@ graceful.gracefulify(fs);
const file = module.exports;
-file.saveFileToLocal = async function (filename, folder, tempPath) {
+file.saveFileToLocal = async function (filename, folder, tempPath, { unique = false } = {}) {
/*
* remarkable doesn't allow spaces in hyperlinks, once that's fixed, remove this.
*/
- filename = filename.split('.').map(name => slugify(name)).join('.');
-
- const uploadPath = path.join(nconf.get('upload_path'), folder, filename);
+ const slugified = filename.split('.').map(name => slugify(name)).join('.');
+ filename = file.stripResized(slugified);
+ let uploadPath = path.join(nconf.get('upload_path'), folder, filename);
if (!file.isPathInside(nconf.get('upload_path'), uploadPath)) {
throw new Error('[[error:invalid-path]]');
}
- winston.verbose(`Saving file ${filename} to : ${uploadPath}`);
await mkdirp(path.dirname(uploadPath));
const extension = path.extname(filename).toLowerCase();
if (extension === '.svg') {
@@ -35,14 +34,50 @@ file.saveFileToLocal = async function (filename, folder, tempPath) {
} else if (extension === '.xml') {
await sanitizeXml(tempPath);
}
+ // avoid overwriting the original file when stripResized() changes the filename.
+ const preventOverwrite = unique || filename !== slugified;
+ if (preventOverwrite) {
+ uploadPath = await copyFileWithUniqueName(tempPath, uploadPath);
+ filename = path.basename(uploadPath);
+ } else {
+ await fs.promises.copyFile(tempPath, uploadPath);
+ }
- await fs.promises.copyFile(tempPath, uploadPath);
+ winston.verbose(`Saved file ${filename} to : ${uploadPath}`);
return {
url: `/assets/uploads/${folder ? `${folder}/` : ''}${filename}`,
path: uploadPath,
};
};
+async function copyFileWithUniqueName(sourcePath, destinationPath) {
+ const ext = path.extname(destinationPath);
+ const base = path.basename(destinationPath, ext);
+ const dir = path.dirname(destinationPath);
+
+ let counter = 0;
+
+ /* eslint-disable no-await-in-loop */
+ for (;;) {
+ try {
+ await fs.promises.copyFile(sourcePath, destinationPath, fs.constants.COPYFILE_EXCL);
+ return destinationPath;
+ } catch (err) {
+ // Windows reports EPERM instead of EEXIST for exclusive creates
+ const collision = err.code === 'EEXIST' ||
+ (err.code === 'EPERM' && await file.exists(destinationPath).catch(() => false));
+
+ if (!collision || counter >= 100) {
+ throw err;
+ }
+
+ counter += 1;
+ destinationPath = path.join(dir, `${base}-${counter}${ext}`);
+ }
+ }
+ /* eslint-enable no-await-in-loop */
+}
+
file.isPathInside = function (base, targetPath) {
const resolvedBase = path.resolve(base);
const resolvedTarget = path.resolve(base, targetPath);
@@ -68,6 +103,14 @@ file.appendToFileName = function (filename, string) {
return filename.substring(0, dotIndex) + string + filename.substring(dotIndex);
};
+file.stripResized = function (filename) {
+ const raw = String(filename || 'upload');
+ const extension = path.extname(raw) || '';
+ const basename = raw.slice(0, raw.length - extension.length);
+ const stripped = basename.split('-resized').join('') || 'upload';
+ return `${stripped}${extension}`;
+};
+
file.allowedExtensions = function () {
return parseExtensions(require('./meta').config.allowedFileExtensions);
};
diff --git a/test/files/test-resized.png b/test/files/test-resized.png
new file mode 100644
index 0000000000..6a6c184126
Binary files /dev/null and b/test/files/test-resized.png differ
diff --git a/test/uploads.js b/test/uploads.js
index 29266d382e..5764cfb313 100644
--- a/test/uploads.js
+++ b/test/uploads.js
@@ -103,6 +103,19 @@ describe('Upload Controllers', () => {
assert.deepStrictEqual(Object.keys(body.response.images[0]), ['url', 'name']);
});
+ it('should upload an image with -resized.png in its filename', async () => {
+ const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/test-resized.png'), {}, jar, csrf_token);
+ assert.equal(response.statusCode, 200);
+ const image = body.response.images[0];
+ // image name is unchanged
+ assert.strictEqual(image.name, 'test-resized.png');
+ // saved file has no -resized at the end ie test-resized.png becomes test.png
+ assert(image.url.endsWith('-test.png'));
+ // user record doesn't have -resized at the end
+ const [userUpload] = await db.getSortedSetRevRange(`uid:${regularUid}:uploads`, 0, 0);
+ assert(image.url.endsWith(userUpload), userUpload);
+ });
+
it('should upload an svg image to a post', async () => {
const oldValue = meta.config.allowedFileExtensions;
meta.config.allowedFileExtensions = 'png,jpg,bmp,html,svg';