MediaWiki  master
MSCompoundFileReader.php
Go to the documentation of this file.
1 <?php
2 /*
3  * Copyright 2019 Wikimedia Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may
6  * not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software distributed
12  * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
13  * OF ANY KIND, either express or implied. See the License for the
14  * specific language governing permissions and limitations under the License.
15  */
16 
33  private $file;
34  private $header;
35  private $mime;
36  private $mimeFromClsid;
37  private $error;
38  private $errorCode;
39  private $valid = false;
40 
41  private $sectorLength;
42  private $difat;
43  private $fat = [];
44 
45  const TYPE_UNALLOCATED = 0;
46  const TYPE_STORAGE = 1;
47  const TYPE_STREAM = 2;
48  const TYPE_ROOT = 5;
49 
50  const ERROR_FILE_OPEN = 1;
51  const ERROR_SEEK = 2;
52  const ERROR_READ = 3;
56 
57  private static $mimesByClsid = [
58  // From http://justsolve.archiveteam.org/wiki/Microsoft_Compound_File
59  '00020810-0000-0000-C000-000000000046' => 'application/vnd.ms-excel',
60  '00020820-0000-0000-C000-000000000046' => 'application/vnd.ms-excel',
61  '00020906-0000-0000-C000-000000000046' => 'application/msword',
62  '64818D10-4F9B-11CF-86EA-00AA00B929E8' => 'application/vnd.ms-powerpoint',
63  ];
64 
77  public static function readFile( $fileName ) {
78  $handle = fopen( $fileName, 'r' );
79  if ( $handle === false ) {
80  return [
81  'valid' => false,
82  'error' => 'file does not exist',
83  'errorCode' => self::ERROR_FILE_OPEN
84  ];
85  }
86  return self::readHandle( $handle );
87  }
88 
101  public static function readHandle( $fileHandle ) {
102  $reader = new self( $fileHandle );
103  $info = [
104  'valid' => $reader->valid,
105  'mime' => $reader->mime,
106  'mimeFromClsid' => $reader->mimeFromClsid
107  ];
108  if ( $reader->error ) {
109  $info['error'] = $reader->error;
110  $info['errorCode'] = $reader->errorCode;
111  }
112  return $info;
113  }
114 
115  private function __construct( $fileHandle ) {
116  $this->file = $fileHandle;
117  try {
118  $this->init();
119  } catch ( RuntimeException $e ) {
120  $this->valid = false;
121  $this->error = $e->getMessage();
122  $this->errorCode = $e->getCode();
123  }
124  }
125 
126  private function init() {
127  $this->header = $this->unpackOffset( 0, [
128  'header_signature' => 8,
129  'header_clsid' => 16,
130  'minor_version' => 2,
131  'major_version' => 2,
132  'byte_order' => 2,
133  'sector_shift' => 2,
134  'mini_sector_shift' => 2,
135  'reserved' => 6,
136  'num_dir_sectors' => 4,
137  'num_fat_sectors' => 4,
138  'first_dir_sector' => 4,
139  'transaction_signature_number' => 4,
140  'mini_stream_cutoff_size' => 4,
141  'first_mini_fat_sector' => 4,
142  'num_mini_fat_sectors' => 4,
143  'first_difat_sector' => 4,
144  'num_difat_sectors' => 4,
145  'difat' => 436,
146  ] );
147  if ( $this->header['header_signature'] !== "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" ) {
148  $this->error( 'invalid signature: ' . bin2hex( $this->header['header_signature'] ),
149  self::ERROR_INVALID_SIGNATURE );
150  }
151  // @phan-suppress-next-line PhanTypeInvalidRightOperandOfIntegerOp
152  $this->sectorLength = 1 << $this->header['sector_shift'];
153  $this->readDifat();
154  $this->readDirectory();
155 
156  $this->valid = true;
157  }
158 
159  private function sectorOffset( $sectorId ) {
160  return $this->sectorLength * ( $sectorId + 1 );
161  }
162 
163  private function decodeClsid( $binaryClsid ) {
164  $parts = unpack( 'Va/vb/vc/C8d', $binaryClsid );
165  return sprintf( "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
166  $parts['a'],
167  $parts['b'],
168  $parts['c'],
169  $parts['d1'],
170  $parts['d2'],
171  $parts['d3'],
172  $parts['d4'],
173  $parts['d5'],
174  $parts['d6'],
175  $parts['d7'],
176  $parts['d8']
177  );
178  }
179 
185  private function unpackOffset( $offset, $struct ) {
186  $block = $this->readOffset( $offset, array_sum( $struct ) );
187  return $this->unpack( $block, 0, $struct );
188  }
189 
196  private function unpack( $block, $offset, $struct ) {
197  $data = [];
198  foreach ( $struct as $key => $length ) {
199  if ( $length > 4 ) {
200  $data[$key] = substr( $block, $offset, $length );
201  } else {
202  $data[$key] = $this->bin2dec( $block, $offset, $length );
203  }
204  $offset += $length;
205  }
206  return $data;
207  }
208 
209  private function bin2dec( $str, $offset, $length ) {
210  $value = 0;
211  for ( $i = $length - 1; $i >= 0; $i-- ) {
212  $value *= 256;
213  $value += ord( $str[$offset + $i] );
214  }
215  return $value;
216  }
217 
218  private function readOffset( $offset, $length ) {
219  $this->fseek( $offset );
220  Wikimedia\suppressWarnings();
221  $block = fread( $this->file, $length );
222  Wikimedia\restoreWarnings();
223  if ( $block === false ) {
224  $this->error( 'error reading from file', self::ERROR_READ );
225  }
226  if ( strlen( $block ) !== $length ) {
227  $this->error( 'unable to read the required number of bytes from the file',
228  self::ERROR_READ_PAST_END );
229  }
230  return $block;
231  }
232 
233  private function readSector( $sectorId ) {
234  // @phan-suppress-next-line PhanTypeInvalidRightOperandOfIntegerOp
235  return $this->readOffset( $this->sectorOffset( $sectorId ), 1 << $this->header['sector_shift'] );
236  }
237 
238  private function error( $message, $code ) {
239  throw new RuntimeException( $message, $code );
240  }
241 
242  private function fseek( $offset ) {
243  Wikimedia\suppressWarnings();
244  $result = fseek( $this->file, $offset );
245  Wikimedia\restoreWarnings();
246  if ( $result !== 0 ) {
247  $this->error( "unable to seek to offset $offset", self::ERROR_SEEK );
248  }
249  }
250 
251  private function readDifat() {
252  $binaryDifat = $this->header['difat'];
253  $nextDifatSector = $this->header['first_difat_sector'];
254  for ( $i = 0; $i < $this->header['num_difat_sectors']; $i++ ) {
255  $block = $this->readSector( $nextDifatSector );
256  $binaryDifat .= substr( $block, 0, $this->sectorLength - 4 );
257  $nextDifatSector = $this->bin2dec( $block, $this->sectorLength - 4, 4 );
258  if ( $nextDifatSector == 0xFFFFFFFE ) {
259  break;
260  }
261  }
262 
263  $this->difat = [];
264  for ( $pos = 0; $pos < strlen( $binaryDifat ); $pos += 4 ) {
265  $fatSector = $this->bin2dec( $binaryDifat, $pos, 4 );
266  if ( $fatSector < 0xFFFFFFFC ) {
267  $this->difat[] = $fatSector;
268  } else {
269  break;
270  }
271  }
272  }
273 
274  private function getNextSectorIdFromFat( $sectorId ) {
275  $entriesPerSector = intdiv( $this->sectorLength, 4 );
276  $fatSectorId = intdiv( $sectorId, $entriesPerSector );
277  $fatSectorArray = $this->getFatSector( $fatSectorId );
278  return $fatSectorArray[$sectorId % $entriesPerSector];
279  }
280 
281  private function getFatSector( $fatSectorId ) {
282  if ( !isset( $this->fat[$fatSectorId] ) ) {
283  $fat = [];
284  if ( !isset( $this->difat[$fatSectorId] ) ) {
285  $this->error( 'FAT sector requested beyond the end of the DIFAT', self::ERROR_INVALID_FORMAT );
286  }
287  $absoluteSectorId = $this->difat[$fatSectorId];
288  $block = $this->readSector( $absoluteSectorId );
289  for ( $pos = 0; $pos < strlen( $block ); $pos += 4 ) {
290  $fat[] = $this->bin2dec( $block, $pos, 4 );
291  }
292  $this->fat[$fatSectorId] = $fat;
293  }
294  return $this->fat[$fatSectorId];
295  }
296 
297  private function readDirectory() {
298  $dirSectorId = $this->header['first_dir_sector'];
299  $binaryDir = '';
300  $seenSectorIds = [];
301  while ( $dirSectorId !== 0xFFFFFFFE ) {
302  if ( isset( $seenSectorIds[$dirSectorId] ) ) {
303  $this->error( 'FAT loop detected', self::ERROR_INVALID_FORMAT );
304  }
305  $seenSectorIds[$dirSectorId] = true;
306 
307  $binaryDir .= $this->readSector( $dirSectorId );
308  $dirSectorId = $this->getNextSectorIdFromFat( $dirSectorId );
309  }
310 
311  $struct = [
312  'name_raw' => 64,
313  'name_length' => 2,
314  'object_type' => 1,
315  'color' => 1,
316  'sid_left' => 4,
317  'sid_right' => 4,
318  'sid_child' => 4,
319  'clsid' => 16,
320  'state_bits' => 4,
321  'create_time_low' => 4,
322  'create_time_high' => 4,
323  'modify_time_low' => 4,
324  'modify_time_high' => 4,
325  'first_sector' => 4,
326  'size_low' => 4,
327  'size_high' => 4,
328  ];
329  $entryLength = array_sum( $struct );
330 
331  for ( $pos = 0; $pos < strlen( $binaryDir ); $pos += $entryLength ) {
332  $entry = $this->unpack( $binaryDir, $pos, $struct );
333 
334  // According to [MS-CFB] size_high may contain garbage due to a
335  // bug in a writer, it's best to pretend it is zero
336  $entry['size_high'] = 0;
337 
338  $type = $entry['object_type'];
339  if ( $type == self::TYPE_UNALLOCATED ) {
340  continue;
341  }
342 
343  $name = iconv( 'UTF-16LE', 'UTF-8', substr( $entry['name_raw'], 0, $entry['name_length'] - 2 ) );
344 
345  $clsid = $this->decodeClsid( $entry['clsid'] );
346  if ( $type == self::TYPE_ROOT && isset( self::$mimesByClsid[$clsid] ) ) {
347  $this->mimeFromClsid = self::$mimesByClsid[$clsid];
348  }
349 
350  if ( $name === 'Workbook' ) {
351  $this->mime = 'application/vnd.ms-excel';
352  } elseif ( $name === 'WordDocument' ) {
353  $this->mime = 'application/msword';
354  } elseif ( $name === 'PowerPoint Document' ) {
355  $this->mime = 'application/vnd.ms-powerpoint';
356  }
357  }
358  }
359 }
Read the directory of a Microsoft Compound File Binary file, a.k.a.
readOffset( $offset, $length)
unpack( $block, $offset, $struct)
static readHandle( $fileHandle)
Read from an open seekable handle.
bin2dec( $str, $offset, $length)
unpackOffset( $offset, $struct)
static static readFile( $fileName)
Read a file by name.