-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
363 lines (310 loc) · 9.98 KB
/
parser.go
File metadata and controls
363 lines (310 loc) · 9.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package main
import (
"bytes"
"context"
"fmt"
"io"
"log/slog"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/andrianbdn/iospng"
"github.com/klauspost/compress/zip"
"howett.net/plist"
)
const (
MaxRetries = 3
RetryDelay = 1000 * time.Millisecond
)
var infoPlistRegex = regexp.MustCompile(`^Payload/[^/]+\.app/Info\.plist$`)
// HttpReaderAt implements io.ReaderAt using HTTP Range requests
type HttpReaderAt struct {
ctx context.Context
client *http.Client
url string
}
func (r *HttpReaderAt) ReadAt(p []byte, off int64) (int, error) {
if len(p) == 0 {
return 0, nil
}
rangeHeader := fmt.Sprintf("bytes=%d-%d", off, off+int64(len(p))-1)
var lastErr error
for attempt := 0; attempt <= MaxRetries; attempt++ {
if attempt > 0 {
// Exponential backoff: 1s, 2s, 3s...
time.Sleep(RetryDelay * time.Duration(attempt))
slog.Debug("Retrying range request", "url", r.url, "range", rangeHeader, "attempt", attempt)
}
req, err := http.NewRequestWithContext(r.ctx, "GET", r.url, nil)
if err != nil {
return 0, err
}
req.Header.Set("Range", rangeHeader)
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
resp, err := r.client.Do(req)
if err != nil {
lastErr = fmt.Errorf("HTTP request failed: %w", err)
continue
}
if resp.StatusCode != http.StatusPartialContent {
if resp.StatusCode == http.StatusOK && off > 0 {
resp.Body.Close()
return 0, fmt.Errorf("server does not support range requests (status 200 for offset %d)", off)
}
if resp.StatusCode >= 500 {
lastErr = fmt.Errorf("server error %d for range %s", resp.StatusCode, rangeHeader)
resp.Body.Close()
continue
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return 0, fmt.Errorf("unexpected status code %d for range %s", resp.StatusCode, rangeHeader)
}
}
n, err := io.ReadFull(resp.Body, p)
resp.Body.Close()
if err != nil && err != io.ErrUnexpectedEOF {
lastErr = fmt.Errorf("failed to read body: %w", err)
continue
}
return n, err
}
return 0, lastErr
}
// OpenRemoteZip opens a remote ZIP file using HTTP Range requests and returns a zip.Reader and its total size
func OpenRemoteZip(ctx context.Context, url string, client *http.Client, knownSize int64) (*zip.Reader, int64, error) {
var actualSize int64 = knownSize
if actualSize <= 0 {
var resp *http.Response
var err error
// Initial request to get size and check availability
for attempt := 1; attempt <= MaxRetries+1; attempt++ {
req, _ := http.NewRequestWithContext(ctx, "HEAD", url, nil)
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
resp, err = client.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
break
}
// Fallback to GET if HEAD is not supported or fails
req, _ = http.NewRequestWithContext(ctx, "GET", url, nil)
req.Header.Set("Range", "bytes=0-0")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
resp, err = client.Do(req)
if err == nil && (resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusPartialContent) {
break
}
if attempt <= MaxRetries {
if resp != nil {
resp.Body.Close()
}
time.Sleep(RetryDelay * time.Duration(attempt))
continue
}
return nil, 0, fmt.Errorf("failed to reach URL after %d attempts: %v", MaxRetries+1, err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusPartialContent {
cr := resp.Header.Get("Content-Range")
if cr != "" {
parts := regexp.MustCompile(`/(\d+)$`).FindStringSubmatch(cr)
if len(parts) > 1 {
actualSize, _ = strconv.ParseInt(parts[1], 10, 64)
}
}
} else {
contentLength := resp.Header.Get("Content-Length")
actualSize, _ = strconv.ParseInt(contentLength, 10, 64)
}
}
if actualSize <= 0 {
return nil, 0, fmt.Errorf("could not determine file size")
}
readerAt := &HttpReaderAt{
ctx: ctx,
client: client,
url: url,
}
zr, err := zip.NewReader(readerAt, actualSize)
if err != nil {
return nil, 0, fmt.Errorf("failed to read zip header: %w", err)
}
return zr, actualSize, nil
}
// FetchAndParseIPA fetches an IPA from a URL and extracts metadata
func FetchAndParseIPA(ctx context.Context, url string, client *http.Client) (*IPAData, error) {
zr, actualSize, err := OpenRemoteZip(ctx, url, client, 0)
if err != nil {
return nil, err
}
fileSizeStr := fmt.Sprintf("%.2f MB", float64(actualSize)/1024/1024)
// First pass: try to find Info.plist in the standard location to avoid iterating through thousands of files
var lastParseErr error
for _, file := range zr.File {
if infoPlistRegex.MatchString(file.Name) {
data, err := parseInfoPlist(file, url, actualSize, fileSizeStr, zr)
if err == nil {
return data, nil
}
lastParseErr = err
slog.Warn("Failed to parse Info.plist in standard location, falling back", "path", file.Name, "error", err)
}
}
if lastParseErr != nil {
return nil, fmt.Errorf("failed to parse Info.plist: %w", lastParseErr)
}
return nil, fmt.Errorf("Info.plist not found in the IPA")
}
func parseInfoPlist(file *zip.File, url string, actualSize int64, fileSizeStr string, zr *zip.Reader) (*IPAData, error) {
rc, err := file.Open()
if err != nil {
return nil, fmt.Errorf("failed to open %s: %v", file.Name, err)
}
defer rc.Close()
buf := new(bytes.Buffer)
_, err = io.Copy(buf, rc)
if err != nil {
return nil, fmt.Errorf("failed to read %s: %v", file.Name, err)
}
var plistData map[string]interface{}
_, err = plist.Unmarshal(buf.Bytes(), &plistData)
if err != nil {
return nil, fmt.Errorf("failed to parse Info.plist: %v", err)
}
return &IPAData{
Name: getString(plistData, "CFBundleName", getString(plistData, "CFBundleDisplayName", "Unknown")),
Version: getString(plistData, "CFBundleShortVersionString", "Unknown"),
Build: getString(plistData, "CFBundleVersion", "Unknown"),
BundleID: getString(plistData, "CFBundleIdentifier", "Unknown"),
URL: url,
FileSize: fileSizeStr,
RawSize: actualSize,
IconPath: findBestIcon(plistData, zr),
}, nil
}
// ExtractIcon extracts a specific file from the IPA
func ExtractIcon(ctx context.Context, urlStr string, iconPath string, client *http.Client, knownSize int64) ([]byte, string, error) {
zr, _, err := OpenRemoteZip(ctx, urlStr, client, knownSize)
if err != nil {
return nil, "", err
}
for _, file := range zr.File {
if file.Name == iconPath {
rc, err := file.Open()
if err != nil {
return nil, "", err
}
// Fix Apple's "CgBI" optimized PNGs
if strings.HasSuffix(strings.ToLower(iconPath), ".png") {
data, err := io.ReadAll(rc)
if err != nil {
return nil, "", err
}
outBuf := new(bytes.Buffer)
err = iospng.PngRevertOptimization(bytes.NewReader(data), outBuf)
if err == nil {
return outBuf.Bytes(), "image/png", nil
} else {
slog.Warn("Could not de-crush PNG", "path", iconPath, "error", err)
return data, "image/png", nil
}
}
// For non-PNG or failed de-crush, stream the data
buf := new(bytes.Buffer)
_, err = io.Copy(buf, rc)
if err != nil {
return nil, "", err
}
contentType := "image/png"
if strings.HasSuffix(strings.ToLower(iconPath), ".jpg") || strings.HasSuffix(strings.ToLower(iconPath), ".jpeg") {
contentType = "image/jpeg"
}
return buf.Bytes(), contentType, nil
}
}
return nil, "", fmt.Errorf("icon not found")
}
func findBestIcon(plistData map[string]interface{}, zr *zip.Reader) string {
fileMap := make(map[string]bool)
for _, f := range zr.File {
fileMap[f.Name] = true
}
appFolder := ""
for _, f := range zr.File {
if strings.HasPrefix(f.Name, "Payload/") && strings.Contains(f.Name, ".app/Info.plist") {
idx := strings.Index(f.Name, ".app/Info.plist")
appFolder = f.Name[:idx+5]
break
}
}
if appFolder == "" {
return ""
}
var iconFiles []string
extractFromIconsDict := func(dict interface{}) {
if d, ok := dict.(map[string]interface{}); ok {
if primary, ok := d["CFBundlePrimaryIcon"].(map[string]interface{}); ok {
if files, ok := primary["CFBundleIconFiles"].([]interface{}); ok {
for _, f := range files {
if s, ok := f.(string); ok {
iconFiles = append(iconFiles, s)
}
}
}
}
}
}
extractFromIconsDict(plistData["CFBundleIcons"])
extractFromIconsDict(plistData["CFBundleIcons~ipad"])
if files, ok := plistData["CFBundleIconFiles"].([]interface{}); ok {
for _, f := range files {
if s, ok := f.(string); ok {
iconFiles = append(iconFiles, s)
}
}
}
if f, ok := plistData["CFBundleIconFile"].(string); ok {
iconFiles = append(iconFiles, f)
}
suffixes := []string{"@3x.png", "@2x.png", ".png", "@3x~iphone.png", "@2x~iphone.png", "~iphone.png", "@3x~ipad.png", "@2x~ipad.png", "~ipad.png"}
for i := len(iconFiles) - 1; i >= 0; i-- {
baseName := iconFiles[i]
for _, s := range suffixes {
target := appFolder + baseName + s
if strings.HasSuffix(baseName, ".png") {
target = appFolder + baseName
}
if fileMap[target] {
return target
}
}
}
fallbacks := []string{
"AppIcon60x60@3x.png", "AppIcon60x60@2x.png", "AppIcon40x40@3x.png", "AppIcon40x40@2x.png",
"Icon-60@3x.png", "Icon-60@2x.png", "Icon-76@2x.png", "Icon-76.png",
"Icon@3x.png", "Icon@2x.png", "Icon.png",
}
for _, fb := range fallbacks {
if fileMap[appFolder+fb] {
return appFolder + fb
}
}
for _, f := range zr.File {
if strings.HasPrefix(f.Name, appFolder) && strings.HasSuffix(f.Name, ".png") {
lowerName := strings.ToLower(f.Name)
if strings.Contains(lowerName, "appicon") || (strings.Contains(lowerName, "icon") && !strings.Contains(lowerName, "launch")) {
return f.Name
}
}
}
return ""
}
func getString(m map[string]interface{}, key string, defaultValue string) string {
if v, ok := m[key]; ok {
if s, ok := v.(string); ok {
return s
}
}
return defaultValue
}