From 898e36baf6e7f2c7b6f23659bc1a3df7e3769c90 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Tue, 22 Jun 2021 14:11:22 +0100 Subject: [PATCH] MDL-71991 files: check return value of rename when writing files --- lib/filestorage/file_system_filedir.php | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/filestorage/file_system_filedir.php b/lib/filestorage/file_system_filedir.php index 103dcca41e5..192781c30d3 100644 --- a/lib/filestorage/file_system_filedir.php +++ b/lib/filestorage/file_system_filedir.php @@ -391,7 +391,14 @@ class file_system_filedir extends file_system { ignore_user_abort($prev); throw new file_exception('storedfilecannotcreatefile'); } - rename($hashfile.'.tmp', $hashfile); + if (!rename($hashfile.'.tmp', $hashfile)) { + // Something very strange went wrong. + @unlink($hashfile . '.tmp'); + // Note, we don't try to clean up $hashfile. Almost certainly, if it exists + // (e.g. written by another process?) it will be right, so don't wipe it. + ignore_user_abort($prev); + throw new file_exception('storedfilecannotcreatefile'); + } chmod($hashfile, $this->filepermissions); // Fix permissions if needed. @unlink($hashfile.'.tmp'); // Just in case anything fails in a weird way. ignore_user_abort($prev); @@ -465,7 +472,14 @@ class file_system_filedir extends file_system { ignore_user_abort($prev); throw new file_exception('storedfilecannotcreatefile'); } - rename($hashfile.'.tmp', $hashfile); + if (!rename($hashfile.'.tmp', $hashfile)) { + // Something very strange went wrong. + @unlink($hashfile . '.tmp'); + // Note, we don't try to clean up $hashfile. Almost certainly, if it exists + // (e.g. written by another process?) it will be right, so don't wipe it. + ignore_user_abort($prev); + throw new file_exception('storedfilecannotcreatefile'); + } chmod($hashfile, $this->filepermissions); // Fix permissions if needed. @unlink($hashfile.'.tmp'); // Just in case anything fails in a weird way. ignore_user_abort($prev);