OSDN Git Service

Refactored the "LockedFile" class + moved hash computation to a separate class, for...
[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
25 //Internal
26 #include "Global.h"
27 #include "FileHash.h"
28
29 //MUtils
30 #include <MUtils/OSSupport.h>
31 #include <MUtils/Exception.h>
32
33 //Qt
34 #include <QResource>
35 #include <QFile>
36 #include <QFileInfo>
37 #include <QDir>
38 #include <QCryptographicHash>
39
40 //CRT
41 #include <stdio.h>
42 #include <io.h>
43 #include <fcntl.h>
44 #include <stdexcept>
45
46 //Windows includes
47 #define NOMINMAX
48 #define WIN32_LEAN_AND_MEAN
49 #include <Windows.h>
50
51 ///////////////////////////////////////////////////////////////////////////////
52
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
59
60 #define VALID_HANDLE(H) (((H) != NULL) && ((H) != INVALID_HANDLE_VALUE))
61
62 static void CLOSE_HANDLE(HANDLE &h)
63 {
64         if(VALID_HANDLE(h))
65         {
66                 CloseHandle(h);
67                 h = NULL;
68         }
69 }
70
71 ///////////////////////////////////////////////////////////////////////////////
72
73 static __forceinline void doWriteOutput(QFile &outFile, const QResource *const resource)
74 {
75         for(int i = 0; i < 64; i++)
76         {
77                 if(outFile.open(QIODevice::WriteOnly))
78                 {
79                         break;
80                 }
81                 if(i == 0)
82                 {
83                         qWarning("Failed to open file on first attemp, retrying...");
84                 }
85                 Sleep(25);
86         }
87         
88         //Write data to file
89         if(outFile.isOpen() && outFile.isWritable())
90         {
91                 if(outFile.write(reinterpret_cast<const char*>(resource->data()), resource->size()) != resource->size())
92                 {
93                         QFile::remove(QFileInfo(outFile).canonicalFilePath());
94                         MUTILS_THROW_FMT("File '%s' could not be written!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
95                 }
96         }
97         else
98         {
99                 MUTILS_THROW_FMT("File '%s' could not be created!", MUTILS_UTF8(QFileInfo(outFile).fileName()));
100         }
101
102         //Close file after it has been written
103         outFile.close();
104 }
105
106 static __forceinline void doValidateFileExists(const QString &filePath)
107 {
108         QFileInfo existingFileInfo(filePath);
109         existingFileInfo.setCaching(false);
110         
111         //Make sure the file exists, before we try to lock it
112         if((!existingFileInfo.exists()) || (!existingFileInfo.isFile()) || filePath.isEmpty())
113         {
114                 MUTILS_THROW_FMT("File '%s' does not exist!", MUTILS_UTF8(filePath));
115         }
116 }
117
118 static __forceinline void doLockFile(HANDLE &fileHandle, const QString &filePath, QFile *const outFile)
119 {
120         for(int i = 0; i < 64; i++)
121         {
122                 fileHandle = CreateFileW(MUTILS_WCHR(QDir::toNativeSeparators(filePath)), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
123                 if(VALID_HANDLE(fileHandle))
124                 {
125                         break;
126                 }
127                 if(i == 0)
128                 {
129                         qWarning("Failed to lock file on first attemp, retrying...");
130                 }
131                 Sleep(25);
132         }
133         
134         //Locked successfully?
135         if(!VALID_HANDLE(fileHandle))
136         {
137                 if(outFile)
138                 {
139                         QFile::remove(QFileInfo(*outFile).canonicalFilePath());
140                 }
141                 MUTILS_THROW_FMT("File '%s' could not be locked!", MUTILS_UTF8(QFileInfo(filePath).fileName()));
142         }
143 }
144
145 static __forceinline void doInitFileDescriptor(const HANDLE &fileHandle, int &fileDescriptor)
146 {
147         fileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(fileHandle), _O_RDONLY | _O_BINARY);
148         if(fileDescriptor < 0)
149         {
150                 MUTILS_THROW_FMT("Failed to obtain C Runtime file descriptor!");
151         }
152 }
153
154 static __forceinline void doValidateHash(HANDLE &fileHandle, const int &fileDescriptor, const QByteArray &expectedHash, const QString &filePath)
155 {
156         QFile checkFile;
157
158         //Now re-open the file for reading
159         if(g_useFileDescrForQFile)
160         {
161                 checkFile.open(fileDescriptor, QIODevice::ReadOnly);
162         }
163         else
164         {
165                 checkFile.setFileName(filePath);
166                 for(int i = 0; i < 64; i++)
167                 {
168                         if(checkFile.open(QIODevice::ReadOnly)) break;
169                         if(!i) qWarning("Failed to re-open file on first attemp, retrying...");
170                         Sleep(100);
171                 }
172         }
173
174         //Opened successfully
175         if(!checkFile.isOpen())
176         {
177                 QFile::remove(filePath);
178                 MUTILS_THROW_FMT("File '%s' could not be read!", MUTILS_UTF8(QFileInfo(filePath).fileName()));
179         }
180
181         //Verify file contents
182         const QByteArray hash = FileHash::computeHash(checkFile);
183         checkFile.close();
184
185         //Compare hashes
186         if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
187         {
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()));
192         }
193 }
194
195 ///////////////////////////////////////////////////////////////////////////////
196
197 LockedFile::LockedFile(QResource *const resource, const QString &outPath, const QByteArray &expectedHash, const bool bOwnsFile)
198 :
199         m_bOwnsFile(bOwnsFile),
200         m_filePath(QFileInfo(outPath).absoluteFilePath())
201 {
202         m_fileDescriptor = -1;
203         HANDLE fileHandle = NULL;
204                 
205         //Make sure the resource is valid
206         if(!(resource->isValid() && resource->data()))
207         {
208                 MUTILS_THROW_FMT("The resource at %p is invalid!", resource);
209         }
210
211         //Write data to output file
212         QFile outFile(m_filePath);
213         doWriteOutput(outFile, resource);
214
215         //Now lock the file!
216         doLockFile(fileHandle, m_filePath, &outFile);
217
218         //Get file descriptor
219         doInitFileDescriptor(fileHandle, m_fileDescriptor);
220
221         //Validate file hash
222         doValidateHash(fileHandle, m_fileDescriptor, expectedHash, m_filePath);
223 }
224
225 LockedFile::LockedFile(const QString &filePath, const QByteArray &expectedHash, const bool bOwnsFile)
226 :
227         m_bOwnsFile(bOwnsFile),
228         m_filePath(QFileInfo(filePath).absoluteFilePath())
229 {
230         m_fileDescriptor = -1;
231         HANDLE fileHandle = NULL;
232         
233         //Make sure the file exists, before we try to lock it
234         doValidateFileExists(m_filePath);
235
236         //Now lock the file!
237         doLockFile(fileHandle, m_filePath, NULL);
238
239         //Get file descriptor
240         doInitFileDescriptor(fileHandle, m_fileDescriptor);
241
242         //Validate file hash
243         doValidateHash(fileHandle, m_fileDescriptor, expectedHash, m_filePath);
244 }
245
246 LockedFile::LockedFile(const QString &filePath, const bool bOwnsFile)
247 :
248         m_bOwnsFile(bOwnsFile),
249         m_filePath(QFileInfo(filePath).canonicalFilePath())
250 {
251         m_fileDescriptor = -1;
252         HANDLE fileHandle = NULL;
253         
254         //Make sure the file exists, before we try to lock it
255         doValidateFileExists(m_filePath);
256
257         //Now lock the file!
258         doLockFile(fileHandle, m_filePath, NULL);
259
260         //Get file descriptor
261         doInitFileDescriptor(fileHandle, m_fileDescriptor);
262 }
263
264 LockedFile::~LockedFile(void)
265 {
266         if(m_fileDescriptor >= 0)
267         {
268                 _close(m_fileDescriptor);
269                 m_fileDescriptor = -1;
270         }
271         if(m_bOwnsFile)
272         {
273                 if(QFileInfo(m_filePath).exists())
274                 {
275                         for(int i = 0; i < 64; i++)
276                         {
277                                 if(QFile::remove(m_filePath)) break;
278                                 MUtils::OS::sleep_ms(1);
279                         }
280                 }
281         }
282 }
283
284 const QString &LockedFile::filePath()
285 {
286         return m_filePath;
287 }