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
|
<?php
declare(strict_types=1);
namespace ZipStream;
use Closure;
use DateTimeInterface;
use DeflateContext;
use RuntimeException;
use ZipStream\Exception\FileSizeIncorrectException;
use ZipStream\Exception\OverflowException;
use ZipStream\Exception\ResourceActionException;
use ZipStream\Exception\SimulationFileUnknownException;
use ZipStream\Exception\StreamNotReadableException;
use ZipStream\Exception\StreamNotSeekableException;
/**
* @internal
*/
class File
{
private const CHUNKED_READ_BLOCK_SIZE = 0x1000000;
private Version $version;
private int $compressedSize = 0;
private int $uncompressedSize = 0;
private int $crc = 0;
private int $generalPurposeBitFlag = 0;
private readonly string $fileName;
/**
* @var resource|null
*/
private $stream;
/**
* @param Closure $dataCallback
* @psalm-param Closure(): resource $dataCallback
*/
public function __construct(
string $fileName,
private readonly Closure $dataCallback,
private readonly OperationMode $operationMode,
private readonly int $startOffset,
private readonly CompressionMethod $compressionMethod,
private readonly string $comment,
private readonly DateTimeInterface $lastModificationDateTime,
private readonly int $deflateLevel,
private readonly ?int $maxSize,
private readonly ?int $exactSize,
private readonly bool $enableZip64,
private readonly bool $enableZeroHeader,
private readonly Closure $send,
private readonly Closure $recordSentBytes,
) {
$this->fileName = self::filterFilename($fileName);
$this->checkEncoding();
if ($this->enableZeroHeader) {
$this->generalPurposeBitFlag |= GeneralPurposeBitFlag::ZERO_HEADER;
}
$this->version = $this->compressionMethod === CompressionMethod::DEFLATE ? Version::DEFLATE : Version::STORE;
}
public function cloneSimulationExecution(): self
{
return new self(
$this->fileName,
$this->dataCallback,
OperationMode::NORMAL,
$this->startOffset,
$this->compressionMethod,
$this->comment,
$this->lastModificationDateTime,
$this->deflateLevel,
$this->maxSize,
$this->exactSize,
$this->enableZip64,
$this->enableZeroHeader,
$this->send,
$this->recordSentBytes,
);
}
public function process(): string
{
$forecastSize = $this->forecastSize();
if ($this->enableZeroHeader) {
// No calculation required
} elseif ($this->isSimulation() && $forecastSize !== null) {
$this->uncompressedSize = $forecastSize;
$this->compressedSize = $forecastSize;
} else {
$this->readStream(send: false);
if (rewind($this->unpackStream()) === false) {
throw new ResourceActionException('rewind', $this->unpackStream());
}
}
$this->addFileHeader();
$detectedSize = $forecastSize ?? ($this->compressedSize > 0 ? $this->compressedSize : null);
if (
$this->isSimulation() &&
$detectedSize !== null
) {
($this->recordSentBytes)($detectedSize);
} else {
$this->readStream(send: true);
}
$this->addFileFooter();
return $this->getCdrFile();
}
/**
* @return resource
*/
private function unpackStream()
{
if ($this->stream) {
return $this->stream;
}
if ($this->operationMode === OperationMode::SIMULATE_STRICT) {
throw new SimulationFileUnknownException();
}
$this->stream = ($this->dataCallback)();
if (!$this->enableZeroHeader && !stream_get_meta_data($this->stream)['seekable']) {
throw new StreamNotSeekableException();
}
if (!(
str_contains(stream_get_meta_data($this->stream)['mode'], 'r')
|| str_contains(stream_get_meta_data($this->stream)['mode'], 'w+')
|| str_contains(stream_get_meta_data($this->stream)['mode'], 'a+')
|| str_contains(stream_get_meta_data($this->stream)['mode'], 'x+')
|| str_contains(stream_get_meta_data($this->stream)['mode'], 'c+')
)) {
throw new StreamNotReadableException();
}
return $this->stream;
}
private function forecastSize(): ?int
{
if ($this->compressionMethod !== CompressionMethod::STORE) {
return null;
}
if ($this->exactSize !== null) {
return $this->exactSize;
}
$fstat = fstat($this->unpackStream());
if (!$fstat || !array_key_exists('size', $fstat) || $fstat['size'] < 1) {
return null;
}
if ($this->maxSize !== null && $this->maxSize < $fstat['size']) {
return $this->maxSize;
}
return $fstat['size'];
}
/**
* Create and send zip header for this file.
*/
private function addFileHeader(): void
{
$forceEnableZip64 = $this->enableZeroHeader && $this->enableZip64;
$footer = $this->buildZip64ExtraBlock($forceEnableZip64);
$zip64Enabled = $footer !== '';
if ($zip64Enabled) {
$this->version = Version::ZIP64;
}
if ($this->generalPurposeBitFlag & GeneralPurposeBitFlag::EFS) {
// Put the tricky entry to
// force Linux unzip to lookup EFS flag.
$footer .= Zs\ExtendedInformationExtraField::generate();
}
$data = LocalFileHeader::generate(
versionNeededToExtract: $this->version->value,
generalPurposeBitFlag: $this->generalPurposeBitFlag,
compressionMethod: $this->compressionMethod,
lastModificationDateTime: $this->lastModificationDateTime,
crc32UncompressedData: $this->crc,
compressedSize: $zip64Enabled
? 0xFFFFFFFF
: $this->compressedSize,
uncompressedSize: $zip64Enabled
? 0xFFFFFFFF
: $this->uncompressedSize,
fileName: $this->fileName,
extraField: $footer,
);
($this->send)($data);
}
/**
* Strip characters that are not legal in Windows filenames
* to prevent compatibility issues
*/
private static function filterFilename(
/**
* Unprocessed filename
*/
string $fileName
): string {
// strip leading slashes from file name
// (fixes bug in windows archive viewer)
$fileName = ltrim($fileName, '/');
return str_replace(['\\', ':', '*', '?', '"', '<', '>', '|'], '_', $fileName);
}
private function checkEncoding(): void
{
// Sets Bit 11: Language encoding flag (EFS). If this bit is set,
// the filename and comment fields for this file
// MUST be encoded using UTF-8. (see APPENDIX D)
if (mb_check_encoding($this->fileName, 'UTF-8') &&
mb_check_encoding($this->comment, 'UTF-8')) {
$this->generalPurposeBitFlag |= GeneralPurposeBitFlag::EFS;
}
}
private function buildZip64ExtraBlock(bool $force = false): string
{
$outputZip64ExtraBlock = false;
$originalSize = null;
if ($force || $this->uncompressedSize > 0xFFFFFFFF) {
$outputZip64ExtraBlock = true;
$originalSize = $this->uncompressedSize;
}
$compressedSize = null;
if ($force || $this->compressedSize > 0xFFFFFFFF) {
$outputZip64ExtraBlock = true;
$compressedSize = $this->compressedSize;
}
// If this file will start over 4GB limit in ZIP file,
// CDR record will have to use Zip64 extension to describe offset
// to keep consistency we use the same value here
$relativeHeaderOffset = null;
if ($this->startOffset > 0xFFFFFFFF) {
$outputZip64ExtraBlock = true;
$relativeHeaderOffset = $this->startOffset;
}
if (!$outputZip64ExtraBlock) {
return '';
}
if (!$this->enableZip64) {
throw new OverflowException();
}
return Zip64\ExtendedInformationExtraField::generate(
originalSize: $originalSize,
compressedSize: $compressedSize,
relativeHeaderOffset: $relativeHeaderOffset,
diskStartNumber: null,
);
}
private function addFileFooter(): void
{
if (($this->compressedSize > 0xFFFFFFFF || $this->uncompressedSize > 0xFFFFFFFF) && $this->version !== Version::ZIP64) {
throw new OverflowException();
}
if (!$this->enableZeroHeader) {
return;
}
if ($this->version === Version::ZIP64) {
$footer = Zip64\DataDescriptor::generate(
crc32UncompressedData: $this->crc,
compressedSize: $this->compressedSize,
uncompressedSize: $this->uncompressedSize,
);
} else {
$footer = DataDescriptor::generate(
crc32UncompressedData: $this->crc,
compressedSize: $this->compressedSize,
uncompressedSize: $this->uncompressedSize,
);
}
($this->send)($footer);
}
private function readStream(bool $send): void
{
$this->compressedSize = 0;
$this->uncompressedSize = 0;
$hash = hash_init('crc32b');
$deflate = $this->compressionInit();
while (
!feof($this->unpackStream()) &&
($this->maxSize === null || $this->uncompressedSize < $this->maxSize) &&
($this->exactSize === null || $this->uncompressedSize < $this->exactSize)
) {
$readLength = min(
($this->maxSize ?? PHP_INT_MAX) - $this->uncompressedSize,
($this->exactSize ?? PHP_INT_MAX) - $this->uncompressedSize,
self::CHUNKED_READ_BLOCK_SIZE
);
$data = fread($this->unpackStream(), $readLength);
hash_update($hash, $data);
$this->uncompressedSize += strlen($data);
if ($deflate) {
$data = deflate_add(
$deflate,
$data,
feof($this->unpackStream()) ? ZLIB_FINISH : ZLIB_NO_FLUSH
);
}
$this->compressedSize += strlen($data);
if ($send) {
($this->send)($data);
}
}
if ($this->exactSize !== null && $this->uncompressedSize !== $this->exactSize) {
throw new FileSizeIncorrectException(expectedSize: $this->exactSize, actualSize: $this->uncompressedSize);
}
$this->crc = hexdec(hash_final($hash));
}
private function compressionInit(): ?DeflateContext
{
switch ($this->compressionMethod) {
case CompressionMethod::STORE:
// Noting to do
return null;
case CompressionMethod::DEFLATE:
$deflateContext = deflate_init(
ZLIB_ENCODING_RAW,
['level' => $this->deflateLevel]
);
if (!$deflateContext) {
// @codeCoverageIgnoreStart
throw new RuntimeException("Can't initialize deflate context.");
// @codeCoverageIgnoreEnd
}
// False positive, resource is no longer returned from this function
return $deflateContext;
default:
// @codeCoverageIgnoreStart
throw new RuntimeException('Unsupported Compression Method ' . print_r($this->compressionMethod, true));
// @codeCoverageIgnoreEnd
}
}
private function getCdrFile(): string
{
$footer = $this->buildZip64ExtraBlock();
return CentralDirectoryFileHeader::generate(
versionMadeBy: ZipStream::ZIP_VERSION_MADE_BY,
versionNeededToExtract: $this->version->value,
generalPurposeBitFlag: $this->generalPurposeBitFlag,
compressionMethod: $this->compressionMethod,
lastModificationDateTime: $this->lastModificationDateTime,
crc32: $this->crc,
compressedSize: $this->compressedSize > 0xFFFFFFFF
? 0xFFFFFFFF
: $this->compressedSize,
uncompressedSize: $this->uncompressedSize > 0xFFFFFFFF
? 0xFFFFFFFF
: $this->uncompressedSize,
fileName: $this->fileName,
extraField: $footer,
fileComment: $this->comment,
diskNumberStart: 0,
internalFileAttributes: 0,
externalFileAttributes: 32,
relativeOffsetOfLocalHeader: $this->startOffset > 0xFFFFFFFF
? 0xFFFFFFFF
: $this->startOffset,
);
}
private function isSimulation(): bool
{
return $this->operationMode === OperationMode::SIMULATE_LAX || $this->operationMode === OperationMode::SIMULATE_STRICT;
}
}
|