Actually make RegExp-based file renaming work.
[LameXP.git] / src / LockedFile.cpp
blob24770e7163c8588205f7f5c1729b0376b5485241
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"
24 #include "Global.h"
26 //MUtils
27 #include <MUtils/OSSupport.h>
28 #include <MUtils/Hash_Keccak.h>
29 #include <MUtils/Exception.h>
31 //Qt
32 #include <QResource>
33 #include <QFile>
34 #include <QFileInfo>
35 #include <QDir>
36 #include <QCryptographicHash>
38 #include <stdio.h>
39 #include <io.h>
40 #include <fcntl.h>
41 #include <stdexcept>
43 //Windows includes
44 #define NOMINMAX
45 #define WIN32_LEAN_AND_MEAN
46 #include <Windows.h>
48 ///////////////////////////////////////////////////////////////////////////////
50 // WARNING: Passing file descriptors into Qt does NOT work with dynamically linked CRT!
51 #ifdef QT_NODLL
52 static const bool g_useFileDescrForQFile = true;
53 #else
54 static const bool g_useFileDescrForQFile = false;
55 #endif
57 #define VALID_HANDLE(H) (((H) != NULL) && ((H) != INVALID_HANDLE_VALUE))
59 static void CLOSE_HANDLE(HANDLE &h)
61 if(VALID_HANDLE(h))
63 CloseHandle(h);
64 h = NULL;
68 ///////////////////////////////////////////////////////////////////////////////
70 static const char *g_blnk = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
71 static const char *g_seed = "c375d83b4388329408dfcbb4d9a065b6e06d28272f25ef299c70b506e26600af79fd2f866ae24602daf38f25c9d4b7e1";
72 static const char *g_salt = "ee9f7bdabc170763d2200a7e3030045aafe380011aefc1730e547e9244c62308aac42a976feeca224ba553de0c4bb883";
74 QByteArray LockedFile::fileHash(QFile &file)
76 QByteArray hash = QByteArray::fromHex(g_blnk);
78 if(file.isOpen() && file.reset())
80 MUtils::Hash::Keccak keccak;
82 const QByteArray data = file.readAll();
83 const QByteArray seed = QByteArray::fromHex(g_seed);
84 const QByteArray salt = QByteArray::fromHex(g_salt);
86 if(keccak.init(MUtils::Hash::Keccak::hb384))
88 bool ok = true;
89 ok = ok && keccak.addData(seed);
90 ok = ok && keccak.addData(data);
91 ok = ok && keccak.addData(salt);
92 if(ok)
94 const QByteArray digest = keccak.finalize();
95 if(!digest.isEmpty()) hash = digest.toHex();
100 return hash;
103 ///////////////////////////////////////////////////////////////////////////////
105 LockedFile::LockedFile(QResource *const resource, const QString &outPath, const QByteArray &expectedHash, const bool bOwnsFile)
107 m_bOwnsFile(bOwnsFile),
108 m_filePath(QFileInfo(outPath).absoluteFilePath())
110 m_fileDescriptor = -1;
111 HANDLE fileHandle = NULL;
113 //Make sure the resource is valid
114 if(!(resource->isValid() && resource->data()))
116 MUTILS_THROW_FMT("The resource at %p is invalid!", resource);
119 QFile outFile(m_filePath);
121 //Open output file
122 for(int i = 0; i < 64; i++)
124 if(outFile.open(QIODevice::WriteOnly)) break;
125 if(!i) qWarning("Failed to open file on first attemp, retrying...");
126 Sleep(100);
129 //Write data to file
130 if(outFile.isOpen() && outFile.isWritable())
132 if(outFile.write(reinterpret_cast<const char*>(resource->data()), resource->size()) != resource->size())
134 QFile::remove(QFileInfo(outFile).canonicalFilePath());
135 MUTILS_THROW_FMT("File '%s' could not be written!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
138 else
140 MUTILS_THROW_FMT("File '%s' could not be created!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
143 //Close file after it has been written
144 outFile.close();
146 //Now lock the file!
147 for(int i = 0; i < 64; i++)
149 fileHandle = CreateFileW(MUTILS_WCHR(QDir::toNativeSeparators(m_filePath)), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
150 if(VALID_HANDLE(fileHandle)) break;
151 if(!i) qWarning("Failed to lock file on first attemp, retrying...");
152 Sleep(100);
155 //Locked successfully?
156 if(!VALID_HANDLE(fileHandle))
158 QFile::remove(QFileInfo(outFile).canonicalFilePath());
159 MUTILS_THROW_FMT("File '%s' could not be locked!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
162 //Get file descriptor
163 m_fileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(fileHandle), _O_RDONLY | _O_BINARY);
164 if(m_fileDescriptor < 0)
166 MUTILS_THROW_FMT("Failed to obtain C Runtime file descriptor!");
169 QFile checkFile;
171 //Now re-open the file for reading
172 if(g_useFileDescrForQFile)
174 checkFile.open(m_fileDescriptor, QIODevice::ReadOnly);
176 else
178 checkFile.setFileName(m_filePath);
179 for(int i = 0; i < 64; i++)
181 if(checkFile.open(QIODevice::ReadOnly)) break;
182 if(!i) qWarning("Failed to re-open file on first attemp, retrying...");
183 Sleep(100);
187 //Opened successfully
188 if(!checkFile.isOpen())
190 QFile::remove(m_filePath);
191 MUTILS_THROW_FMT("File '%s' could not be read!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
194 //Verify file contents
195 const QByteArray hash = fileHash(checkFile);
196 checkFile.close();
198 //Compare hashes
199 if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
201 qWarning("\nFile checksum error:\n A = %s\n B = %s\n", expectedHash.constData(), hash.constData());
202 CLOSE_HANDLE(fileHandle);
203 QFile::remove(m_filePath);
204 MUTILS_THROW_FMT("File '%s' is corruputed, take care!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
208 LockedFile::LockedFile(const QString &filePath, const bool bOwnsFile)
210 m_bOwnsFile(bOwnsFile),
211 m_filePath(QFileInfo(filePath).canonicalFilePath())
213 m_fileDescriptor = -1;
214 HANDLE fileHandle = NULL;
216 QFileInfo existingFileInfo(filePath);
217 existingFileInfo.setCaching(false);
219 //Make sure the file exists, before we try to lock it
220 if((!existingFileInfo.exists()) || (!existingFileInfo.isFile()) || m_filePath.isEmpty())
222 MUTILS_THROW_FMT("File '%s' does not exist!", MUTILS_UTF8(filePath));
225 //Now lock the file
226 for(int i = 0; i < 64; i++)
228 fileHandle = CreateFileW(MUTILS_WCHR(QDir::toNativeSeparators(m_filePath)), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
229 if(VALID_HANDLE(fileHandle)) break;
230 if(!i) qWarning("Failed to lock file on first attemp, retrying...");
231 Sleep(100);
234 //Locked successfully?
235 if(!VALID_HANDLE(fileHandle))
237 MUTILS_THROW_FMT("File '%s' could not be locked!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
240 //Get file descriptor
241 m_fileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(fileHandle), _O_RDONLY | _O_BINARY);
242 if(m_fileDescriptor < 0)
244 MUTILS_THROW_FMT("Failed to obtain C Runtime file descriptor!");
248 LockedFile::~LockedFile(void)
250 if(m_fileDescriptor >= 0)
252 _close(m_fileDescriptor);
253 m_fileDescriptor = -1;
255 if(m_bOwnsFile)
257 if(QFileInfo(m_filePath).exists())
259 for(int i = 0; i < 64; i++)
261 if(QFile::remove(m_filePath)) break;
262 MUtils::OS::sleep_ms(1);
268 const QString &LockedFile::filePath()
270 return m_filePath;
273 void LockedFile::selfTest()
275 if(!MUtils::Hash::Keccak::selfTest())
277 MUTILS_THROW("QKeccakHash self-test has failed!");