summaryrefslogtreecommitdiffstats
path: root/src/libs/7zip/win/CPP/7zip/Archive/CpioHandler.cpp
blob: 0f32ef663851a6b87834df49772a7a04f01e2d93 (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
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
// CpioHandler.cpp

#include "StdAfx.h"

#include "Common/ComTry.h"
#include "Common/StringConvert.h"
#include "Common/StringToInt.h"

#include "Windows/PropVariant.h"
#include "Windows/Time.h"

#include "../Common/LimitedStreams.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamUtils.h"

#include "../Compress/CopyCoder.h"

#include "Common/ItemNameUtils.h"

namespace NArchive {
namespace NCpio {

namespace NFileHeader
{
  namespace NMagic
  {
    const char *kMagic1 = "070701";
    const char *kMagic2 = "070702";
    const char *kMagic3 = "070707";
    const char *kEndName = "TRAILER!!!";

    const Byte kMagicForRecord2[2] = { 0xC7, 0x71 };
  }

  const UInt32 kRecord2Size = 26;
  /*
  struct CRecord2
  {
    unsigned short c_magic;
    short c_dev;
    unsigned short c_ino;
    unsigned short c_mode;
    unsigned short c_uid;
    unsigned short c_gid;
    unsigned short c_nlink;
    short c_rdev;
    unsigned short c_mtimes[2];
    unsigned short c_namesize;
    unsigned short c_filesizes[2];
  };
  */
 
  const UInt32 kRecordSize = 110;
  /*
  struct CRecord
  {
    char Magic[6];  // "070701" for "new" portable format, "070702" for CRC format
    char inode[8];
    char Mode[8];
    char UID[8];
    char GID[8];
    char nlink[8];
    char mtime[8];
    char Size[8]; // must be 0 for FIFOs and directories
    char DevMajor[8];
    char DevMinor[8];
    char RDevMajor[8];  //only valid for chr and blk special files
    char RDevMinor[8];  //only valid for chr and blk special files
    char NameSize[8]; // count includes terminating NUL in pathname
    char ChkSum[8];  // 0 for "new" portable format; for CRC format the sum of all the bytes in the file
    bool CheckMagic() const
    { return memcmp(Magic, NMagic::kMagic1, 6) == 0 ||
             memcmp(Magic, NMagic::kMagic2, 6) == 0; };
  };
  */

  const UInt32 kOctRecordSize = 76;
 
}

struct CItem
{
  AString Name;
  UInt32 inode;
  UInt32 Mode;
  UInt32 UID;
  UInt32 GID;
  UInt32 Size;
  UInt32 MTime;

  // char LinkFlag;
  // AString LinkName; ?????
  char Magic[8];
  UInt32 NumLinks;
  UInt32 DevMajor;
  UInt32 DevMinor;
  UInt32 RDevMajor;
  UInt32 RDevMinor;
  UInt32 ChkSum;

  UInt32 Align;

  bool IsDir() const { return (Mode & 0170000) == 0040000; }
};

class CItemEx: public CItem
{
public:
  UInt64 HeaderPosition;
  UInt32 HeaderSize;
  UInt64 GetDataPosition() const { return HeaderPosition + HeaderSize; };
};

const UInt32 kMaxBlockSize = NFileHeader::kRecordSize;

class CInArchive
{
  CMyComPtr<IInStream> m_Stream;
  UInt64 m_Position;

  UInt16 _blockSize;
  Byte _block[kMaxBlockSize];
  UInt32 _blockPos;
  Byte ReadByte();
  UInt16 ReadUInt16();
  UInt32 ReadUInt32();
  
  bool ReadNumber(UInt32 &resultValue);
  bool ReadOctNumber(int size, UInt32 &resultValue);

  HRESULT ReadBytes(void *data, UInt32 size, UInt32 &processedSize);
public:
  HRESULT Open(IInStream *inStream);
  HRESULT GetNextItem(bool &filled, CItemEx &itemInfo);
  HRESULT Skip(UInt64 numBytes);
  HRESULT SkipDataRecords(UInt64 dataSize, UInt32 align);
};

HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 &processedSize)
{
  size_t realProcessedSize = size;
  RINOK(ReadStream(m_Stream, data, &realProcessedSize));
  processedSize = (UInt32)realProcessedSize;
  m_Position += processedSize;
  return S_OK;
}

Byte CInArchive::ReadByte()
{
  if (_blockPos >= _blockSize)
    throw "Incorrect cpio archive";
  return _block[_blockPos++];
}

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

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

HRESULT CInArchive::Open(IInStream *inStream)
{
  RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &m_Position));
  m_Stream = inStream;
  return S_OK;
}

