Follow-up r84814: revert redundant summary message addition.
[lhc/web/wiklou.git] / includes / ZipDirectoryReader.php
1 <?php
2
3 /**
4 * A class for reading ZIP file directories, for the purposes of upload
5 * verification.
6 *
7 * Only a functional interface is provided: ZipFileReader::read(). No access is
8 * given to object instances.
9 *
10 */
11 class ZipDirectoryReader {
12 /**
13 * Read a ZIP file and call a function for each file discovered in it.
14 *
15 * Because this class is aimed at verification, an error is raised on
16 * suspicious or ambiguous input, instead of emulating some standard
17 * behaviour.
18 *
19 * @param $fileName The archive file name
20 * @param $callback The callback function. It will be called for each file
21 * with a single associative array each time, with members:
22 *
23 * - name: The file name. Directories conventionally have a trailing
24 * slash.
25 *
26 * - mtime: The file modification time, in MediaWiki 14-char format
27 *
28 * - size: The uncompressed file size
29 *
30 * @param $options An associative array of read options, with the option
31 * name in the key. This may currently contain:
32 *
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
36 * ZIP64.
37 *
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.
46 *
47 * @return A Status object. The following fatal errors are defined:
48 *
49 * - zip-file-open-error: The file could not be opened.
50 *
51 * - zip-wrong-format: The file does not appear to be a ZIP file.
52 *
53 * - zip-bad: There was something wrong or ambiguous about the file
54 * data.
55 *
56 * - zip-unsupported: The ZIP file uses features which
57 * ZipDirectoryReader does not support.
58 *
59 * The default messages for those fatal errors are written in a way that
60 * makes sense for upload verification.
61 *
62 * If a fatal error is returned, more information about the error will be
63 * available in the debug log.
64 *
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.
68 */
69 public static function read( $fileName, $callback, $options = array() ) {
70 $zdr = new self( $fileName, $callback, $options );
71 return $zdr->execute();
72 }
73
74 /** The file name */
75 var $fileName;
76
77 /** The opened file resource */
78 var $file;
79
80 /** The cached length of the file, or null if it has not been loaded yet. */
81 var $fileLength;
82
83 /** A segmented cache of the file contents */
84 var $buffer;
85
86 /** The file data callback */
87 var $callback;
88
89 /** The ZIP64 mode */
90 var $zip64 = false;
91
92 /** Stored headers */
93 var $eocdr, $eocdr64, $eocdr64Locator;
94
95 /** The "extra field" ID for ZIP64 central directory entries */
96 const ZIP64_EXTRA_HEADER = 0x0001;
97
98 /** The segment size for the file contents cache */
99 const SEGSIZE = 16384;
100
101 /** The index of the "general field" bit for UTF-8 file names */
102 const GENERAL_UTF8 = 11;
103
104 /** The index of the "general field" bit for central directory encryption */
105 const GENERAL_CD_ENCRYPTED = 13;
106
107
108 /**
109 * Private constructor
110 */
111 protected function __construct( $fileName, $callback, $options ) {
112 $this->fileName = $fileName;
113 $this->callback = $callback;
114
115 if ( isset( $options['zip64'] ) ) {
116 $this->zip64 = $options['zip64'];
117 }
118 }
119
120 /**
121 * Read the directory according to settings in $this.
122 */
123 function execute() {
124 $this->file = fopen( $this->fileName, 'r' );
125 $this->data = array();
126 if ( !$this->file ) {
127 return Status::newFatal( 'zip-file-open-error' );
128 }
129
130 $status = Status::newGood();
131 try {
132 $this->readEndOfCentralDirectoryRecord();
133 if ( $this->zip64 ) {
134 list( $offset, $size ) = $this->findZip64CentralDirectory();
135 $this->readCentralDirectory( $offset, $size );
136 } else {
137 if ( $this->eocdr['CD size'] == 0xffffffff
138 || $this->eocdr['CD offset'] == 0xffffffff
139 || $this->eocdr['CD entries total'] == 0xffff )
140 {
141 $this->error( 'zip-unsupported', 'Central directory header indicates ZIP64, ' .
142 'but we are in legacy mode. Rejecting this upload is necessary to avoid '.
143 'opening vulnerabilities on clients using OpenJDK 7 or later.' );
144 }
145
146 list( $offset, $size ) = $this->findOldCentralDirectory();
147 $this->readCentralDirectory( $offset, $size );
148 }
149 } catch ( ZipDirectoryReaderError $e ) {
150 $status->fatal( $e->getErrorCode() );
151 }
152
153 fclose( $this->file );
154 return $status;
155 }
156
157 /**
158 * Throw an error, and log a debug message
159 */
160 function error( $code, $debugMessage ) {
161 wfDebug( __CLASS__.": Fatal error: $debugMessage\n" );
162 throw new ZipDirectoryReaderError( $code );
163 }
164
165 /**
166 * Read the header which is at the end of the central directory,
167 * unimaginatively called the "end of central directory record" by the ZIP
168 * spec.
169 */
170 function readEndOfCentralDirectoryRecord() {
171 $info = array(
172 'signature' => 4,
173 'disk' => 2,
174 'CD start disk' => 2,
175 'CD entries this disk' => 2,
176 'CD entries total' => 2,
177 'CD size' => 4,
178 'CD offset' => 4,
179 'file comment length' => 2,
180 );
181 $structSize = $this->getStructSize( $info );
182 $startPos = $this->getFileLength() - 65536 - $structSize;
183 if ( $startPos < 0 ) {
184 $startPos = 0;
185 }
186
187 $block = $this->getBlock( $startPos );
188 $sigPos = strrpos( $block, "PK\x05\x06" );
189 if ( $sigPos === false ) {
190 $this->error( 'zip-wrong-format',
191 "zip file lacks EOCDR signature. It probably isn't a zip file." );
192 }
193
194 $this->eocdr = $this->unpack( substr( $block, $sigPos ), $info );
195 $this->eocdr['EOCDR size'] = $structSize + $this->eocdr['file comment length'];
196
197 if ( $structSize + $this->eocdr['file comment length'] != strlen( $block ) - $sigPos ) {
198 $this->error( 'zip-bad', 'trailing bytes after the end of the file comment' );
199 }
200 if ( $this->eocdr['disk'] !== 0
201 || $this->eocdr['CD start disk'] !== 0 )
202 {
203 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR)' );
204 }
205 $this->eocdr += $this->unpack(
206 $block,
207 array( 'file comment' => array( 'string', $this->eocdr['file comment length'] ) ),
208 $sigPos + $structSize );
209 $this->eocdr['position'] = $startPos + $sigPos;
210 }
211
212 /**
213 * Read the header called the "ZIP64 end of central directory locator". An
214 * error will be raised if it does not exist.
215 */
216 function readZip64EndOfCentralDirectoryLocator() {
217 $info = array(
218 'signature' => array( 'string', 4 ),
219 'eocdr64 start disk' => 4,
220 'eocdr64 offset' => 8,
221 'number of disks' => 4,
222 );
223 $structSize = $this->getStructSize( $info );
224
225 $block = $this->getBlock( $this->getFileLength() - $this->eocdr['EOCDR size']
226 - $structSize, $structSize );
227 $this->eocdr64Locator = $data = $this->unpack( $block, $info );
228
229 if ( $data['signature'] !== "PK\x06\x07" ) {
230 // Note: Java will allow this and continue to read the
231 // EOCDR64, so we have to reject the upload, we can't
232 // just use the EOCDR header instead.
233 $this->error( 'zip-bad', 'wrong signature on Zip64 end of central directory locator' );
234 }
235 }
236
237 /**
238 * Read the header called the "ZIP64 end of central directory record". It
239 * may replace the regular "end of central directory record" in ZIP64 files.
240 */
241 function readZip64EndOfCentralDirectoryRecord() {
242 if ( $this->eocdr64Locator['eocdr64 start disk'] != 0
243 || $this->eocdr64Locator['number of disks'] != 0 )
244 {
245 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR64 locator)' );
246 }
247
248 $info = array(
249 'signature' => array( 'string', 4 ),
250 'EOCDR64 size' => 8,
251 'version made by' => 2,
252 'version needed' => 2,
253 'disk' => 4,
254 'CD start disk' => 4,
255 'CD entries this disk' => 8,
256 'CD entries total' => 8,
257 'CD size' => 8,
258 'CD offset' => 8
259 );
260 $structSize = $this->getStructSize( $info );
261 $block = $this->getBlock( $this->eocdr64Locator['eocdr64 offset'], $structSize );
262 $this->eocdr64 = $data = $this->unpack( $block, $info );
263 if ( $data['signature'] !== "PK\x06\x06" ) {
264 $this->error( 'zip-bad', 'wrong signature on Zip64 end of central directory record' );
265 }
266 if ( $data['disk'] !== 0
267 || $data['CD start disk'] !== 0 )
268 {
269 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR64)' );
270 }
271 }
272
273 /**
274 * Find the location of the central directory, as would be seen by a
275 * non-ZIP64 reader.
276 *
277 * @return List containing offset, size and end position.
278 */
279 function findOldCentralDirectory() {
280 $size = $this->eocdr['CD size'];
281 $offset = $this->eocdr['CD offset'];
282 $endPos = $this->eocdr['position'];
283
284 // Some readers use the EOCDR position instead of the offset field
285 // to find the directory, so to be safe, we check if they both agree.
286 if ( $offset + $size != $endPos ) {
287 $this->error( 'zip-bad', 'the central directory does not immediately precede the end ' .
288 'of central directory record' );
289 }
290 return array( $offset, $size );
291 }
292
293 /**
294 * Find the location of the central directory, as would be seen by a
295 * ZIP64-compliant reader.
296 *
297 * @return List containing offset, size and end position.
298 */
299 function findZip64CentralDirectory() {
300 // The spec is ambiguous about the exact rules of precedence between the
301 // ZIP64 headers and the original headers. Here we follow zip_util.c
302 // from OpenJDK 7.
303 $size = $this->eocdr['CD size'];
304 $offset = $this->eocdr['CD offset'];
305 $numEntries = $this->eocdr['CD entries total'];
306 $endPos = $this->eocdr['position'];
307 if ( $size == 0xffffffff
308 || $offset == 0xffffffff
309 || $numEntries == 0xffff )
310 {
311 $this->readZip64EndOfCentralDirectoryLocator();
312
313 if ( isset( $this->eocdr64Locator['eocdr64 offset'] ) ) {
314 $this->readZip64EndOfCentralDirectoryRecord();
315 if ( isset( $this->eocdr64['CD offset'] ) ) {
316 $size = $this->eocdr64['CD size'];
317 $offset = $this->eocdr64['CD offset'];
318 $endPos = $this->eocdr64Locator['eocdr64 offset'];
319 }
320 }
321 }
322 // Some readers use the EOCDR position instead of the offset field
323 // to find the directory, so to be safe, we check if they both agree.
324 if ( $offset + $size != $endPos ) {
325 $this->error( 'zip-bad', 'the central directory does not immediately precede the end ' .
326 'of central directory record' );
327 }
328 return array( $offset, $size );
329 }
330
331 /**
332 * Read the central directory at the given location
333 */
334 function readCentralDirectory( $offset, $size ) {
335 $block = $this->getBlock( $offset, $size );
336
337 $fixedInfo = array(
338 'signature' => array( 'string', 4 ),
339 'version made by' => 2,
340 'version needed' => 2,
341 'general bits' => 2,
342 'compression method' => 2,
343 'mod time' => 2,
344 'mod date' => 2,
345 'crc-32' => 4,
346 'compressed size' => 4,
347 'uncompressed size' => 4,
348 'name length' => 2,
349 'extra field length' => 2,
350 'comment length' => 2,
351 'disk number start' => 2,
352 'internal attrs' => 2,
353 'external attrs' => 4,
354 'local header offset' => 4,
355 );
356 $fixedSize = $this->getStructSize( $fixedInfo );
357
358 $pos = 0;
359 while ( $pos < $size ) {
360 $data = $this->unpack( $block, $fixedInfo, $pos );
361 $pos += $fixedSize;
362
363 if ( $data['signature'] !== "PK\x01\x02" ) {
364 $this->error( 'zip-bad', 'Invalid signature found in directory entry' );
365 }
366
367 $variableInfo = array(
368 'name' => array( 'string', $data['name length'] ),
369 'extra field' => array( 'string', $data['extra field length'] ),
370 'comment' => array( 'string', $data['comment length'] ),
371 );
372 $data += $this->unpack( $block, $variableInfo, $pos );
373 $pos += $this->getStructSize( $variableInfo );
374
375 if ( $this->zip64 && (
376 $data['compressed size'] == 0xffffffff
377 || $data['uncompressed size'] == 0xffffffff
378 || $data['local header offset'] == 0xffffffff ) )
379 {
380 $zip64Data = $this->unpackZip64Extra( $data['extra field'] );
381 if ( $zip64Data ) {
382 $data = $zip64Data + $data;
383 }
384 }
385
386 if ( $this->testBit( $data['general bits'], self::GENERAL_CD_ENCRYPTED ) ) {
387 $this->error( 'zip-unsupported', 'central directory encryption is not supported' );
388 }
389
390 // Convert the timestamp into MediaWiki format
391 // For the format, please see the MS-DOS 2.0 Programmer's Reference,
392 // pages 3-5 and 3-6.
393 $time = $data['mod time'];
394 $date = $data['mod date'];
395
396 $year = 1980 + ( $date >> 9 );
397 $month = ( $date >> 5 ) & 15;
398 $day = $date & 31;
399 $hour = ( $time >> 11 ) & 31;
400 $minute = ( $time >> 5 ) & 63;
401 $second = ( $time & 31 ) * 2;
402 $timestamp = sprintf( "%04d%02d%02d%02d%02d%02d",
403 $year, $month, $day, $hour, $minute, $second );
404
405 // Convert the character set in the file name
406 if ( !function_exists( 'iconv' )
407 || $this->testBit( $data['general bits'], self::GENERAL_UTF8 ) )
408 {
409 $name = $data['name'];
410 } else {
411 $name = iconv( 'CP437', 'UTF-8', $data['name'] );
412 }
413
414 // Compile a data array for the user, with a sensible format
415 $userData = array(
416 'name' => $name,
417 'mtime' => $timestamp,
418 'size' => $data['uncompressed size'],
419 );
420 call_user_func( $this->callback, $userData );
421 }
422 }
423
424 /**
425 * Interpret ZIP64 "extra field" data and return an associative array.
426 */
427 function unpackZip64Extra( $extraField ) {
428 $extraHeaderInfo = array(
429 'id' => 2,
430 'size' => 2,
431 );
432 $extraHeaderSize = $this->getStructSize( $extraHeaderInfo );
433
434 $zip64ExtraInfo = array(
435 'uncompressed size' => 8,
436 'compressed size' => 8,
437 'local header offset' => 8,
438 'disk number start' => 4,
439 );
440
441 $extraPos = 0;
442 while ( $extraPos < strlen( $extraField ) ) {
443 $extra = $this->unpack( $extraField, $extraHeaderInfo, $extraPos );
444 $extraPos += $extraHeaderSize;
445 $extra += $this->unpack( $extraField,
446 array( 'data' => array( 'string', $extra['size'] ) ),
447 $extraPos );
448 $extraPos += $extra['size'];
449
450 if ( $extra['id'] == self::ZIP64_EXTRA_HEADER ) {
451 return $this->unpack( $extra['data'], $zip64ExtraInfo );
452 }
453 }
454
455 return false;
456 }
457
458 /**
459 * Get the length of the file.
460 */
461 function getFileLength() {
462 if ( $this->fileLength === null ) {
463 $stat = fstat( $this->file );
464 $this->fileLength = $stat['size'];
465 }
466 return $this->fileLength;
467 }
468
469 /**
470 * Get the file contents from a given offset. If there are not enough bytes
471 * in the file to satisfy the request, an exception will be thrown.
472 *
473 * @param $start The byte offset of the start of the block.
474 * @param $length The number of bytes to return. If omitted, the remainder
475 * of the file will be returned.
476 *
477 * @return string
478 */
479 function getBlock( $start, $length = null ) {
480 $fileLength = $this->getFileLength();
481 if ( $start >= $fileLength ) {
482 $this->error( 'zip-bad', "getBlock() requested position $start, " .
483 "file length is $fileLength" );
484 }
485 if ( $length === null ) {
486 $length = $fileLength - $start;
487 }
488 $end = $start + $length;
489 if ( $end > $fileLength ) {
490 $this->error( 'zip-bad', "getBlock() requested end position $end, " .
491 "file length is $fileLength" );
492 }
493 $startSeg = floor( $start / self::SEGSIZE );
494 $endSeg = ceil( $end / self::SEGSIZE );
495
496 $block = '';
497 for ( $segIndex = $startSeg; $segIndex <= $endSeg; $segIndex++ ) {
498 $block .= $this->getSegment( $segIndex );
499 }
500
501 $block = substr( $block,
502 $start - $startSeg * self::SEGSIZE,
503 $length );
504
505 if ( strlen( $block ) < $length ) {
506 $this->error( 'zip-bad', 'getBlock() returned an unexpectedly small amount of data' );
507 }
508
509 return $block;
510 }
511
512 /**
513 * Get a section of the file starting at position $segIndex * self::SEGSIZE,
514 * of length self::SEGSIZE. The result is cached. This is a helper function
515 * for getBlock().
516 *
517 * If there are not enough bytes in the file to satsify the request, the
518 * return value will be truncated. If a request is made for a segment beyond
519 * the end of the file, an empty string will be returned.
520 */
521 function getSegment( $segIndex ) {
522 if ( !isset( $this->buffer[$segIndex] ) ) {
523 $bytePos = $segIndex * self::SEGSIZE;
524 if ( $bytePos >= $this->getFileLength() ) {
525 $this->buffer[$segIndex] = '';
526 return '';
527 }
528 if ( fseek( $this->file, $bytePos ) ) {
529 $this->error( 'zip-bad', "seek to $bytePos failed" );
530 }
531 $seg = fread( $this->file, self::SEGSIZE );
532 if ( $seg === false ) {
533 $this->error( 'zip-bad', "read from $bytePos failed" );
534 }
535 $this->buffer[$segIndex] = $seg;
536 }
537 return $this->buffer[$segIndex];
538 }
539
540 /**
541 * Get the size of a structure in bytes. See unpack() for the format of $struct.
542 */
543 function getStructSize( $struct ) {
544 $size = 0;
545 foreach ( $struct as $key => $type ) {
546 if ( is_array( $type ) ) {
547 list( $typeName, $fieldSize ) = $type;
548 $size += $fieldSize;
549 } else {
550 $size += $type;
551 }
552 }
553 return $size;
554 }
555
556 /**
557 * Unpack a binary structure. This is like the built-in unpack() function
558 * except nicer.
559 *
560 * @param $string The binary data input
561 *
562 * @param $struct An associative array giving structure members and their
563 * types. In the key is the field name. The value may be either an
564 * integer, in which case the field is a little-endian unsigned integer
565 * encoded in the given number of bytes, or an array, in which case the
566 * first element of the array is the type name, and the subsequent
567 * elements are type-dependent parameters. Only one such type is defined:
568 * - "string": The second array element gives the length of string.
569 * Not null terminated.
570 *
571 * @param $offset The offset into the string at which to start unpacking.
572 *
573 * @return Unpacked associative array. Note that large integers in the input
574 * may be represented as floating point numbers in the return value, so
575 * the use of weak comparison is advised.
576 */
577 function unpack( $string, $struct, $offset = 0 ) {
578 $size = $this->getStructSize( $struct );
579 if ( $offset + $size > strlen( $string ) ) {
580 $this->error( 'zip-bad', 'unpack() would run past the end of the supplied string' );
581 }
582
583 $data = array();
584 $pos = $offset;
585 foreach ( $struct as $key => $type ) {
586 if ( is_array( $type ) ) {
587 list( $typeName, $fieldSize ) = $type;
588 switch ( $typeName ) {
589 case 'string':
590 $data[$key] = substr( $string, $pos, $fieldSize );
591 $pos += $fieldSize;
592 break;
593 default:
594 throw new MWException( __METHOD__.": invalid type \"$typeName\"" );
595 }
596 } else {
597 // Unsigned little-endian integer
598 $length = intval( $type );
599 $bytes = substr( $string, $pos, $length );
600
601 // Calculate the value. Use an algorithm which automatically
602 // upgrades the value to floating point if necessary.
603 $value = 0;
604 for ( $i = $length - 1; $i >= 0; $i-- ) {
605 $value *= 256;
606 $value += ord( $string[$pos + $i] );
607 }
608
609 // Throw an exception if there was loss of precision
610 if ( $value > pow( 2, 52 ) ) {
611 $this->error( 'zip-unsupported', 'number too large to be stored in a double. ' .
612 'This could happen if we tried to unpack a 64-bit structure ' .
613 'at an invalid location.' );
614 }
615 $data[$key] = $value;
616 $pos += $length;
617 }
618 }
619
620 return $data;
621 }
622
623 /**
624 * Returns a bit from a given position in an integer value, converted to
625 * boolean.
626 *
627 * @param $value integer
628 * @param $bitIndex The index of the bit, where 0 is the LSB.
629 */
630 function testBit( $value, $bitIndex ) {
631 return (bool)( ( $value >> $bitIndex ) & 1 );
632 }
633
634 /**
635 * Debugging helper function which dumps a string in hexdump -C format.
636 */
637 function hexDump( $s ) {
638 $n = strlen( $s );
639 for ( $i = 0; $i < $n; $i += 16 ) {
640 printf( "%08X ", $i );
641 for ( $j = 0; $j < 16; $j++ ) {
642 print " ";
643 if ( $j == 8 ) {
644 print " ";
645 }
646 if ( $i + $j >= $n ) {
647 print " ";
648 } else {
649 printf( "%02X", ord( $s[$i + $j] ) );
650 }
651 }
652
653 print " |";
654 for ( $j = 0; $j < 16; $j++ ) {
655 if ( $i + $j >= $n ) {
656 print " ";
657 } elseif ( ctype_print( $s[$i + $j] ) ) {
658 print $s[$i + $j];
659 } else {
660 print '.';
661 }
662 }
663 print "|\n";
664 }
665 }
666 }
667
668 /**
669 * Internal exception class. Will be caught by private code.
670 */
671 class ZipDirectoryReaderError extends Exception {
672 var $code;
673
674 function __construct( $code ) {
675 $this->code = $code;
676 parent::__construct( "ZipDirectoryReader error: $code" );
677 }
678
679 function getErrorCode() {
680 return $this->code;
681 }
682 }