| 1 | package hostimage |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "encoding/xml" |
| 6 | "io" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | func localMacImage(host Identity, directories ...string) (Plan, bool) { |
| 13 | for _, directory := range directories { |
| 14 | entries, err := os.ReadDir(directory) |
| 15 | if err != nil { |
| 16 | continue |
| 17 | } |
| 18 | for _, entry := range entries { |
| 19 | if !strings.EqualFold(filepath.Ext(entry.Name()), ".ipsw") || entry.Type()&os.ModeSymlink != 0 { |
| 20 | continue |
| 21 | } |
| 22 | path := filepath.Join(directory, entry.Name()) |
| 23 | info, err := entry.Info() |
| 24 | if err != nil || !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > 64<<30 { |
| 25 | continue |
| 26 | } |
| 27 | version, build, err := macImageIdentity(path) |
| 28 | if err != nil || version != host.Version || build != host.Build { |
| 29 | continue |
| 30 | } |
| 31 | return Plan{Host: host, Version: version, Build: build, Format: "ipsw", Bytes: info.Size(), Path: path, Modified: info.ModTime().UnixNano()}, true |
| 32 | } |
| 33 | } |
| 34 | return Plan{}, false |
| 35 | } |
| 36 | |
| 37 | func macImageIdentity(path string) (string, string, error) { |
| 38 | archive, err := zip.OpenReader(path) |
| 39 | if err != nil { |
| 40 | return "", "", err |
| 41 | } |
| 42 | defer archive.Close() |
| 43 | manifest, err := archive.Open("BuildManifest.plist") |
| 44 | if err != nil { |
| 45 | return "", "", err |
| 46 | } |
| 47 | defer manifest.Close() |
| 48 | |
| 49 | |
| 50 | decoder := xml.NewDecoder(io.LimitReader(manifest, 128<<20)) |
| 51 | depth := 0 |
| 52 | var key, version, build string |
| 53 | for { |
| 54 | token, err := decoder.Token() |
| 55 | if err != nil { |
| 56 | return version, build, err |
| 57 | } |
| 58 | switch element := token.(type) { |
| 59 | case xml.StartElement: |
| 60 | depth++ |
| 61 | if depth == 3 && element.Name.Local == "key" { |
| 62 | if err = decoder.DecodeElement(&key, &element); err != nil { |
| 63 | return "", "", err |
| 64 | } |
| 65 | depth-- |
| 66 | } else if depth == 3 && element.Name.Local == "string" { |
| 67 | var value string |
| 68 | if err = decoder.DecodeElement(&value, &element); err != nil { |
| 69 | return "", "", err |
| 70 | } |
| 71 | depth-- |
| 72 | switch key { |
| 73 | case "ProductVersion": |
| 74 | version = value |
| 75 | case "ProductBuildVersion": |
| 76 | build = value |
| 77 | } |
| 78 | if version != "" && build != "" { |
| 79 | return version, build, nil |
| 80 | } |
| 81 | } |
| 82 | case xml.EndElement: |
| 83 | depth-- |
| 84 | } |
| 85 | } |
| 86 | } |