| 1 | package dmg |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/binary" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | ) |
| 11 | |
| 12 | type DMG struct { |
| 13 | r io.ReaderAt |
| 14 | udifOffset int64 |
| 15 | sigBlob []byte |
| 16 | |
| 17 | rsf udifResourceFile |
| 18 | } |
| 19 | |
| 20 | func Open(f *os.File) (*DMG, error) { |
| 21 | // read and parse UDIF header |
| 22 | udifOffset, err := f.Seek(-512, io.SeekEnd) |
| 23 | if err != nil { |
| 24 | return nil, err |
| 25 | } |
| 26 | d := &DMG{r: f, udifOffset: udifOffset} |
| 27 | if err := binary.Read(f, binary.BigEndian, &d.rsf); err != nil { |
| 28 | return nil, err |
| 29 | } |
| 30 | if d.rsf.Signature != udifSignature { |
| 31 | return nil, errors.New("dmg file magic not found") |
| 32 | } |
| 33 | // read and parse signature |
| 34 | if d.rsf.SignatureLength != 0 { |
| 35 | if d.rsf.SignatureLength > 10e6 { |
| 36 | return nil, fmt.Errorf("unreasonably large dmg signature of %d bytes", d.rsf.SignatureLength) |
| 37 | } |
| 38 | d.sigBlob = make([]byte, d.rsf.SignatureLength) |
| 39 | if _, err := f.ReadAt(d.sigBlob, d.rsf.SignatureOffset); err != nil { |
| 40 | return nil, err |
| 41 | } |
| 42 | } |
| 43 | return d, nil |
| 44 | } |
| 45 | |
| 46 | const udifSignature = 0x6B6F6C79 // koly |
| 47 | |
| 48 | type udifFlags uint32 |
| 49 | |
| 50 | type udifResourceFile struct { |
| 51 | Signature uint32 |
| 52 | Version uint32 |
| 53 | HeaderSize uint32 |
| 54 | Flags udifFlags |
| 55 | |
| 56 | RunningDataForkOffset int64 |
| 57 | DataForkOffset int64 |
| 58 | DataForkLength int64 |
| 59 | ResourceForkOffset int64 |
| 60 | ResourceForkLength int64 |
| 61 | |
| 62 | SegmentNumber uint32 |
| 63 | SegmentCount uint32 |
| 64 | SegmentID [4]uint32 |
| 65 | |
| 66 | DataForkChecksum udifChecksum |
| 67 | |
| 68 | XMLOffset int64 |
| 69 | XMLLength int64 |
| 70 | _ [64]byte |
| 71 | |
| 72 | SignatureOffset int64 |
| 73 | SignatureLength int64 |
| 74 | _ [40]byte |
| 75 | |
| 76 | MasterChecksum udifChecksum |
| 77 | |
| 78 | ImageVariant uint32 |
| 79 | SectorCount int64 |
| 80 | |
| 81 | _ [3]uint32 |
| 82 | } |
| 83 | |
| 84 | // serialize with zeroed signature length for hashing |
| 85 | func (rsf udifResourceFile) ForHashing() []byte { |
| 86 | rsf.SignatureLength = 0 |
| 87 | var b bytes.Buffer |
| 88 | _ = binary.Write(&b, binary.BigEndian, rsf) |
| 89 | return b.Bytes() |
| 90 | } |
| 91 | |
| 92 | type udifChecksum struct { |
| 93 | Type uint32 |
| 94 | Size uint32 |
| 95 | Data [32]uint32 // TODO |
| 96 | } |