跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

chown.go

727 行 · 21.1 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package apfs
5
6import (
7 "encoding/binary"
8 "errors"
9 "fmt"
10 "hash/crc32"
11 "os"
12 "strings"
13)
14
15var le = binary.LittleEndian
16
17// Chown sets the owner and group of files on an unmounted APFS disk image.
18// volumeRole selects the target volume (e.g., VolRoleData).
19// Paths are relative to the volume root (e.g., "Library/LaunchDaemons/foo.plist").
20func Chown(diskPath string, volumeRole uint16, uid, gid uint32, paths ...string) error {
21 c, err := openContainer(diskPath)
22 if err != nil {
23 return err
24 }
25 defer c.close()
26
27 vol, err := c.findVolume(volumeRole)
28 if err != nil {
29 return err
30 }
31
32 fsRootPhys, err := c.omapLookup(vol.omapTreeAddr, vol.rootTreeOID, vol.latestXID)
33 if err != nil {
34 return fmt.Errorf("resolving filesystem root tree OID %d: %w", vol.rootTreeOID, err)
35 }
36
37 for _, path := range paths {
38 inodeNum, err := c.resolvePath(fsRootPhys, vol.omapTreeAddr, vol.latestXID, path)
39 if err != nil {
40 return fmt.Errorf("resolving path %#q: %w", path, err)
41 }
42 if err := c.chownInode(fsRootPhys, vol.omapTreeAddr, vol.latestXID, inodeNum, uid, gid); err != nil {
43 return fmt.Errorf("chown inode %d (%#q): %w", inodeNum, path, err)
44 }
45 }
46 return nil
47}
48
49// container holds the open disk image file, the byte offset where
50// the APFS container starts (nonzero for GPT-partitioned disks),
51// and the APFS block size.
52type container struct {
53 f *os.File
54 baseOffset int64 // byte offset of APFS container within file
55 blockSize uint32
56}
57
58// volumeInfo holds resolved volume information.
59type volumeInfo struct {
60 omapTreeAddr uint64 // physical address of volume omap B-tree root
61 rootTreeOID uint64 // virtual OID of filesystem B-tree root
62 latestXID uint64 // transaction ID of the volume superblock
63}
64
65func openContainer(path string) (*container, error) {
66 f, err := os.OpenFile(path, os.O_RDWR, 0)
67 if err != nil {
68 return nil, fmt.Errorf("open disk: %w", err)
69 }
70 c := &container{f: f}
71
72 hdr := make([]byte, 4096) // minimum APFS block size
73 if _, err := f.ReadAt(hdr, 0); err != nil {
74 f.Close()
75 return nil, fmt.Errorf("read block 0: %w", err)
76 }
77
78 if le.Uint32(hdr[nxMagicOff:]) == nxMagic {
79 // Raw APFS container (no partition table).
80 c.blockSize = le.Uint32(hdr[nxBlockSizeOff:])
81 } else {
82 // Look for a GPT partition table and find the APFS partition.
83 offset, err := findAPFSPartitionGPT(f)
84 if err != nil {
85 f.Close()
86 return nil, fmt.Errorf("finding APFS partition: %w", err)
87 }
88 c.baseOffset = offset
89 if _, err := f.ReadAt(hdr, offset); err != nil {
90 f.Close()
91 return nil, fmt.Errorf("read APFS superblock at offset %d: %w", offset, err)
92 }
93 if le.Uint32(hdr[nxMagicOff:]) != nxMagic {
94 f.Close()
95 return nil, fmt.Errorf("APFS partition at offset %d has bad magic", offset)
96 }
97 c.blockSize = le.Uint32(hdr[nxBlockSizeOff:])
98 }
99
100 if c.blockSize < 4096 {
101 f.Close()
102 return nil, fmt.Errorf("invalid block size %d", c.blockSize)
103 }
104 return c, nil
105}
106
107// GPT constants.
108const (
109 gptHeaderSignature = "EFI PART"
110 gptLBASectorSize = 512
111)
112
113// apfsPartTypeGUID is the APFS Container partition type GUID as stored
114// on disk (mixed-endian encoding per GPT spec).
115// 7C3457EF-0000-11AA-AA11-00306543ECAC.
116var apfsPartTypeGUID = [16]byte{
117 0xEF, 0x57, 0x34, 0x7C, // time_low (LE)
118 0x00, 0x00, // time_mid (LE)
119 0xAA, 0x11, // time_hi_and_version (LE)
120 0xAA, 0x11, // clock_seq
121 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC, // node
122}
123
124// findAPFSPartitionGPT reads a GPT partition table and returns the
125// byte offset of the first APFS Container partition.
126func findAPFSPartitionGPT(f *os.File) (int64, error) {
127 // Read GPT header at LBA 1.
128 gptHdr := make([]byte, gptLBASectorSize)
129 if _, err := f.ReadAt(gptHdr, gptLBASectorSize); err != nil {
130 return 0, fmt.Errorf("reading GPT header: %w", err)
131 }
132 if string(gptHdr[0:8]) != gptHeaderSignature {
133 return 0, fmt.Errorf("no GPT header found (expected %#q)", gptHeaderSignature)
134 }
135
136 partEntryLBA := le.Uint64(gptHdr[72:])
137 numEntries := le.Uint32(gptHdr[80:])
138 entrySize := le.Uint32(gptHdr[84:])
139
140 entryBuf := make([]byte, entrySize)
141 for i := range numEntries {
142 off := int64(partEntryLBA)*gptLBASectorSize + int64(i)*int64(entrySize)
143 if _, err := f.ReadAt(entryBuf, off); err != nil {
144 return 0, fmt.Errorf("reading GPT entry %d: %w", i, err)
145 }
146
147 var typeGUID [16]byte
148 copy(typeGUID[:], entryBuf[0:16])
149 if typeGUID == apfsPartTypeGUID {
150 firstLBA := le.Uint64(entryBuf[32:])
151 return int64(firstLBA) * gptLBASectorSize, nil
152 }
153
154 // Stop at empty entries.
155 allZero := true
156 for _, b := range typeGUID {
157 if b != 0 {
158 allZero = false
159 break
160 }
161 }
162 if allZero {
163 break
164 }
165 }
166 return 0, errors.New("no APFS partition found in GPT")
167}
168
169func (c *container) close() {
170 c.f.Close()
171}
172
173func (c *container) readBlock(addr uint64) ([]byte, error) {
174 buf := make([]byte, c.blockSize)
175 _, err := c.f.ReadAt(buf, c.baseOffset+int64(addr)*int64(c.blockSize))
176 if err != nil {
177 return nil, fmt.Errorf("read block %d: %w", addr, err)
178 }
179 return buf, nil
180}
181
182func (c *container) writeBlock(addr uint64, data []byte) error {
183 _, err := c.f.WriteAt(data, c.baseOffset+int64(addr)*int64(c.blockSize))
184 if err != nil {
185 return fmt.Errorf("write block %d: %w", addr, err)
186 }
187 return nil
188}
189
190// latestSuperblock scans the checkpoint descriptor area for the
191// superblock with the highest valid transaction ID.
192func (c *container) latestSuperblock() ([]byte, error) {
193 // Read block 0 at full block size to get checkpoint descriptor area info.
194 block0, err := c.readBlock(0)
195 if err != nil {
196 return nil, err
197 }
198 if err := verifyChecksum(block0); err != nil {
199 return nil, fmt.Errorf("block 0 checksum: %w", err)
200 }
201
202 descBase := le.Uint64(block0[nxXPDescBaseOff:])
203 descBlocks := le.Uint32(block0[nxXPDescBlocksOff:]) & nxXPDescBlocksMask
204
205 var bestBlock []byte
206 var bestXID uint64
207
208 for i := range descBlocks {
209 blk, err := c.readBlock(descBase + uint64(i))
210 if err != nil {
211 continue
212 }
213 if verifyChecksum(blk) != nil {
214 continue
215 }
216 oType := le.Uint32(blk[objTypeOff:]) & objTypeMask
217 if oType != objectTypeNXSuperblock {
218 continue
219 }
220 if le.Uint32(blk[nxMagicOff:]) != nxMagic {
221 continue
222 }
223 xid := le.Uint64(blk[objXIDOff:])
224 if xid > bestXID {
225 bestXID = xid
226 bestBlock = blk
227 }
228 }
229 if bestBlock == nil {
230 return nil, errors.New("no valid container superblock found in checkpoint area")
231 }
232 return bestBlock, nil
233}
234
235// findVolume locates the volume with the given role.
236func (c *container) findVolume(role uint16) (*volumeInfo, error) {
237 sb, err := c.latestSuperblock()
238 if err != nil {
239 return nil, fmt.Errorf("reading container superblock: %w", err)
240 }
241
242 // Read the container omap to resolve volume virtual OIDs.
243 containerOmapAddr := le.Uint64(sb[nxOmapOIDOff:])
244 containerOmap, err := c.readBlock(containerOmapAddr)
245 if err != nil {
246 return nil, fmt.Errorf("reading container omap at %d: %w", containerOmapAddr, err)
247 }
248 containerOmapTreeAddr := le.Uint64(containerOmap[omapTreeOIDOff:])
249
250 containerXID := le.Uint64(sb[objXIDOff:])
251
252 for i := range nxMaxFileSystems {
253 off := nxFSOIDOff + i*8
254 volOID := le.Uint64(sb[off:])
255 if volOID == 0 {
256 continue
257 }
258 // Resolve virtual OID through container omap.
259 volPhysAddr, err := c.omapLookup(containerOmapTreeAddr, volOID, containerXID)
260 if err != nil {
261 continue // skip volumes we can't resolve
262 }
263 volBlock, err := c.readBlock(volPhysAddr)
264 if err != nil {
265 continue
266 }
267 if verifyChecksum(volBlock) != nil {
268 continue
269 }
270 if le.Uint32(volBlock[apfsMagicOff:]) != apfsMagic {
271 continue
272 }
273 volRole := le.Uint16(volBlock[apfsRoleOff:])
274 if volRole == role {
275 omapAddr := le.Uint64(volBlock[apfsOmapOIDOff:])
276 omapBlock, err := c.readBlock(omapAddr)
277 if err != nil {
278 return nil, fmt.Errorf("reading volume omap: %w", err)
279 }
280 return &volumeInfo{
281 omapTreeAddr: le.Uint64(omapBlock[omapTreeOIDOff:]),
282 rootTreeOID: le.Uint64(volBlock[apfsRootTreeOIDOff:]),
283 latestXID: le.Uint64(volBlock[objXIDOff:]),
284 }, nil
285 }
286 }
287 return nil, fmt.Errorf("no volume with role %#x found", role)
288}
289
290// omapLookup searches the omap B-tree for a virtual OID, returning
291// the physical address from the entry with the highest xid <= maxXID.
292func (c *container) omapLookup(omapTreeAddr, oid, maxXID uint64) (uint64, error) {
293 blk, err := c.readBlock(omapTreeAddr)
294 if err != nil {
295 return 0, err
296 }
297
298 for {
299 if verifyChecksum(blk) != nil {
300 return 0, errors.New("omap node checksum failed")
301 }
302 if err := verifyBTreeNodeType(blk); err != nil {
303 return 0, fmt.Errorf("omap node: %w", err)
304 }
305 flags := le.Uint16(blk[btnFlagsOff:])
306 nkeys := le.Uint32(blk[btnNKeysOff:])
307 tspOff := le.Uint16(blk[btnTableSpaceOff:])
308 tspLen := le.Uint16(blk[btnTableSpaceOff+2:])
309
310 tocStart := btnDataOff + uint32(tspOff)
311 keyAreaStart := tocStart + uint32(tspLen)
312
313 isLeaf := flags&btnodeLeaf != 0
314 isFixedKV := flags&btnodeFixedKVSize != 0
315 isRoot := flags&btnodeRoot != 0
316
317 valueAreaEnd := c.blockSize
318 if isRoot {
319 valueAreaEnd -= btreeInfoSize
320 }
321
322 if isLeaf {
323 // Search for matching oid with highest xid <= maxXID.
324 var bestPhysAddr uint64
325 var bestXID uint64
326 found := false
327
328 for i := range nkeys {
329 kOff, vOff := c.readTocEntry(blk, tocStart, i, isFixedKV)
330 keyStart := keyAreaStart + kOff
331 entryOID := le.Uint64(blk[keyStart:])
332 entryXID := le.Uint64(blk[keyStart+8:])
333
334 if entryOID == oid && entryXID <= maxXID {
335 // Value: ov_flags(4) + ov_size(4) + ov_paddr(8).
336 valStart := valueAreaEnd - vOff
337 physAddr := le.Uint64(blk[valStart+8:])
338 if !found || entryXID > bestXID {
339 bestPhysAddr = physAddr
340 bestXID = entryXID
341 found = true
342 }
343 }
344 }
345 if !found {
346 return 0, fmt.Errorf("omap entry for OID %d not found", oid)
347 }
348 return bestPhysAddr, nil
349 }
350
351 // Internal node: find the last key <= (oid, maxXID) and descend.
352 childIdx := uint32(0)
353 for i := range nkeys {
354 kOff, _ := c.readTocEntry(blk, tocStart, i, isFixedKV)
355 keyStart := keyAreaStart + kOff
356 entryOID := le.Uint64(blk[keyStart:])
357 entryXID := le.Uint64(blk[keyStart+8:])
358
359 cmp := compareOmapKey(entryOID, entryXID, oid, maxXID)
360 if cmp <= 0 {
361 childIdx = i
362 } else {
363 break
364 }
365 }
366
367 // Read child pointer (physical address, 8 bytes).
368 _, vOff := c.readTocEntry(blk, tocStart, childIdx, isFixedKV)
369 childAddr := le.Uint64(blk[valueAreaEnd-vOff:])
370
371 blk, err = c.readBlock(childAddr)
372 if err != nil {
373 return 0, fmt.Errorf("reading omap child node: %w", err)
374 }
375 }
376}
377
378// readTocEntry reads the key and value offsets from a ToC entry.
379// For fixed-KV nodes (kvoff_t): 4 bytes per entry (k_off u16, v_off u16).
380// For variable-KV nodes (kvloc_t): 8 bytes per entry (k.off u16, k.len u16, v.off u16, v.len u16).
381// Returns keyOffset and valueOffset (both relative to their respective areas).
382func (c *container) readTocEntry(blk []byte, tocStart, index uint32, fixedKV bool) (keyOff, valOff uint32) {
383 if fixedKV {
384 off := tocStart + index*4
385 return uint32(le.Uint16(blk[off:])), uint32(le.Uint16(blk[off+2:]))
386 }
387 off := tocStart + index*8
388 return uint32(le.Uint16(blk[off:])), uint32(le.Uint16(blk[off+4:]))
389}
390
391// verifyBTreeNodeType checks that a block's object type indicates a
392// B-tree node: OBJECT_TYPE_BTREE (0x02, root) or OBJECT_TYPE_BTREE_NODE
393// (0x03, non-root).
394func verifyBTreeNodeType(blk []byte) error {
395 oType := le.Uint32(blk[objTypeOff:]) & objTypeMask
396 if oType != 0x02 && oType != 0x03 {
397 return fmt.Errorf("expected B-tree node type (2 or 3), got %#x", oType)
398 }
399 return nil
400}
401
402func compareOmapKey(oid1, xid1, oid2, xid2 uint64) int {
403 if oid1 < oid2 {
404 return -1
405 }
406 if oid1 > oid2 {
407 return 1
408 }
409 if xid1 < xid2 {
410 return -1
411 }
412 if xid1 > xid2 {
413 return 1
414 }
415 return 0
416}
417
418// compareFSKeyHeader compares two filesystem B-tree key headers.
419// APFS sorts filesystem keys by (obj_id, type), not by the raw uint64.
420func compareFSKeyHeader(a, b uint64) int {
421 aID := a & objIDMask
422 bID := b & objIDMask
423 if aID < bID {
424 return -1
425 }
426 if aID > bID {
427 return 1
428 }
429 aType := a >> objTypeShift
430 bType := b >> objTypeShift
431 if aType < bType {
432 return -1
433 }
434 if aType > bType {
435 return 1
436 }
437 return 0
438}
439
440var crc32cTable = crc32.MakeTable(crc32.Castagnoli)
441
442// drecNameHash computes the 22-bit directory record name hash as stored
443// in the upper bits of j_drec_hashed_key_t.name_len_and_hash.
444//
445// Per the Apple APFS Reference: NFD-normalize the name, encode as UTF-32LE
446// (without null terminator), compute CRC-32C, complement, keep low 22 bits.
447// The complement cancels with the CRC's standard finalization XOR, so we
448// use ^crc32.Checksum to get the raw CRC.
449func drecNameHash(name string) uint32 {
450 runes := []rune(strings.ToLower(name))
451 buf := make([]byte, len(runes)*4)
452 for i, r := range runes {
453 le.PutUint32(buf[i*4:], uint32(r))
454 }
455 return ^crc32.Checksum(buf, crc32cTable) & 0x3FFFFF
456}
457
458// compareDrecKey compares a directory record key from a B-tree node
459// against a target (parentCNID, name). Returns <0, 0, or >0.
460func (c *container) compareDrecKey(blk []byte, keyStart uint32, targetKeyHeader uint64, targetName string, targetHash uint32) int {
461 keyHeader := le.Uint64(blk[keyStart:])
462 cmp := compareFSKeyHeader(keyHeader, targetKeyHeader)
463 if cmp != 0 {
464 return cmp
465 }
466 // Headers match (same parent CNID and type DIR_REC).
467 // Compare name hash for hashed keys, or name directly for non-hashed.
468 val32 := le.Uint32(blk[keyStart+8:])
469 if val32&0xFFFFFC00 != 0 {
470 // Hashed key: compare hash values (upper 22 bits).
471 entryHash := (val32 >> 10) & 0x3FFFFF
472 if entryHash < targetHash {
473 return -1
474 }
475 if entryHash > targetHash {
476 return 1
477 }
478 // Hash collision: compare actual names.
479 entryName := c.readDrecName(blk, keyStart+8)
480 return strings.Compare(strings.ToLower(entryName), strings.ToLower(targetName))
481 }
482 // Non-hashed key: compare names directly.
483 entryName := c.readDrecName(blk, keyStart+8)
484 return strings.Compare(entryName, targetName)
485}
486
487// resolvePath walks path components from the volume root, returning
488// the inode number of the final path element.
489func (c *container) resolvePath(fsRootPhys, omapTreeAddr, maxXID uint64, path string) (uint64, error) {
490 parts := strings.Split(strings.Trim(path, "/"), "/")
491 cnid := uint64(rootDirInodeNum)
492
493 for _, name := range parts {
494 if name == "" {
495 continue
496 }
497 fileID, err := c.lookupDirEntry(fsRootPhys, omapTreeAddr, maxXID, cnid, name)
498 if err != nil {
499 return 0, fmt.Errorf("looking up %#q in directory (cnid %d): %w", name, cnid, err)
500 }
501 cnid = fileID
502 }
503 return cnid, nil
504}
505
506// lookupDirEntry searches the filesystem B-tree for a directory record
507// matching parentCNID and name, returning the file_id from j_drec_val_t.
508func (c *container) lookupDirEntry(fsRootPhys, omapTreeAddr, maxXID, parentCNID uint64, name string) (uint64, error) {
509 targetKeyHeader := (uint64(apfsTypeDirRec) << objTypeShift) | (parentCNID & objIDMask)
510 targetHash := drecNameHash(name)
511
512 blk, err := c.readBlock(fsRootPhys)
513 if err != nil {
514 return 0, err
515 }
516
517 for {
518 if verifyChecksum(blk) != nil {
519 return 0, errors.New("filesystem B-tree node checksum failed")
520 }
521 if err := verifyBTreeNodeType(blk); err != nil {
522 return 0, fmt.Errorf("filesystem B-tree node: %w", err)
523 }
524 flags := le.Uint16(blk[btnFlagsOff:])
525 nkeys := le.Uint32(blk[btnNKeysOff:])
526 tspOff := le.Uint16(blk[btnTableSpaceOff:])
527 tspLen := le.Uint16(blk[btnTableSpaceOff+2:])
528
529 tocStart := btnDataOff + uint32(tspOff)
530 keyAreaStart := tocStart + uint32(tspLen)
531
532 isLeaf := flags&btnodeLeaf != 0
533 isFixedKV := flags&btnodeFixedKVSize != 0
534 isRoot := flags&btnodeRoot != 0
535
536 valueAreaEnd := c.blockSize
537 if isRoot {
538 valueAreaEnd -= btreeInfoSize
539 }
540
541 if isLeaf {
542 for i := range nkeys {
543 kOff, vOff := c.readTocEntry(blk, tocStart, i, isFixedKV)
544 keyStart := keyAreaStart + kOff
545 keyHeader := le.Uint64(blk[keyStart:])
546
547 if keyHeader != targetKeyHeader {
548 continue
549 }
550
551 // Parse the directory record key name.
552 entryName := c.readDrecName(blk, keyStart+8)
553 if entryName != name {
554 continue
555 }
556
557 // Read file_id from j_drec_val_t (first 8 bytes of value).
558 valStart := valueAreaEnd - vOff
559 return le.Uint64(blk[valStart:]), nil
560 }
561 return 0, fmt.Errorf("directory entry %#q not found", name)
562 }
563
564 // Internal node: find the child to descend into.
565 // The last key <= our target determines the child.
566 // For DIR_REC keys with matching headers, we also compare the
567 // name hash to find the correct subtree.
568 childIdx := uint32(0)
569 for i := range nkeys {
570 kOff, _ := c.readTocEntry(blk, tocStart, i, isFixedKV)
571 keyStart := keyAreaStart + kOff
572 cmp := c.compareDrecKey(blk, keyStart, targetKeyHeader, name, targetHash)
573 if cmp <= 0 {
574 childIdx = i
575 } else {
576 break
577 }
578 }
579
580 // Read child OID (virtual) and resolve through omap.
581 _, vOff := c.readTocEntry(blk, tocStart, childIdx, isFixedKV)
582 childOID := le.Uint64(blk[valueAreaEnd-vOff:])
583 childPhys, err := c.omapLookup(omapTreeAddr, childOID, maxXID)
584 if err != nil {
585 return 0, fmt.Errorf("resolving child OID %d: %w", childOID, err)
586 }
587 blk, err = c.readBlock(childPhys)
588 if err != nil {
589 return 0, err
590 }
591 }
592}
593
594// readDrecName reads a directory record name from the key data
595// starting at nameFieldOff. Handles both hashed (j_drec_hashed_key_t,
596// 4-byte name_len_and_hash) and non-hashed (j_drec_key_t, 2-byte
597// name_len) formats.
598func (c *container) readDrecName(blk []byte, nameFieldOff uint32) string {
599 // Heuristic: if the 4-byte field at nameFieldOff has its upper
600 // bits set (hash), it's a hashed key. For non-hashed keys, the
601 // 2-byte name_len is followed by the name bytes.
602 //
603 // In j_drec_hashed_key_t: name_len_and_hash (uint32) where
604 // lower 10 bits = name length including null terminator.
605 // In j_drec_key_t: name_len (uint16) = name length including
606 // null terminator.
607 //
608 // We distinguish them by checking: if the upper 22 bits of the
609 // first uint32 are nonzero, it's hashed.
610 val32 := le.Uint32(blk[nameFieldOff:])
611 if val32&0xFFFFFC00 != 0 {
612 // Hashed: lower 10 bits = length (including null terminator).
613 nameLen := int(val32 & 0x3FF)
614 nameStart := nameFieldOff + 4
615 if nameLen > 1 {
616 return string(blk[nameStart : nameStart+uint32(nameLen-1)])
617 }
618 return ""
619 }
620 // Non-hashed: 2-byte name_len.
621 nameLen := int(le.Uint16(blk[nameFieldOff:]))
622 nameStart := nameFieldOff + 2
623 if nameLen > 1 {
624 return string(blk[nameStart : nameStart+uint32(nameLen-1)])
625 }
626 return ""
627}
628
629// chownInode finds an inode in the filesystem B-tree and modifies
630// its owner and group fields.
631func (c *container) chownInode(fsRootPhys, omapTreeAddr, maxXID, inodeNum uint64, uid, gid uint32) error {
632 targetKeyHeader := (uint64(apfsTypeInode) << objTypeShift) | (inodeNum & objIDMask)
633
634 blkAddr := fsRootPhys
635 blk, err := c.readBlock(blkAddr)
636 if err != nil {
637 return err
638 }
639
640 // Walk down to the leaf containing the inode.
641 for {
642 if verifyChecksum(blk) != nil {
643 return errors.New("filesystem B-tree node checksum failed")
644 }
645 if err := verifyBTreeNodeType(blk); err != nil {
646 return fmt.Errorf("filesystem B-tree node: %w", err)
647 }
648 flags := le.Uint16(blk[btnFlagsOff:])
649 nkeys := le.Uint32(blk[btnNKeysOff:])
650 tspOff := le.Uint16(blk[btnTableSpaceOff:])
651 tspLen := le.Uint16(blk[btnTableSpaceOff+2:])
652
653 tocStart := btnDataOff + uint32(tspOff)
654 keyAreaStart := tocStart + uint32(tspLen)
655
656 isLeaf := flags&btnodeLeaf != 0
657 isFixedKV := flags&btnodeFixedKVSize != 0
658 isRoot := flags&btnodeRoot != 0
659
660 valueAreaEnd := c.blockSize
661 if isRoot {
662 valueAreaEnd -= btreeInfoSize
663 }
664
665 if isLeaf {
666 for i := range nkeys {
667 kOff, vOff := c.readTocEntry(blk, tocStart, i, isFixedKV)
668 keyStart := keyAreaStart + kOff
669 keyHeader := le.Uint64(blk[keyStart:])
670
671 if keyHeader != targetKeyHeader {
672 continue
673 }
674
675 // Found the inode. Validate before writing.
676 valStart := valueAreaEnd - vOff
677
678 if valStart+inodeGroupOff+4 > c.blockSize {
679 return fmt.Errorf("inode %d value exceeds block boundary", inodeNum)
680 }
681
682 if privateID := le.Uint64(blk[valStart+inodePrivateIDOff:]); privateID != inodeNum {
683 return fmt.Errorf("inode %d has mismatched private_id %d", inodeNum, privateID)
684 }
685
686 currentUID := le.Uint32(blk[valStart+inodeOwnerOff:])
687 currentGID := le.Uint32(blk[valStart+inodeGroupOff:])
688 if currentUID != noownersPlaceholderID || currentGID != noownersPlaceholderID {
689 return fmt.Errorf("inode %d has ownership %d:%d, expected %d:%d from noowners mount",
690 inodeNum, currentUID, currentGID, noownersPlaceholderID, noownersPlaceholderID)
691 }
692
693 le.PutUint32(blk[valStart+inodeOwnerOff:], uid)
694 le.PutUint32(blk[valStart+inodeGroupOff:], gid)
695 updateChecksum(blk)
696 return c.writeBlock(blkAddr, blk)
697 }
698 return fmt.Errorf("inode %d not found in filesystem B-tree", inodeNum)
699 }
700
701 // Internal node: descend.
702 childIdx := uint32(0)
703 for i := range nkeys {
704 kOff, _ := c.readTocEntry(blk, tocStart, i, isFixedKV)
705 keyStart := keyAreaStart + kOff
706 keyHeader := le.Uint64(blk[keyStart:])
707
708 if compareFSKeyHeader(keyHeader, targetKeyHeader) <= 0 {
709 childIdx = i
710 } else {
711 break
712 }
713 }
714
715 _, vOff := c.readTocEntry(blk, tocStart, childIdx, isFixedKV)
716 childOID := le.Uint64(blk[valueAreaEnd-vOff:])
717 childPhys, err := c.omapLookup(omapTreeAddr, childOID, maxXID)
718 if err != nil {
719 return fmt.Errorf("resolving child OID %d: %w", childOID, err)
720 }
721 blkAddr = childPhys
722 blk, err = c.readBlock(blkAddr)
723 if err != nil {
724 return err
725 }
726 }
727}