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"
27 #include <MUtils/OSSupport.h>
28 #include <MUtils/Hash_Keccak.h>
29 #include <MUtils/Exception.h>
36 #include <QCryptographicHash>
45 #define WIN32_LEAN_AND_MEAN
48 ///////////////////////////////////////////////////////////////////////////////
50 // WARNING: Passing file descriptors into Qt does NOT work with dynamically linked CRT!
52 static const bool g_useFileDescrForQFile = true;
54 static const bool g_useFileDescrForQFile = false;
57 static void CLOSE_HANDLE(HANDLE &h)
59 if((h != NULL) && (h != INVALID_HANDLE_VALUE))
66 ///////////////////////////////////////////////////////////////////////////////
68 static const char *g_blnk = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
69 static const char *g_seed = "c375d83b4388329408dfcbb4d9a065b6e06d28272f25ef299c70b506e26600af79fd2f866ae24602daf38f25c9d4b7e1";
70 static const char *g_salt = "ee9f7bdabc170763d2200a7e3030045aafe380011aefc1730e547e9244c62308aac42a976feeca224ba553de0c4bb883";
72 QByteArray LockedFile::fileHash(QFile &file)
74 QByteArray hash = QByteArray::fromHex(g_blnk);
76 if(file.isOpen() && file.reset())
78 MUtils::Hash::Keccak keccak;
80 const QByteArray data = file.readAll();
81 const QByteArray seed = QByteArray::fromHex(g_seed);
82 const QByteArray salt = QByteArray::fromHex(g_salt);
84 if(keccak.init(MUtils::Hash::Keccak::hb384))
87 ok = ok && keccak.addData(seed);
88 ok = ok && keccak.addData(data);
89 ok = ok && keccak.addData(salt);
92 const QByteArray digest = keccak.finalize();
93 if(!digest.isEmpty()) hash = digest.toHex();
101 ///////////////////////////////////////////////////////////////////////////////
103 LockedFile::LockedFile(QResource *const resource, const QString &outPath, const QByteArray &expectedHash, const bool bOwnsFile)
105 m_bOwnsFile(bOwnsFile),
106 m_filePath(QFileInfo(outPath).absoluteFilePath())
108 m_fileDescriptor = -1;
109 HANDLE fileHandle = NULL;
111 //Make sure the resource is valid
112 if(!(resource->isValid() && resource->data()))
114 MUTILS_THROW_FMT("The resource at %p is invalid!", resource);
117 QFile outFile(m_filePath);
120 for(int i = 0; i < 64; i++)
122 if(outFile.open(QIODevice::WriteOnly)) break;
123 if(!i) qWarning("Failed to open file on first attemp, retrying...");
128 if(outFile.isOpen() && outFile.isWritable())
130 if(outFile.write(reinterpret_cast<const char*>(resource->data()), resource->size()) != resource->size())
132 QFile::remove(QFileInfo(outFile).canonicalFilePath());
133 MUTILS_THROW_FMT("File '%s' could not be written!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
138 MUTILS_THROW_FMT("File '%s' could not be created!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
141 //Close file after it has been written
145 for(int i = 0; i < 64; i++)
147 fileHandle = CreateFileW(MUTILS_WCHR(QDir::toNativeSeparators(m_filePath)), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
148 if((fileHandle != NULL) && (fileHandle != INVALID_HANDLE_VALUE)) break;
149 if(!i) qWarning("Failed to lock file on first attemp, retrying...");
153 //Locked successfully?
154 if((fileHandle == NULL) || (fileHandle == INVALID_HANDLE_VALUE))
156 QFile::remove(QFileInfo(outFile).canonicalFilePath());
157 MUTILS_THROW_FMT("File '%s' could not be locked!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
160 //Get file descriptor
161 m_fileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(fileHandle), _O_RDONLY | _O_BINARY);
162 if(m_fileDescriptor < 0)
164 MUTILS_THROW_FMT("Failed to obtain C Runtime file descriptor!");
169 //Now re-open the file for reading
170 if(g_useFileDescrForQFile)
172 checkFile.open(m_fileDescriptor, QIODevice::ReadOnly);
176 checkFile.setFileName(m_filePath);
177 for(int i = 0; i < 64; i++)
179 if(checkFile.open(QIODevice::ReadOnly)) break;
180 if(!i) qWarning("Failed to re-open file on first attemp, retrying...");
185 //Opened successfully
186 if(!checkFile.isOpen())
188 QFile::remove(m_filePath);
189 MUTILS_THROW_FMT("File '%s' could not be read!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
192 //Verify file contents
193 const QByteArray hash = fileHash(checkFile);
197 if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
199 qWarning("\nFile checksum error:\n A = %s\n B = %s\n", expectedHash.constData(), hash.constData());
200 CLOSE_HANDLE(fileHandle);
201 QFile::remove(m_filePath);
202 MUTILS_THROW_FMT("File '%s' is corruputed, take care!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
206 LockedFile::LockedFile(const QString &filePath, const bool bOwnsFile)
208 m_bOwnsFile(bOwnsFile),
209 m_filePath(QFileInfo(filePath).canonicalFilePath())
211 m_fileDescriptor = -1;
212 HANDLE fileHandle = NULL;
214 QFileInfo existingFileInfo(filePath);
215 existingFileInfo.setCaching(false);
217 //Make sure the file exists, before we try to lock it
218 if((!existingFileInfo.exists()) || (!existingFileInfo.isFile()) || m_filePath.isEmpty())
220 MUTILS_THROW_FMT("File '%s' does not exist!", MUTILS_UTF8(filePath));
224 for(int i = 0; i < 64; i++)
226 fileHandle = CreateFileW(MUTILS_WCHR(QDir::toNativeSeparators(m_filePath)), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
227 if((fileHandle != NULL) && (fileHandle != INVALID_HANDLE_VALUE)) break;
228 if(!i) qWarning("Failed to lock file on first attemp, retrying...");
232 //Locked successfully?
233 if((fileHandle == NULL) || (fileHandle == INVALID_HANDLE_VALUE))
235 MUTILS_THROW_FMT("File '%s' could not be locked!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
238 //Get file descriptor
239 m_fileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(fileHandle), _O_RDONLY | _O_BINARY);
240 if(m_fileDescriptor < 0)
242 MUTILS_THROW_FMT("Failed to obtain C Runtime file descriptor!");
246 LockedFile::~LockedFile(void)
248 if(m_fileDescriptor >= 0)
250 _close(m_fileDescriptor);
251 m_fileDescriptor = -1;
255 if(QFileInfo(m_filePath).exists())
257 for(int i = 0; i < 64; i++)
259 if(QFile::remove(m_filePath)) break;
260 MUtils::OS::sleep_ms(1);
266 const QString &LockedFile::filePath()
271 void LockedFile::selfTest()
273 if(!MUtils::Hash::Keccak::selfTest())
275 MUTILS_THROW("QKeccakHash self-test has failed!");