-
Notifications
You must be signed in to change notification settings - Fork 601
/
Copy pathdesktop.go
327 lines (288 loc) · 10.5 KB
/
desktop.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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2014-2016 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package wrappers
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/snap"
)
// From the freedesktop Desktop Entry Specification¹,
//
// Keys with type localestring may be postfixed by [LOCALE], where
// LOCALE is the locale type of the entry. LOCALE must be of the form
// lang_COUNTRY.ENCODING@MODIFIER, where _COUNTRY, .ENCODING, and
// @MODIFIER may be omitted. If a postfixed key occurs, the same key
// must be also present without the postfix.
//
// When reading in the desktop entry file, the value of the key is
// selected by matching the current POSIX locale for the LC_MESSAGES
// category against the LOCALE postfixes of all occurrences of the
// key, with the .ENCODING part stripped.
//
// sadly POSIX doesn't mention what values are valid for LC_MESSAGES,
// beyond mentioning² that it's implementation-defined (and can be of
// the form [language[_territory][.codeset][@modifier]])
//
// 1. https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s04.html
// 2. http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_02
//
// So! The following is simplistic, and based on the contents of
// PROVIDED_LOCALES in locales.config, and does not cover all of
// "locales -m" (and ignores XSetLocaleModifiers(3), which may or may
// not be related). Patches welcome, as long as it's readable.
//
// REVIEWERS: this could also be left as `(?:\[[@_.A-Za-z-]\])?=` if even
// the following is hard to read:
const localizedSuffix = `(?:\[[a-z]+(?:_[A-Z]+)?(?:\.[0-9A-Z-]+)?(?:@[a-z]+)?\])?=`
var isValidDesktopFileLine = regexp.MustCompile(strings.Join([]string{
// NOTE (mostly to self): as much as possible keep the
// individual regexp simple, optimize for legibility
//
// empty lines and comments
`^\s*$`,
`^\s*#`,
// headers
`^\[Desktop Entry\]$`,
`^\[Desktop Action [0-9A-Za-z-]+\]$`,
`^\[[A-Za-z0-9-]+ Shortcut Group\]$`,
// https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s05.html
"^Type=",
"^Version=",
"^Name" + localizedSuffix,
"^GenericName" + localizedSuffix,
"^NoDisplay=",
"^Comment" + localizedSuffix,
"^Icon=",
"^Hidden=",
"^OnlyShowIn=",
"^NotShowIn=",
"^Exec=",
// Note that we do not support TryExec, it does not make sense
// in the snap context
"^Terminal=",
"^Actions=",
"^MimeType=",
"^Categories=",
"^Keywords" + localizedSuffix,
"^StartupNotify=",
"^StartupWMClass=",
// unity extension
"^X-Ayatana-Desktop-Shortcuts=",
"^TargetEnvironment=",
}, "|")).Match
// rewriteExecLine rewrites a "Exec=" line to use the wrapper path for snap application.
func rewriteExecLine(s *snap.Info, desktopFile, line string) (string, error) {
env := fmt.Sprintf("env BAMF_DESKTOP_FILE_HINT=%s ", desktopFile)
cmd := strings.SplitN(line, "=", 2)[1]
for _, app := range s.Apps {
wrapper := app.WrapperPath()
validCmd := filepath.Base(wrapper)
if s.InstanceKey != "" {
// wrapper uses s.InstanceName(), with the instance key
// set the command will be 'snap_foo.app' instead of
// 'snap.app', need to account for that
validCmd = snap.JoinSnapApp(s.SnapName(), app.Name)
}
// check the prefix to allow %flag style args
// this is ok because desktop files are not run through sh
// so we don't have to worry about the arguments too much
if cmd == validCmd {
return "Exec=" + env + wrapper, nil
} else if strings.HasPrefix(cmd, validCmd+" ") {
return fmt.Sprintf("Exec=%s%s%s", env, wrapper, line[len("Exec=")+len(validCmd):]), nil
}
}
logger.Noticef("cannot use line %q for desktop file %q (snap %s)", line, desktopFile, s.InstanceName())
// The Exec= line in the desktop file is invalid. Instead of failing
// hard we rewrite the Exec= line. The convention is that the desktop
// file has the same name as the application we can use this fact here.
df := filepath.Base(desktopFile)
desktopFileApp := strings.TrimSuffix(df, filepath.Ext(df))
app, ok := s.Apps[desktopFileApp]
if ok {
newExec := fmt.Sprintf("Exec=%s%s", env, app.WrapperPath())
logger.Noticef("rewriting desktop file %q to %q", desktopFile, newExec)
return newExec, nil
}
return "", fmt.Errorf("invalid exec command: %q", cmd)
}
func rewriteIconLine(s *snap.Info, line string) (string, error) {
icon := strings.SplitN(line, "=", 2)[1]
// If there is a path separator, assume the icon is a path name
if strings.ContainsRune(icon, filepath.Separator) {
if !strings.HasPrefix(icon, "${SNAP}/") {
return "", fmt.Errorf("icon path %q is not part of the snap", icon)
}
if filepath.Clean(icon) != icon {
return "", fmt.Errorf("icon path %q is not canonicalized, did you mean %q?", icon, filepath.Clean(icon))
}
return line, nil
}
// If the icon is prefixed with "snap.${SNAP_NAME}.", rewrite
// to the instance name.
snapIconPrefix := fmt.Sprintf("snap.%s.", s.SnapName())
if strings.HasPrefix(icon, snapIconPrefix) {
return fmt.Sprintf("Icon=snap.%s.%s", s.InstanceName(), icon[len(snapIconPrefix):]), nil
}
// If the icon has any other "snap." prefix, treat this as an error.
if strings.HasPrefix(icon, "snap.") {
return "", fmt.Errorf("invalid icon name: %q, must start with %q", icon, snapIconPrefix)
}
// Allow other icons names through unchanged.
return line, nil
}
func sanitizeDesktopFile(s *snap.Info, desktopFile string, rawcontent []byte) []byte {
var newContent bytes.Buffer
mountDir := []byte(s.MountDir())
scanner := bufio.NewScanner(bytes.NewReader(rawcontent))
for i := 0; scanner.Scan(); i++ {
bline := scanner.Bytes()
if !isValidDesktopFileLine(bline) {
logger.Debugf("ignoring line %d (%q) in source of desktop file %q", i, bline, filepath.Base(desktopFile))
continue
}
// rewrite exec lines to an absolute path for the binary
if bytes.HasPrefix(bline, []byte("Exec=")) {
var err error
line, err := rewriteExecLine(s, desktopFile, string(bline))
if err != nil {
// something went wrong, ignore the line
continue
}
bline = []byte(line)
}
// rewrite icon line if it references an icon theme icon
if bytes.HasPrefix(bline, []byte("Icon=")) {
line, err := rewriteIconLine(s, string(bline))
if err != nil {
logger.Debugf("ignoring icon in source desktop file %q: %s", filepath.Base(desktopFile), err)
continue
}
bline = []byte(line)
}
// do variable substitution
bline = bytes.Replace(bline, []byte("${SNAP}"), mountDir, -1)
newContent.Grow(len(bline) + 1)
newContent.Write(bline)
newContent.WriteByte('\n')
// insert snap name
if bytes.Equal(bline, []byte("[Desktop Entry]")) {
newContent.Write([]byte("X-SnapInstanceName=" + s.InstanceName() + "\n"))
}
}
return newContent.Bytes()
}
func updateDesktopDatabase(desktopFiles []string) error {
if len(desktopFiles) == 0 {
return nil
}
if _, err := exec.LookPath("update-desktop-database"); err == nil {
if output, err := exec.Command("update-desktop-database", dirs.SnapDesktopFilesDir).CombinedOutput(); err != nil {
return fmt.Errorf("cannot update-desktop-database %q: %s", output, err)
}
logger.Debugf("update-desktop-database successful")
}
return nil
}
// desktopPrefix returns the prefix string for the desktop files that
// belongs to the given snapInstance. We need to do something custom
// here because a) we need to be compatible with the world before we had
// parallel installs b) we can't just use the usual "_" parallel installs
// separator because that is already used as the separator between snap
// and desktop filename.
func desktopPrefix(s *snap.Info) string {
if s.SnapName() == s.InstanceName() {
return s.SnapName()
}
// we cannot use the usual "_" separator because that is also used
// to separate "$snap_$desktopfile"
return fmt.Sprintf("%s+%s", s.SnapName(), s.InstanceKey)
}
// AddSnapDesktopFiles puts in place the desktop files for the applications from the snap.
func AddSnapDesktopFiles(s *snap.Info) (err error) {
var created []string
defer func() {
if err == nil {
return
}
for _, fn := range created {
os.Remove(fn)
}
}()
if err := os.MkdirAll(dirs.SnapDesktopFilesDir, 0755); err != nil {
return err
}
baseDir := s.MountDir()
desktopFiles, err := filepath.Glob(filepath.Join(baseDir, "meta", "gui", "*.desktop"))
if err != nil {
return fmt.Errorf("cannot get desktop files for %v: %s", baseDir, err)
}
for _, df := range desktopFiles {
content, err := ioutil.ReadFile(df)
if err != nil {
return err
}
// FIXME: don't blindly use the snap desktop filename, mangle it
// but we can't just use the app name because a desktop file
// may call the same app with multiple parameters, e.g.
// --create-new, --open-existing etc
installedDesktopFileName := filepath.Join(dirs.SnapDesktopFilesDir, fmt.Sprintf("%s_%s", desktopPrefix(s), filepath.Base(df)))
content = sanitizeDesktopFile(s, installedDesktopFileName, content)
if err := osutil.AtomicWriteFile(installedDesktopFileName, content, 0755, 0); err != nil {
return err
}
created = append(created, installedDesktopFileName)
}
// updates mime info etc
if err := updateDesktopDatabase(desktopFiles); err != nil {
return err
}
return nil
}
// RemoveSnapDesktopFiles removes the added desktop files for the applications in the snap.
func RemoveSnapDesktopFiles(s *snap.Info) error {
removedDesktopFiles := make([]string, 0, len(s.Apps))
desktopFiles, err := filepath.Glob(filepath.Join(dirs.SnapDesktopFilesDir, fmt.Sprintf("%s_*.desktop", desktopPrefix(s))))
if err != nil {
return nil
}
for _, df := range desktopFiles {
if err := os.Remove(df); err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
removedDesktopFiles = append(removedDesktopFiles, df)
}
}
// updates mime info etc
if err := updateDesktopDatabase(removedDesktopFiles); err != nil {
return err
}
return nil
}