Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ZipIn.cpp « Zip « Archive « 7zip - github.com/kornelski/7z.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 59f1e0aefb23309932fdcd5be762bc64f4ee4668 (plain)
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
// Archive/ZipIn.cpp

#include "StdAfx.h"

#include "ZipIn.h"
#include "Windows/Defs.h"
#include "Common/StringConvert.h"
#include "Common/DynamicBuffer.h"
#include "../../Common/LimitedStreams.h"
#include "../../Common/StreamUtils.h"

namespace NArchive {
namespace NZip {
 
// static const char kEndOfString = '\0';
  
bool CInArchive::Open(IInStream *inStream, const UInt64 *searchHeaderSizeLimit)
{
  m_Stream = inStream;
  if(m_Stream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition) != S_OK)
    return false;
  m_Position = m_StreamStartPosition;
  return FindAndReadMarker(searchHeaderSizeLimit);
}

void CInArchive::Close()
{
  m_Stream.Release();
}

//////////////////////////////////////
// Markers

static inline bool TestMarkerCandidate(const Byte *p, UInt32 &value)
{
  value = p[0] | (((UInt32)p[1]) << 8) | (((UInt32)p[2]) << 16) | (((UInt32)p[3]) << 24);
  return (value == NSignature::kLocalFileHeader) ||
    (value == NSignature::kEndOfCentralDir);
}

bool CInArchive::FindAndReadMarker(const UInt64 *searchHeaderSizeLimit)
{
  m_ArchiveInfo.Clear();
  m_ArchiveInfo.StartPosition = 0;
  m_Position = m_StreamStartPosition;
  if(m_Stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL) != S_OK)
    return false;

  Byte marker[NSignature::kMarkerSize];
  UInt32 processedSize; 
  ReadBytes(marker, NSignature::kMarkerSize, &processedSize);
  if(processedSize != NSignature::kMarkerSize)
    return false;
  if (TestMarkerCandidate(marker, m_Signature))
    return true;

  CByteDynamicBuffer dynamicBuffer;
  static const UInt32 kSearchMarkerBufferSize = 0x10000;
  dynamicBuffer.EnsureCapacity(kSearchMarkerBufferSize);
  Byte *buffer = dynamicBuffer;
  UInt32 numBytesPrev = NSignature::kMarkerSize - 1;
  memmove(buffer, marker + 1, numBytesPrev);
  UInt64 curTestPos = m_StreamStartPosition + 1;
  while(true)
  {
    if (searchHeaderSizeLimit != NULL)
      if (curTestPos - m_StreamStartPosition > *searchHeaderSizeLimit)
        return false;
    UInt32 numReadBytes = kSearchMarkerBufferSize - numBytesPrev;
    ReadBytes(buffer + numBytesPrev, numReadBytes, &processedSize);
    UInt32 numBytesInBuffer = numBytesPrev + processedSize;
    if (numBytesInBuffer < NSignature::kMarkerSize)
      return false;
    UInt32 numTests = numBytesInBuffer - NSignature::kMarkerSize + 1;
    for(UInt32 pos = 0; pos < numTests; pos++, curTestPos++)
    { 
      if (TestMarkerCandidate(buffer + pos, m_Signature))
      {
        m_ArchiveInfo.StartPosition = curTestPos;
        m_Position = curTestPos + NSignature::kMarkerSize;
        if(m_Stream->Seek(m_Position, STREAM_SEEK_SET, NULL) != S_OK)
          return false;
        return true;
      }
    }
    numBytesPrev = numBytesInBuffer - numTests;
    memmove(buffer, buffer + numTests, numBytesPrev);
  }
}

HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 *processedSize)
{
  UInt32 realProcessedSize;
  HRESULT result = ReadStream(m_Stream, data, size, &realProcessedSize);
  if(processedSize != NULL)
    *processedSize = realProcessedSize;
  m_Position += realProcessedSize;
  return result;
}

void CInArchive::IncreaseRealPosition(UInt64 addValue)
{
  if(m_Stream->Seek(addValue, STREAM_SEEK_CUR, &m_Position) != S_OK)
    throw CInArchiveException(CInArchiveException::kSeekStreamError);
}

bool CInArchive::ReadBytesAndTestSize(void *data, UInt32 size)
{
  UInt32 realProcessedSize;
  if(ReadBytes(data, size, &realProcessedSize) != S_OK)
    throw CInArchiveException(CInArchiveException::kReadStreamError);
  return (realProcessedSize == size);
}

