Updated OggEnc2 binaries to v2.88 using libvorbis v1.3.5 and aoTuV v6.03_2015 (2015...
[LameXP.git] / src / LockedFile.cpp
bloba164bce4509e66e7c5204ee73450adaf10a4e5f0
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
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"
25 //Internal
26 #include "Global.h"
27 #include "FileHash.h"
29 //MUtils
30 #include <MUtils/OSSupport.h>
31 #include <MUtils/Exception.h>
33 //Qt
34 #include <QResource>
35 #include <QFile>
36 #include <QFileInfo>
37 #include <QDir>
38 #include <QCryptographicHash>
40 //CRT
41 #include <stdio.h>
42 #include <io.h>
43 #include <fcntl.h>
44 #include <stdexcept>
46 //Windows includes
47 #define NOMINMAX
48 #define WIN32_LEAN_AND_MEAN
49 #include <Windows.h>
51 ///////////////////////////////////////////////////////////////////////////////
53 // WARNING: Passing file descriptors into Qt does NOT work with dynamically linked CRT!
54 #ifdef QT_NODLL
55 static const bool g_useFileDescrForQFile = true;
56 #else
57 static const bool g_useFileDescrForQFile = false;
58 #endif
60 #define VALID_HANDLE(H) (((H) != NULL) && ((H) != INVALID_HANDLE_VALUE))
62 static void CLOSE_HANDLE(HANDLE &h)
64 if(VALID_HANDLE(h))
66 CloseHandle(h);
67 h = NULL;
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))
79 break;
81 if(i == 0)
83 qWarning("Failed to open file on first attemp, retrying...");
85 Sleep(25);
88 //Write data to file
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()));
97 else
99 MUTILS_THROW_FMT("File '%s' could not be created!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
102 //Close file after it has been written
103 outFile.close();
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))
125 break;
127 if(i == 0)
129 qWarning("Failed to lock file on first attemp, retrying...");
131 Sleep(25);
134 //Locked successfully?
135 if(!VALID_HANDLE(fileHandle))
137 if(outFile)
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)
156 QFile checkFile;
158 //Now re-open the file for reading
159 if(g_useFileDescrForQFile)
161 checkFile.open(fileDescriptor, QIODevice::ReadOnly);
163 else
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...");
170 Sleep(100);
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);
183 checkFile.close();
185 //Compare hashes
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 static __forceinline bool doRemoveFile(const QString &filePath)
197 for(int i = 0; i < 32; i++)
199 if(MUtils::remove_file(filePath))
201 return true;
203 MUtils::OS::sleep_ms(1);
205 return false;
208 ///////////////////////////////////////////////////////////////////////////////
210 LockedFile::LockedFile(QResource *const resource, const QString &outPath, const QByteArray &expectedHash, const bool bOwnsFile)
212 m_bOwnsFile(bOwnsFile),
213 m_filePath(QFileInfo(outPath).absoluteFilePath())
215 m_fileDescriptor = -1;
216 HANDLE fileHandle = NULL;
218 //Make sure the resource is valid
219 if(!(resource->isValid() && resource->data()))
221 MUTILS_THROW_FMT("The resource at %p is invalid!", resource);
224 //Write data to output file
225 QFile outFile(m_filePath);
226 doWriteOutput(outFile, resource);
228 //Now lock the file!
229 doLockFile(fileHandle, m_filePath, &outFile);
231 //Get file descriptor
232 doInitFileDescriptor(fileHandle, m_fileDescriptor);
234 //Validate file hash
235 doValidateHash(fileHandle, m_fileDescriptor, expectedHash, m_filePath);
238 LockedFile::LockedFile(const QString &filePath, const QByteArray &expectedHash, const bool bOwnsFile)
240 m_bOwnsFile(bOwnsFile),
241 m_filePath(QFileInfo(filePath).absoluteFilePath())
243 m_fileDescriptor = -1;
244 HANDLE fileHandle = NULL;
246 //Make sure the file exists, before we try to lock it
247 doValidateFileExists(m_filePath);
249 //Now lock the file!
250 doLockFile(fileHandle, m_filePath, NULL);
252 //Get file descriptor
253 doInitFileDescriptor(fileHandle, m_fileDescriptor);
255 //Validate file hash
256 doValidateHash(fileHandle, m_fileDescriptor, expectedHash, m_filePath);
259 LockedFile::LockedFile(const QString &filePath, const bool bOwnsFile)
261 m_bOwnsFile(bOwnsFile),
262 m_filePath(QFileInfo(filePath).canonicalFilePath())
264 m_fileDescriptor = -1;
265 HANDLE fileHandle = NULL;
267 //Make sure the file exists, before we try to lock it
268 doValidateFileExists(m_filePath);
270 //Now lock the file!
271 doLockFile(fileHandle, m_filePath, NULL);
273 //Get file descriptor
274 doInitFileDescriptor(fileHandle, m_fileDescriptor);
277 LockedFile::~LockedFile(void)
279 if(m_fileDescriptor >= 0)
281 _close(m_fileDescriptor);
282 m_fileDescriptor = -1;
284 if(m_bOwnsFile)
286 doRemoveFile(m_filePath);
290 const QString &LockedFile::filePath()
292 return m_filePath;