forked from irwir/eMule
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArchiveRecovery.cpp
1924 lines (1666 loc) · 54 KB
/
ArchiveRecovery.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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//this file is part of eMule
//Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//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 of the License, 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 this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include "emule.h"
#include "ArchiveRecovery.h"
#include "OtherFunctions.h"
#include "Preferences.h"
#include "PartFile.h"
#include <zlib/zlib.h>
#include "Log.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#pragma pack(push,1)
typedef struct {
BYTE type;
WORD flags;
WORD size;
} RARMAINHDR;
#pragma pack(pop)
#pragma pack(push,1)
typedef struct {
BYTE type;
WORD flags;
WORD size;
DWORD packetSize;
DWORD unpacketSize;
BYTE hostOS;
DWORD fileCRC;
DWORD fileTime;
BYTE unpVer;
BYTE method;
WORD nameSize;
DWORD fileAttr;
} RARFILEHDR;
#pragma pack(pop)
void CArchiveRecovery::recover(CPartFile *partFile, bool preview, bool bCreatePartFileCopy)
{
if (partFile->m_bPreviewing || partFile->m_bRecoveringArchive)
return;
partFile->m_bRecoveringArchive = true;
AddLogLine(true, _T("%s \"%s\""), GetResString(IDS_ATTEMPTING_RECOVERY), partFile->GetFileName());
// Get the current filled list for this file
CTypedPtrList<CPtrList, Gap_Struct*> *filled = new CTypedPtrList<CPtrList, Gap_Struct*>;
partFile->GetFilledList(filled);
#ifdef _DEBUG
{
int i = 0;
TRACE("%s: filled\n", __FUNCTION__);
POSITION pos = filled->GetHeadPosition();
while (pos){
Gap_Struct* gap = filled->GetNext(pos);
TRACE("%3u: %10u %10u (%u)\n", i++, gap->start, gap->end, gap->end - gap->start + 1);
}
}
#endif
// The rest of the work can be safely done in a new thread
ThreadParam *tp = new ThreadParam;
tp->partFile = partFile;
tp->filled = filled;
tp->preview = preview;
tp->bCreatePartFileCopy = bCreatePartFileCopy;
// - do NOT use Windows API 'CreateThread' to create a thread which uses MFC/CRT -> lot of mem leaks!
if (!AfxBeginThread(run, (LPVOID)tp)){
partFile->m_bRecoveringArchive = false;
LogError(LOG_STATUSBAR, _T("%s \"%s\""), GetResString(IDS_RECOVERY_FAILED), partFile->GetFileName());
// Need to delete the memory here as won't be done in thread
DeleteMemory(tp);
}
}
UINT AFX_CDECL CArchiveRecovery::run(LPVOID lpParam)
{
ThreadParam *tp = (ThreadParam *)lpParam;
DbgSetThreadName("ArchiveRecovery");
InitThreadLocale();
if (!performRecovery(tp->partFile, tp->filled, tp->preview, tp->bCreatePartFileCopy))
theApp.QueueLogLine(true, _T("%s \"%s\""), GetResString(IDS_RECOVERY_FAILED), tp->partFile->GetFileName());
tp->partFile->m_bRecoveringArchive = false;
// Delete memory used by copied gap list
DeleteMemory(tp);
return 0;
}
bool CArchiveRecovery::performRecovery(CPartFile *partFile, CTypedPtrList<CPtrList, Gap_Struct*> *filled,
bool preview, bool bCreatePartFileCopy)
{
if (filled->GetCount()==0)
return false;
bool success = false;
try
{
CFile temp;
CString tempFileName;
if (bCreatePartFileCopy)
{
// Copy the file
tempFileName = partFile->GetTempPath() + partFile->GetFileName().Mid(0, 5) + _T("-rec.tmp");
if (!CopyFile(partFile, filled, tempFileName))
return false;
// Open temp file for reading
if (!temp.Open(tempFileName, CFile::modeRead|CFile::shareDenyWrite))
return false;
}
else
{
if (!temp.Open(partFile->GetFilePath(), CFile::modeRead | CFile::shareDenyNone))
return false;
}
// Open the output file
EFileType myAtype=GetFileTypeEx(partFile);
CString ext;
if (myAtype==ARCHIVE_ZIP)
ext=_T(".zip");
else if (myAtype==ARCHIVE_RAR)
ext=_T(".rar");
else if (myAtype==ARCHIVE_ACE)
ext=_T(".ace");
CString outputFileName = partFile->GetTempPath() + partFile->GetFileName().Mid(0, 5) + _T("-rec") + ext;
CFile output;
ULONGLONG ulTempFileSize = 0;
if (output.Open(outputFileName, CFile::modeWrite | CFile::shareDenyWrite | CFile::modeCreate))
{
// Process the output file
if ( myAtype==ARCHIVE_ZIP)
success = recoverZip(&temp, &output, NULL, filled, (temp.GetLength() == partFile->GetFileSize()));
else if(myAtype==ARCHIVE_RAR)
success = recoverRar(&temp, &output, NULL, filled);
else if(myAtype==ARCHIVE_ACE)
success = recoverAce(&temp, &output, NULL, filled);
ulTempFileSize = output.GetLength();
// Close output
output.Close();
}
// Close temp file
temp.Close();
// Remove temp file
if (!tempFileName.IsEmpty() )
CFile::Remove(tempFileName);
// Report success
if (success)
{
theApp.QueueLogLine(true, _T("%s \"%s\""), GetResString(IDS_RECOVERY_SUCCESSFUL), partFile->GetFileName());
theApp.QueueDebugLogLine(false, _T("Archive recovery: Part file size: %s, temp. archive file size: %s (%.1f%%)"), CastItoXBytes(partFile->GetFileSize()), CastItoXBytes(ulTempFileSize), partFile->GetFileSize() > (uint64)0 ? (ulTempFileSize * 100.0 / (uint64)partFile->GetFileSize()) : 0.0);
// Preview file if required
if (preview)
{
SHELLEXECUTEINFO SE;
memset(&SE,0,sizeof(SE));
SE.fMask = SEE_MASK_NOCLOSEPROCESS ;
SE.lpVerb = _T("open");
SE.lpFile = outputFileName;
SE.nShow = SW_SHOW;
SE.cbSize = sizeof(SE);
ShellExecuteEx(&SE);
if (SE.hProcess)
{
WaitForSingleObject(SE.hProcess, INFINITE);
CloseHandle(SE.hProcess);
}
CFile::Remove(outputFileName);
}
} else
CFile::Remove(outputFileName);
}
catch (CFileException* error){
error->Delete();
}
catch (...){
ASSERT(0);
}
return success;
}
bool CArchiveRecovery::recoverZip(CFile *zipInput, CFile *zipOutput, archiveScannerThreadParams_s* aitp ,
CTypedPtrList<CPtrList, Gap_Struct*> *filled, bool fullSize)
{
bool retVal = false;
long fileCount = 0;
try
{
CTypedPtrList<CPtrList, ZIP_CentralDirectory*>* centralDirectoryEntries;
if (aitp==NULL) {
centralDirectoryEntries= new CTypedPtrList<CPtrList, ZIP_CentralDirectory*>;
} else {
centralDirectoryEntries=aitp->ai->centralDirectoryEntries;
}
Gap_Struct *fill;
// If the central directory is intact this is simple
if (fullSize && readZipCentralDirectory(zipInput, centralDirectoryEntries, filled))
{
if (centralDirectoryEntries->GetCount() == 0)
{
if (aitp == NULL)
delete centralDirectoryEntries;
return false;
}
// if only read directory, return now
if (zipOutput==NULL) {
if (aitp == NULL) {
ASSERT(0); // FIXME
delete centralDirectoryEntries;
return false;
}
aitp->ai->bZipCentralDir = true;
return true;
}
ZIP_CentralDirectory *cdEntry;
POSITION pos = centralDirectoryEntries->GetHeadPosition();
bool deleteCD;
for (int i=centralDirectoryEntries->GetCount(); i>0; i--)
{
deleteCD = false;
cdEntry = centralDirectoryEntries->GetAt(pos);
uint32 lenEntry = sizeof(ZIP_Entry) + cdEntry->lenFilename + cdEntry->lenExtraField + cdEntry->lenCompressed;
if (IsFilled(cdEntry->relativeOffsetOfLocalHeader, cdEntry->relativeOffsetOfLocalHeader + lenEntry, filled))
{
zipInput->Seek(cdEntry->relativeOffsetOfLocalHeader, CFile::begin);
// Update offset
cdEntry->relativeOffsetOfLocalHeader = (UINT)zipOutput->GetPosition();
if (!processZipEntry(zipInput, zipOutput, lenEntry, NULL))
deleteCD = true;
}
else
deleteCD = true;
if (deleteCD)
{
delete [] cdEntry->filename;
if (cdEntry->lenExtraField > 0)
delete [] cdEntry->extraField;
if (cdEntry->lenComment > 0)
delete [] cdEntry->comment;
delete cdEntry;
POSITION del = pos;
centralDirectoryEntries->GetNext(pos);
centralDirectoryEntries->RemoveAt(del);
}
else
centralDirectoryEntries->GetNext(pos);
}
}
else // Have to scan the file the hard way
{
// Loop through filled areas of the file looking for entries
POSITION pos = filled->GetHeadPosition();
while (pos != NULL)
{
fill = filled->GetNext(pos);
uint32 filePos = (UINT)zipInput->GetPosition();
// The file may have been positioned to the next entry in ScanForMarker() or processZipEntry()
if (filePos > fill->end)
continue;
if (filePos < fill->start)
zipInput->Seek(fill->start, CFile::begin);
// If there is any problem, then don't bother checking the rest of this part
for (;;)
{
if (aitp && !aitp->m_bIsValid)
return 0;
// Scan for entry marker within this filled area
if (!scanForZipMarker(zipInput, aitp, (uint32)ZIP_LOCAL_HEADER_MAGIC, (UINT)(fill->end - zipInput->GetPosition() + 1)))
break;
if (zipInput->GetPosition() > fill->end)
break;
if (!processZipEntry(zipInput, zipOutput, (UINT)(fill->end - zipInput->GetPosition() + 1), centralDirectoryEntries))
break;
}
}
if (!zipOutput)
{
retVal = (centralDirectoryEntries->GetCount()>0 );
if (aitp == NULL)
delete centralDirectoryEntries;
return retVal;
}
}
// Remember offset before CD entries
uint32 startOffset = (UINT)zipOutput->GetPosition();
// Write all central directory entries
fileCount = centralDirectoryEntries->GetCount();
if (fileCount > 0)
{
ZIP_CentralDirectory *cdEntry;
POSITION pos = centralDirectoryEntries->GetHeadPosition();
while (pos != NULL)
{
cdEntry = centralDirectoryEntries->GetNext(pos);
writeUInt32(zipOutput, ZIP_CD_MAGIC);
writeUInt16(zipOutput, cdEntry->versionMadeBy);
writeUInt16(zipOutput, cdEntry->versionToExtract);
writeUInt16(zipOutput, cdEntry->generalPurposeFlag);
writeUInt16(zipOutput, cdEntry->compressionMethod);
writeUInt16(zipOutput, cdEntry->lastModFileTime);
writeUInt16(zipOutput, cdEntry->lastModFileDate);
writeUInt32(zipOutput, cdEntry->crc32);
writeUInt32(zipOutput, cdEntry->lenCompressed);
writeUInt32(zipOutput, cdEntry->lenUncompressed);
writeUInt16(zipOutput, cdEntry->lenFilename);
writeUInt16(zipOutput, cdEntry->lenExtraField);
writeUInt16(zipOutput, cdEntry->lenComment);
writeUInt16(zipOutput, 0); // Disk number start
writeUInt16(zipOutput, cdEntry->internalFileAttributes);
writeUInt32(zipOutput, cdEntry->externalFileAttributes);
writeUInt32(zipOutput, cdEntry->relativeOffsetOfLocalHeader);
zipOutput->Write(cdEntry->filename, cdEntry->lenFilename);
if (cdEntry->lenExtraField > 0)
zipOutput->Write(cdEntry->extraField, cdEntry->lenExtraField);
if (cdEntry->lenComment > 0)
zipOutput->Write(cdEntry->comment, cdEntry->lenComment);
delete [] cdEntry->filename;
if (cdEntry->lenExtraField > 0)
delete [] cdEntry->extraField;
if (cdEntry->lenComment > 0)
delete [] cdEntry->comment;
delete cdEntry;
}
// Remember offset before CD entries
uint32 endOffset = (UINT)zipOutput->GetPosition();
// Write end of central directory
writeUInt32(zipOutput, ZIP_END_CD_MAGIC);
writeUInt16(zipOutput, 0); // Number of this disk
writeUInt16(zipOutput, 0); // Number of the disk with the start of the central directory
writeUInt16(zipOutput, (uint16)fileCount);
writeUInt16(zipOutput, (uint16)fileCount);
writeUInt32(zipOutput, endOffset - startOffset);
writeUInt32(zipOutput, startOffset);
writeUInt16(zipOutput, (uint16)strlen(ZIP_COMMENT));
zipOutput->Write(ZIP_COMMENT, strlen(ZIP_COMMENT));
centralDirectoryEntries->RemoveAll();
}
if (aitp == NULL)
delete centralDirectoryEntries;
retVal = true;
}
catch (CFileException* error){
error->Delete();
}
catch (...){
ASSERT(0);
}
// Tell the user how many files were recovered
CString msg;
if (fileCount == 1)
msg = GetResString(IDS_RECOVER_SINGLE);
else
msg.Format(GetResString(IDS_RECOVER_MULTIPLE), fileCount);
theApp.QueueLogLine(true, _T("%s"), msg);
return retVal;
}
bool CArchiveRecovery::readZipCentralDirectory(CFile *zipInput, CTypedPtrList<CPtrList, ZIP_CentralDirectory*> *centralDirectoryEntries, CTypedPtrList<CPtrList, Gap_Struct*> *filled)
{
bool retVal = false;
try
{
// Ideally this zip file will not have a comment and the End-CD will be easy to find
zipInput->Seek(-22, CFile::end);
if (!(readUInt32(zipInput) == ZIP_END_CD_MAGIC))
{
// Have to look for it, comment could be up to 65535 chars but only try with less than 1k
zipInput->Seek(-1046, CFile::end);
if (!scanForZipMarker(zipInput, NULL, (uint32)ZIP_END_CD_MAGIC, 1046))
return false;
// Skip it again
readUInt32(zipInput);
}
// Found End-CD
// Only interested in offset of first CD
zipInput->Seek(12, CFile::current);
uint32 startOffset = readUInt32(zipInput);
if (!IsFilled(startOffset, (UINT)zipInput->GetLength(), filled))
return false;
// Goto first CD and start reading
zipInput->Seek(startOffset, CFile::begin);
ZIP_CentralDirectory *cdEntry;
while (readUInt32(zipInput) == ZIP_CD_MAGIC)
{
cdEntry = new ZIP_CentralDirectory;
cdEntry->versionMadeBy = readUInt16(zipInput);
cdEntry->versionToExtract = readUInt16(zipInput);
cdEntry->generalPurposeFlag = readUInt16(zipInput);
cdEntry->compressionMethod = readUInt16(zipInput);
cdEntry->lastModFileTime = readUInt16(zipInput);
cdEntry->lastModFileDate = readUInt16(zipInput);
cdEntry->crc32 = readUInt32(zipInput);
cdEntry->lenCompressed = readUInt32(zipInput);
cdEntry->lenUncompressed = readUInt32(zipInput);
cdEntry->lenFilename = readUInt16(zipInput);
cdEntry->lenExtraField = readUInt16(zipInput);
cdEntry->lenComment = readUInt16(zipInput);
cdEntry->diskNumberStart = readUInt16(zipInput);
cdEntry->internalFileAttributes = readUInt16(zipInput);
cdEntry->externalFileAttributes = readUInt32(zipInput);
cdEntry->relativeOffsetOfLocalHeader= readUInt32(zipInput);
if (cdEntry->lenFilename > 0)
{
cdEntry->filename = new BYTE[cdEntry->lenFilename];
zipInput->Read(cdEntry->filename, cdEntry->lenFilename);
}
if (cdEntry->lenExtraField > 0)
{
cdEntry->extraField = new BYTE[cdEntry->lenExtraField];
zipInput->Read(cdEntry->extraField, cdEntry->lenExtraField);
}
if (cdEntry->lenComment > 0)
{
cdEntry->comment = new BYTE[cdEntry->lenComment];
zipInput->Read(cdEntry->comment, cdEntry->lenComment);
}
centralDirectoryEntries->AddTail(cdEntry);
}
retVal = true;
}
catch (CFileException* error){
error->Delete();
}
catch (...){
ASSERT(0);
}
return retVal;
}
bool CArchiveRecovery::processZipEntry(CFile *zipInput, CFile *zipOutput, uint32 available, CTypedPtrList<CPtrList, ZIP_CentralDirectory*> *centralDirectoryEntries)
{
if (available < 26)
return false;
bool retVal = false;
long startOffset=0;
try
{
// Need to know where it started
if (zipOutput)
startOffset = (long)zipOutput->GetPosition();
else
startOffset = (long)zipInput->GetPosition();
// Entry format :
// 4 2 bytes Version needed to extract
// 6 2 bytes General purpose bit flag
// 8 2 bytes Compression method
// 10 2 bytes Last mod file time
// 12 2 bytes Last mod file date
// 14 4 bytes CRC-32
// 18 4 bytes Compressed size (n)
// 22 4 bytes Uncompressed size
// 26 2 bytes Filename length (f)
// 28 2 bytes Extra field length (e)
// (f)bytes Filename
// (e)bytes Extra field
// (n)bytes Compressed data
// Read header
if (readUInt32(zipInput) != ZIP_LOCAL_HEADER_MAGIC)
return false;
ZIP_Entry entry = {0};
entry.versionToExtract = readUInt16(zipInput);
entry.generalPurposeFlag = readUInt16(zipInput);
entry.compressionMethod = readUInt16(zipInput);
entry.lastModFileTime = readUInt16(zipInput);
entry.lastModFileDate = readUInt16(zipInput);
entry.crc32 = readUInt32(zipInput);
entry.lenCompressed = readUInt32(zipInput);
entry.lenUncompressed = readUInt32(zipInput);
entry.lenFilename = readUInt16(zipInput);
entry.lenExtraField = readUInt16(zipInput);
// Do some quick checks at this stage that data is looking ok
if ((entry.crc32 == 0) && (entry.lenCompressed == 0) && (entry.lenUncompressed == 0) && (entry.lenFilename != 0))
; // this is a directory entry
else if ((entry.crc32 == 0) || (entry.lenCompressed == 0) || (entry.lenUncompressed == 0) || (entry.lenFilename == 0))
return false;
// Is this entry complete
if ((entry.lenFilename + entry.lenExtraField +
((zipOutput!=NULL)?entry.lenCompressed:0)
) > (available - 26))
{
// Move the file pointer to the start of the next entry
zipInput->Seek((entry.lenFilename + entry.lenExtraField + entry.lenCompressed), CFile::current);
return false;
}
// Filename
if (entry.lenFilename > MAX_PATH)
return false; // Possibly corrupt, don't allocate lots of memory
entry.filename = new BYTE[entry.lenFilename];
if (zipInput->Read(entry.filename, entry.lenFilename) != entry.lenFilename)
{
delete [] entry.filename;
return false;
}
// Extra data
if (entry.lenExtraField > 0)
{
entry.extraField = new BYTE[entry.lenExtraField];
zipInput->Read(entry.extraField, entry.lenExtraField);
}
if (zipOutput) {
// Output
writeUInt32(zipOutput, ZIP_LOCAL_HEADER_MAGIC);
writeUInt16(zipOutput, entry.versionToExtract);
writeUInt16(zipOutput, entry.generalPurposeFlag);
writeUInt16(zipOutput, entry.compressionMethod);
writeUInt16(zipOutput, entry.lastModFileTime);
writeUInt16(zipOutput, entry.lastModFileDate);
writeUInt32(zipOutput, entry.crc32);
writeUInt32(zipOutput, entry.lenCompressed);
writeUInt32(zipOutput, entry.lenUncompressed);
writeUInt16(zipOutput, entry.lenFilename);
writeUInt16(zipOutput, entry.lenExtraField);
if (entry.lenFilename > 0)
zipOutput->Write(entry.filename, entry.lenFilename);
if (entry.lenExtraField > 0)
zipOutput->Write(entry.extraField, entry.lenExtraField);
// Read and write compressed data to avoid reading all into memory
uint32 written = 0;
BYTE buf[4096];
uint32 lenChunk = 4096;
while (written < entry.lenCompressed)
{
lenChunk = (entry.lenCompressed - written);
if (lenChunk > 4096)
lenChunk = 4096;
lenChunk = zipInput->Read(buf, lenChunk);
if (lenChunk == 0)
break;
written += lenChunk;
zipOutput->Write(buf, lenChunk);
}
zipOutput->Flush();
}
//Central directory:
if (centralDirectoryEntries != NULL)
{
ZIP_CentralDirectory *cdEntry = new ZIP_CentralDirectory;
cdEntry->header = ZIP_CD_MAGIC;
cdEntry->versionMadeBy = entry.versionToExtract;
cdEntry->versionToExtract = entry.versionToExtract;
cdEntry->generalPurposeFlag = entry.generalPurposeFlag;
cdEntry->compressionMethod = entry.compressionMethod;
cdEntry->lastModFileTime = entry.lastModFileTime;
cdEntry->lastModFileDate = entry.lastModFileDate;
cdEntry->crc32 = entry.crc32;
cdEntry->lenCompressed = entry.lenCompressed;
cdEntry->lenUncompressed = entry.lenUncompressed;
cdEntry->lenFilename = entry.lenFilename;
cdEntry->lenExtraField = entry.lenExtraField;
cdEntry->diskNumberStart = 0;
cdEntry->internalFileAttributes = 1;
cdEntry->externalFileAttributes = 0x81B60020;
cdEntry->relativeOffsetOfLocalHeader = startOffset;
cdEntry->filename = entry.filename;
if (entry.lenExtraField > 0)
cdEntry->extraField = entry.extraField;
cdEntry->lenComment = 0;
if (zipOutput!=NULL) {
cdEntry->lenComment = (uint16)strlen(ZIP_COMMENT);
cdEntry->comment = new BYTE[cdEntry->lenComment];
memcpy(cdEntry->comment, ZIP_COMMENT, cdEntry->lenComment);
}
centralDirectoryEntries->AddTail(cdEntry);
}
else
{
delete [] entry.filename;
if (entry.lenExtraField > 0)
delete [] entry.extraField;
}
retVal = true;
// skip data when reading directory only
if (zipOutput==NULL) {
// out of available data?
if ((entry.lenFilename + entry.lenExtraField + entry.lenCompressed ) > (available - 26))
return false;
zipInput->Seek( entry.lenCompressed, CFile::current);
}
}
catch (CFileException* error){
error->Delete();
}
catch (...){
ASSERT(0);
}
return retVal;
}
void CArchiveRecovery::DeleteMemory(ThreadParam *tp)
{
POSITION pos = tp->filled->GetHeadPosition();
while (pos != NULL)
delete tp->filled->GetNext(pos);
tp->filled->RemoveAll();
delete tp->filled;
delete tp;
}
bool CArchiveRecovery::CopyFile(CPartFile *partFile, CTypedPtrList<CPtrList, Gap_Struct*> *filled, CString tempFileName)
{
bool retVal = false;
try
{
CFile srcFile;
if (!srcFile.Open(partFile->GetFilePath(), CFile::modeRead | CFile::shareDenyNone))
return false;
// Open destination file and set length to last filled end position
CFile destFile;
destFile.Open(tempFileName, CFile::modeWrite | CFile::shareDenyWrite | CFile::modeCreate);
Gap_Struct *fill = filled->GetTail();
destFile.SetLength(fill->end);
BYTE buffer[4096];
uint32 read;
uint32 copied;
// Loop through filled areas and copy data
partFile->m_bPreviewing = true;
POSITION pos = filled->GetHeadPosition();
while (pos != NULL)
{
fill = filled->GetNext(pos);
copied = 0;
srcFile.Seek(fill->start, CFile::begin);
destFile.Seek(fill->start, CFile::begin);
while ((read = srcFile.Read(buffer, 4096)) > 0)
{
destFile.Write(buffer, read);
copied += read;
// Stop when finished fill (don't worry about extra)
if (fill->start + copied >= fill->end)
break;
}
}
destFile.Close();
srcFile.Close();
partFile->m_bPreviewing = false;
retVal = true;
}
catch (CFileException* error){
error->Delete();
}
catch (...){
ASSERT(0);
}
return retVal;
}
bool CArchiveRecovery::recoverRar(CFile *rarInput, CFile *rarOutput, archiveScannerThreadParams_s* aitp,
CTypedPtrList<CPtrList, Gap_Struct*> *filled)
{
bool retVal = false;
long fileCount = 0;
try
{
// Try to get file header and main header
//
bool bValidFileHeader = false;
bool bOldFormat = false;
bool bValidMainHeader = false;
BYTE fileHeader[7] = {0};
RARMAINHDR mainHeader = {0};
if (rarInput->Read(fileHeader, sizeof fileHeader) == sizeof fileHeader)
{
if (fileHeader[0] == 0x52) {
if (fileHeader[1] == 0x45 && fileHeader[2] ==0x7e && fileHeader[3] == 0x5e) {
bOldFormat = true;
bValidFileHeader = true;
}
else if (fileHeader[1] == 0x61 && fileHeader[2] == 0x72 && fileHeader[3] == 0x21 && fileHeader[4] == 0x1a && fileHeader[5] == 0x07 && fileHeader[6] == 0x00) {
bValidFileHeader = true;
}
}
if (bValidFileHeader && !bOldFormat)
{
WORD checkCRC;
if (rarInput->Read(&checkCRC, sizeof checkCRC) == sizeof checkCRC)
{
if (rarInput->Read(&mainHeader, sizeof mainHeader) == sizeof mainHeader)
{
if (mainHeader.type == 0x73)
{
DWORD crc = crc32(0, (Bytef*)&mainHeader, sizeof mainHeader);
for (UINT i = 0; i < sizeof(WORD) + sizeof(DWORD); i++)
{
BYTE ch;
if (rarInput->Read(&ch, sizeof ch) != sizeof ch)
break;
crc = crc32(crc, &ch, 1);
}
if (checkCRC == (WORD)crc)
bValidMainHeader = true;
}
}
}
}
rarInput->SeekToBegin();
}
static const BYTE start[] = {
// RAR file header
0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00,
// main header
0x08, 0x1A, // CRC
0x73, // type
0x02, 0x00, // flags
0x3B, 0x00, // size
0x00, 0x00, // AV
0x00, 0x00, // AV
0x00, 0x00, // AV
// main comment
0xCA, 0x44, // CRC
0x75, // type
0x00, 0x00, // flags
0x2E, 0x00, // size
0x12, 0x00, 0x14, 0x34, 0x2B,
0x4A, 0x08, 0x15, 0x48, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0A, 0x2B, 0xF9, 0x0E, 0xE2, 0xC1,
0x32, 0xFB, 0x9E, 0x04, 0x10, 0x50, 0xD7, 0xFE, 0xCD, 0x75, 0x87, 0x9C, 0x28, 0x85, 0xDF, 0xA3,
0x97, 0xE0 };
// If this is a 'solid' archive the chance to successfully decompress any entries gets higher,
// when we pass the 'solid' main header bit to the temp. archive.
BYTE start1[sizeof start];
memcpy(start1, start, sizeof start);
if (bValidFileHeader && bValidMainHeader && (mainHeader.flags & 0x0008/*MHD_SOLID*/)) {
start1[10] |= 8; /*MHD_SOLID*/
*((short*)&start1[7]) = (short)crc32(0, &start1[9], 11);
}
if (aitp)
aitp->ai->rarFlags=mainHeader.flags;
if (rarOutput)
rarOutput->Write(start1, sizeof(start1));
RAR_BlockFile *block;
// loop filled blocks
POSITION pos = filled->GetHeadPosition();
Gap_Struct *fill;
while (pos != NULL)
{
fill = filled->GetNext(pos);
rarInput->Seek(fill->start , CFile::begin);
while ((block = scanForRarFileHeader(rarInput, aitp, (fill->end - rarInput->GetPosition() ))) != NULL)
{
if (aitp){
aitp->ai->RARdir->AddTail(block);
if (!aitp->m_bIsValid)
return false;
}
if (rarOutput!=NULL && IsFilled((UINT)block->offsetData, (UINT)(block->offsetData + block->dataLength), filled))
{
// Don't include directories in file count
if ((block->HEAD_FLAGS & 0xE0) != 0xE0)
fileCount++;
if (rarOutput)
writeRarBlock(rarInput, rarOutput, block);
}
else
{
rarInput->Seek(block->offsetData + block->dataLength, CFile::begin);
}
if (aitp==NULL) {
delete [] block->FILE_NAME;
delete block;
}
if (rarInput->GetPosition() >=fill->end)
break;
}
}
retVal = true;
}
catch (CFileException* error){
error->Delete();
}
catch (...){
ASSERT(0);
}
// Tell the user how many files were recovered
if (aitp==NULL) {
CString msg;
if (fileCount == 1)
msg = GetResString(IDS_RECOVER_SINGLE);
else
msg.Format(GetResString(IDS_RECOVER_MULTIPLE), fileCount);
theApp.QueueLogLine(true, _T("%s"), msg);
}
return retVal;
}
bool CArchiveRecovery::IsFilled(uint32 start, uint32 end, CTypedPtrList<CPtrList, Gap_Struct*> *filled)
{
POSITION pos = filled->GetHeadPosition();
Gap_Struct *fill;
while (pos != NULL)
{
fill = filled->GetNext(pos);
if (fill->start > start)
return false;
if (fill->end >= end)
return true;
}
return false;
}
// This will find the marker in the file and leave it positioned at the position to read the marker again
bool CArchiveRecovery::scanForZipMarker(CFile *input, archiveScannerThreadParams_s* aitp, uint32 marker, uint32 available)
{
try
{
//uint32 originalOffset = input->GetPosition();
int lenChunk = 51200; // 50k buffer
BYTE chunk[51200];
BYTE *foundPos = NULL;
int pos = 0;
while ((available > 0) && ((lenChunk = input->Read(chunk, lenChunk)) > 0))
{
available -= lenChunk;
foundPos = &chunk[0];
// Move back one, will be incremented in loop
foundPos--;
while (foundPos != NULL)
{
if (aitp && !aitp->m_bIsValid)
return false;
// Find first matching byte
foundPos = (BYTE*)memchr( foundPos+1, (marker & 0xFF), (lenChunk - (foundPos+1 - (&chunk[0]))) );
if (foundPos == NULL)
break;
// Test for end of buffer
pos = foundPos - (&chunk[0]);
if ((pos + 3) > lenChunk)
{
// Re-read buffer starting from found first byte position
input->Seek(pos - lenChunk, CFile::current);
break;
}
if (aitp) {
ProcessProgress(aitp, input->GetPosition() );
}
// Check for other bytes
if (chunk[pos + 1] == ((marker >> 8) & 0xFF))
{
if (chunk[pos + 2] == ((marker >> 16) & 0xFF))
{
if (chunk[pos + 3] == ((marker >> 24) & 0xFF))
{
// Found it
input->Seek(pos - lenChunk, CFile::current);
return true;
}
}
}
}
}
}
catch (CFileException* error){
error->Delete();
}
catch (...){
ASSERT(0);
}
return false;
}
#define TESTCHUNKSIZE 51200 // 50k buffer
// This will find a file block in the file and leave it positioned at the end of the filename
RAR_BlockFile *CArchiveRecovery::scanForRarFileHeader(CFile *input, archiveScannerThreadParams_s* aitp, UINT64 available)
{
RAR_BlockFile *retVal = NULL;
try
{
UINT lenChunk;
BYTE chunk[TESTCHUNKSIZE];
BYTE *foundPos = NULL;
ULONGLONG foundOffset;
ULONGLONG chunkOffset;
UINT64 chunkstart;
uint16 headCRC;
BYTE checkCRC[sizeof(RARFILEHDR) + 8 + sizeof(DWORD)*2 + 512];
unsigned checkCRCsize = 0;
uint16 lenFileName;
BYTE *fileName;
uint32 crc;
while (available > 0)
{
chunkstart=input->GetPosition();
lenChunk = input->Read(chunk, (UINT)(min(available, TESTCHUNKSIZE)) );
if (lenChunk==0)
break;
available-=lenChunk;
foundPos = &chunk[0];
// Move back one, will be incremented in loop
foundPos--;
while (foundPos != NULL)
{
if (aitp && !aitp->m_bIsValid)
return false;
// Find rar head block marker
foundPos = (BYTE*)memchr( foundPos+1, RAR_HEAD_FILE, (lenChunk - (foundPos+1 - (&chunk[0])) ) );
if (foundPos == NULL)
break;
chunkOffset = foundPos - (&chunk[0]);
foundOffset = chunkstart + chunkOffset;
if (aitp) {