bool CInArchive::ReadNumber(UInt32 &resultValue)
{
  resultValue = 0;
  for (int i = 0; i < 8; i++)
  {
    char c = char(ReadByte());
    int d;
    if (c >= '0' && c <= '9')
      d = c - '0';
    else if (c >= 'A' && c <= 'F')
      d = 10 + c - 'A';
    else if (c >= 'a' && c <= 'f')
      d = 10 + c - 'a';
    else
      return false;
    resultValue *= 0x10;
    resultValue += d;
  }
  return true;
}

static bool OctalToNumber(const char *s, UInt64 &res)
{
  const char *end;
  res = ConvertOctStringToUInt64(s, &end);
  return (*end == ' ' || *end == 0);
}

static bool OctalToNumber32(const char *s, UInt32 &res)
{
  UInt64 res64;
  if (!OctalToNumber(s, res64))
    return false;
  res = (UInt32)res64;
  return (res64 <= 0xFFFFFFFF);
}

bool CInArchive::ReadOctNumber(int size, UInt32 &resultValue)
{
  char sz[32 + 4];
  int i;
  for (i = 0; i < size && i < 32; i++)
    sz[i] = (char)ReadByte();
  sz[i] = 0;
  return OctalToNumber32(sz, resultValue);
}

#define GetFromHex(y) { if (!ReadNumber(y)) return S_FALSE; }
#define GetFromOct6(y) { if (!ReadOctNumber(6, y)) return S_FALSE; }
#define GetFromOct11(y) { if (!ReadOctNumber(11, y)) return S_FALSE; }

static unsigned short ConvertValue(unsigned short value, bool convert)
{
  if (!convert)
    return value;
  return (unsigned short)((((unsigned short)(value & 0xFF)) << 8) | (value >> 8));
}

static UInt32 GetAlignedSize(UInt32 size, UInt32 align)
{
  while ((size & (align - 1)) != 0)
    size++;
  return size;
}


