Add dirmark so RecentChanges displays properly with CleanChanges extension and wgBett...
[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 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:
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 Array 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 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 * @return Status
124 */
125 function execute() {
126 $this->file = fopen( $this->fileName, 'r' );
127 $this->data = array();
128 if ( !$this->file ) {
129 return Status::newFatal( 'zip-file-open-error' );
130 }
131
132 $status = Status::newGood();
133 try {
134 $this->readEndOfCentralDirectoryRecord();
135 if ( $this->zip64 ) {
136 list( $offset, $size ) = $this->findZip64CentralDirectory();
137 $this->readCentralDirectory( $offset, $size );
138 } else {
139 if ( $this->eocdr['CD size'] == 0xffffffff
140 || $this->eocdr['CD offset'] == 0xffffffff
141 || $this->eocdr['CD entries total'] == 0xffff )
142 {
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.' );
146 }
147
148 list( $offset, $size ) = $this->findOldCentralDirectory();
149 $this->readCentralDirectory( $offset, $size );
150 }
151 } catch ( ZipDirectoryReaderError $e ) {
152 $status->fatal( $e->getErrorCode() );
153 }
154
155 fclose( $this->file );
156 return $status;
157 }
158
159 /**
160 * Throw an error, and log a debug message
161 */
162 function error( $code, $debugMessage ) {
163 wfDebug( __CLASS__.": Fatal error: $debugMessage\n" );
164 throw new ZipDirectoryReaderError( $code );
165 }
166
167 /**
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
170 * spec.
171 */
172 function readEndOfCentralDirectoryRecord() {
173 $info = array(
174 'signature' => 4,
175 'disk' => 2,
176 'CD start disk' => 2,
177 'CD entries this disk' => 2,
178 'CD entries total' => 2,
179 'CD size' => 4,
180 'CD offset' => 4,
181 'file comment length' => 2,
182 );
183 $structSize = $this->getStructSize( $info );
184 $startPos = $this->getFileLength() - 65536 - $structSize;
185 if ( $startPos < 0 ) {
186 $startPos = 0;
187 }
188
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." );
194 }
195
196 $this->eocdr = $this->unpack( substr( $block, $sigPos ), $info );
197 $this->eocdr['EOCDR size'] = $structSize + $this->eocdr['file comment length'];
198
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' );
201 }
202 if ( $this->eocdr['disk'] !== 0
203 || $this->eocdr['CD start disk'] !== 0 )
204 {
205 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR)' );
206 }
207 $this->eocdr += $this->unpack(
208 $block,
209 array( 'file comment' => array( 'string', $this->eocdr['file comment length'] ) ),
210 $sigPos + $structSize );
211 $this->eocdr['position'] = $startPos + $sigPos;
212 }
213
214 /**
215 * Read the header called the "ZIP64 end of central directory locator". An
216 * error will be raised if it does not exist.
217 */
218 function readZip64EndOfCentralDirectoryLocator() {
219 $info = array(
220 'signature' => array( 'string', 4 ),
221 'eocdr64 start disk' => 4,
222 'eocdr64 offset' => 8,
223 'number of disks' => 4,
224 );
225 $structSize = $this->getStructSize( $info );
226
227 $block = $this->getBlock( $this->getFileLength() - $this->eocdr['EOCDR size']
228 - $structSize, $structSize );
229 $this->eocdr64Locator = $data = $this->unpack( $block, $info );
230
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' );
236 }
237 }
238
239 /**
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.
242 */
243 function readZip64EndOfCentralDirectoryRecord() {
244 if ( $this->eocdr64Locator['eocdr64 start disk'] != 0
245 || $this->eocdr64Locator['number of disks'] != 0 )
246 {
247 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR64 locator)' );
248 }
249
250 $info = array(
251 'signature' => array( 'string', 4 ),
252 'EOCDR64 size' => 8,
253 'version made by' => 2,
254 'version needed' => 2,
255 'disk' => 4,
256 'CD start disk' => 4,
257 'CD entries this disk' => 8,
258 'CD entries total' => 8,
259 'CD size' => 8,
260 'CD offset' => 8
261 );
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' );
267 }
268 if ( $data['disk'] !== 0
269 || $data['CD start disk'] !== 0 )
270 {
271 $this->error( 'zip-unsupported', 'more than one disk (in EOCDR64)' );
272 }
273 }
274
275 /**
276 * Find the location of the central directory, as would be seen by a
277 * non-ZIP64 reader.
278 *
279 * @return List containing offset, size and end position.
280 */
281 function findOldCentralDirectory() {
282 $size = $this->eocdr['CD size'];
283 $offset = $this->eocdr['CD offset'];
284 $endPos = $this->eocdr['position'];
285
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' );
291 }
292 return array( $offset, $size );
293 }
294
295 /**
296 * Find the location of the central directory, as would be seen by a
297 * ZIP64-compliant reader.
298 *
299 * @return List containing offset, size and end position.
300 */
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
304 // from OpenJDK 7.
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 )
312 {
313 $this->readZip64EndOfCentralDirectoryLocator();
314
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'];
321 }
322 }
323 }
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' );
329 }
330 return array( $offset, $size );
331 }
332
333 /**
334 * Read the central directory at the given location
335 */
336 function readCentralDirectory( $offset, $size ) {
337 $block = $this->getBlock( $offset, $size );
338
339 $fixedInfo = array(
340 'signature' => array( 'string', 4 ),
341 'version made by' => 2,
342 'version needed' => 2,
343 'general bits' => 2,
344 'compression method' => 2,
345 'mod time' => 2,
346 'mod date' => 2,
347 'crc-32' => 4,
348 'compressed size' => 4,
349 'uncompressed size' => 4,
350 'name length' => 2,
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,
357 );
358 $fixedSize = $this->getStructSize( $fixedInfo );
359
360 $pos = 0;
361 while ( $pos < $size ) {
362 $data = $this->unpack( $block, $fixedInfo, $pos );
363 $pos += $fixedSize;
364
365 if ( $data['signature'] !== "PK\x01\x02" ) {
366 $this->error( 'zip-bad', 'Invalid signature found in directory entry' );
367 }
368
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'] ),
373 );
374 $data += $this->unpack( $block, $variableInfo, $pos );
375 $pos += $this->getStructSize( $variableInfo );
376
377 if ( $this->zip64 && (
378 $data['compressed size'] == 0xffffffff
379 || $data['uncompressed size'] == 0xffffffff
380 || $data['local header offset'] == 0xffffffff ) )
381 {
382 $zip64Data = $this->unpackZip64Extra( $data['extra field'] );
383 if ( $zip64Data ) {
384 $data = $zip64Data + $data;
385 }
386 }
387
388 if ( $this->testBit( $data['general bits'], self::GENERAL_CD_ENCRYPTED ) ) {
389 $this->error( 'zip-unsupported', 'central directory encryption is not supported' );
390 }
391
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'];
397
398 $year = 1980 + ( $date >> 9 );
399 $month = ( $date >> 5 ) & 15;
400 $day = $date & 31;
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 );
406
407 // Convert the character set in the file name
408 if ( !function_exists( 'iconv' )
409 || $this->testBit( $data['general bits'], self::GENERAL_UTF8 ) )
410 {
411 $name = $data['name'];
412 } else {
413 $name = iconv( 'CP437', 'UTF-8', $data['name'] );
414 }
415
416 // Compile a data array for the user, with a sensible format
417 $userData = array(
418 'name' => $name,
419 'mtime' => $timestamp,
420 'size' => $data['uncompressed size'],
421 );
422 call_user_func( $this->callback, $userData );
423 }
424 }
425
426 /**
427 * Interpret ZIP64 "extra field" data and return an associative array.
428 */
429 function unpackZip64Extra( $extraField ) {
430 $extraHeaderInfo = array(
431 'id' => 2,
432 'size' => 2,
433 );
434 $extraHeaderSize = $this->getStructSize( $extraHeaderInfo );
435
436 $zip64ExtraInfo = array(
437 'uncompressed size' => 8,
438 'compressed size' => 8,
439 'local header offset' => 8,
440 'disk number start' => 4,
441 );
442
443 $extraPos = 0;
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'] ) ),
449 $extraPos );
450 $extraPos += $extra['size'];
451
452 if ( $extra['id'] == self::ZIP64_EXTRA_HEADER ) {
453 return $this->unpack( $extra['data'], $zip64ExtraInfo );
454 }
455 }
456
457 return false;
458 }
459
460 /**
461 * Get the length of the file.
462 */
463 function getFileLength() {
464 if ( $this->fileLength === null ) {
465 $stat = fstat( $this->file );
466 $this->fileLength = $stat['size'];
467 }
468 return $this->fileLength;
469 }
470
471 /**
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.
474 *
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.
478 *
479 * @return string
480 */
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" );
486 }
487 if ( $length === null ) {
488 $length = $fileLength - $start;
489 }
490 $end = $start + $length;
491 if ( $end > $fileLength ) {
492 $this->error( 'zip-bad', "getBlock() requested end position $end, " .
493 "file length is $fileLength" );
494 }
495 $startSeg = floor( $start / self::SEGSIZE );
496 $endSeg = ceil( $end / self::SEGSIZE );
497
498 $block = '';
499 for ( $segIndex = $startSeg; $segIndex <= $endSeg; $segIndex++ ) {
500 $block .= $this->getSegment( $segIndex );
501 }
502
503 $block = substr( $block,
504 $start - $startSeg * self::SEGSIZE,
505 $length );
506
507 if ( strlen( $block ) < $length ) {
508 $this->error( 'zip-bad', 'getBlock() returned an unexpectedly small amount of data' );
509 }
510
511 return $block;
512 }
513
514 /**
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
517 * for getBlock().
518 *
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.
522 */
523 function getSegment( $segIndex ) {
524 if ( !isset( $this->buffer[$segIndex] ) ) {
525 $bytePos = $segIndex * self::SEGSIZE;
526 if ( $bytePos >= $this->getFileLength() ) {
527 $this->buffer[$segIndex] = '';
528 return '';
529 }
530 if ( fseek( $this->file, $bytePos ) ) {
531 $this->error( 'zip-bad', "seek to $bytePos failed" );
532 }
533 $seg = fread( $this->file, self::SEGSIZE );
534 if ( $seg === false ) {
535 $this->error( 'zip-bad', "read from $bytePos failed" );
536 }
537 $this->buffer[$segIndex] = $seg;
538 }
539 return $this->buffer[$segIndex];
540 }
541
542 /**
543 * Get the size of a structure in bytes. See unpack() for the format of $struct.
544 */
545 function getStructSize( $struct ) {
546 $size = 0;
547 foreach ( $struct as $type ) {
548 if ( is_array( $type ) ) {
549 list( $typeName, $fieldSize ) = $type;
550 $size += $fieldSize;
551 } else {
552 $size += $type;
553 }
554 }
555 return $size;
556 }
557
558 /**
559 * Unpack a binary structure. This is like the built-in unpack() function
560 * except nicer.
561 *
562 * @param $string The binary data input
563 *
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.
572 *
573 * @param $offset The offset into the string at which to start unpacking.
574 *
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.
578 */
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' );
583 }
584
585 $data = array();
586 $pos = $offset;
587 foreach ( $struct as $key => $type ) {
588 if ( is_array( $type ) ) {
589 list( $typeName, $fieldSize ) = $type;
590 switch ( $typeName ) {
591 case 'string':
592 $data[$key] = substr( $string, $pos, $fieldSize );
593 $pos += $fieldSize;
594 break;
595 default:
596 throw new MWException( __METHOD__.": invalid type \"$typeName\"" );
597 }
598 } else {
599 // Unsigned little-endian integer
600 $length = intval( $type );
601 $bytes = substr( $string, $pos, $length );
602
603 // Calculate the value. Use an algorithm which automatically
604 // upgrades the value to floating point if necessary.
605 $value = 0;
606 for ( $i = $length - 1; $i >= 0; $i-- ) {
607 $value *= 256;
608 $value += ord( $string[$pos + $i] );
609 }
610
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.' );
616 }
617 $data[$key] = $value;
618 $pos += $length;
619 }
620 }
621
622 return $data;
623 }
624
625 /**
626 * Returns a bit from a given position in an integer value, converted to
627 * boolean.
628 *
629 * @param $value integer
630 * @param $bitIndex The index of the bit, where 0 is the LSB.
631 */
632 function testBit( $value, $bitIndex ) {
633 return (bool)( ( $value >> $bitIndex ) & 1 );
634 }
635
636 /**
637 * Debugging helper function which dumps a string in hexdump -C format.
638 */
639 function hexDump( $s ) {
640 $n = strlen( $s );
641 for ( $i = 0; $i < $n; $i += 16 ) {
642 printf( "%08X ", $i );
643 for ( $j = 0; $j < 16; $j++ ) {
644 print " ";
645 if ( $j == 8 ) {
646 print " ";
647 }
648 if ( $i + $j >= $n ) {
649 print " ";
650 } else {
651 printf( "%02X", ord( $s[$i + $j] ) );
652 }
653 }
654
655 print " |";
656 for ( $j = 0; $j < 16; $j++ ) {
657 if ( $i + $j >= $n ) {
658 print " ";
659 } elseif ( ctype_print( $s[$i + $j] ) ) {
660 print $s[$i + $j];
661 } else {
662 print '.';
663 }
664 }
665 print "|\n";
666 }
667 }
668 }
669
670 /**
671 * Internal exception class. Will be caught by private code.
672 */
673 class ZipDirectoryReaderError extends Exception {
674 var $code;
675
676 function __construct( $code ) {
677 $this->code = $code;
678 parent::__construct( "ZipDirectoryReader error: $code" );
679 }
680
681 function getErrorCode() {
682 return $this->code;
683 }
684 }