| 1 | <?php |
| 2 | /************************************************************* |
| 3 | # 076 License |
| 4 | |
| 5 | Copyright (c) テクニカル諏訪子 |
| 6 | |
| 7 | Permission is hereby granted to any person obtaining a copy of the software |
| 8 | Little Beast (the "Software") to use, modify, merge, copy, publish, distribute, |
| 9 | sublicense, and/or sell copies of the Software, subject to the following conditions: |
| 10 | |
| 11 | 1. **Origin Attribution**: |
| 12 | - You must not misrepresent the origin of the Software; you must not claim |
| 13 | you created the original Software. |
| 14 | - If the Software is used in a product, you must either: |
| 15 | a. Provide clear attribution in the product's documentation, user interface, |
| 16 | or other visible areas, **OR** |
| 17 | b. Pay the original developers a fee they specify in writing. |
| 18 | 2. **Usage Restriction**: |
| 19 | - The Software, or any derivative works, dependencies, or libraries |
| 20 | incorporating it, must not be used for censorship or to suppress freedom of |
| 21 | speech, expression, or creativity. Prohibited uses include, but are not |
| 22 | limited to: |
| 23 | - Censorship of so-called "hate speech", visuals, non-mainstream opinions, |
| 24 | ideas, or objective reality. |
| 25 | - Tools or systems designed to restrict access to information or |
| 26 | artistic works. |
| 27 | 3. **Notice Preservation**: |
| 28 | - This license and the above copyright notice must remain intact in all copies |
| 29 | of the source code. |
| 30 | |
| 31 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, |
| 32 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A |
| 33 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 34 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 35 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE |
| 36 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 37 | */ |
| 38 | namespace Std\Lib\Git; |
| 39 | |
| 40 | /** |
| 41 | * 受け取ったパックを読んで保存する(git index-pack、git unpack-objects) |
| 42 | * |
| 43 | * ストリームから読みながら一時ファイルに書き、差分を解決してIDを計算し、.idx(v2)と.revを作る。 |
| 44 | * オブジェクトが少なければルーズオブジェクトにする。 |
| 45 | */ |
| 46 | final class PackIndexer { |
| 47 | /** @var resource */ |
| 48 | private $in; |
| 49 | /** @var resource */ |
| 50 | private $tmp; |
| 51 | private string $buf = ''; |
| 52 | private $hash; |
| 53 | private int $pos = 0; |
| 54 | private string $tmpPath = ''; |
| 55 | /** @var array オフセット => [種類, 大きさ, データの位置, 元のオフセット, 元のID(bin), crc] */ |
| 56 | private array $entries = []; |
| 57 | /** @var array オフセット => ID(bin) */ |
| 58 | private array $ids = []; |
| 59 | /** @var array ID(hex) => オフセット */ |
| 60 | private array $byId = []; |
| 61 | /** @var array オフセット => 種類 */ |
| 62 | private array $types = []; |
| 63 | private array $cache = []; |
| 64 | private int $cacheBytes = 0; |
| 65 | private ?Pack $pack = null; |
| 66 | /** 参照しているID(接続の確認用) */ |
| 67 | private array $links = []; |
| 68 | private bool $thin = false; |
| 69 | |
| 70 | public function __construct(private Repository $repo) {} |
| 71 | |
| 72 | /** |
| 73 | * パックを受け取る |
| 74 | * |
| 75 | * @param resource $in 入力(パックの始まりから) |
| 76 | * @param int $unpackLimit これより少なければルーズオブジェクトにする |
| 77 | * @param callable|null $progress fn(string $what, int $done, int $total) |
| 78 | * @return array objects(ID => 種類)、links(参照しているID => true)、pack(パックのパス、ルーズならnull) |
| 79 | */ |
| 80 | public function receive($in, int $unpackLimit = 100, ?callable $progress = null): array { |
| 81 | $this->in = $in; |
| 82 | $this->hash = hash_init($this->repo->hashAlgo); |
| 83 | $dir = $this->repo->objects->dir().'/pack'; |
| 84 | $this->repo->mkdir($dir); |
| 85 | $this->tmpPath = $dir.'/tmp_pack_'.bin2hex(random_bytes(6)); |
| 86 | $tmp = @fopen($this->tmpPath, 'w+b'); |
| 87 | if ($tmp === false) throw new GitException("一時ファイルを作れません:{$this->tmpPath}"); |
| 88 | $this->tmp = $tmp; |
| 89 | try { |
| 90 | $head = $this->read(12); |
| 91 | if (substr($head, 0, 4) !== 'PACK' || !in_array(unpack('N', $head, 4)[1], [2, 3], true)) throw new GitException('パックではありません'); |
| 92 | $count = unpack('N', $head, 8)[1]; |
| 93 | for ($i = 0; $i < $count; $i++) { |
| 94 | $this->readEntry(); |
| 95 | if ($progress && (($i + 1) % 1000 === 0 || $i + 1 === $count)) $progress('受信', $i + 1, $count); |
| 96 | } |
| 97 | $sum = hash_final($this->hash, true); |
| 98 | $trailer = $this->read($this->repo->hashLen, false); |
| 99 | if ($trailer !== $sum) throw new GitException('パックのチェックサムが違います'); |
| 100 | fwrite($this->tmp, $trailer); |
| 101 | fflush($this->tmp); |
| 102 | $this->resolveAll($progress); |
| 103 | $objects = []; |
| 104 | foreach ($this->ids as $off => $bin) $objects[bin2hex($bin)] = $this->types[$off]; |
| 105 | // 中に無い物を参照しているか(相手が持っている物はOK、無い物は接続の確認で) |
| 106 | foreach (array_keys($this->links) as $l) if (isset($objects[$l])) unset($this->links[$l]); |
| 107 | if ($count < $unpackLimit || $this->thin) { |
| 108 | foreach (array_keys($this->entries) as $off) { |
| 109 | [$type, $data] = $this->resolve($off); |
| 110 | $this->repo->objects->write($type, $data); |
| 111 | } |
| 112 | $path = null; |
| 113 | } else { |
| 114 | $path = $this->install($sum); |
| 115 | } |
| 116 | return ['objects' => $objects, 'links' => $this->links, 'pack' => $path]; |
| 117 | } finally { |
| 118 | $this->pack = null; |
| 119 | if (is_resource($this->tmp)) fclose($this->tmp); |
| 120 | @unlink($this->tmpPath); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /** 入力からnバイト(ハッシュと一時ファイルにも) */ |
| 125 | private function read(int $n, bool $hash = true): string { |
| 126 | while (strlen($this->buf) < $n) { |
| 127 | $s = fread($this->in, max(65536, $n - strlen($this->buf))); |
| 128 | if ($s === false || $s === '') { |
| 129 | if (feof($this->in)) throw new GitException('パックが途中で終わりました'); |
| 130 | continue; |
| 131 | } |
| 132 | $this->buf .= $s; |
| 133 | } |
| 134 | $out = substr($this->buf, 0, $n); |
| 135 | $this->buf = (string)substr($this->buf, $n); |
| 136 | if ($hash) { |
| 137 | hash_update($this->hash, $out); |
| 138 | fwrite($this->tmp, $out); |
| 139 | $this->pos += $n; |
| 140 | } |
| 141 | return $out; |
| 142 | } |
| 143 | |
| 144 | private function readEntry(): void { |
| 145 | $offset = $this->pos; |
| 146 | $crc = hash_init('crc32b'); |
| 147 | $b = ord($h = $this->read(1)); |
| 148 | $raw = $h; |
| 149 | $type = ($b >> 4) & 7; |
| 150 | $size = $b & 15; |
| 151 | $shift = 4; |
| 152 | while ($b & 0x80) { |
| 153 | $b = ord($h = $this->read(1)); |
| 154 | $raw .= $h; |
| 155 | $size |= ($b & 0x7f) << $shift; |
| 156 | $shift += 7; |
| 157 | } |
| 158 | $baseOff = null; |
| 159 | $baseId = null; |
| 160 | if ($type === Pack::OFS_DELTA) { |
| 161 | $b = ord($h = $this->read(1)); |
| 162 | $raw .= $h; |
| 163 | $n = $b & 0x7f; |
| 164 | while ($b & 0x80) { |
| 165 | $b = ord($h = $this->read(1)); |
| 166 | $raw .= $h; |
| 167 | $n = (($n + 1) << 7) | ($b & 0x7f); |
| 168 | } |
| 169 | $baseOff = $offset - $n; |
| 170 | if (!isset($this->entries[$baseOff])) throw new GitException('壊れたパック(OFS_DELTAの元)'); |
| 171 | } else if ($type === Pack::REF_DELTA) { |
| 172 | $baseId = $this->read($this->repo->hashLen); |
| 173 | $raw .= $baseId; |
| 174 | } else if (!isset(Pack::TYPES[$type])) { |
| 175 | throw new GitException("壊れたパック(種類{$type})"); |
| 176 | } |
| 177 | hash_update($crc, $raw); |
| 178 | $dataAt = $this->pos; |
| 179 | // zlibのデータ(長さは展開しないと分からない) |
| 180 | $ctx = inflate_init(ZLIB_ENCODING_DEFLATE); |
| 181 | $out = ''; |
| 182 | $readBefore = 0; |
| 183 | while (true) { |
| 184 | if ($this->buf === '') { |
| 185 | $s = fread($this->in, 65536); |
| 186 | if ($s === false || $s === '') { |
| 187 | if (feof($this->in)) throw new GitException('パックが途中で終わりました'); |
| 188 | continue; |
| 189 | } |
| 190 | $this->buf = $s; |
| 191 | } |
| 192 | $res = @inflate_add($ctx, $this->buf, ZLIB_SYNC_FLUSH); |
| 193 | if ($res === false) throw new GitException('壊れたパック(zlib)'); |
| 194 | $out .= $res; |
| 195 | if (strlen($out) > $size) throw new GitException('壊れたパック(大きさ)'); |
| 196 | $total = inflate_get_read_len($ctx); |
| 197 | $used = $total - $readBefore; |
| 198 | $readBefore = $total; |
| 199 | $chunk = substr($this->buf, 0, $used); |
| 200 | $this->buf = (string)substr($this->buf, $used); |
| 201 | hash_update($this->hash, $chunk); |
| 202 | hash_update($crc, $chunk); |
| 203 | fwrite($this->tmp, $chunk); |
| 204 | $this->pos += $used; |
| 205 | if (inflate_get_status($ctx) === ZLIB_STREAM_END) break; |
| 206 | } |
| 207 | if (strlen($out) !== $size) throw new GitException('壊れたパック(大きさ)'); |
| 208 | $this->entries[$offset] = [$type, $size, $dataAt, $baseOff, $baseId, unpack('N', hash_final($crc, true))[1]]; |
| 209 | if (isset(Pack::TYPES[$type])) $this->found($offset, Pack::TYPES[$type], $out); |
| 210 | } |
| 211 | |
| 212 | /** IDが分かったオブジェクト */ |
| 213 | private function found(int $off, string $type, string $data): void { |
| 214 | $id = $this->repo->hashObject($type, $data); |
| 215 | $this->ids[$off] = hex2bin($id); |
| 216 | $this->byId[$id] = $off; |
| 217 | $this->types[$off] = $type; |
| 218 | $this->check($id, $type, $data); |
| 219 | } |
| 220 | |
| 221 | /** 中身の確認と、参照しているID */ |
| 222 | private function check(string $id, string $type, string $data): void { |
| 223 | $repo = $this->repo; |
| 224 | try { |
| 225 | if ($type === 'commit') { |
| 226 | $c = Commit::parse($data); |
| 227 | if (!$repo->isId($c->tree) || $c->author === null || $c->committer === null) throw new GitException("壊れたコミット:{$id}"); |
| 228 | $this->links[$c->tree] = true; |
| 229 | foreach ($c->parents as $p) { |
| 230 | if (!$repo->isId($p)) throw new GitException("壊れたコミット:{$id}"); |
| 231 | $this->links[$p] = true; |
| 232 | } |
| 233 | } else if ($type === 'tree') { |
| 234 | foreach (Tree::parse($data, $repo->hashLen)->entries as [$mode, $name, $eid]) { |
| 235 | if (!in_array($mode, [Tree::FILE, Tree::EXEC, Tree::LINK, Tree::DIR, Tree::SUBMODULE, '100664'], true) || $name === '' || $name === '.' || $name === '..' || str_contains($name, '/') |
| 236 | || strcasecmp($name, '.git') === 0) { |
| 237 | throw new GitException("不正なツリー:{$id}({$name})"); |
| 238 | } |
| 239 | if ($mode !== Tree::SUBMODULE) $this->links[$eid] = true; |
| 240 | } |
| 241 | } else if ($type === 'tag') { |
| 242 | $t = Tag::parse($data); |
| 243 | if (!$repo->isId($t->object)) throw new GitException("壊れたタグ:{$id}"); |
| 244 | $this->links[$t->object] = true; |
| 245 | } |
| 246 | } catch (GitException $e) { |
| 247 | throw $e; |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | /** 差分を全部解決する */ |
| 252 | private function resolveAll(?callable $progress): void { |
| 253 | $this->pack = new Pack($this->tmpPath, $this->repo->hashLen, false); |
| 254 | $pending = array_keys(array_filter($this->entries, fn($e) => !isset(Pack::TYPES[$e[0]]))); |
| 255 | $total = count($pending); |
| 256 | while (!empty($pending)) { |
| 257 | $left = []; |
| 258 | foreach ($pending as $off) { |
| 259 | if (isset($this->ids[$off])) continue; |
| 260 | if ($this->resolve($off, true) === null) $left[] = $off; |
| 261 | } |
| 262 | if (count($left) === count($pending)) { |
| 263 | // 元がパックに無い(シンパック):リポジトリの物を使う |
| 264 | foreach ($left as $off) { |
| 265 | $bid = $this->entries[$off][4]; |
| 266 | if ($bid === null || !$this->repo->objects->exists(bin2hex($bid))) throw new GitException('差分の元が有りません:'.($bid === null ? '?' : bin2hex($bid))); |
| 267 | $this->thin = true; |
| 268 | } |
| 269 | foreach ($left as $off) $this->resolve($off); |
| 270 | break; |
| 271 | } |
| 272 | $pending = $left; |
| 273 | if ($progress) $progress('差分の解決', $total - count($pending), $total); |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /** |
| 278 | * オフセットのオブジェクト |
| 279 | * |
| 280 | * @param bool $inPackOnly 元が(まだ)分からなければnull |
| 281 | * @return array|null [種類, データ] |
| 282 | */ |
| 283 | private function resolve(int $off, bool $inPackOnly = false): ?array { |
| 284 | if (isset($this->cache[$off])) return $this->cache[$off]; |
| 285 | [$type, $size, $dataAt, $baseOff, $baseId] = $this->entries[$off]; |
| 286 | if (isset(Pack::TYPES[$type])) { |
| 287 | $obj = [Pack::TYPES[$type], $this->pack->inflate($dataAt, $size)]; |
| 288 | } else { |
| 289 | if ($baseOff !== null) { |
| 290 | $base = $this->resolve($baseOff, $inPackOnly); |
| 291 | } else { |
| 292 | $hex = bin2hex($baseId); |
| 293 | if (isset($this->byId[$hex])) $base = $this->resolve($this->byId[$hex], $inPackOnly); |
| 294 | else if ($inPackOnly) return null; |
| 295 | else $base = $this->repo->objects->read($hex); |
| 296 | } |
| 297 | if ($base === null) return null; |
| 298 | $obj = [$base[0], Delta::apply($base[1], $this->pack->inflate($dataAt, $size))]; |
| 299 | if (!isset($this->ids[$off])) $this->found($off, $obj[0], $obj[1]); |
| 300 | } |
| 301 | $n = strlen($obj[1]); |
| 302 | if ($n < 8388608) { |
| 303 | while ($this->cacheBytes + $n > 67108864 && !empty($this->cache)) { |
| 304 | $k = array_key_first($this->cache); |
| 305 | $this->cacheBytes -= strlen($this->cache[$k][1]); |
| 306 | unset($this->cache[$k]); |
| 307 | } |
| 308 | $this->cache[$off] = $obj; |
| 309 | $this->cacheBytes += $n; |
| 310 | } |
| 311 | return $obj; |
| 312 | } |
| 313 | |
| 314 | /** パックと.idx・.revを置く */ |
| 315 | private function install(string $sum): string { |
| 316 | $h = $this->repo->hashLen; |
| 317 | $sorted = $this->ids; |
| 318 | asort($sorted, SORT_STRING); |
| 319 | $fan = array_fill(0, 256, 0); |
| 320 | foreach ($sorted as $bin) $fan[ord($bin[0])]++; |
| 321 | $idx = "\xfftOc".pack('N', 2); |
| 322 | $acc = 0; |
| 323 | for ($i = 0; $i < 256; $i++) { |
| 324 | $acc += $fan[$i]; |
| 325 | $idx .= pack('N', $acc); |
| 326 | } |
| 327 | $names = ''; |
| 328 | $crcs = ''; |
| 329 | $offs = ''; |
| 330 | $large = ''; |
| 331 | $nLarge = 0; |
| 332 | $position = []; |
| 333 | $n = 0; |
| 334 | foreach ($sorted as $off => $bin) { |
| 335 | $names .= $bin; |
| 336 | $crcs .= pack('N', $this->entries[$off][5]); |
| 337 | if ($off < 0x80000000) { |
| 338 | $offs .= pack('N', $off); |
| 339 | } else { |
| 340 | $offs .= pack('N', 0x80000000 | $nLarge++); |
| 341 | $large .= pack('J', $off); |
| 342 | } |
| 343 | $position[$off] = $n++; |
| 344 | } |
| 345 | $idx .= $names.$crcs.$offs.$large.$sum; |
| 346 | $idx .= hash($this->repo->hashAlgo, $idx, true); |
| 347 | ksort($position); |
| 348 | $rev = 'RIDX'.pack('NN', 1, $this->repo->hashAlgo === 'sha1' ? 1 : 2).pack('N*', ...array_values($position)).$sum; |
| 349 | $rev .= hash($this->repo->hashAlgo, $rev, true); |
| 350 | |
| 351 | $base = $this->repo->objects->dir().'/pack/pack-'.bin2hex($sum); |
| 352 | $this->pack = null; |
| 353 | fclose($this->tmp); |
| 354 | if (!is_file($base.'.pack')) { |
| 355 | if (!@rename($this->tmpPath, $base.'.pack')) throw new GitException('パックを保存出来ません'); |
| 356 | $this->repo->chmodFile($base.'.pack', true); |
| 357 | } |
| 358 | $this->repo->writeFile($base.'.rev', $rev, true); |
| 359 | $this->repo->writeFile($base.'.idx', $idx, true); |
| 360 | $this->repo->objects->packs(true); |
| 361 | return $base.'.pack'; |
| 362 | } |
| 363 | } |