diff --git a/src/Tar.php b/src/Tar.php index 6700243..35df22a 100644 --- a/src/Tar.php +++ b/src/Tar.php @@ -726,7 +726,11 @@ protected function parseHeader($block) // a pax global header holds defaults for all entries following it if ($header['typeflag'] === 'g') { $records = $this->parsePaxRecords($this->readMetadata($header['size'])); - $this->paxGlobal = array_merge($this->paxGlobal, $records); + // assign in place instead of array_merge() so a long run of global headers stays + // linear: rebuilding the whole map per header would be quadratic in their number + foreach ($records as $key => $value) { + $this->paxGlobal[$key] = $value; + } return false; } @@ -751,8 +755,10 @@ protected function parseHeader($block) if ($filename !== '') { $header['filename'] = $filename; } - // entry specific records win over the global ones - $header = $this->applyPaxRecords($header, array_merge($this->paxGlobal, $records)); + // entry specific records win over the global ones; only the few keywords the entry + // can use are looked up so a large global map does not make every entry linear in it + $records = $this->mergeRelevantPaxRecords($records); + $header = $this->applyPaxRecords($header, $records); if (!in_array($header['typeflag'], self::SUPPORTED_TYPEFLAGS, true)) { // the data blocks hold metadata or an unsupported entry, throw them away @@ -824,6 +830,26 @@ protected function parsePaxRecords($data) return $records; } + /** + * Combine entry specific pax records with the global ones, keeping only the keywords that + * applyPaxRecords() actually uses + * + * Entry specific records win over the global ones. Only a fixed set of keywords is looked + * up, so the cost does not depend on how many global records a hostile archive declares. + * + * @param string[] $records the entry specific pax records + * @return string[] the records to apply to the entry + */ + protected function mergeRelevantPaxRecords($records) + { + foreach (array('path', 'uname', 'gname', 'size', 'mtime', 'uid', 'gid') as $keyword) { + if (!array_key_exists($keyword, $records) && isset($this->paxGlobal[$keyword])) { + $records[$keyword] = $this->paxGlobal[$keyword]; + } + } + return $records; + } + /** * Apply the given pax records to a decoded header * diff --git a/tests/TarTestCase.php b/tests/TarTestCase.php index 15ac34f..7266081 100644 --- a/tests/TarTestCase.php +++ b/tests/TarTestCase.php @@ -579,6 +579,116 @@ public function testPaxRecords() $this->assertEquals("testcontent2\n", file_get_contents("$out/$path")); } + /** + * A long run of pax global headers must be processed in linear time + * + * Each global header used to rebuild the whole map of accumulated global records, which is + * quadratic in the number of headers. A hostile archive could spend minutes of CPU on a few + * compressed megabytes. The generated archive below needs about ten seconds on the quadratic + * code and about one once the records are assigned in place, so the time limit tells the two + * apart while staying clear of the linear runtime on a slow machine. + */ + public function testPaxGlobalHeaderIsLinear() + { + $count = 64000; + $gzip = extension_loaded('zlib'); + + // build the archive: $count pax global headers each adding one distinct record, the last + // one setting the owner, followed by a single regular file that inherits it. It is written + // gzip compressed when possible so the near identical headers stay a small fixture on disk + $file = tempnam(sys_get_temp_dir(), 'paxlin'); + $fh = $gzip ? gzopen($file, 'wb1') : fopen($file, 'wb'); + $write = $gzip ? 'gzwrite' : 'fwrite'; + for ($i = 0; $i < $count; $i++) { + $record = $this->makePaxRecord('key' . $i, 'value' . $i); + $write($fh, $this->makeTarBlock('globalheader', $record, 'g')); + } + $write($fh, $this->makeTarBlock('owner', $this->makePaxRecord('uname', 'theowner'), 'g')); + $write($fh, $this->makeTarBlock('plain.txt', "hello\n", '0')); + $write($fh, str_repeat("\0", 1024)); + $gzip ? gzclose($fh) : fclose($fh); + + $start = microtime(true); + $tar = new Tar(); + $tar->open($file); + $content = $tar->contents(); + $elapsed = microtime(true) - $start; + + unlink($file); + + // the global headers are metadata, only the regular file is an entry, and it inherits + // the last global record, proving the in-place assignment keeps the behaviour + $this->assertCount(1, $content); + $this->assertEquals('plain.txt', $content[0]->getPath()); + $this->assertEquals('theowner', $content[0]->getOwner()); + + // the quadratic code needs roughly ten seconds here and grows with the square of the + // header count, the in-place assignment needs about one; the generous limit tells them + // apart without being flaky on a slow machine + $this->assertLessThan( + 5, + $elapsed, + 'Processing pax global headers took too long, it is no longer linear' + ); + } + + /** + * Build a single pax record in its " =\n" wire format + * + * @param string $keyword + * @param string $value + * @return string + */ + protected function makePaxRecord($keyword, $value) + { + // the declared length counts the whole record including the length digits themselves, + // so grow the candidate until it is self-consistent + $body = $keyword . '=' . $value . "\n"; + $length = strlen($body); + do { + $length++; + $total = strlen((string)$length) + 1 + strlen($body); + } while ($total !== $length); + return $length . ' ' . $body; + } + + /** + * Build a single 512 byte ustar block with a valid checksum, plus the padded data blocks + * + * @param string $name the entry name + * @param string $data the entry data + * @param string $typeflag the ustar type flag + * @return string + */ + protected function makeTarBlock($name, $data, $typeflag) + { + $header = pack('a100', $name) + . pack('a8', sprintf("%07o", 0644)) + . pack('a8', sprintf("%07o", 0)) + . pack('a8', sprintf("%07o", 0)) + . pack('a12', sprintf("%011o", strlen($data))) + . pack('a12', sprintf("%011o", 0)) + . pack('a8', ' ') + . pack('a1', $typeflag) + . pack('a100', '') + . pack('a6', 'ustar') + . pack('a2', '00') + . pack('a32', '') + . pack('a32', '') + . pack('a8', '') + . pack('a8', '') + . pack('a155', '') + . pack('a12', ''); + $checksum = 0; + for ($i = 0; $i < 512; $i++) { + $checksum += ord($header[$i]); + } + $header = substr_replace($header, pack('a8', sprintf("%06o\0 ", $checksum)), 148, 8); + + $padding = (512 - (strlen($data) % 512)) % 512; + return $header . $data . str_repeat("\0", $padding); + } + /** * Pax extended headers are metadata and should not show up as entries */