-
Notifications
You must be signed in to change notification settings - Fork 3
/
appimage.go
463 lines (375 loc) · 10.9 KB
/
appimage.go
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
// Drop-in replacemnt for go-appimage for sandboxing and use with shappimages
// NOT FINISHED AND STILL LACKING BASIC FEATURES
// THIS SHOULD BE USED FOR TESTING PURPOSES *ONLY* UNTIL IN A STABLE STATE
package aisap
import (
"bufio"
"crypto/md5"
"debug/elf"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
squashfs "github.com/CalebQ42/squashfs"
xdg "github.com/adrg/xdg"
helpers "github.com/mgord9518/aisap/helpers"
permissions "github.com/mgord9518/aisap/permissions"
profiles "github.com/mgord9518/aisap/profiles"
ini "gopkg.in/ini.v1"
)
type AppImage struct {
Desktop *ini.File // INI of internal desktop entry
Path string // Location of AppImage
dataDir string // The AppImage's `HOME` directory
rootDir string // Can be used to give the AppImage fake system files
tempDir string // The AppImage's `/tmp` directory
mountDir string // The location the AppImage is mounted at
md5 string // MD5 of AppImage's URI
Name string // AppImage name from the desktop entry
Version string
UpdateInfo string
Offset int // Offset of SquashFS image
imageType int // Type of AppImage (1=ISO 9660 ELF, 2=squashfs ELF, -2=shImg shell)
architecture []string // List of CPU architectures supported by the bundle
reader *squashfs.Reader
file *os.File
// These will both be removed when the Zig-implemented C bindings
// become usable
CurrentArg int // Should only ever be used for the C bindings
WrapArgsList []string // Should only ever be used for the C bindings
}
// Current version of aisap
// Defined in `zig/build.zig.zon`
// When using aisap as a library, `--ldflags="-X github.com/mgord9518/aisap.Version=[VERSION HERE]"`
// should be updated to the value contained in build.zig.zon
var (
Version = "UNDEFINED"
)
// Create a new AppImage object from a path
func NewAppImage(src string) (*AppImage, error) {
var err error
ai := &AppImage{Path: src}
if !helpers.FileExists(ai.Path) {
return nil, errors.New("file not found!")
}
b := md5.Sum([]byte("file://" + ai.Path))
ai.md5 = fmt.Sprintf("%x", b)
ai.imageType, err = helpers.GetAppImageType(ai.Path)
if err != nil {
return nil, err
}
ai.rootDir = "/"
ai.dataDir = ai.Path + ".home"
ai.Offset, err = helpers.GetOffset(src)
if err != nil {
return nil, err
}
if ai.imageType == -2 || ai.imageType == 2 {
ai.file, err = os.Open(ai.Path)
if err != nil {
return nil, err
}
info, _ := ai.file.Stat()
off64 := int64(ai.Offset)
r := io.NewSectionReader(ai.file, off64, info.Size()-off64)
ai.reader, err = squashfs.NewReader(r)
if err != nil {
return nil, err
}
}
// Prefer local entry if it exists (located at $XDG_DATA_HOME/aisap/[ai.Name])
desktopReader, err := ai.getEntry()
if err != nil {
return ai, err
}
ai.Desktop, err = ini.LoadSources(ini.LoadOptions{
IgnoreInlineComment: true,
}, desktopReader)
if err != nil {
return ai, err
}
ai.Name = ai.Desktop.Section("Desktop Entry").Key("Name").Value()
ai.Version = ai.Desktop.Section("Desktop Entry").Key("X-AppImage-Version").Value()
ai.UpdateInfo, _ = helpers.ReadUpdateInfo(ai.Path)
if ai.Version == "" {
ai.Version = "1.0"
}
return ai, nil
}
// Retrieve permissions from the AppImage in the following order:
//
// 1: User-configured settings in ~/.local/share/aisap/profiles/[ai.Name]
// 2: aisap internal permissions library
// 3: Permissions defined in the AppImage's desktop file
func (ai AppImage) Permissions() (*permissions.AppImagePerms, error) {
var perms *permissions.AppImagePerms
var err error
// If PREFER_AISAP_PROFILE is set, attempt to use it over the AppImage's
// suggested permissions. If no profile exists in aisap, fall back on saved
// permissions in aisap, and then finally the AppImage's internal desktop
// entry
// Typically this should be unset unless testing a custom profile against
// aisap's
if _, present := os.LookupEnv("PREFER_AISAP_PROFILE"); present {
perms, err = profiles.FromName(ai.Name)
if err != nil {
perms, err = permissions.FromSystem(ai.Name)
}
} else {
perms, err = permissions.FromSystem(ai.Name)
if err != nil {
perms, err = profiles.FromName(ai.Name)
}
}
// Fall back to permissions inside AppImage if all else fails
if err != nil {
return permissions.FromIni(ai.Desktop)
}
return perms, nil
}
// Returns `true` if the AppImage in question is both executable and has
// its profile copied to the aisap config dir. This is to ensure the
// permissions can't change under the user's feet through an update to the
// AppImage
func (ai *AppImage) Trusted() bool {
aisapConfig := filepath.Join(xdg.DataHome, "aisap", "profiles")
filePath := filepath.Join(aisapConfig, ai.Name)
// If the AppImage permissions exist in aisap's config directory and the
// AppImage is executable, we consider it trusted
if helpers.FileExists(filePath) {
info, err := os.Stat(ai.Path)
if err != nil {
return false
}
return info.Mode()&0100 != 0
}
return false
}
func (ai *AppImage) SetTrusted(trusted bool) error {
aisapConfig := filepath.Join(xdg.DataHome, "aisap", "profiles")
filePath := filepath.Join(aisapConfig, ai.Name)
if trusted {
if !helpers.DirExists(aisapConfig) {
os.MkdirAll(aisapConfig, 0744)
}
info, err := os.Stat(ai.Path)
if err != nil {
return err
}
os.Chmod(ai.Path, info.Mode()|0100)
if helpers.FileExists(filePath) {
return errors.New("entry already exists in aisap config dir")
}
desktopReader, _ := ai.getEntry()
permFile, _ := os.Create(filePath)
io.Copy(permFile, desktopReader)
} else {
os.Remove(filePath)
}
return nil
}
// Return a reader for the `.DirIcon` file of the AppImage
func (ai *AppImage) Thumbnail() (io.Reader, error) {
// Try to extract from zip, continue to SquashFS if it fails
if ai.imageType == -2 {
r, err := helpers.ExtractResourceReader(ai.Path, "icon/256.png")
if err == nil {
return r, nil
}
}
return ai.ExtractFileReader(".DirIcon")
}
func (ai *AppImage) RootDir() string {
return ai.rootDir
}
func (ai *AppImage) DataDir() string {
return ai.dataDir
}
func (ai *AppImage) TempDir() string {
return ai.tempDir
}
func (ai *AppImage) Md5() string {
return ai.md5
}
func (ai *AppImage) MountDir() string {
return ai.mountDir
}
// Set the directory the sandbox pulls system files from
func (ai *AppImage) SetRootDir(d string) {
ai.rootDir = d
}
// Set the directory for the sandboxed AppImage's `HOME`
func (ai *AppImage) SetDataDir(d string) {
ai.dataDir = d
}
// Set the directory for the sandboxed AppImage's `TMPDIR`
func (ai *AppImage) SetTempDir(d string) {
ai.tempDir = d
}
// Return type of AppImage
func (ai *AppImage) Type() int {
t, _ := helpers.GetAppImageType(ai.Path)
return t
}
func (ai *AppImage) Architectures() []string {
s, _ := ai.getArchitectures()
return s
}
// Extract a file from the AppImage's interal filesystem image
func (ai *AppImage) ExtractFile(path string, dest string, resolveSymlinks bool) error {
// Remove file if it already exists
os.Remove(filepath.Join(dest))
info, err := os.Lstat(path)
// True if file is symlink and `resolveSymlinks` is false
if info != nil && !resolveSymlinks &&
info.Mode()&os.ModeSymlink == os.ModeSymlink {
target, _ := os.Readlink(path)
err = os.Symlink(target, dest)
} else {
inF, err := ai.ExtractFileReader(path)
defer inF.Close()
if err != nil {
return err
}
info, err := os.Stat(path)
perms := info.Mode().Perm()
outF, err := os.Create(dest)
defer outF.Close()
if err != nil {
return err
}
err = os.Chmod(dest, perms)
if err != nil {
return err
}
_, err = io.Copy(outF, inF)
if err != nil {
return err
}
}
return err
}
// Like `ExtractFile()` but gives access to the reader instead of extracting
func (ai *AppImage) ExtractFileReader(path string) (io.ReadCloser, error) {
f, err := ai.reader.Open(path)
if err != nil {
return f, err
}
r := f.(*squashfs.File)
if r.IsSymlink() {
r = r.GetSymlinkFile()
}
return r, err
}
// Returns the icon reader of the AppImage, valid formats are SVG and PNG
func (ai *AppImage) Icon() (io.ReadCloser, string, error) {
if ai.imageType == -2 {
r, err := helpers.ExtractResourceReader(ai.Path, "icon/default.svg")
if err == nil {
return r, "icon/default.svg", nil
}
r, err = helpers.ExtractResourceReader(ai.Path, "icon/default.png")
if err == nil {
return r, "icon/default.png", nil
}
}
if ai.Desktop == nil {
return nil, "", InvalidDesktopFile
}
// Return error if desktop file has no icon
iconf := ai.Desktop.Section("Desktop Entry").Key("Icon").Value()
if iconf == "" {
return nil, "", NoIcon
}
// If the desktop entry specifies an extension, use it
if strings.HasSuffix(iconf, ".png") || strings.HasSuffix(iconf, ".svg") {
r, err := ai.ExtractFileReader(iconf)
return r, iconf, err
}
// If not, iterate through all AppImage specified image formats
extensions := []string{
".png",
".svg",
}
for _, ext := range extensions {
r, err := ai.ExtractFileReader(iconf + ext)
if err == nil {
return r, path.Base(iconf + ext), err
}
}
return nil, "", InvalidIconExtension
}
// Extract the desktop file from the AppImage
func (ai *AppImage) getEntry() (io.Reader, error) {
var r io.Reader
var err error
if ai.imageType == -2 {
r, err = helpers.ExtractResourceReader(ai.Path, "desktop_entry")
}
// Extract from SquashFS if type 2 or zip fails
if ai.imageType == 2 || err != nil {
// Return all `.desktop` files. A vadid AppImage should only have one
var fp []string
fp, err = ai.reader.Glob("*.desktop")
if len(fp) != 1 {
return nil, NoDesktopFile
}
entry, err := ai.reader.Open(fp[0])
r := entry.(*squashfs.File)
if r.IsSymlink() {
r = r.GetSymlinkFile()
}
return r, err
}
return r, err
}
// Determine what architectures a bundle supports
func (ai *AppImage) getArchitectures() ([]string, error) {
a := ai.Desktop.Section("Desktop Entry").Key("X-AppImage-Architecture").Value()
s := helpers.SplitKey(a)
if len(s) > 0 {
return s, nil
}
// If undefined in the desktop entry, assume arch via ELF AppImage runtime
if ai.Type() >= 0 {
e, err := elf.NewFile(ai.file)
if err != nil {
return s, err
}
switch e.Machine {
case elf.EM_386:
return []string{"i386"}, nil
case elf.EM_X86_64:
return []string{"x86_64"}, nil
case elf.EM_ARM:
return []string{"armhf"}, nil
case elf.EM_AARCH64:
return []string{"aarch64"}, nil
}
}
// Assume arch via shImg runtime
if ai.Type() < -1 {
scanner := bufio.NewScanner(ai.file)
arches := []string{}
counter := 0
for scanner.Scan() {
counter++
if strings.HasPrefix(scanner.Text(), "arch='") {
str := scanner.Text()
str = strings.ReplaceAll(str, "arch='", "")
str = strings.ReplaceAll(str, "'", "")
arches = helpers.SplitKey(str)
return arches, nil
}
// All shImg info should be at the top of the file, 50 is more than
// enough
if counter >= 50 {
break
}
}
}
return s, errors.New("failed to determine arch")
}