OSDN Git Service

Updated OggEnc2 binaries to v2.87 using libvorbis v1.3.4 and aoTuV v6.03_2014 (2014...
[lamexp/LameXP.git] / src / LockedFile.cpp
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.
10 //
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.
15 //
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.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 #include "LockedFile.h"
24 #include "Global.h"
25
26 //MUtils
27 #include <MUtils/OSSupport.h>
28 #include <MUtils/Hash_Keccak.h>
29 #include <MUtils/Exception.h>
30
31 //Qt
32 #include <QResource>
33 #include <QFile>
34 #include <QFileInfo>
35 #include <QDir>
36 #include <QCryptographicHash>
37
38 #include <stdio.h>
39 #include <io.h>
40 #include <fcntl.h>
41 #include <stdexcept>
42
43 //Windows includes
44 #define NOMINMAX
45 #define WIN32_LEAN_AND_MEAN
46 #include <Windows.h>
47
48 ///////////////////////////////////////////////////////////////////////////////
49
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
56
57 static void CLOSE_HANDLE(HANDLE &h)
58 {
59         if((h != NULL) && (h != INVALID_HANDLE_VALUE))
60         {
61                 CloseHandle(h);
62                 h = NULL;
63         }
64 }
65
66 ///////////////////////////////////////////////////////////////////////////////
67
68 static const char *g_blnk = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
69 static const char *g_seed = "c375d83b4388329408dfcbb4d9a065b6e06d28272f25ef299c70b506e26600af79fd2f866ae24602daf38f25c9d4b7e1";
70 static const char *g_salt = "ee9f7bdabc170763d2200a7e3030045aafe380011aefc1730e547e9244c62308aac42a976feeca224ba553de0c4bb883";
71
72 QByteArray LockedFile::fileHash(QFile &file)
73 {
74         QByteArray hash = QByteArray::fromHex(g_blnk);
75
76         if(file.isOpen() && file.reset())
77         {
78                 MUtils::Hash::Keccak keccak;
79
80                 const QByteArray data = file.readAll();
81                 const QByteArray seed = QByteArray::fromHex(g_seed);
82                 const QByteArray salt = QByteArray::fromHex(g_salt);
83         
84                 if(keccak.init(MUtils::Hash::Keccak::hb384))
85                 {
86                         bool ok = true;
87                         ok = ok && keccak.addData(seed);
88                         ok = ok && keccak.addData(data);
89                         ok = ok && keccak.addData(salt);
90                         if(ok)
91                         {
92                                 const QByteArray digest = keccak.finalize();
93                                 if(!digest.isEmpty()) hash = digest.toHex();
94                         }
95                 }
96         }
97
98         return hash;
99 }
100
101 ///////////////////////////////////////////////////////////////////////////////
102
103 LockedFile::LockedFile(QResource *const resource, const QString &outPath, const QByteArray &expectedHash, const bool bOwnsFile)
104 :
105         m_bOwnsFile(bOwnsFile),
106         m_filePath(QFileInfo(outPath).absoluteFilePath())
107 {
108         m_fileDescriptor = -1;
109         HANDLE fileHandle = NULL;
110                 
111         //Make sure the resource is valid
112         if(!(resource->isValid() && resource->data()))
113         {
114                 MUTILS_THROW_FMT("The resource at %p is invalid!", resource);
115         }
116
117         QFile outFile(m_filePath);
118         
119         //Open output file
120         for(int i = 0; i < 64; i++)
121         {
122                 if(outFile.open(QIODevice::WriteOnly)) break;
123                 if(!i) qWarning("Failed to open file on first attemp, retrying...");
124                 Sleep(100);
125         }
126         
127         //Write data to file
128         if(outFile.isOpen() && outFile.isWritable())
129         {
130                 if(outFile.write(reinterpret_cast<const char*>(resource->data()), resource->size()) != resource->size())
131                 {
132                         QFile::remove(QFileInfo(outFile).canonicalFilePath());
133                         MUTILS_THROW_FMT("File '%s' could not be written!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
134                 }
135         }
136         else
137         {
138                 MUTILS_THROW_FMT("File '%s' could not be created!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
139         }
140
141         //Close file after it has been written
142         outFile.close();
143
144         //Now lock the file!
145         for(int i = 0; i < 64; i++)
146         {
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...");
150                 Sleep(100);
151         }
152         
153         //Locked successfully?
154         if((fileHandle == NULL) || (fileHandle == INVALID_HANDLE_VALUE))
155         {
156                 QFile::remove(QFileInfo(outFile).canonicalFilePath());
157                 MUTILS_THROW_FMT("File '%s' could not be locked!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
158         }
159
160         //Get file descriptor
161         m_fileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(fileHandle), _O_RDONLY | _O_BINARY);
162         if(m_fileDescriptor < 0)
163         {
164                 MUTILS_THROW_FMT("Failed to obtain C Runtime file descriptor!");
165         }
166
167         QFile checkFile;
168
169         //Now re-open the file for reading
170         if(g_useFileDescrForQFile)
171         {
172                 checkFile.open(m_fileDescriptor, QIODevice::ReadOnly);
173         }
174         else
175         {
176                 checkFile.setFileName(m_filePath);
177                 for(int i = 0; i < 64; i++)
178                 {
179                         if(checkFile.open(QIODevice::ReadOnly)) break;
180                         if(!i) qWarning("Failed to re-open file on first attemp, retrying...");
181                         Sleep(100);
182                 }
183         }
184
185         //Opened successfully
186         if(!checkFile.isOpen())
187         {
188                 QFile::remove(m_filePath);
189                 MUTILS_THROW_FMT("File '%s' could not be read!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
190         }
191
192         //Verify file contents
193         const QByteArray hash = fileHash(checkFile);
194         checkFile.close();
195
196         //Compare hashes
197         if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
198         {
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()));
203         }
204 }
205
206 LockedFile::LockedFile(const QString &filePath, const bool bOwnsFile)
207 :
208         m_bOwnsFile(bOwnsFile),
209         m_filePath(QFileInfo(filePath).canonicalFilePath())
210 {
211         m_fileDescriptor = -1;
212         HANDLE fileHandle = NULL;
213
214         QFileInfo existingFileInfo(filePath);
215         existingFileInfo.setCaching(false);
216         
217         //Make sure the file exists, before we try to lock it
218         if((!existingFileInfo.exists()) || (!existingFileInfo.isFile()) || m_filePath.isEmpty())
219         {
220                 MUTILS_THROW_FMT("File '%s' does not exist!", MUTILS_UTF8(filePath));
221         }
222         
223         //Now lock the file
224         for(int i = 0; i < 64; i++)
225         {
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...");
229                 Sleep(100);
230         }
231
232         //Locked successfully?
233         if((fileHandle == NULL) || (fileHandle == INVALID_HANDLE_VALUE))
234         {
235                 MUTILS_THROW_FMT("File '%s' could not be locked!", MUTILS_UTF8(QFileInfo(m_filePath).fileName()));
236         }
237
238         //Get file descriptor
239         m_fileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(fileHandle), _O_RDONLY | _O_BINARY);
240         if(m_fileDescriptor < 0)
241         {
242                 MUTILS_THROW_FMT("Failed to obtain C Runtime file descriptor!");
243         }
244 }
245
246 LockedFile::~LockedFile(void)
247 {
248         if(m_fileDescriptor >= 0)
249         {
250                 _close(m_fileDescriptor);
251                 m_fileDescriptor = -1;
252         }
253         if(m_bOwnsFile)
254         {
255                 if(QFileInfo(m_filePath).exists())
256                 {
257                         for(int i = 0; i < 64; i++)
258                         {
259                                 if(QFile::remove(m_filePath)) break;
260                                 MUtils::OS::sleep_ms(1);
261                         }
262                 }
263         }
264 }
265
266 const QString &LockedFile::filePath()
267 {
268         return m_filePath;
269 }
270
271 void LockedFile::selfTest()
272 {
273         if(!MUtils::Hash::Keccak::selfTest())
274         {
275                 MUTILS_THROW("QKeccakHash self-test has failed!");
276         }
277 }