void CInArchive::SafeReadBytes(void *data, UInt32 size)
{
  if(!ReadBytesAndTestSize(data, size))
    throw CInArchiveException(CInArchiveException::kUnexpectedEndOfArchive);
}

void CInArchive::ReadBuffer(CByteBuffer &buffer, UInt32 size)
{
  buffer.SetCapacity(size);
  if (size > 0)
    SafeReadBytes(buffer, size);
}

Byte CInArchive::ReadByte()
{
  Byte b;
  SafeReadBytes(&b, 1);
  return b;
}

UInt16 CInArchive::ReadUInt16()
{
  UInt16 value = 0;
  for (int i = 0; i < 2; i++)
    value |= (((UInt16)ReadByte()) << (8 * i));
  return value;
}

UInt32 CInArchive::ReadUInt32()
{
  UInt32 value = 0;
  for (int i = 0; i < 4; i++)
    value |= (((UInt32)ReadByte()) << (8 * i));
  return value;
}

UInt64 CInArchive::ReadUInt64()
{
  UInt64 value = 0;
  for (int i = 0; i < 8; i++)
    value |= (((UInt64)ReadByte()) << (8 * i));
  return value;
}

bool CInArchive::ReadUInt32(UInt32 &value)
{
  value = 0;
  for (int i = 0; i < 4; i++)
  {
    Byte b;
    if (!ReadBytesAndTestSize(&b, 1))
      return false;
    value |= (UInt32(b) << (8 * i));
  }
  return true;
}


AString CInArchive::ReadFileName(UInt32 nameSize)
{
  if (nameSize == 0)
    return AString();
  SafeReadBytes(m_NameBuffer.GetBuffer(nameSize), nameSize);
  m_NameBuffer.ReleaseBuffer(nameSize);
  return m_NameBuffer;
}

void CInArchive::GetArchiveInfo(CInArchiveInfo &archiveInfo) const
{
  archiveInfo = m_ArchiveInfo;
}

void CInArchive::ThrowIncorrectArchiveException()
{
  throw CInArchiveException(CInArchiveException::kIncorrectArchive);
}

static UInt32 GetUInt32(const Byte *data)
{
  return 
      ((UInt32)(Byte)data[0]) |
      (((UInt32)(Byte)data[1]) << 8) |
      (((UInt32)(Byte)data[2]) << 16) |
      (((UInt32)(Byte)data[3]) << 24);
}


void CInArchive::ReadExtra(UInt32 extraSize, CExtraBlock &extraBlock, 
    UInt64 &unpackSize, UInt64 &packSize, UInt64 &localHeaderOffset, UInt32 &diskStartNumber)
{
  extraBlock.Clear();
  UInt32 remain = extraSize;
  while(remain >= 4)
  {
    CExtraSubBlock subBlock;
    subBlock.ID = ReadUInt16();
    UInt32 dataSize = ReadUInt16();
    remain -= 4;
    if (dataSize > remain) // it's bug
      dataSize = remain;
    if (subBlock.ID == 0x1)
    {
      if (unpackSize == 0xFFFFFFFF)
      {
        if (dataSize < 8)
          break;
        unpackSize = ReadUInt64();
        remain -= 8;
        dataSize -= 8;
      }
      if (packSize == 0xFFFFFFFF)
      {
        if (dataSize < 8)
          break;
        packSize = ReadUInt64();
        remain -= 8;
        dataSize -= 8;
      }
      if (localHeaderOffset == 0xFFFFFFFF)
      {
        if (dataSize < 8)
          break;
        localHeaderOffset = ReadUInt64();
        remain -= 8;
        dataSize -= 8;
      }
      if (diskStartNumber == 0xFFFF)
      {
        if (dataSize < 4)
          break;
        diskStartNumber = ReadUInt32();
        remain -= 4;
        dataSize -= 4;
      }
      for (UInt32 i = 0; i < dataSize; i++)
        ReadByte();
    }
    else
    {
      ReadBuffer(subBlock.Data, dataSize);
      extraBlock.SubBlocks.Add(subBlock);
    }
    remain -= dataSize;
  }
  IncreaseRealPosition(remain);
}

HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items, CProgressVirt *progress)
{
  // m_Signature must be kLocalFileHeaderSignature or
  // kEndOfCentralDirSignature
  // m_Position points to next byte after signature

  items.Clear();

  if (progress != 0)
  {
    UInt64 numItems = items.Size();
    RINOK(progress->SetCompleted(&numItems));
  }

  while(m_Signature == NSignature::kLocalFileHeader)
  {
    // FSeek points to next byte after signature
    // NFileHeader::CLocalBlock localHeader;
    CItemEx item;
    item.LocalHeaderPosition = m_Position - m_StreamStartPosition - 4; // points to signature;
    
    // SafeReadBytes(&localHeader, sizeof(localHeader));

    item.ExtractVersion.Version = ReadByte();
    item.ExtractVersion.HostOS = ReadByte();
    item.Flags = ReadUInt16() & NFileHeader::NFlags::kUsedBitsMask; 
    item.CompressionMethod = ReadUInt16();
    item.Time =  ReadUInt32();
    item.FileCRC = ReadUInt32();
    item.PackSize = ReadUInt32();
    item.UnPackSize = ReadUInt32();
    UInt32 fileNameSize = ReadUInt16();
    item.LocalExtraSize = ReadUInt16();
    item.Name = ReadFileName(fileNameSize);
    /*
    if (!NItemName::IsNameLegal(item.Name))
      ThrowIncorrectArchiveException();
    */

    item.FileHeaderWithNameSize = 4 + 
        NFileHeader::kLocalBlockSize + fileNameSize;

    // IncreaseRealPosition(item.LocalExtraSize);
    if (item.LocalExtraSize > 0)
    {
      UInt64 localHeaderOffset = 0;
      UInt32 diskStartNumber = 0;
      CExtraBlock extraBlock;
      ReadExtra(item.LocalExtraSize, extraBlock, item.UnPackSize, item.PackSize, 
          localHeaderOffset, diskStartNumber);
    }

    if (item.HasDescriptor())
    {
      const int kBufferSize = (1 << 12);
      Byte buffer[kBufferSize];

      UInt32 numBytesInBuffer = 0;
      UInt32 packedSize = 0;

      bool descriptorWasFound = false;
      while (true)
      {
        UInt32 processedSize;
        RINOK(ReadBytes(buffer + numBytesInBuffer, 
            kBufferSize - numBytesInBuffer, &processedSize));
        numBytesInBuffer += processedSize;
        if (numBytesInBuffer < NFileHeader::kDataDescriptorSize)
          ThrowIncorrectArchiveException();
        UInt32 i;
        for (i = 0; i <= numBytesInBuffer - NFileHeader::kDataDescriptorSize; i++)
        {
          // descriptorSignature field is Info-ZIP's extension 
          // to Zip specification.
          UInt32 descriptorSignature = GetUInt32(buffer + i);

          // !!!! It must be fixed for Zip64 archives
          UInt32 descriptorPackSize = GetUInt32(buffer + i + 8);
          if (descriptorSignature== NSignature::kDataDescriptor &&
            descriptorPackSize == packedSize + i)
          {
            descriptorWasFound = true;
            item.FileCRC = GetUInt32(buffer + i + 4);
            item.PackSize = descriptorPackSize;
            item.UnPackSize = GetUInt32(buffer + i + 12);
            IncreaseRealPosition(Int64(Int32(0 - (numBytesInBuffer - i - 
                NFileHeader::kDataDescriptorSize))));
            break;
          };
        }
        if (descriptorWasFound)
          break;
        packedSize += i;
        int j;
        for (j = 0; i < numBytesInBuffer; i++, j++)
          buffer[j] = buffer[i];    
        numBytesInBuffer = j;
      }
    }
    else
      IncreaseRealPosition(item.PackSize);

    items.Add(item);
    if (progress != 0)
    {
      UInt64 numItems = items.Size();
      RINOK(progress->SetCompleted(&numItems));
    }
    if (!ReadUInt32(m_Signature))
      break;
  }
  UInt64 centralDirectorySize = 0;
  UInt64 centralDirectoryStartOffset = m_Position - 4;
  for(int i = 0; i < items.Size(); i++)
  {
    if (progress != 0)
    {
      UInt64 numItems = items.Size();
      RINOK(progress->SetCompleted(&numItems));
    }
    // if(m_Signature == NSignature::kEndOfCentralDir)
    //   break;
    if(m_Signature != NSignature::kCentralFileHeader)
      ThrowIncorrectArchiveException();
  
    // NFileHeader::CBlock header;
    // SafeReadBytes(&header, sizeof(header));

    Byte headerMadeByVersionVersion = ReadByte();
    Byte headerMadeByVersionHostOS = ReadByte();
    Byte centalHeaderExtractVersionVersion = ReadByte();
    Byte centalHeaderExtractVersionHostOS = ReadByte();
    UInt16 headerFlags = ReadUInt16() & NFileHeader::NFlags::kUsedBitsMask; 
    UInt16 headerCompressionMethod = ReadUInt16();
    UInt32 headerTime =  ReadUInt32();
    UInt32 headerFileCRC = ReadUInt32();
    UInt64 headerPackSize = ReadUInt32();
    UInt64 headerUnPackSize = ReadUInt32();
    UInt16 headerNameSize = ReadUInt16();
    UInt16 headerExtraSize = ReadUInt16();
    UInt16 headerCommentSize = ReadUInt16();
    UInt32 headerDiskNumberStart = ReadUInt16();
    UInt16 headerInternalAttributes = ReadUInt16();
    UInt32 headerExternalAttributes = ReadUInt32();
    UInt64 localHeaderOffset = ReadUInt32();
    AString centralName = ReadFileName(headerNameSize);
    
    // item.Name = ReadFileName(fileNameSize);

    CExtraBlock centralExtra;
    if (headerExtraSize > 0)
    {
      ReadExtra(headerExtraSize, centralExtra, headerUnPackSize, headerPackSize, localHeaderOffset, headerDiskNumberStart);
    }
    
    int index;
    int left = 0, right = items.Size();
    while(true)
    {
      if (left >= right)
        ThrowIncorrectArchiveException();
      index = (left + right) / 2;
      UInt64 position = items[index].LocalHeaderPosition;
      if (localHeaderOffset == position)
        break;
      if (localHeaderOffset < position)
        right = index;
      else
        left = index + 1;
    }
    CItemEx &item = items[index];
    item.MadeByVersion.Version = headerMadeByVersionVersion;
    item.MadeByVersion.HostOS = headerMadeByVersionHostOS;
    item.CentralExtra = centralExtra;

    if (
        // item.ExtractVersion != centalHeaderExtractVersion ||
        item.Flags != headerFlags ||
        item.CompressionMethod != headerCompressionMethod ||
        // item.Time != header.Time ||
        item.FileCRC != headerFileCRC)
      ThrowIncorrectArchiveException();

    if (item.Name.Length() != centralName.Length())
      ThrowIncorrectArchiveException(); // test it maybe better compare names
    item.Name = centralName;

    // item.CentralExtraPosition = m_Position;
    // item.CentralExtraSize = headerExtraSize;
    // item.CommentSize = headerCommentSize;
    if (headerDiskNumberStart != 0)
      throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported);
    item.InternalAttributes = headerInternalAttributes;
    item.ExternalAttributes = headerExternalAttributes;

    // May be these strings must be deleted
    if (item.IsDirectory())
    {
      // if (item.PackSize != 0 /*  || item.UnPackSize != 0 */)
      //   ThrowIncorrectArchiveException();
      item.UnPackSize = 0;
    }

    UInt32 currentRecordSize = 4 + NFileHeader::kCentralBlockSize + 
        headerNameSize + headerExtraSize + headerCommentSize;

    centralDirectorySize += currentRecordSize;

    // IncreaseRealPosition(headerExtraSize);

    if (
        item.PackSize != headerPackSize ||
        item.UnPackSize != headerUnPackSize
        )
      ThrowIncorrectArchiveException();

    // IncreaseRealPosition(headerCommentSize);
    ReadBuffer(item.Comment, headerCommentSize);

    if (!ReadUInt32(m_Signature))
      break;
  }
  UInt32 thisDiskNumber = 0;
  UInt32 startCDDiskNumber = 0;
  UInt64 numEntriesInCDOnThisDisk = 0;
  UInt64 numEntriesInCD = 0;
  UInt64 cdSize = 0;
  UInt64 cdStartOffsetFromRecord = 0;
  bool isZip64 = false;
  UInt64 zip64EndOfCDStartOffset = m_Position - 4;
  if(m_Signature == NSignature::kZip64EndOfCentralDir)
  {
    isZip64 = true;
    UInt64 recordSize = ReadUInt64();
    UInt16 versionMade = ReadUInt16();
    UInt16 versionNeedExtract = ReadUInt16();
    thisDiskNumber = ReadUInt32();
    startCDDiskNumber = ReadUInt32();
    numEntriesInCDOnThisDisk = ReadUInt64();
    numEntriesInCD = ReadUInt64();
    cdSize = ReadUInt64();
    cdStartOffsetFromRecord = ReadUInt64();
    IncreaseRealPosition(recordSize - kZip64EndOfCentralDirRecordSize);
    if (!ReadUInt32(m_Signature))
      return S_FALSE;
    if (thisDiskNumber != 0 || startCDDiskNumber != 0)
      throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported);
    if (numEntriesInCDOnThisDisk != items.Size() ||
        numEntriesInCD != items.Size() ||
        cdSize != centralDirectorySize ||
        (cdStartOffsetFromRecord != centralDirectoryStartOffset &&
        (!items.IsEmpty())))
      ThrowIncorrectArchiveException();
  }
  if(m_Signature == NSignature::kZip64EndOfCentralDirLocator)
  {
    UInt32 startEndCDDiskNumber = ReadUInt32();
    UInt64 endCDStartOffset = ReadUInt64();
    UInt32 numberOfDisks = ReadUInt32();
    if (zip64EndOfCDStartOffset != endCDStartOffset)
      ThrowIncorrectArchiveException();
    if (!ReadUInt32(m_Signature))
      return S_FALSE;
  }
  if(m_Signature != NSignature::kEndOfCentralDir)
    ThrowIncorrectArchiveException();

  UInt16 thisDiskNumber16 = ReadUInt16();
  if (!isZip64 || thisDiskNumber16)
    thisDiskNumber = thisDiskNumber16;

  UInt16 startCDDiskNumber16 = ReadUInt16();
  if (!isZip64 || startCDDiskNumber16 != 0xFFFF)
    startCDDiskNumber = startCDDiskNumber16;

  UInt16 numEntriesInCDOnThisDisk16 = ReadUInt16();
  if (!isZip64 || numEntriesInCDOnThisDisk16 != 0xFFFF)
    numEntriesInCDOnThisDisk = numEntriesInCDOnThisDisk16;

  UInt16 numEntriesInCD16 = ReadUInt16();
  if (!isZip64 || numEntriesInCD16 != 0xFFFF)
    numEntriesInCD = numEntriesInCD16;

  UInt32 cdSize32 = ReadUInt32();
  if (!isZip64 || cdSize32 != 0xFFFFFFFF)
    cdSize = cdSize32;

  UInt32 cdStartOffsetFromRecord32 = ReadUInt32();
  if (!isZip64 || cdStartOffsetFromRecord32 != 0xFFFFFFFF)
    cdStartOffsetFromRecord = cdStartOffsetFromRecord32;

  UInt16 commentSize = ReadUInt16();
  ReadBuffer(m_ArchiveInfo.Comment, commentSize);
  
  if (thisDiskNumber != 0 || startCDDiskNumber != 0)
    throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported);
  if ((UInt16)numEntriesInCDOnThisDisk != ((UInt16)items.Size()) ||
      (UInt16)numEntriesInCD != ((UInt16)items.Size()) ||
      (UInt32)cdSize != (UInt32)centralDirectorySize ||
      ((UInt32)(cdStartOffsetFromRecord) != (UInt32)centralDirectoryStartOffset &&
        (!items.IsEmpty())))
    ThrowIncorrectArchiveException();
  
  return S_OK;
}

ISequentialInStream* CInArchive::CreateLimitedStream(UInt64 position, UInt64 size)
{
  CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
  CMyComPtr<ISequentialInStream> inStream(streamSpec);
  SeekInArchive(position);
  streamSpec->Init(m_Stream, size);
  return inStream.Detach();
}

IInStream* CInArchive::CreateStream()
{
  CMyComPtr<IInStream> inStream = m_Stream;
  return inStream.Detach();
}

bool CInArchive::SeekInArchive(UInt64 position)
{
  UInt64 newPosition;
  if(m_Stream->Seek(position, STREAM_SEEK_SET, &newPosition) != S_OK)
    return false;
  return (newPosition == position);
}

}}