HRESULT CInArchive::GetNextItem(bool &filled, CItemEx &item)
{
  filled = false;

  UInt32 processedSize;
  item.HeaderPosition = m_Position;

  _blockSize = kMaxBlockSize;
  RINOK(ReadBytes(_block, 2, processedSize));
  if (processedSize != 2)
    return S_FALSE;
  _blockPos = 0;

  UInt32 nameSize;

  bool oldBE =
    _block[0] == NFileHeader::NMagic::kMagicForRecord2[1] &&
    _block[1] == NFileHeader::NMagic::kMagicForRecord2[0];

  bool binMode = (_block[0] == NFileHeader::NMagic::kMagicForRecord2[0] &&
    _block[1] == NFileHeader::NMagic::kMagicForRecord2[1]) ||
    oldBE;

  if (binMode)
  {
    RINOK(ReadBytes(_block + 2, NFileHeader::kRecord2Size - 2, processedSize));
    if (processedSize != NFileHeader::kRecord2Size - 2)
      return S_FALSE;
    item.Align = 2;
    _blockPos = 2;
    item.DevMajor = 0;
    item.DevMinor = ConvertValue(ReadUInt16(), oldBE);
    item.inode = ConvertValue(ReadUInt16(), oldBE);
    item.Mode = ConvertValue(ReadUInt16(), oldBE);
    item.UID = ConvertValue(ReadUInt16(), oldBE);
    item.GID = ConvertValue(ReadUInt16(), oldBE);
    item.NumLinks = ConvertValue(ReadUInt16(), oldBE);
    item.RDevMajor =0;
    item.RDevMinor = ConvertValue(ReadUInt16(), oldBE);
    UInt16 timeHigh = ConvertValue(ReadUInt16(), oldBE);
    UInt16 timeLow = ConvertValue(ReadUInt16(), oldBE);
    item.MTime = (UInt32(timeHigh) << 16) + timeLow;
    nameSize = ConvertValue(ReadUInt16(), oldBE);
    UInt16 sizeHigh = ConvertValue(ReadUInt16(), oldBE);
    UInt16 sizeLow = ConvertValue(ReadUInt16(), oldBE);
    item.Size = (UInt32(sizeHigh) << 16) + sizeLow;

    item.ChkSum = 0;
    item.HeaderSize = GetAlignedSize(
        nameSize + NFileHeader::kRecord2Size, item.Align);
    nameSize = item.HeaderSize - NFileHeader::kRecord2Size;
  }
  else
  {
    RINOK(ReadBytes(_block + 2, 4, processedSize));
    if (processedSize != 4)
      return S_FALSE;

    bool magicOK =
        memcmp(_block, NFileHeader::NMagic::kMagic1, 6) == 0 ||
        memcmp(_block, NFileHeader::NMagic::kMagic2, 6) == 0;
    _blockPos = 6;
    if (magicOK)
    {
      RINOK(ReadBytes(_block + 6, NFileHeader::kRecordSize - 6, processedSize));
      if (processedSize != NFileHeader::kRecordSize - 6)
        return S_FALSE;
      item.Align = 4;

      GetFromHex(item.inode);
      GetFromHex(item.Mode);
      GetFromHex(item.UID);
      GetFromHex(item.GID);
      GetFromHex(item.NumLinks);
      UInt32 mTime;
      GetFromHex(mTime);
      item.MTime = mTime;
      GetFromHex(item.Size);
      GetFromHex(item.DevMajor);
      GetFromHex(item.DevMinor);
      GetFromHex(item.RDevMajor);
      GetFromHex(item.RDevMinor);
      GetFromHex(nameSize);
      GetFromHex(item.ChkSum);
      item.HeaderSize = GetAlignedSize(
          nameSize + NFileHeader::kRecordSize, item.Align);
      nameSize = item.HeaderSize - NFileHeader::kRecordSize;
    }
    else
    {
      if (!memcmp(_block, NFileHeader::NMagic::kMagic3, 6) == 0)
        return S_FALSE;
      RINOK(ReadBytes(_block + 6, NFileHeader::kOctRecordSize - 6, processedSize));
      if (processedSize != NFileHeader::kOctRecordSize - 6)
        return S_FALSE;
      item.Align = 1;
      item.DevMajor = 0;
      GetFromOct6(item.DevMinor);
      GetFromOct6(item.inode);
      GetFromOct6(item.Mode);
      GetFromOct6(item.UID);
      GetFromOct6(item.GID);
      GetFromOct6(item.NumLinks);
      item.RDevMajor = 0;
      GetFromOct6(item.RDevMinor);
      UInt32 mTime;
      GetFromOct11(mTime);
      item.MTime = mTime;
      GetFromOct6(nameSize);
      GetFromOct11(item.Size);  // ?????
      item.HeaderSize = GetAlignedSize(
          nameSize + NFileHeader::kOctRecordSize, item.Align);
      nameSize = item.HeaderSize - NFileHeader::kOctRecordSize;
    }
  }
  if (nameSize == 0 || nameSize >= (1 << 27))
    return E_FAIL;
  RINOK(ReadBytes(item.Name.GetBuffer(nameSize), nameSize, processedSize));
  if (processedSize != nameSize)
    return E_FAIL;
  item.Name.ReleaseBuffer();
  if (strcmp(item.Name, NFileHeader::NMagic::kEndName) == 0)
    return S_OK;
  filled = true;
  return S_OK;
}

HRESULT CInArchive::Skip(UInt64 numBytes)
{
  UInt64 newPostion;
  RINOK(m_Stream->Seek(numBytes, STREAM_SEEK_CUR, &newPostion));
  m_Position += numBytes;
  if (m_Position != newPostion)
    return E_FAIL;
  return S_OK;
}

HRESULT CInArchive::SkipDataRecords(UInt64 dataSize, UInt32 align)
{
  while ((dataSize & (align - 1)) != 0)
    dataSize++;
  return Skip(dataSize);
}


class CHandler:
  public IInArchive,
  public IInArchiveGetStream,
  public CMyUnknownImp
{
  CObjectVector<CItemEx> _items;
  CMyComPtr<IInStream> _stream;
public:
  MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
  INTERFACE_IInArchive(;)
  STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
};

/*
enum
{
  kpidinode = kpidUserDefined,
  kpidiChkSum
};
*/

STATPROPSTG kProps[] =
{
  { NULL, kpidPath, VT_BSTR},
  { NULL, kpidIsDir, VT_BOOL},
  { NULL, kpidSize, VT_UI8},
  { NULL, kpidPackSize, VT_UI8},
  { NULL, kpidMTime, VT_FILETIME},
  { NULL, kpidPosixAttrib, VT_UI4},
  // { L"inode", kpidinode, VT_UI4}
  // { L"CheckSum", kpidiChkSum, VT_UI4}
};

IMP_IInArchive_Props
IMP_IInArchive_ArcProps_NO

STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)
{
  COM_TRY_BEGIN
  // try
  {
    CInArchive archive;

    UInt64 endPos = 0;
    bool needSetTotal = true;

    if (callback != NULL)
    {
      RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos));
      RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
    }

    RINOK(archive.Open(stream));

    _items.Clear();

    for (;;)
    {
      CItemEx item;
      bool filled;
      HRESULT result = archive.GetNextItem(filled, item);
      if (result == S_FALSE)
        return S_FALSE;
      if (result != S_OK)
        return S_FALSE;
      if (!filled)
        break;
      _items.Add(item);
      archive.SkipDataRecords(item.Size, item.Align);
      if (callback != NULL)
      {
        if (needSetTotal)
        {
          RINOK(callback->SetTotal(NULL, &endPos));
          needSetTotal = false;
        }
        if (_items.Size() % 100 == 0)
        {
          UInt64 numFiles = _items.Size();
          UInt64 numBytes = item.HeaderPosition;
          RINOK(callback->SetCompleted(&numFiles, &numBytes));
        }
      }
    }
    if (_items.Size() == 0)
      return S_FALSE;

    _stream = stream;
  }
  /*
  catch(...)
  {
    return S_FALSE;
  }
  */
  return S_OK;
  COM_TRY_END
}

STDMETHODIMP CHandler::Close()
{
  _items.Clear();
  _stream.Release();
  return S_OK;
}

STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
  *numItems = _items.Size();
  return S_OK;
}

STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
  COM_TRY_BEGIN
  NWindows::NCOM::CPropVariant prop;
  const CItemEx &item = _items[index];

  switch(propID)
  {
    case kpidPath: prop = NItemName::GetOSName(MultiByteToUnicodeString(item.Name, CP_OEMCP)); break;
    case kpidIsDir: prop = item.IsDir(); break;
    case kpidSize:
    case kpidPackSize:
      prop = (UInt64)item.Size;
      break;
    case kpidMTime:
    {
      if (item.MTime != 0)
      {
        FILETIME utc;
        NWindows::NTime::UnixTimeToFileTime(item.MTime, utc);
        prop = utc;
      }
      break;
    }
    case kpidPosixAttrib: prop = item.Mode; break;
    /*
    case kpidinode:  prop = item.inode; break;
    case kpidiChkSum:  prop = item.ChkSum; break;
    */
  }
  prop.Detach(value);
  return S_OK;
  COM_TRY_END
}

STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
    Int32 testMode, IArchiveExtractCallback *extractCallback)
{
  COM_TRY_BEGIN
  bool allFilesMode = (numItems == (UInt32)-1);
  if (allFilesMode)
    numItems = _items.Size();
  if (numItems == 0)
    return S_OK;
  UInt64 totalSize = 0;
  UInt32 i;
  for (i = 0; i < numItems; i++)
    totalSize += _items[allFilesMode ? i : indices[i]].Size;
  extractCallback->SetTotal(totalSize);

  UInt64 currentTotalSize = 0;
  
  NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
  CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;

  CLocalProgress *lps = new CLocalProgress;
  CMyComPtr<ICompressProgressInfo> progress = lps;
  lps->Init(extractCallback, false);

  CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
  CMyComPtr<ISequentialInStream> inStream(streamSpec);
  streamSpec->SetStream(_stream);

  for (i = 0; i < numItems; i++)
  {
    lps->InSize = lps->OutSize = currentTotalSize;
    RINOK(lps->SetCur());
    CMyComPtr<ISequentialOutStream> outStream;
    Int32 askMode = testMode ?
        NExtract::NAskMode::kTest :
        NExtract::NAskMode::kExtract;
    Int32 index = allFilesMode ? i : indices[i];
    const CItemEx &item = _items[index];
    RINOK(extractCallback->GetStream(index, &outStream, askMode));
    currentTotalSize += item.Size;
    if (item.IsDir())
    {
      RINOK(extractCallback->PrepareOperation(askMode));
      RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
      continue;
    }
    if (!testMode && !outStream)
      continue;
    RINOK(extractCallback->PrepareOperation(askMode));
    if (testMode)
    {
      RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
      continue;
    }
    RINOK(_stream->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL));
    streamSpec->Init(item.Size);
    RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress));
    outStream.Release();
    RINOK(extractCallback->SetOperationResult((copyCoderSpec->TotalSize == item.Size) ?
        NExtract::NOperationResult::kOK:
        NExtract::NOperationResult::kDataError));
  }
  return S_OK;
  COM_TRY_END
}

STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
{
  COM_TRY_BEGIN
  const CItemEx &item = _items[index];
  return CreateLimitedInStream(_stream, item.GetDataPosition(), item.Size, stream);
  COM_TRY_END
}

static IInArchive *CreateArc() { return new NArchive::NCpio::CHandler; }

static CArcInfo g_ArcInfo =
  { L"Cpio", L"cpio", 0, 0xED, { 0 }, 0, false, CreateArc, 0 };

REGISTER_ARC(Cpio)

}}