1
// ZipCentralDir.cpp: implementation of the CZipCentralDir class.
3
////////////////////////////////////////////////////////////////////////////////
4
// Copyright (C) 2000 Tadeusz Dracz.
5
// For conditions of distribution and use, see copyright notice in ZipArchive.h
6
////////////////////////////////////////////////////////////////////////////////
10
#include "ZipCentralDir.h"
11
#include "ZipArchive.h"
22
bool CreateMapping(HANDLE hFile)
24
m_hFileMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE,
25
0, 0, _T("ZipArchive Mapping File"));
28
// Get pointer to memory representing file
29
m_pFileMap = MapViewOfFile(m_hFileMap, FILE_MAP_WRITE, 0, 0, 0);
30
return (m_pFileMap != NULL);
36
UnmapViewOfFile(m_pFileMap);
41
CloseHandle(m_hFileMap);
52
#define ZIPCENTRALDIRSIZE 22
54
//////////////////////////////////////////////////////////////////////
55
// Construction/Destruction
56
char CZipCentralDir::m_gszSignature[] = {0x50, 0x4b, 0x05, 0x06};
57
CZipCentralDir::CZipCentralDir()
59
m_bConvertAfterOpen = true;
60
m_bFindFastEnabled = false;
63
m_iBufferSize = 32768;
67
void CZipCentralDir::Init()
70
m_uBytesBeforeZip = m_uCentrDirPos = 0;
72
m_pszComment.Release();
75
CZipCentralDir::~CZipCentralDir()
80
void CZipCentralDir::Read()
84
m_uCentrDirPos = Locate();
85
m_pStorage->m_pFile->Seek(m_uCentrDirPos, CFile::begin);
86
CZipAutoBuffer buf(ZIPCENTRALDIRSIZE);
87
DWORD uRead = m_pStorage->m_pFile->Read(buf, ZIPCENTRALDIRSIZE );
88
if (uRead != ZIPCENTRALDIRSIZE)
89
ThrowError(ZIP_BADZIPFILE);
90
memcpy(&m_szSignature, buf, 4);
91
memcpy(&m_uThisDisk, buf + 4, 2);
92
memcpy(&m_uDiskWithCD, buf + 6, 2);
93
memcpy(&m_uDiskEntriesNo, buf + 8, 2);
94
memcpy(&m_uEntriesNumber, buf + 10, 2);
95
memcpy(&m_uSize, buf + 12, 4);
96
memcpy(&m_uOffset, buf + 16, 4);
97
memcpy(&uCommentSize, buf + 20, 2);
101
m_pStorage->UpdateSpanMode(m_uThisDisk);
102
// if m_uThisDisk is not zero, it is enough to say that it is multi archive
103
ASSERT((!m_uThisDisk && (m_uEntriesNumber == m_uDiskEntriesNo) && !m_uDiskWithCD) || m_uThisDisk);
107
if (!m_pStorage->IsSpanMode() && ((DWORD)m_uCentrDirPos < m_uOffset + m_uSize))
108
ThrowError(ZIP_BADZIPFILE);
112
m_pszComment.Allocate(uCommentSize);
113
uRead = m_pStorage->m_pFile->Read(m_pszComment, uCommentSize);
114
if (uRead != uCommentSize)
115
ThrowError(ZIP_BADZIPFILE);
118
m_uBytesBeforeZip = m_pStorage->IsSpanMode() ? 0 : m_uCentrDirPos - m_uSize - m_uOffset;
120
if ((!m_uSize && m_uEntriesNumber) || (!m_uEntriesNumber && m_uSize))
121
ThrowError(ZIP_BADZIPFILE);
124
m_pStorage->ChangeDisk(m_uDiskWithCD);
132
// return the location of the beginning of the "end" record in the file
133
DWORD CZipCentralDir::Locate()
136
// maximum size of end of central dir record
137
long uMaxRecordSize = 0xffff + ZIPCENTRALDIRSIZE;
138
DWORD uFileSize = m_pStorage->m_pFile->GetLength();
140
if ((DWORD)uMaxRecordSize > uFileSize)
141
uMaxRecordSize = uFileSize;
143
CZipAutoBuffer buf(m_iBufferSize);
148
while (uPosInFile < uMaxRecordSize)
150
uPosInFile = uRead + m_iBufferSize;
151
if (uPosInFile > uMaxRecordSize)
152
uPosInFile = uMaxRecordSize;
154
int iToRead = uPosInFile - uRead;
156
m_pStorage->m_pFile->Seek(-uPosInFile, CFile::end);
157
int iActuallyRead = m_pStorage->m_pFile->Read(buf, iToRead);
158
if (iActuallyRead != iToRead)
159
ThrowError(ZIP_BADZIPFILE);
160
// search from the very last bytes to prevent an error if inside archive
161
// there are packed other arhives
162
for (int i = iToRead - 4; i >=0 ; i--)
163
if (!memcmp((char*)buf + i, m_gszSignature, 4))
164
return uFileSize - (uPosInFile - i);
166
uRead += iToRead - 3;
170
ThrowError(ZIP_CDIR_NOTFOUND);
174
void CZipCentralDir::ThrowError(int err)
176
AfxThrowZipException(err, m_pStorage->m_pFile->GetFilePath());
180
void CZipCentralDir::ReadHeaders()
182
m_pStorage->m_pFile->Seek(m_uOffset + m_uBytesBeforeZip, CFile::begin);
184
for (int i = 0; i < m_uEntriesNumber; i++)
186
CZipFileHeader* pHeader = new CZipFileHeader;
187
m_headers.Add(pHeader); // bezpoļæ½rednio nastļæ½puje w razie wyjļæ½tku
189
if (!pHeader->Read(m_pStorage))
190
ThrowError(ZIP_BADZIPFILE);
191
ConvertFileName(true, true, pHeader);
193
if (m_bFindFastEnabled)
194
BuildFindFastArray();
198
// remove all headers from the central dir
199
void CZipCentralDir::Clear(bool bEverything)
201
m_pOpenedFile = NULL;
202
m_pLocalExtraField.Release();
207
m_findarray.RemoveAll();
208
m_pszComment.Release();
214
bool CZipCentralDir::IsValidIndex(WORD uIndex)
217
bool ret = uIndex < m_headers.GetSize();
220
TRACE(_T("Not a valid index.\n"));
225
// open the file for extracting
226
void CZipCentralDir::OpenFile(WORD uIndex)
228
WORD uLocalExtraFieldSize;
229
m_pOpenedFile = m_headers[uIndex];
230
m_pStorage->ChangeDisk(m_pOpenedFile->m_uDiskStart);
231
m_pStorage->m_pFile->Seek(m_pOpenedFile->m_uOffset + m_uBytesBeforeZip, CFile::begin);
232
if (!m_pOpenedFile->ReadLocal(m_pStorage, uLocalExtraFieldSize))
233
ThrowError(ZIP_BADZIPFILE);
236
m_pLocalExtraField.Release(); // just in case
237
if (uLocalExtraFieldSize)
239
int iCurrDsk = m_pStorage->GetCurrentDisk();
240
m_pLocalExtraField.Allocate(uLocalExtraFieldSize);
241
m_pStorage->Read(m_pLocalExtraField, uLocalExtraFieldSize, true);
242
if (m_pStorage->GetCurrentDisk() != iCurrDsk)
243
ThrowError(ZIP_BADZIPFILE);
248
void CZipCentralDir::CloseFile()
252
m_pLocalExtraField.Release();
253
if (m_pOpenedFile->IsDataDescr())
255
CZipAutoBuffer buf(12);
256
m_pStorage->Read(buf, 4, false);
257
// in span mode, files that are divided between disks have bit 3 of flag set
258
// which tell about the presence of the data descriptor after the compressed data
259
// This signature may be in the disk spanning archive that is one volume only
260
// (it is detected as a non disk spanning archive)
261
if (memcmp(buf, CZipStorage::m_gszExtHeaderSignat, 4) != 0) // there is no signature
262
m_pStorage->m_pFile->Seek(-4, CFile::current);
265
m_pStorage->Read(buf, 12, false);
266
if (!m_pOpenedFile->CheckCrcAndSizes(buf))
267
ThrowError(ZIP_BADZIPFILE);
269
m_pOpenedFile = NULL;
272
// add new header using the argument as a template
273
void CZipCentralDir::AddNewFile(CZipFileHeader & header)
275
CZipFileHeader* pHeader = new CZipFileHeader(header);
276
m_pOpenedFile = pHeader;
277
m_headers.Add(pHeader);
278
if (m_bFindFastEnabled)
279
InsertFindFastElement(pHeader, WORD(m_headers.GetSize() - 1)); // GetSize IS > 0, 'cos we've just added a header
281
m_pStorage->m_pFile->SeekToEnd();
284
// called during adding or deleting files; remove the central dir from the disk
285
void CZipCentralDir::RemoveFromDisk()
289
ASSERT(!m_pStorage->IsSpanMode()); // you can't add files to the existing disk span archive or to delete them from it
290
m_pStorage->m_pFile->SetLength(m_uBytesBeforeZip + m_uOffset);
296
void CZipCentralDir::CloseNewFile()
298
CZipAutoBuffer buf(12 + 4);
300
bool bIsSpan = m_pStorage->IsSpanMode() != 0;
301
bool bEncrypted = m_pOpenedFile->IsEncrypted();
302
if (m_pOpenedFile->IsDataDescr())
304
if (bIsSpan || bEncrypted)
306
memcpy(buf, m_pStorage->m_gszExtHeaderSignat, 4);
310
else /*if (!IsSpan)*/
312
ASSERT(!bIsSpan && !bEncrypted);
314
m_pStorage->m_pFile->Seek(m_pOpenedFile->m_uOffset + 14, CFile::begin);
315
// we don't have to restore the pointer, because before adding a new file,
316
// the pointer is moved to the end
319
m_pOpenedFile->GetCrcAndSizes(buf + iToWrite);
322
// offset set during writting the local header
323
m_pOpenedFile->m_uOffset -= m_uBytesBeforeZip;
325
// write the data descriptor and a disk spanning signature at once
326
m_pStorage->Write(buf, iToWrite, true);
327
if (!bIsSpan && bEncrypted)
329
// write the information to the local header too
331
m_pStorage->m_pFile->Seek(m_pOpenedFile->m_uOffset + 14, CFile::begin);
332
m_pStorage->Write(buf + 4, 12, true);
338
m_pOpenedFile = NULL;
342
void CZipCentralDir::Write()
346
if (!m_pStorage->IsSpanMode())
349
m_pStorage->m_pFile->SeekToEnd();
351
m_uEntriesNumber = (WORD)m_headers.GetSize();
353
bool bDontAllowDiskChange = false;
354
// if there is a disk spanning archive in creation and it is only one-volume,
355
// (current disk is 0 so far, no bytes has been written so we know they are
356
// all in the buffer) make sure that it will be after writting central dir
357
// and make it a non disk spanning archive
358
if (m_pStorage->IsSpanMode() && m_pStorage->GetCurrentDisk() == 0)
360
DWORD uVolumeFree = m_pStorage->VolumeLeft();
361
// calculate the size of data descriptors already in the buffer or on the disk
362
// (they will be removed in the non disk spanning archive):
363
// multi span signature at the beginnig (4 bytes) + the size of the data
364
// descr. for each file (multi span signature + 12 bytes data)
365
// the count of bytes to add: central dir size - total to remove;
366
DWORD uToGrow = GetSize(true) - (4 + m_uEntriesNumber * (4 + 12));
367
if (uVolumeFree >= uToGrow)
368
// lets make sure it will be one-disk archive
370
// can the operation be done only in the buffer?
371
if (!m_pStorage->m_iBytesWritten && // no bytes on the disk yet
372
(m_pStorage->GetFreeInBuffer() >= uToGrow)) // is the buffer big enough?
374
RemoveDataDescr(true);
375
bDontAllowDiskChange = true; // if the disk change occurs somehow, we'll throw an error later
380
m_pStorage->m_pFile->Flush();
381
if (RemoveDataDescr(false))
382
bDontAllowDiskChange = true; // if the disk change occurs somehow, we'll throw an error later
388
m_uThisDisk = (WORD)m_pStorage->GetCurrentDisk();
389
DWORD uSize = WriteCentralEnd();
390
if (bDontAllowDiskChange && (m_pStorage->GetCurrentDisk() != 0))
391
ThrowError(ZIP_BADZIPFILE);
392
// if after adding a central directory there is a disk change,
393
// update the information and write it again
394
if (m_uThisDisk != m_pStorage->GetCurrentDisk())
396
m_uThisDisk = (WORD)m_pStorage->GetCurrentDisk();
397
if (m_uEntriesNumber)
399
m_uDiskEntriesNo = 0;
403
m_uDiskWithCD = m_uThisDisk;
407
if (m_pStorage->m_uBytesInWriteBuffer >= uSize)
408
// if the data is still in the buffer, simply remove it
409
m_pStorage->m_uBytesInWriteBuffer -= uSize;
413
m_pStorage->m_iBytesWritten -= uSize;
414
m_pStorage->m_pFile->SeekToBegin();
422
void CZipCentralDir::WriteHeaders()
424
m_uDiskEntriesNo = 0;
425
m_uDiskWithCD = (WORD)m_pStorage->GetCurrentDisk();
426
m_uOffset = m_pStorage->GetPosition() - m_uBytesBeforeZip;
427
if (!m_uEntriesNumber)
430
WORD iDisk = m_uDiskWithCD;
431
for (int i = 0; i < m_uEntriesNumber; i++)
433
CZipFileHeader* pHeader = m_headers[i];
434
ConvertFileName(false, true, pHeader);
435
m_uSize += pHeader->Write(m_pStorage);
436
if (m_pStorage->GetCurrentDisk() != iDisk)
438
m_uDiskEntriesNo = 1;
439
iDisk = (WORD)m_pStorage->GetCurrentDisk();
440
// update the information about the offset and starting disk if the
441
// first header was written on the new disk
445
m_uDiskWithCD = iDisk;
453
DWORD CZipCentralDir::WriteCentralEnd()
455
DWORD uSize = GetSize();
456
CZipAutoBuffer buf(uSize);
457
WORD uCommentSize = (WORD)m_pszComment.GetSize();
458
memcpy(buf, m_gszSignature, 4);
459
memcpy(buf + 4, &m_uThisDisk, 2);
460
memcpy(buf + 6, &m_uDiskWithCD, 2);
461
memcpy(buf + 8, &m_uDiskEntriesNo, 2);
462
memcpy(buf + 10, &m_uEntriesNumber, 2);
463
memcpy(buf + 12, &m_uSize, 4);
464
memcpy(buf + 16, &m_uOffset, 4);
465
memcpy(buf + 20, &uCommentSize, 2);
466
memcpy(buf + 22, m_pszComment, uCommentSize);
467
m_pStorage->Write(buf, uSize, true);
472
void CZipCentralDir::RemoveFile(WORD uIndex)
474
CZipFileHeader* pHeader = m_headers[uIndex];
475
if (m_bFindFastEnabled)
477
int i = FindFileNameIndex(pHeader->GetFileName(), true);
479
int uIndex = m_findarray[i].m_uIndex;
480
m_findarray.RemoveAt(i);
481
// shift down the indexes
482
for (int j = 0; j < m_findarray.GetSize(); j++)
484
if (m_findarray[j].m_uIndex > uIndex)
485
m_findarray[j].m_uIndex--;
489
m_headers.RemoveAt(uIndex);
493
DWORD CZipCentralDir::GetSize(bool bWhole)
498
for (int i = 0; i < m_headers.GetSize(); i++)
499
uHeaders += m_headers[i]->GetSize();
501
return ZIPCENTRALDIRSIZE + m_pszComment.GetSize() + uHeaders;
504
// remove data descriptors from the write buffer in the disk spanning volume
505
// that is one-disk only (do not remove from password encrypted files)
506
bool CZipCentralDir::RemoveDataDescr(bool bFromBuffer)
513
uSize = m_pStorage->m_uBytesInWriteBuffer;
514
pFile = m_pStorage->m_pWriteBuffer;
518
uSize = m_pStorage->m_pFile->GetLength();
519
if (!ah.CreateMapping((HANDLE)m_pStorage->m_pFile->m_hFile))
521
pFile = (char*)ah.m_pFileMap;
524
DWORD uOffsetToChange = 4;
526
DWORD uPosInBuffer = 0;
527
DWORD uExtraHeaderLen;
528
// this will work providing the order in the m_headers is the same as
530
for (int i = 0; i < m_headers.GetSize(); i++)
532
// update the flag value in the local and central header
533
// int uDataDescr = (m_headers[i]->m_uFlag & 8) ? (4 + 12) : 0;
535
CZipFileHeader* pHeader = m_headers[i];
538
char* pSour = pFile + pHeader->m_uOffset;
540
if (!pHeader->IsEncrypted())
542
// removing data descriptor
543
pHeader->m_uFlag &= ~8;
544
// update local header:
545
// write modified flag in the local header
546
memcpy(pSour + 6, &pHeader->m_uFlag, 2);
547
uExtraHeaderLen = 4/*ext. header signature*/ + 12/*data descriptor*/;
550
// do not remove data descriptors from encrypted files
553
// update crc32 and sizes' values
554
pHeader->GetCrcAndSizes(pSour+ 14);
556
uToCopy = (i == (m_headers.GetSize() - 1) ? uSize : m_headers[i + 1]->m_uOffset)
557
- pHeader->m_uOffset - uExtraHeaderLen;
559
memmove(pFile + uPosInBuffer, pSour, uToCopy);
561
uPosInBuffer += uToCopy;
562
pHeader->m_uOffset -= uOffsetToChange;
563
uOffsetToChange += uExtraHeaderLen;
567
m_pStorage->m_uBytesInWriteBuffer = uPosInBuffer;
570
m_pStorage->m_iBytesWritten = uPosInBuffer;
572
m_pStorage->m_pFile->SetLength(uPosInBuffer);
577
void CZipCentralDir::RemoveHeaders()
579
for (int i = 0; i < m_headers.GetSize(); i++)
581
m_headers.RemoveAll();
584
void CZipCentralDir::ConvertAll()
586
ASSERT(!m_bConvertAfterOpen);
587
for (int i = 0; i < m_headers.GetSize(); i++)
588
ConvertFileName(true, false, m_headers[i]);
589
m_bConvertAfterOpen = true;
593
void CZipCentralDir::BuildFindFastArray()
595
m_findarray.RemoveAll();// just in case
596
for (int i = 0; i < m_headers.GetSize(); i++)
597
InsertFindFastElement(m_headers[i], (WORD)i);
600
void CZipCentralDir::InsertFindFastElement(CZipFileHeader* pHeader, WORD uIndex)
602
CString fileName = pHeader->GetFileName();
605
int iSize = m_findarray.GetSize();
607
// Our initial binary search range encompasses the entire array of filenames:
611
// Keep halving our search range until we find the right place
612
// to insert the new element:
613
while ( start < end )
615
// Find the midpoint of the search range:
616
int midpoint = ( start + end ) / 2;
618
// Compare the filename with the filename at the midpoint of the current search range:
619
int result = CompareElement(fileName, (WORD)midpoint, true);
621
// If our filename is larger, it must fall in the first half of the search range:
627
// If it's smaller, it must fall in the last half:
628
else if ( result < 0 )
630
start = midpoint + 1;
633
// If they're equal, we can go ahead and insert here:
636
start = midpoint; break;
639
m_findarray.InsertAt(start, CZipFindFast(pHeader, WORD(uIndex == -1 ? iSize : uIndex /* just in case */)));
642
int CZipCentralDir::FindFileNameIndex(LPCTSTR lpszFileName, bool bCaseSensitive)
645
int end = m_findarray.GetUpperBound();
647
// Keep halving our search range until we find the given element:
648
while ( start <= end )
650
// Find the midpoint of the search range:
651
int midpoint = ( start + end ) / 2;
653
// Compare the given filename with the filename at the midpoint of the search range:
654
int result = CompareElement(lpszFileName, (WORD)midpoint, bCaseSensitive);
656
// If our filename is smaller, it must fall in the first half of the search range:
662
// If it's larger, it must fall in the last half:
663
else if ( result < 0 )
665
start = midpoint + 1;
668
// If they're equal, return the result: