Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / ZipDirectoryReader.php
blob307efcea8de51dd5269e5bfef331ba4127e0a5ab
1 <?php
2 /**
3 * ZIP file directories reader, for the purposes of upload verification.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * A class for reading ZIP file directories, for the purposes of upload
25 * verification.
27 * Only a functional interface is provided: ZipFileReader::read(). No access is
28 * given to object instances.
31 class ZipDirectoryReader {
32 /**
33 * Read a ZIP file and call a function for each file discovered in it.
35 * Because this class is aimed at verification, an error is raised on
36 * suspicious or ambiguous input, instead of emulating some standard
37 * behavior.
39 * @param string $fileName The archive file name
40 * @param array $callback The callback function. It will be called for each file
41 * with a single associative array each time, with members:
43 * - name: The file name. Directories conventionally have a trailing
44 * slash.
46 * - mtime: The file modification time, in MediaWiki 14-char format
48 * - size: The uncompressed file size
50 * @param array $options An associative array of read options, with the option
51 * name in the key. This may currently contain:
53 * - zip64: If this is set to true, then we will emulate a
54 * library with ZIP64 support, like OpenJDK 7. If it is set to
55 * false, then we will emulate a library with no knowledge of
56 * ZIP64.
58 * NOTE: The ZIP64 code is untested and probably doesn't work. It
59 * turned out to be easier to just reject ZIP64 archive uploads,
60 * since they are likely to be very rare. Confirming safety of a
61 * ZIP64 file is fairly complex. What do you do with a file that is
62 * ambiguous and broken when read with a non-ZIP64 reader, but valid
63 * when read with a ZIP64 reader? This situation is normal for a
64 * valid ZIP64 file, and working out what non-ZIP64 readers will make
65 * of such a file is not trivial.
67 * @return Status object. The following fatal errors are defined:
69 * - zip-file-open-error: The file could not be opened.
71 * - zip-wrong-format: The file does not appear to be a ZIP file.
73 * - zip-bad: There was something wrong or ambiguous about the file
74 * data.
76 * - zip-unsupported: The ZIP file uses features which
77 * ZipDirectoryReader does not support.
79 * The default messages for those fatal errors are written in a way that
80 * makes sense for upload verification.
82 * If a fatal error is returned, more information about the error will be
83 * available in the debug log.
85 * Note that the callback function may be called any number of times before
86 * a fatal error is returned. If this occurs, the data sent to the callback
87 * function should be discarded.
89 public static function read( $fileName, $callback, $options = array() ) {
90 $zdr = new self( $fileName, $callback, $options );
91 return $zdr->execute();
94 /** The file name */
95 var $fileName;
97 /** The opened file resource */
98 var $file;
100 /** The cached length of the file, or null if it has not been loaded yet. */
101 var $fileLength;
103 /** A segmented cache of the file contents */
104 var $buffer;
106 /** The file data callback */
107 var $callback;
109 /** The ZIP64 mode */
110 var $zip64 = false;
112 /** Stored headers */
113 var $eocdr, $eocdr64, $eocdr64Locator;
115 var $data;
117 /** The "extra field" ID for ZIP64 central directory entries */
118 const ZIP64_EXTRA_HEADER = 0x0001;
120 /** The segment size for the file contents cache */
121 const SEGSIZE = 16384;
123 /** The index of the "general field" bit for UTF-8 file names */
124 const GENERAL_UTF8 = 11;
126 /** The index of the "general field" bit for central directory encryption */
127 const GENERAL_CD_ENCRYPTED = 13;
130 * Private constructor
132 protected function __construct( $fileName, $callback, $options ) {
133 $this->fileName = $fileName;
134 $this->callback = $callback;
136 if ( isset( $options['zip64'] ) ) {
137 $this->zip64 = $options['zip64'];
142 * Read the directory according to settings in $this.
144 * @return Status
146 function execute() {
147 $this->file = fopen( $this->fileName, 'r' );
148 $this->data = array();
149 if ( !$this->file ) {
150 return Status::newFatal( 'zip-file-open-error' );
153 $status = Status::newGood();
154 try {
155 $this->readEndOfCentralDirectoryRecord();
156 if ( $this->zip64 ) {
157 list( $offset, $size ) = $this->findZip64CentralDirectory();
158 $this->readCentralDirectory( $offset, $size );
159 } else {
160 if ( $this->eocdr['CD size'] == 0xffffffff
161 || $this->eocdr['CD offset'] == 0xffffffff
162 || $this->eocdr['CD entries total'] == 0xffff )
164 $this->error( 'zip-unsupported', 'Central directory header indicates ZIP64, ' .
165 'but we are in legacy mode. Rejecting this upload is necessary to avoid ' .
166 'opening vulnerabilities on clients using OpenJDK 7 or later.' );
169 list( $offset, $size ) = $this->findOldCentralDirectory();
170 $this->readCentralDirectory( $offset, $size );
172 } catch ( ZipDirectoryReaderError $e ) {
173 $status->fatal( $e->getErrorCode() );
176 fclose( $this->file );
177 return $status;
181 * Throw an error, and log a debug message
183 function error( $code, $debugMessage ) {
184 wfDebug( __CLASS__ . ": Fatal error: $debugMessage\n" );
185 throw new ZipDirectoryReaderError( $code );
189 * Read the header which is at the end of the central directory,
190 * unimaginatively called the "end of central directory record" by the ZIP
191 * spec.
193 function readEndOfCentralDirectoryRecord() {
194 $info = array(
195 'signature' => 4,
196 'disk' => 2,
197 'CD start disk' => 2,
198 'CD entries this disk' => 2,
199 'CD entries total' => 2,
200 'CD size' => 4,
201 'CD offset' => 4,
202 'file comment length' => 2,
204 $structSize = $this->getStructSize( $info );
205 $startPos = $this->getFileLength() - 65536 - $structSize;
206 if ( $startPos < 0 ) {
207 $startPos = 0;
210 $block = $this->getBlock( $startPos );
211 $sigPos = strrpos( $block, "PK\x05\x06" );
212 if ( $sigPos === false ) {
213 $this->error( 'zip-wrong-format',
214 "zip file lacks EOCDR signature. It probably isn't a zip file." );
217 $this->eocdr = $this->unpack( substr( $block, $sigPos ), $info );
218 $this->eocdr['EOCDR size'] = $structSize + $this->eocdr['file comment length'];
220 if ( $structSize + $this->eocdr['file comment length'] != strlen( $block ) - $sigPos ) {
221 $this->error( 'zip-bad', 'trailing bytes after the end of the file comment' );
223 if ( $this->eocdr['disk'] !== 0
224 || $this->eocdr['CD start disk'] !== 0 )
226 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR)' );
228 $this->eocdr += $this->unpack(
229 $block,
230 array( 'file comment' => array( 'string', $this->eocdr['file comment length'] ) ),
231 $sigPos + $structSize );
232 $this->eocdr['position'] = $startPos + $sigPos;
236 * Read the header called the "ZIP64 end of central directory locator". An
237 * error will be raised if it does not exist.
239 function readZip64EndOfCentralDirectoryLocator() {
240 $info = array(
241 'signature' => array( 'string', 4 ),
242 'eocdr64 start disk' => 4,
243 'eocdr64 offset' => 8,
244 'number of disks' => 4,
246 $structSize = $this->getStructSize( $info );
248 $block = $this->getBlock( $this->getFileLength() - $this->eocdr['EOCDR size']
249 - $structSize, $structSize );
250 $this->eocdr64Locator = $data = $this->unpack( $block, $info );
252 if ( $data['signature'] !== "PK\x06\x07" ) {
253 // Note: Java will allow this and continue to read the
254 // EOCDR64, so we have to reject the upload, we can't
255 // just use the EOCDR header instead.
256 $this->error( 'zip-bad', 'wrong signature on Zip64 end of central directory locator' );
261 * Read the header called the "ZIP64 end of central directory record". It
262 * may replace the regular "end of central directory record" in ZIP64 files.
264 function readZip64EndOfCentralDirectoryRecord() {
265 if ( $this->eocdr64Locator['eocdr64 start disk'] != 0
266 || $this->eocdr64Locator['number of disks'] != 0 )
268 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR64 locator)' );
271 $info = array(
272 'signature' => array( 'string', 4 ),
273 'EOCDR64 size' => 8,
274 'version made by' => 2,
275 'version needed' => 2,
276 'disk' => 4,
277 'CD start disk' => 4,
278 'CD entries this disk' => 8,
279 'CD entries total' => 8,
280 'CD size' => 8,
281 'CD offset' => 8
283 $structSize = $this->getStructSize( $info );
284 $block = $this->getBlock( $this->eocdr64Locator['eocdr64 offset'], $structSize );
285 $this->eocdr64 = $data = $this->unpack( $block, $info );
286 if ( $data['signature'] !== "PK\x06\x06" ) {
287 $this->error( 'zip-bad', 'wrong signature on Zip64 end of central directory record' );
289 if ( $data['disk'] !== 0
290 || $data['CD start disk'] !== 0 )
292 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR64)' );
297 * Find the location of the central directory, as would be seen by a
298 * non-ZIP64 reader.
300 * @return List containing offset, size and end position.
302 function findOldCentralDirectory() {
303 $size = $this->eocdr['CD size'];
304 $offset = $this->eocdr['CD offset'];
305 $endPos = $this->eocdr['position'];
307 // Some readers use the EOCDR position instead of the offset field
308 // to find the directory, so to be safe, we check if they both agree.
309 if ( $offset + $size != $endPos ) {
310 $this->error( 'zip-bad', 'the central directory does not immediately precede the end ' .
311 'of central directory record' );
313 return array( $offset, $size );
317 * Find the location of the central directory, as would be seen by a
318 * ZIP64-compliant reader.
320 * @return array List containing offset, size and end position.
322 function findZip64CentralDirectory() {
323 // The spec is ambiguous about the exact rules of precedence between the
324 // ZIP64 headers and the original headers. Here we follow zip_util.c
325 // from OpenJDK 7.
326 $size = $this->eocdr['CD size'];
327 $offset = $this->eocdr['CD offset'];
328 $numEntries = $this->eocdr['CD entries total'];
329 $endPos = $this->eocdr['position'];
330 if ( $size == 0xffffffff
331 || $offset == 0xffffffff
332 || $numEntries == 0xffff )
334 $this->readZip64EndOfCentralDirectoryLocator();
336 if ( isset( $this->eocdr64Locator['eocdr64 offset'] ) ) {
337 $this->readZip64EndOfCentralDirectoryRecord();
338 if ( isset( $this->eocdr64['CD offset'] ) ) {
339 $size = $this->eocdr64['CD size'];
340 $offset = $this->eocdr64['CD offset'];
341 $endPos = $this->eocdr64Locator['eocdr64 offset'];
345 // Some readers use the EOCDR position instead of the offset field
346 // to find the directory, so to be safe, we check if they both agree.
347 if ( $offset + $size != $endPos ) {
348 $this->error( 'zip-bad', 'the central directory does not immediately precede the end ' .
349 'of central directory record' );
351 return array( $offset, $size );
355 * Read the central directory at the given location
357 function readCentralDirectory( $offset, $size ) {
358 $block = $this->getBlock( $offset, $size );
360 $fixedInfo = array(
361 'signature' => array( 'string', 4 ),
362 'version made by' => 2,
363 'version needed' => 2,
364 'general bits' => 2,
365 'compression method' => 2,
366 'mod time' => 2,
367 'mod date' => 2,
368 'crc-32' => 4,
369 'compressed size' => 4,
370 'uncompressed size' => 4,
371 'name length' => 2,
372 'extra field length' => 2,
373 'comment length' => 2,
374 'disk number start' => 2,
375 'internal attrs' => 2,
376 'external attrs' => 4,
377 'local header offset' => 4,
379 $fixedSize = $this->getStructSize( $fixedInfo );
381 $pos = 0;
382 while ( $pos < $size ) {
383 $data = $this->unpack( $block, $fixedInfo, $pos );
384 $pos += $fixedSize;
386 if ( $data['signature'] !== "PK\x01\x02" ) {
387 $this->error( 'zip-bad', 'Invalid signature found in directory entry' );
390 $variableInfo = array(
391 'name' => array( 'string', $data['name length'] ),
392 'extra field' => array( 'string', $data['extra field length'] ),
393 'comment' => array( 'string', $data['comment length'] ),
395 $data += $this->unpack( $block, $variableInfo, $pos );
396 $pos += $this->getStructSize( $variableInfo );
398 if ( $this->zip64 && (
399 $data['compressed size'] == 0xffffffff
400 || $data['uncompressed size'] == 0xffffffff
401 || $data['local header offset'] == 0xffffffff ) )
403 $zip64Data = $this->unpackZip64Extra( $data['extra field'] );
404 if ( $zip64Data ) {
405 $data = $zip64Data + $data;
409 if ( $this->testBit( $data['general bits'], self::GENERAL_CD_ENCRYPTED ) ) {
410 $this->error( 'zip-unsupported', 'central directory encryption is not supported' );
413 // Convert the timestamp into MediaWiki format
414 // For the format, please see the MS-DOS 2.0 Programmer's Reference,
415 // pages 3-5 and 3-6.
416 $time = $data['mod time'];
417 $date = $data['mod date'];
419 $year = 1980 + ( $date >> 9 );
420 $month = ( $date >> 5 ) & 15;
421 $day = $date & 31;
422 $hour = ( $time >> 11 ) & 31;
423 $minute = ( $time >> 5 ) & 63;
424 $second = ( $time & 31 ) * 2;
425 $timestamp = sprintf( "%04d%02d%02d%02d%02d%02d",
426 $year, $month, $day, $hour, $minute, $second );
428 // Convert the character set in the file name
429 if ( !function_exists( 'iconv' )
430 || $this->testBit( $data['general bits'], self::GENERAL_UTF8 ) )
432 $name = $data['name'];
433 } else {
434 $name = iconv( 'CP437', 'UTF-8', $data['name'] );
437 // Compile a data array for the user, with a sensible format
438 $userData = array(
439 'name' => $name,
440 'mtime' => $timestamp,
441 'size' => $data['uncompressed size'],
443 call_user_func( $this->callback, $userData );
448 * Interpret ZIP64 "extra field" data and return an associative array.
449 * @return array|bool
451 function unpackZip64Extra( $extraField ) {
452 $extraHeaderInfo = array(
453 'id' => 2,
454 'size' => 2,
456 $extraHeaderSize = $this->getStructSize( $extraHeaderInfo );
458 $zip64ExtraInfo = array(
459 'uncompressed size' => 8,
460 'compressed size' => 8,
461 'local header offset' => 8,
462 'disk number start' => 4,
465 $extraPos = 0;
466 while ( $extraPos < strlen( $extraField ) ) {
467 $extra = $this->unpack( $extraField, $extraHeaderInfo, $extraPos );
468 $extraPos += $extraHeaderSize;
469 $extra += $this->unpack( $extraField,
470 array( 'data' => array( 'string', $extra['size'] ) ),
471 $extraPos );
472 $extraPos += $extra['size'];
474 if ( $extra['id'] == self::ZIP64_EXTRA_HEADER ) {
475 return $this->unpack( $extra['data'], $zip64ExtraInfo );
479 return false;
483 * Get the length of the file.
485 function getFileLength() {
486 if ( $this->fileLength === null ) {
487 $stat = fstat( $this->file );
488 $this->fileLength = $stat['size'];
490 return $this->fileLength;
494 * Get the file contents from a given offset. If there are not enough bytes
495 * in the file to satisfy the request, an exception will be thrown.
497 * @param int $start The byte offset of the start of the block.
498 * @param int $length The number of bytes to return. If omitted, the remainder
499 * of the file will be returned.
501 * @return string
503 function getBlock( $start, $length = null ) {
504 $fileLength = $this->getFileLength();
505 if ( $start >= $fileLength ) {
506 $this->error( 'zip-bad', "getBlock() requested position $start, " .
507 "file length is $fileLength" );
509 if ( $length === null ) {
510 $length = $fileLength - $start;
512 $end = $start + $length;
513 if ( $end > $fileLength ) {
514 $this->error( 'zip-bad', "getBlock() requested end position $end, " .
515 "file length is $fileLength" );
517 $startSeg = floor( $start / self::SEGSIZE );
518 $endSeg = ceil( $end / self::SEGSIZE );
520 $block = '';
521 for ( $segIndex = $startSeg; $segIndex <= $endSeg; $segIndex++ ) {
522 $block .= $this->getSegment( $segIndex );
525 $block = substr( $block,
526 $start - $startSeg * self::SEGSIZE,
527 $length );
529 if ( strlen( $block ) < $length ) {
530 $this->error( 'zip-bad', 'getBlock() returned an unexpectedly small amount of data' );
533 return $block;
537 * Get a section of the file starting at position $segIndex * self::SEGSIZE,
538 * of length self::SEGSIZE. The result is cached. This is a helper function
539 * for getBlock().
541 * If there are not enough bytes in the file to satisfy the request, the
542 * return value will be truncated. If a request is made for a segment beyond
543 * the end of the file, an empty string will be returned.
544 * @return string
546 function getSegment( $segIndex ) {
547 if ( !isset( $this->buffer[$segIndex] ) ) {
548 $bytePos = $segIndex * self::SEGSIZE;
549 if ( $bytePos >= $this->getFileLength() ) {
550 $this->buffer[$segIndex] = '';
551 return '';
553 if ( fseek( $this->file, $bytePos ) ) {
554 $this->error( 'zip-bad', "seek to $bytePos failed" );
556 $seg = fread( $this->file, self::SEGSIZE );
557 if ( $seg === false ) {
558 $this->error( 'zip-bad', "read from $bytePos failed" );
560 $this->buffer[$segIndex] = $seg;
562 return $this->buffer[$segIndex];
566 * Get the size of a structure in bytes. See unpack() for the format of $struct.
567 * @return int
569 function getStructSize( $struct ) {
570 $size = 0;
571 foreach ( $struct as $type ) {
572 if ( is_array( $type ) ) {
573 list( , $fieldSize ) = $type;
574 $size += $fieldSize;
575 } else {
576 $size += $type;
579 return $size;
583 * Unpack a binary structure. This is like the built-in unpack() function
584 * except nicer.
586 * @param string $string The binary data input
588 * @param array $struct An associative array giving structure members and their
589 * types. In the key is the field name. The value may be either an
590 * integer, in which case the field is a little-endian unsigned integer
591 * encoded in the given number of bytes, or an array, in which case the
592 * first element of the array is the type name, and the subsequent
593 * elements are type-dependent parameters. Only one such type is defined:
594 * - "string": The second array element gives the length of string.
595 * Not null terminated.
597 * @param int $offset The offset into the string at which to start unpacking.
599 * @throws MWException
600 * @return array Unpacked associative array. Note that large integers in the input
601 * may be represented as floating point numbers in the return value, so
602 * the use of weak comparison is advised.
604 function unpack( $string, $struct, $offset = 0 ) {
605 $size = $this->getStructSize( $struct );
606 if ( $offset + $size > strlen( $string ) ) {
607 $this->error( 'zip-bad', 'unpack() would run past the end of the supplied string' );
610 $data = array();
611 $pos = $offset;
612 foreach ( $struct as $key => $type ) {
613 if ( is_array( $type ) ) {
614 list( $typeName, $fieldSize ) = $type;
615 switch ( $typeName ) {
616 case 'string':
617 $data[$key] = substr( $string, $pos, $fieldSize );
618 $pos += $fieldSize;
619 break;
620 default:
621 throw new MWException( __METHOD__ . ": invalid type \"$typeName\"" );
623 } else {
624 // Unsigned little-endian integer
625 $length = intval( $type );
627 // Calculate the value. Use an algorithm which automatically
628 // upgrades the value to floating point if necessary.
629 $value = 0;
630 for ( $i = $length - 1; $i >= 0; $i-- ) {
631 $value *= 256;
632 $value += ord( $string[$pos + $i] );
635 // Throw an exception if there was loss of precision
636 if ( $value > pow( 2, 52 ) ) {
637 $this->error( 'zip-unsupported', 'number too large to be stored in a double. ' .
638 'This could happen if we tried to unpack a 64-bit structure ' .
639 'at an invalid location.' );
641 $data[$key] = $value;
642 $pos += $length;
646 return $data;
650 * Returns a bit from a given position in an integer value, converted to
651 * boolean.
653 * @param $value integer
654 * @param int $bitIndex The index of the bit, where 0 is the LSB.
655 * @return bool
657 function testBit( $value, $bitIndex ) {
658 return (bool)( ( $value >> $bitIndex ) & 1 );
662 * Debugging helper function which dumps a string in hexdump -C format.
664 function hexDump( $s ) {
665 $n = strlen( $s );
666 for ( $i = 0; $i < $n; $i += 16 ) {
667 printf( "%08X ", $i );
668 for ( $j = 0; $j < 16; $j++ ) {
669 print " ";
670 if ( $j == 8 ) {
671 print " ";
673 if ( $i + $j >= $n ) {
674 print " ";
675 } else {
676 printf( "%02X", ord( $s[$i + $j] ) );
680 print " |";
681 for ( $j = 0; $j < 16; $j++ ) {
682 if ( $i + $j >= $n ) {
683 print " ";
684 } elseif ( ctype_print( $s[$i + $j] ) ) {
685 print $s[$i + $j];
686 } else {
687 print '.';
690 print "|\n";
696 * Internal exception class. Will be caught by private code.
698 class ZipDirectoryReaderError extends Exception {
699 var $errorCode;
701 function __construct( $code ) {
702 $this->errorCode = $code;
703 parent::__construct( "ZipDirectoryReader error: $code" );
707 * @return mixed
709 function getErrorCode() {
710 return $this->errorCode;