4 * A class for reading ZIP file directories, for the purposes of upload
7 * Only a functional interface is provided: ZipFileReader::read(). No access is
8 * given to object instances.
11 class ZipDirectoryReader
{
13 * Read a ZIP file and call a function for each file discovered in it.
15 * Because this class is aimed at verification, an error is raised on
16 * suspicious or ambiguous input, instead of emulating some standard
19 * @param $fileName string The archive file name
20 * @param $callback Array The callback function. It will be called for each file
21 * with a single associative array each time, with members:
23 * - name: The file name. Directories conventionally have a trailing
26 * - mtime: The file modification time, in MediaWiki 14-char format
28 * - size: The uncompressed file size
30 * @param $options Array An associative array of read options, with the option
31 * name in the key. This may currently contain:
33 * - zip64: If this is set to true, then we will emulate a
34 * library with ZIP64 support, like OpenJDK 7. If it is set to
35 * false, then we will emulate a library with no knowledge of
38 * NOTE: The ZIP64 code is untested and probably doesn't work. It
39 * turned out to be easier to just reject ZIP64 archive uploads,
40 * since they are likely to be very rare. Confirming safety of a
41 * ZIP64 file is fairly complex. What do you do with a file that is
42 * ambiguous and broken when read with a non-ZIP64 reader, but valid
43 * when read with a ZIP64 reader? This situation is normal for a
44 * valid ZIP64 file, and working out what non-ZIP64 readers will make
45 * of such a file is not trivial.
47 * @return Status object. The following fatal errors are defined:
49 * - zip-file-open-error: The file could not be opened.
51 * - zip-wrong-format: The file does not appear to be a ZIP file.
53 * - zip-bad: There was something wrong or ambiguous about the file
56 * - zip-unsupported: The ZIP file uses features which
57 * ZipDirectoryReader does not support.
59 * The default messages for those fatal errors are written in a way that
60 * makes sense for upload verification.
62 * If a fatal error is returned, more information about the error will be
63 * available in the debug log.
65 * Note that the callback function may be called any number of times before
66 * a fatal error is returned. If this occurs, the data sent to the callback
67 * function should be discarded.
69 public static function read( $fileName, $callback, $options = array() ) {
70 $zdr = new self( $fileName, $callback, $options );
71 return $zdr->execute();
77 /** The opened file resource */
80 /** The cached length of the file, or null if it has not been loaded yet. */
83 /** A segmented cache of the file contents */
86 /** The file data callback */
93 var $eocdr, $eocdr64, $eocdr64Locator;
95 /** The "extra field" ID for ZIP64 central directory entries */
96 const ZIP64_EXTRA_HEADER
= 0x0001;
98 /** The segment size for the file contents cache */
99 const SEGSIZE
= 16384;
101 /** The index of the "general field" bit for UTF-8 file names */
102 const GENERAL_UTF8
= 11;
104 /** The index of the "general field" bit for central directory encryption */
105 const GENERAL_CD_ENCRYPTED
= 13;
109 * Private constructor
111 protected function __construct( $fileName, $callback, $options ) {
112 $this->fileName
= $fileName;
113 $this->callback
= $callback;
115 if ( isset( $options['zip64'] ) ) {
116 $this->zip64
= $options['zip64'];
121 * Read the directory according to settings in $this.
126 $this->file
= fopen( $this->fileName
, 'r' );
127 $this->data
= array();
128 if ( !$this->file
) {
129 return Status
::newFatal( 'zip-file-open-error' );
132 $status = Status
::newGood();
134 $this->readEndOfCentralDirectoryRecord();
135 if ( $this->zip64
) {
136 list( $offset, $size ) = $this->findZip64CentralDirectory();
137 $this->readCentralDirectory( $offset, $size );
139 if ( $this->eocdr
['CD size'] == 0xffffffff
140 ||
$this->eocdr
['CD offset'] == 0xffffffff
141 ||
$this->eocdr
['CD entries total'] == 0xffff )
143 $this->error( 'zip-unsupported', 'Central directory header indicates ZIP64, ' .
144 'but we are in legacy mode. Rejecting this upload is necessary to avoid '.
145 'opening vulnerabilities on clients using OpenJDK 7 or later.' );
148 list( $offset, $size ) = $this->findOldCentralDirectory();
149 $this->readCentralDirectory( $offset, $size );
151 } catch ( ZipDirectoryReaderError
$e ) {
152 $status->fatal( $e->getErrorCode() );
155 fclose( $this->file
);
160 * Throw an error, and log a debug message
162 function error( $code, $debugMessage ) {
163 wfDebug( __CLASS__
.": Fatal error: $debugMessage\n" );
164 throw new ZipDirectoryReaderError( $code );
168 * Read the header which is at the end of the central directory,
169 * unimaginatively called the "end of central directory record" by the ZIP
172 function readEndOfCentralDirectoryRecord() {
176 'CD start disk' => 2,
177 'CD entries this disk' => 2,
178 'CD entries total' => 2,
181 'file comment length' => 2,
183 $structSize = $this->getStructSize( $info );
184 $startPos = $this->getFileLength() - 65536 - $structSize;
185 if ( $startPos < 0 ) {
189 $block = $this->getBlock( $startPos );
190 $sigPos = strrpos( $block, "PK\x05\x06" );
191 if ( $sigPos === false ) {
192 $this->error( 'zip-wrong-format',
193 "zip file lacks EOCDR signature. It probably isn't a zip file." );
196 $this->eocdr
= $this->unpack( substr( $block, $sigPos ), $info );
197 $this->eocdr
['EOCDR size'] = $structSize +
$this->eocdr
['file comment length'];
199 if ( $structSize +
$this->eocdr
['file comment length'] != strlen( $block ) - $sigPos ) {
200 $this->error( 'zip-bad', 'trailing bytes after the end of the file comment' );
202 if ( $this->eocdr
['disk'] !== 0
203 ||
$this->eocdr
['CD start disk'] !== 0 )
205 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR)' );
207 $this->eocdr +
= $this->unpack(
209 array( 'file comment' => array( 'string', $this->eocdr
['file comment length'] ) ),
210 $sigPos +
$structSize );
211 $this->eocdr
['position'] = $startPos +
$sigPos;
215 * Read the header called the "ZIP64 end of central directory locator". An
216 * error will be raised if it does not exist.
218 function readZip64EndOfCentralDirectoryLocator() {
220 'signature' => array( 'string', 4 ),
221 'eocdr64 start disk' => 4,
222 'eocdr64 offset' => 8,
223 'number of disks' => 4,
225 $structSize = $this->getStructSize( $info );
227 $block = $this->getBlock( $this->getFileLength() - $this->eocdr
['EOCDR size']
228 - $structSize, $structSize );
229 $this->eocdr64Locator
= $data = $this->unpack( $block, $info );
231 if ( $data['signature'] !== "PK\x06\x07" ) {
232 // Note: Java will allow this and continue to read the
233 // EOCDR64, so we have to reject the upload, we can't
234 // just use the EOCDR header instead.
235 $this->error( 'zip-bad', 'wrong signature on Zip64 end of central directory locator' );
240 * Read the header called the "ZIP64 end of central directory record". It
241 * may replace the regular "end of central directory record" in ZIP64 files.
243 function readZip64EndOfCentralDirectoryRecord() {
244 if ( $this->eocdr64Locator
['eocdr64 start disk'] != 0
245 ||
$this->eocdr64Locator
['number of disks'] != 0 )
247 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR64 locator)' );
251 'signature' => array( 'string', 4 ),
253 'version made by' => 2,
254 'version needed' => 2,
256 'CD start disk' => 4,
257 'CD entries this disk' => 8,
258 'CD entries total' => 8,
262 $structSize = $this->getStructSize( $info );
263 $block = $this->getBlock( $this->eocdr64Locator
['eocdr64 offset'], $structSize );
264 $this->eocdr64
= $data = $this->unpack( $block, $info );
265 if ( $data['signature'] !== "PK\x06\x06" ) {
266 $this->error( 'zip-bad', 'wrong signature on Zip64 end of central directory record' );
268 if ( $data['disk'] !== 0
269 ||
$data['CD start disk'] !== 0 )
271 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR64)' );
276 * Find the location of the central directory, as would be seen by a
279 * @return List containing offset, size and end position.
281 function findOldCentralDirectory() {
282 $size = $this->eocdr
['CD size'];
283 $offset = $this->eocdr
['CD offset'];
284 $endPos = $this->eocdr
['position'];
286 // Some readers use the EOCDR position instead of the offset field
287 // to find the directory, so to be safe, we check if they both agree.
288 if ( $offset +
$size != $endPos ) {
289 $this->error( 'zip-bad', 'the central directory does not immediately precede the end ' .
290 'of central directory record' );
292 return array( $offset, $size );
296 * Find the location of the central directory, as would be seen by a
297 * ZIP64-compliant reader.
299 * @return List containing offset, size and end position.
301 function findZip64CentralDirectory() {
302 // The spec is ambiguous about the exact rules of precedence between the
303 // ZIP64 headers and the original headers. Here we follow zip_util.c
305 $size = $this->eocdr
['CD size'];
306 $offset = $this->eocdr
['CD offset'];
307 $numEntries = $this->eocdr
['CD entries total'];
308 $endPos = $this->eocdr
['position'];
309 if ( $size == 0xffffffff
310 ||
$offset == 0xffffffff
311 ||
$numEntries == 0xffff )
313 $this->readZip64EndOfCentralDirectoryLocator();
315 if ( isset( $this->eocdr64Locator
['eocdr64 offset'] ) ) {
316 $this->readZip64EndOfCentralDirectoryRecord();
317 if ( isset( $this->eocdr64
['CD offset'] ) ) {
318 $size = $this->eocdr64
['CD size'];
319 $offset = $this->eocdr64
['CD offset'];
320 $endPos = $this->eocdr64Locator
['eocdr64 offset'];
324 // Some readers use the EOCDR position instead of the offset field
325 // to find the directory, so to be safe, we check if they both agree.
326 if ( $offset +
$size != $endPos ) {
327 $this->error( 'zip-bad', 'the central directory does not immediately precede the end ' .
328 'of central directory record' );
330 return array( $offset, $size );
334 * Read the central directory at the given location
336 function readCentralDirectory( $offset, $size ) {
337 $block = $this->getBlock( $offset, $size );
340 'signature' => array( 'string', 4 ),
341 'version made by' => 2,
342 'version needed' => 2,
344 'compression method' => 2,
348 'compressed size' => 4,
349 'uncompressed size' => 4,
351 'extra field length' => 2,
352 'comment length' => 2,
353 'disk number start' => 2,
354 'internal attrs' => 2,
355 'external attrs' => 4,
356 'local header offset' => 4,
358 $fixedSize = $this->getStructSize( $fixedInfo );
361 while ( $pos < $size ) {
362 $data = $this->unpack( $block, $fixedInfo, $pos );
365 if ( $data['signature'] !== "PK\x01\x02" ) {
366 $this->error( 'zip-bad', 'Invalid signature found in directory entry' );
369 $variableInfo = array(
370 'name' => array( 'string', $data['name length'] ),
371 'extra field' => array( 'string', $data['extra field length'] ),
372 'comment' => array( 'string', $data['comment length'] ),
374 $data +
= $this->unpack( $block, $variableInfo, $pos );
375 $pos +
= $this->getStructSize( $variableInfo );
377 if ( $this->zip64
&& (
378 $data['compressed size'] == 0xffffffff
379 ||
$data['uncompressed size'] == 0xffffffff
380 ||
$data['local header offset'] == 0xffffffff ) )
382 $zip64Data = $this->unpackZip64Extra( $data['extra field'] );
384 $data = $zip64Data +
$data;
388 if ( $this->testBit( $data['general bits'], self
::GENERAL_CD_ENCRYPTED
) ) {
389 $this->error( 'zip-unsupported', 'central directory encryption is not supported' );
392 // Convert the timestamp into MediaWiki format
393 // For the format, please see the MS-DOS 2.0 Programmer's Reference,
394 // pages 3-5 and 3-6.
395 $time = $data['mod time'];
396 $date = $data['mod date'];
398 $year = 1980 +
( $date >> 9 );
399 $month = ( $date >> 5 ) & 15;
401 $hour = ( $time >> 11 ) & 31;
402 $minute = ( $time >> 5 ) & 63;
403 $second = ( $time & 31 ) * 2;
404 $timestamp = sprintf( "%04d%02d%02d%02d%02d%02d",
405 $year, $month, $day, $hour, $minute, $second );
407 // Convert the character set in the file name
408 if ( !function_exists( 'iconv' )
409 ||
$this->testBit( $data['general bits'], self
::GENERAL_UTF8
) )
411 $name = $data['name'];
413 $name = iconv( 'CP437', 'UTF-8', $data['name'] );
416 // Compile a data array for the user, with a sensible format
419 'mtime' => $timestamp,
420 'size' => $data['uncompressed size'],
422 call_user_func( $this->callback
, $userData );
427 * Interpret ZIP64 "extra field" data and return an associative array.
429 function unpackZip64Extra( $extraField ) {
430 $extraHeaderInfo = array(
434 $extraHeaderSize = $this->getStructSize( $extraHeaderInfo );
436 $zip64ExtraInfo = array(
437 'uncompressed size' => 8,
438 'compressed size' => 8,
439 'local header offset' => 8,
440 'disk number start' => 4,
444 while ( $extraPos < strlen( $extraField ) ) {
445 $extra = $this->unpack( $extraField, $extraHeaderInfo, $extraPos );
446 $extraPos +
= $extraHeaderSize;
447 $extra +
= $this->unpack( $extraField,
448 array( 'data' => array( 'string', $extra['size'] ) ),
450 $extraPos +
= $extra['size'];
452 if ( $extra['id'] == self
::ZIP64_EXTRA_HEADER
) {
453 return $this->unpack( $extra['data'], $zip64ExtraInfo );
461 * Get the length of the file.
463 function getFileLength() {
464 if ( $this->fileLength
=== null ) {
465 $stat = fstat( $this->file
);
466 $this->fileLength
= $stat['size'];
468 return $this->fileLength
;
472 * Get the file contents from a given offset. If there are not enough bytes
473 * in the file to satisfy the request, an exception will be thrown.
475 * @param $start The byte offset of the start of the block.
476 * @param $length The number of bytes to return. If omitted, the remainder
477 * of the file will be returned.
481 function getBlock( $start, $length = null ) {
482 $fileLength = $this->getFileLength();
483 if ( $start >= $fileLength ) {
484 $this->error( 'zip-bad', "getBlock() requested position $start, " .
485 "file length is $fileLength" );
487 if ( $length === null ) {
488 $length = $fileLength - $start;
490 $end = $start +
$length;
491 if ( $end > $fileLength ) {
492 $this->error( 'zip-bad', "getBlock() requested end position $end, " .
493 "file length is $fileLength" );
495 $startSeg = floor( $start / self
::SEGSIZE
);
496 $endSeg = ceil( $end / self
::SEGSIZE
);
499 for ( $segIndex = $startSeg; $segIndex <= $endSeg; $segIndex++
) {
500 $block .= $this->getSegment( $segIndex );
503 $block = substr( $block,
504 $start - $startSeg * self
::SEGSIZE
,
507 if ( strlen( $block ) < $length ) {
508 $this->error( 'zip-bad', 'getBlock() returned an unexpectedly small amount of data' );
515 * Get a section of the file starting at position $segIndex * self::SEGSIZE,
516 * of length self::SEGSIZE. The result is cached. This is a helper function
519 * If there are not enough bytes in the file to satsify the request, the
520 * return value will be truncated. If a request is made for a segment beyond
521 * the end of the file, an empty string will be returned.
523 function getSegment( $segIndex ) {
524 if ( !isset( $this->buffer
[$segIndex] ) ) {
525 $bytePos = $segIndex * self
::SEGSIZE
;
526 if ( $bytePos >= $this->getFileLength() ) {
527 $this->buffer
[$segIndex] = '';
530 if ( fseek( $this->file
, $bytePos ) ) {
531 $this->error( 'zip-bad', "seek to $bytePos failed" );
533 $seg = fread( $this->file
, self
::SEGSIZE
);
534 if ( $seg === false ) {
535 $this->error( 'zip-bad', "read from $bytePos failed" );
537 $this->buffer
[$segIndex] = $seg;
539 return $this->buffer
[$segIndex];
543 * Get the size of a structure in bytes. See unpack() for the format of $struct.
545 function getStructSize( $struct ) {
547 foreach ( $struct as $type ) {
548 if ( is_array( $type ) ) {
549 list( $typeName, $fieldSize ) = $type;
559 * Unpack a binary structure. This is like the built-in unpack() function
562 * @param $string The binary data input
564 * @param $struct An associative array giving structure members and their
565 * types. In the key is the field name. The value may be either an
566 * integer, in which case the field is a little-endian unsigned integer
567 * encoded in the given number of bytes, or an array, in which case the
568 * first element of the array is the type name, and the subsequent
569 * elements are type-dependent parameters. Only one such type is defined:
570 * - "string": The second array element gives the length of string.
571 * Not null terminated.
573 * @param $offset The offset into the string at which to start unpacking.
575 * @return Unpacked associative array. Note that large integers in the input
576 * may be represented as floating point numbers in the return value, so
577 * the use of weak comparison is advised.
579 function unpack( $string, $struct, $offset = 0 ) {
580 $size = $this->getStructSize( $struct );
581 if ( $offset +
$size > strlen( $string ) ) {
582 $this->error( 'zip-bad', 'unpack() would run past the end of the supplied string' );
587 foreach ( $struct as $key => $type ) {
588 if ( is_array( $type ) ) {
589 list( $typeName, $fieldSize ) = $type;
590 switch ( $typeName ) {
592 $data[$key] = substr( $string, $pos, $fieldSize );
596 throw new MWException( __METHOD__
.": invalid type \"$typeName\"" );
599 // Unsigned little-endian integer
600 $length = intval( $type );
601 $bytes = substr( $string, $pos, $length );
603 // Calculate the value. Use an algorithm which automatically
604 // upgrades the value to floating point if necessary.
606 for ( $i = $length - 1; $i >= 0; $i-- ) {
608 $value +
= ord( $string[$pos +
$i] );
611 // Throw an exception if there was loss of precision
612 if ( $value > pow( 2, 52 ) ) {
613 $this->error( 'zip-unsupported', 'number too large to be stored in a double. ' .
614 'This could happen if we tried to unpack a 64-bit structure ' .
615 'at an invalid location.' );
617 $data[$key] = $value;
626 * Returns a bit from a given position in an integer value, converted to
629 * @param $value integer
630 * @param $bitIndex The index of the bit, where 0 is the LSB.
632 function testBit( $value, $bitIndex ) {
633 return (bool)( ( $value >> $bitIndex ) & 1 );
637 * Debugging helper function which dumps a string in hexdump -C format.
639 function hexDump( $s ) {
641 for ( $i = 0; $i < $n; $i +
= 16 ) {
642 printf( "%08X ", $i );
643 for ( $j = 0; $j < 16; $j++
) {
648 if ( $i +
$j >= $n ) {
651 printf( "%02X", ord( $s[$i +
$j] ) );
656 for ( $j = 0; $j < 16; $j++
) {
657 if ( $i +
$j >= $n ) {
659 } elseif ( ctype_print( $s[$i +
$j] ) ) {
671 * Internal exception class. Will be caught by private code.
673 class ZipDirectoryReaderError
extends Exception
{
676 function __construct( $code ) {
678 parent
::__construct( "ZipDirectoryReader error: $code" );
681 function getErrorCode() {