1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "LockedFile.h"
30 #include <MUtils/OSSupport.h>
31 #include <MUtils/Exception.h>
38 #include <QCryptographicHash>
48 #define WIN32_LEAN_AND_MEAN
51 ///////////////////////////////////////////////////////////////////////////////
53 // WARNING: Passing file descriptors into Qt does NOT work with dynamically linked CRT!
55 static const bool g_useFileDescrForQFile = true;
57 static const bool g_useFileDescrForQFile = false;
60 #define VALID_HANDLE(H) (((H) != NULL) && ((H) != INVALID_HANDLE_VALUE))
62 static void CLOSE_HANDLE(HANDLE &h)
71 ///////////////////////////////////////////////////////////////////////////////
73 static __forceinline void doWriteOutput(QFile &outFile, const QResource *const resource)
75 for(int i = 0; i < 64; i++)
77 if(outFile.open(QIODevice::WriteOnly))
83 qWarning("Failed to open file on first attemp, retrying...");
89 if(outFile.isOpen() && outFile.isWritable())
91 if(outFile.write(reinterpret_cast<const char*>(resource->data()), resource->size()) != resource->size())
93 QFile::remove(QFileInfo(outFile).canonicalFilePath());
94 MUTILS_THROW_FMT("File '%s' could not be written!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
99 MUTILS_THROW_FMT("File '%s' could not be created!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
102 //Close file after it has been written
106 static __forceinline void doValidateFileExists(const QString &filePath)
108 QFileInfo existingFileInfo(filePath);
109 existingFileInfo.setCaching(false);
111 //Make sure the file exists, before we try to lock it
112 if((!existingFileInfo.exists()) || (!existingFileInfo.isFile()) || filePath.isEmpty())
114 MUTILS_THROW_FMT("File '%s' does not exist!", MUTILS_UTF8(filePath));
118 static __forceinline void doLockFile(HANDLE &fileHandle, const QString &filePath, QFile *const outFile)
120 for(int i = 0; i < 64; i++)
122 fileHandle = CreateFileW(MUTILS_WCHR(QDir::toNativeSeparators(filePath)), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
123 if(VALID_HANDLE(fileHandle))
129 qWarning("Failed to lock file on first attemp, retrying...");
134 //Locked successfully?
135 if(!VALID_HANDLE(fileHandle))
139 QFile::remove(QFileInfo(*outFile).canonicalFilePath());
141 MUTILS_THROW_FMT("File '%s' could not be locked!", MUTILS_UTF8(QFileInfo(filePath).fileName()));
145 static __forceinline void doInitFileDescriptor(const HANDLE &fileHandle, int &fileDescriptor)
147 fileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(fileHandle), _O_RDONLY | _O_BINARY);
148 if(fileDescriptor < 0)
150 MUTILS_THROW_FMT("Failed to obtain C Runtime file descriptor!");
154 static __forceinline void doValidateHash(HANDLE &fileHandle, const int &fileDescriptor, const QByteArray &expectedHash, const QString &filePath)
158 //Now re-open the file for reading
159 if(g_useFileDescrForQFile)
161 checkFile.open(fileDescriptor, QIODevice::ReadOnly);
165 checkFile.setFileName(filePath);
166 for(int i = 0; i < 64; i++)
168 if(checkFile.open(QIODevice::ReadOnly)) break;
169 if(!i) qWarning("Failed to re-open file on first attemp, retrying...");
174 //Opened successfully
175 if(!checkFile.isOpen())
177 QFile::remove(filePath);
178 MUTILS_THROW_FMT("File '%s' could not be read!", MUTILS_UTF8(QFileInfo(filePath).fileName()));
181 //Verify file contents
182 const QByteArray hash = FileHash::computeHash(checkFile);
186 if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
188 qWarning("\nFile checksum error:\n A = %s\n B = %s\n", expectedHash.constData(), hash.constData());
189 CLOSE_HANDLE(fileHandle);
190 QFile::remove(filePath);
191 MUTILS_THROW_FMT("File '%s' is corruputed, take care!", MUTILS_UTF8(QFileInfo(filePath).fileName()));
195 ///////////////////////////////////////////////////////////////////////////////
197 LockedFile::LockedFile(QResource *const resource, const QString &outPath, const QByteArray &expectedHash, const bool bOwnsFile)
199 m_bOwnsFile(bOwnsFile),
200 m_filePath(QFileInfo(outPath).absoluteFilePath())
202 m_fileDescriptor = -1;
203 HANDLE fileHandle = NULL;
205 //Make sure the resource is valid
206 if(!(resource->isValid() && resource->data()))
208 MUTILS_THROW_FMT("The resource at %p is invalid!", resource);
211 //Write data to output file
212 QFile outFile(m_filePath);
213 doWriteOutput(outFile, resource);
216 doLockFile(fileHandle, m_filePath, &outFile);
218 //Get file descriptor
219 doInitFileDescriptor(fileHandle, m_fileDescriptor);
222 doValidateHash(fileHandle, m_fileDescriptor, expectedHash, m_filePath);
225 LockedFile::LockedFile(const QString &filePath, const QByteArray &expectedHash, const bool bOwnsFile)
227 m_bOwnsFile(bOwnsFile),
228 m_filePath(QFileInfo(filePath).absoluteFilePath())
230 m_fileDescriptor = -1;
231 HANDLE fileHandle = NULL;
233 //Make sure the file exists, before we try to lock it
234 doValidateFileExists(m_filePath);
237 doLockFile(fileHandle, m_filePath, NULL);
239 //Get file descriptor
240 doInitFileDescriptor(fileHandle, m_fileDescriptor);
243 doValidateHash(fileHandle, m_fileDescriptor, expectedHash, m_filePath);
246 LockedFile::LockedFile(const QString &filePath, const bool bOwnsFile)
248 m_bOwnsFile(bOwnsFile),
249 m_filePath(QFileInfo(filePath).canonicalFilePath())
251 m_fileDescriptor = -1;
252 HANDLE fileHandle = NULL;
254 //Make sure the file exists, before we try to lock it
255 doValidateFileExists(m_filePath);
258 doLockFile(fileHandle, m_filePath, NULL);
260 //Get file descriptor
261 doInitFileDescriptor(fileHandle, m_fileDescriptor);
264 LockedFile::~LockedFile(void)
266 if(m_fileDescriptor >= 0)
268 _close(m_fileDescriptor);
269 m_fileDescriptor = -1;
273 if(QFileInfo(m_filePath).exists())
275 for(int i = 0; i < 64; i++)
277 if(QFile::remove(m_filePath)) break;
278 MUtils::OS::sleep_ms(1);
284 const QString &LockedFile::filePath()