/
RarFile.cpp
749 lines (643 loc) · 17.1 KB
/
RarFile.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "system.h"
#include "RarFile.h"
#include <sys/stat.h>
#include "Util.h"
#include "utils/CharsetConverter.h"
#include "utils/URIUtils.h"
#include "URL.h"
#include "Directory.h"
#include "RarManager.h"
#include "settings/AdvancedSettings.h"
#include "FileItem.h"
#include "utils/log.h"
#include "UnrarXLib/rar.hpp"
#include "utils/StringUtils.h"
#ifndef TARGET_POSIX
#include <process.h>
#endif
using namespace XFILE;
using namespace std;
#define SEEKTIMOUT 30000
#ifdef HAS_FILESYSTEM_RAR
CRarFileExtractThread::CRarFileExtractThread() : CThread("RarFileExtract"), hRunning(true), hQuit(true)
{
m_pArc = NULL;
m_pCmd = NULL;
m_pExtract = NULL;
StopThread();
Create();
}
CRarFileExtractThread::~CRarFileExtractThread()
{
hQuit.Set();
AbortableWait(hRestart);
StopThread();
}
void CRarFileExtractThread::Start(Archive* pArc, CommandData* pCmd, CmdExtract* pExtract, int iSize)
{
m_pArc = pArc;
m_pCmd = pCmd;
m_pExtract = pExtract;
m_iSize = iSize;
m_pExtract->GetDataIO().hBufferFilled = new CEvent;
m_pExtract->GetDataIO().hBufferEmpty = new CEvent;
m_pExtract->GetDataIO().hSeek = new CEvent(true);
m_pExtract->GetDataIO().hSeekDone = new CEvent;
m_pExtract->GetDataIO().hQuit = new CEvent(true);
hRunning.Set();
hRestart.Set();
}
void CRarFileExtractThread::OnStartup()
{
}
void CRarFileExtractThread::OnExit()
{
}
void CRarFileExtractThread::Process()
{
while (AbortableWait(hQuit,1) != WAIT_SIGNALED)
{
if (AbortableWait(hRestart,1) == WAIT_SIGNALED)
{
bool Repeat = false;
try
{
m_pExtract->ExtractCurrentFile(m_pCmd,*m_pArc,m_iSize,Repeat);
}
catch (int rarErrCode)
{
CLog::Log(LOGERROR,"filerar CFileRarExtractThread::Process failed. CmdExtract::ExtractCurrentFile threw a UnrarXLib error code of %d",rarErrCode);
}
catch (...)
{
CLog::Log(LOGERROR,"filerar CFileRarExtractThread::Process failed. CmdExtract::ExtractCurrentFile threw an Unknown exception");
}
hRunning.Reset();
}
}
hRestart.Set();
}
#endif
CRarFile::CRarFile()
{
m_strCacheDir.Empty();
m_strRarPath.Empty();
m_strPassword.Empty();
m_strPathInRar.Empty();
m_bFileOptions = 0;
#ifdef HAS_FILESYSTEM_RAR
m_pArc = NULL;
m_pCmd = NULL;
m_pExtract = NULL;
m_pExtractThread = NULL;
#endif
m_szBuffer = NULL;
m_szStartOfBuffer = NULL;
m_iDataInBuffer = 0;
m_bUseFile = false;
m_bOpen = false;
m_bSeekable = true;
}
CRarFile::~CRarFile()
{
#ifdef HAS_FILESYSTEM_RAR
if (!m_bOpen)
return;
if (m_bUseFile)
{
m_File.Close();
g_RarManager.ClearCachedFile(m_strRarPath,m_strPathInRar);
}
else
{
CleanUp();
if (m_pExtractThread)
{
delete m_pExtractThread;
m_pExtractThread = NULL;
}
}
#endif
}
bool CRarFile::Open(const CURL& url)
{
InitFromUrl(url);
CFileItemList items;
g_RarManager.GetFilesInRar(items,m_strRarPath,false);
int i;
for (i=0;i<items.Size();++i)
{
if (items[i]->GetLabel() == m_strPathInRar)
break;
}
if (i<items.Size())
{
if (items[i]->m_idepth == 0x30) // stored
{
if (!OpenInArchive())
return false;
m_iFileSize = items[i]->m_dwSize;
m_bOpen = true;
// perform 'noidx' check
CFileInfo* pFile = g_RarManager.GetFileInRar(m_strRarPath,m_strPathInRar);
if (pFile)
{
if (pFile->m_iIsSeekable == -1)
{
if (Seek(-1,SEEK_END) == -1)
{
m_bSeekable = false;
pFile->m_iIsSeekable = 0;
}
}
else
m_bSeekable = (pFile->m_iIsSeekable == 1);
}
return true;
}
else
{
CFileInfo* info = g_RarManager.GetFileInRar(m_strRarPath,m_strPathInRar);
if ((!info || !CFile::Exists(info->m_strCachedPath)) && m_bFileOptions & EXFILE_NOCACHE)
return false;
m_bUseFile = true;
CStdString strPathInCache;
if (!g_RarManager.CacheRarredFile(strPathInCache, m_strRarPath, m_strPathInRar,
EXFILE_AUTODELETE | m_bFileOptions, m_strCacheDir,
items[i]->m_dwSize))
{
CLog::Log(LOGERROR,"filerar::open failed to cache file %s",m_strPathInRar.c_str());
return false;
}
if (!m_File.Open( strPathInCache ))
{
CLog::Log(LOGERROR,"filerar::open failed to open file in cache: %s",strPathInCache.c_str());
return false;
}
m_bOpen = true;
return true;
}
}
return false;
}
bool CRarFile::Exists(const CURL& url)
{
InitFromUrl(url);
// First step:
// Make sure that the archive exists in the filesystem.
if (!CFile::Exists(m_strRarPath, false))
return false;
// Second step:
// Make sure that the requested file exists in the archive.
bool bResult;
if (!g_RarManager.IsFileInRar(bResult, m_strRarPath, m_strPathInRar))
return false;
return bResult;
}
int CRarFile::Stat(const CURL& url, struct __stat64* buffer)
{
memset(buffer, 0, sizeof(struct __stat64));
if (Open(url))
{
buffer->st_size = GetLength();
buffer->st_mode = _S_IFREG;
Close();
errno = 0;
return 0;
}
if (CDirectory::Exists(url.Get()))
{
buffer->st_mode = _S_IFDIR;
return 0;
}
errno = ENOENT;
return -1;
}
bool CRarFile::OpenForWrite(const CURL& url)
{
return false;
}
unsigned int CRarFile::Read(void *lpBuf, int64_t uiBufSize)
{
#ifdef HAS_FILESYSTEM_RAR
if (!m_bOpen)
return 0;
if (m_bUseFile)
return m_File.Read(lpBuf,uiBufSize);
if (m_iFilePosition >= GetLength()) // we are done
return 0;
if( !m_pExtract->GetDataIO().hBufferEmpty->WaitMSec(5000) )
{
CLog::Log(LOGERROR, "%s - Timeout waiting for buffer to empty", __FUNCTION__);
return 0;
}
uint8_t* pBuf = (uint8_t*)lpBuf;
int64_t uicBufSize = uiBufSize;
if (m_iDataInBuffer > 0)
{
int64_t iCopy = uiBufSize<m_iDataInBuffer?uiBufSize:m_iDataInBuffer;
memcpy(lpBuf,m_szStartOfBuffer,size_t(iCopy));
m_szStartOfBuffer += iCopy;
m_iDataInBuffer -= int(iCopy);
pBuf += iCopy;
uicBufSize -= iCopy;
m_iFilePosition += iCopy;
}
while ((uicBufSize > 0) && m_iFilePosition < GetLength() )
{
if (m_iDataInBuffer <= 0)
{
m_pExtract->GetDataIO().SetUnpackToMemory(m_szBuffer,MAXWINMEMSIZE);
m_szStartOfBuffer = m_szBuffer;
m_iBufferStart = m_iFilePosition;
}
m_pExtract->GetDataIO().hBufferFilled->Set();
m_pExtract->GetDataIO().hBufferEmpty->Wait();
if (m_pExtract->GetDataIO().NextVolumeMissing)
break;
m_iDataInBuffer = MAXWINMEMSIZE-m_pExtract->GetDataIO().UnpackToMemorySize;
if (m_iDataInBuffer < 0 ||
m_iDataInBuffer > MAXWINMEMSIZE - (m_szStartOfBuffer - m_szBuffer))
{
// invalid data returned by UnrarXLib, prevent a crash
CLog::Log(LOGERROR, "CRarFile::Read - Data buffer in inconsistent state");
m_iDataInBuffer = 0;
}
if (m_iDataInBuffer == 0)
break;
if (m_iDataInBuffer > uicBufSize)
{
memcpy(pBuf,m_szStartOfBuffer,int(uicBufSize));
m_szStartOfBuffer += uicBufSize;
pBuf += int(uicBufSize);
m_iFilePosition += uicBufSize;
m_iDataInBuffer -= int(uicBufSize);
uicBufSize = 0;
}
else
{
memcpy(pBuf,m_szStartOfBuffer,size_t(m_iDataInBuffer));
m_iFilePosition += m_iDataInBuffer;
m_szStartOfBuffer += m_iDataInBuffer;
uicBufSize -= m_iDataInBuffer;
pBuf += m_iDataInBuffer;
m_iDataInBuffer = 0;
}
}
m_pExtract->GetDataIO().hBufferEmpty->Set();
return static_cast<unsigned int>(uiBufSize-uicBufSize);
#else
return 0;
#endif
}
unsigned int CRarFile::Write(void *lpBuf, int64_t uiBufSize)
{
return 0;
}
void CRarFile::Close()
{
#ifdef HAS_FILESYSTEM_RAR
if (!m_bOpen)
return;
if (m_bUseFile)
{
m_File.Close();
g_RarManager.ClearCachedFile(m_strRarPath,m_strPathInRar);
m_bOpen = false;
}
else
{
CleanUp();
if (m_pExtractThread)
{
delete m_pExtractThread;
m_pExtractThread = NULL;
}
m_bOpen = false;
}
#endif
}
int64_t CRarFile::Seek(int64_t iFilePosition, int iWhence)
{
#ifdef HAS_FILESYSTEM_RAR
if (!m_bOpen)
return -1;
if (!m_bSeekable)
return -1;
if (m_bUseFile)
return m_File.Seek(iFilePosition,iWhence);
if( !m_pExtract->GetDataIO().hBufferEmpty->WaitMSec(SEEKTIMOUT) )
{
CLog::Log(LOGERROR, "%s - Timeout waiting for buffer to empty", __FUNCTION__);
return -1;
}
m_pExtract->GetDataIO().hBufferEmpty->Set();
switch (iWhence)
{
case SEEK_CUR:
if (iFilePosition == 0)
return m_iFilePosition; // happens sometimes
iFilePosition += m_iFilePosition;
break;
case SEEK_END:
if (iFilePosition == 0) // do not seek to end
{
m_iFilePosition = this->GetLength();
m_iDataInBuffer = 0;
m_iBufferStart = this->GetLength();
return this->GetLength();
}
iFilePosition += GetLength();
case SEEK_SET:
break;
default:
return -1;
}
if (iFilePosition > this->GetLength())
return -1;
if (iFilePosition == m_iFilePosition) // happens a lot
return m_iFilePosition;
if ((iFilePosition >= m_iBufferStart) && (iFilePosition < m_iBufferStart+MAXWINMEMSIZE)
&& (m_iDataInBuffer > 0)) // we are within current buffer
{
m_iDataInBuffer = MAXWINMEMSIZE-(iFilePosition-m_iBufferStart);
m_szStartOfBuffer = m_szBuffer+MAXWINMEMSIZE-m_iDataInBuffer;
m_iFilePosition = iFilePosition;
return m_iFilePosition;
}
if (iFilePosition < m_iBufferStart )
{
CleanUp();
if (!OpenInArchive())
return -1;
if( !m_pExtract->GetDataIO().hBufferEmpty->WaitMSec(SEEKTIMOUT) )
{
CLog::Log(LOGERROR, "%s - Timeout waiting for buffer to empty", __FUNCTION__);
return -1;
}
m_pExtract->GetDataIO().hBufferEmpty->Set();
m_pExtract->GetDataIO().m_iSeekTo = iFilePosition;
}
else
m_pExtract->GetDataIO().m_iSeekTo = iFilePosition;
m_pExtract->GetDataIO().SetUnpackToMemory(m_szBuffer,MAXWINMEMSIZE);
m_pExtract->GetDataIO().hSeek->Set();
m_pExtract->GetDataIO().hBufferFilled->Set();
if( !m_pExtract->GetDataIO().hSeekDone->WaitMSec(SEEKTIMOUT))
{
CLog::Log(LOGERROR, "%s - Timeout waiting for seek to finish", __FUNCTION__);
return -1;
}
if (m_pExtract->GetDataIO().NextVolumeMissing)
{
m_iFilePosition = m_iFileSize;
return -1;
}
if( !m_pExtract->GetDataIO().hBufferEmpty->WaitMSec(SEEKTIMOUT) )
{
CLog::Log(LOGERROR, "%s - Timeout waiting for buffer to empty", __FUNCTION__);
return -1;
}
m_iDataInBuffer = m_pExtract->GetDataIO().m_iSeekTo; // keep data
m_iBufferStart = m_pExtract->GetDataIO().m_iStartOfBuffer;
if (m_iDataInBuffer < 0 || m_iDataInBuffer > MAXWINMEMSIZE)
{
// invalid data returned by UnrarXLib, prevent a crash
CLog::Log(LOGERROR, "CRarFile::Seek - Data buffer in inconsistent state");
m_iDataInBuffer = 0;
return -1;
}
m_szStartOfBuffer = m_szBuffer+MAXWINMEMSIZE-m_iDataInBuffer;
m_iFilePosition = iFilePosition;
return m_iFilePosition;
#else
return -1;
#endif
}
int64_t CRarFile::GetLength()
{
if (!m_bOpen)
return 0;
if (m_bUseFile)
return m_File.GetLength();
return m_iFileSize;
}
int64_t CRarFile::GetPosition()
{
if (!m_bOpen)
return -1;
if (m_bUseFile)
return m_File.GetPosition();
return m_iFilePosition;
}
int CRarFile::Write(const void* lpBuf, int64_t uiBufSize)
{
return -1;
}
void CRarFile::Flush()
{
if (m_bUseFile)
m_File.Flush();
}
void CRarFile::InitFromUrl(const CURL& url)
{
m_strCacheDir = g_advancedSettings.m_cachePath;//url.GetDomain();
URIUtils::AddSlashAtEnd(m_strCacheDir);
m_strRarPath = url.GetHostName();
m_strPassword = url.GetUserName();
m_strPathInRar = url.GetFileName();
vector<std::string> options;
StringUtils::Tokenize(url.GetOptions().Mid(1), options, "&");
m_bFileOptions = 0;
for( vector<std::string>::iterator it = options.begin();it != options.end(); it++)
{
int iEqual = (*it).find('=');
if( iEqual >= 0 )
{
CStdString strOption = StringUtils::Left((*it), iEqual);
CStdString strValue = StringUtils::Mid((*it), iEqual+1);
if( strOption.Equals("flags") )
m_bFileOptions = atoi(strValue.c_str());
else if( strOption.Equals("cache") )
m_strCacheDir = strValue;
}
}
}
void CRarFile::CleanUp()
{
#ifdef HAS_FILESYSTEM_RAR
try
{
if (m_pExtractThread)
{
if (m_pExtractThread->hRunning.WaitMSec(1))
{
m_pExtract->GetDataIO().hQuit->Set();
while (m_pExtractThread->hRunning.WaitMSec(1))
Sleep(1);
}
delete m_pExtract->GetDataIO().hBufferFilled;
delete m_pExtract->GetDataIO().hBufferEmpty;
delete m_pExtract->GetDataIO().hSeek;
delete m_pExtract->GetDataIO().hSeekDone;
delete m_pExtract->GetDataIO().hQuit;
}
if (m_pExtract)
{
delete m_pExtract;
m_pExtract = NULL;
}
if (m_pArc)
{
delete m_pArc;
m_pArc = NULL;
}
if (m_pCmd)
{
delete m_pCmd;
m_pCmd = NULL;
}
if (m_szBuffer)
{
delete[] m_szBuffer;
m_szBuffer = NULL;
m_szStartOfBuffer = NULL;
}
}
catch (int rarErrCode)
{
CLog::Log(LOGERROR,"filerar failed in UnrarXLib while deleting CFileRar with an UnrarXLib error code of %d",rarErrCode);
}
catch (...)
{
CLog::Log(LOGERROR,"filerar failed in UnrarXLib while deleting CFileRar with an Unknown exception");
}
#endif
}
bool CRarFile::OpenInArchive()
{
#ifdef HAS_FILESYSTEM_RAR
try
{
int iHeaderSize;
InitCRC();
m_pCmd = new CommandData;
if (!m_pCmd)
{
CleanUp();
return false;
}
// Set the arguments for the extract command
strcpy(m_pCmd->Command, "X");
m_pCmd->AddArcName(const_cast<char*>(m_strRarPath.c_str()),NULL);
strncpy(m_pCmd->ExtrPath, m_strCacheDir.c_str(), sizeof (m_pCmd->ExtrPath) - 2);
m_pCmd->ExtrPath[sizeof (m_pCmd->ExtrPath) - 2] = 0;
AddEndSlash(m_pCmd->ExtrPath);
// Set password for encrypted archives
if ((m_strPassword.size() > 0) &&
(m_strPassword.size() < sizeof (m_pCmd->Password)))
{
strcpy(m_pCmd->Password, m_strPassword.c_str());
}
m_pCmd->ParseDone();
// Open the archive
m_pArc = new Archive(m_pCmd);
if (!m_pArc)
{
CleanUp();
return false;
}
if (!m_pArc->WOpen(m_strRarPath.c_str(),NULL))
{
CleanUp();
return false;
}
if (!(m_pArc->IsOpened() && m_pArc->IsArchive(true)))
{
CleanUp();
return false;
}
m_pExtract = new CmdExtract;
if (!m_pExtract)
{
CleanUp();
return false;
}
m_pExtract->GetDataIO().SetUnpackToMemory(m_szBuffer,0);
m_pExtract->GetDataIO().SetCurrentCommand(*(m_pCmd->Command));
struct FindData FD;
if (FindFile::FastFind(m_strRarPath.c_str(),NULL,&FD))
m_pExtract->GetDataIO().TotalArcSize+=FD.Size;
m_pExtract->ExtractArchiveInit(m_pCmd,*m_pArc);
while (true)
{
if ((iHeaderSize = m_pArc->ReadHeader()) <= 0)
{
CleanUp();
return false;
}
if (m_pArc->GetHeaderType() == FILE_HEAD)
{
CStdString strFileName;
if (wcslen(m_pArc->NewLhd.FileNameW) > 0)
{
g_charsetConverter.wToUTF8(m_pArc->NewLhd.FileNameW, strFileName);
}
else
{
g_charsetConverter.unknownToUTF8(m_pArc->NewLhd.FileName, strFileName);
}
/* replace back slashes into forward slashes */
/* this could get us into troubles, file could two different files, one with / and one with \ */
strFileName.Replace('\\', '/');
if (strFileName == m_strPathInRar)
{
break;
}
}
m_pArc->SeekToNext();
}
m_szBuffer = new uint8_t[MAXWINMEMSIZE];
m_szStartOfBuffer = m_szBuffer;
m_pExtract->GetDataIO().SetUnpackToMemory(m_szBuffer,0);
m_iDataInBuffer = -1;
m_iFilePosition = 0;
m_iBufferStart = 0;
delete m_pExtractThread;
m_pExtractThread = new CRarFileExtractThread();
m_pExtractThread->Start(m_pArc,m_pCmd,m_pExtract,iHeaderSize);
return true;
}
catch (int rarErrCode)
{
CLog::Log(LOGERROR,"filerar failed in UnrarXLib while CFileRar::OpenInArchive with an UnrarXLib error code of %d",rarErrCode);
return false;
}
catch (...)
{
CLog::Log(LOGERROR,"filerar failed in UnrarXLib while CFileRar::OpenInArchive with an Unknown exception");
return false;
}
#else
return false;
#endif
}