File: main.go

package info (click to toggle)
snapd 2.72-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 80,412 kB
  • sloc: sh: 16,506; ansic: 16,211; python: 11,213; makefile: 1,919; exp: 190; awk: 58; xml: 22
file content (320 lines) | stat: -rw-r--r-- 9,192 bytes parent folder | download | duplicates (3)
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
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2014-2015 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 main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"syscall"

	"github.com/jessevdk/go-flags"

	"github.com/snapcore/snapd/dirs"
	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/osutil"
	"github.com/snapcore/snapd/snap"
	"github.com/snapcore/snapd/snap/snapenv"

	// sets up the snap.NewContainerFromDir hook from snapdir
	_ "github.com/snapcore/snapd/snap/snapdir"
)

// for the tests
var syscallExec = syscall.Exec
var syscallStat = syscall.Stat
var osReadlink = os.Readlink

// commandline args
var opts struct {
	Command string `long:"command" description:"use a different command like {stop,post-stop} from the app"`
	Hook    string `long:"hook" description:"hook to run" hidden:"yes"`
}

func init() {
	// plug/slot sanitization not used nor possible from snap-exec, make it no-op
	snap.SanitizePlugsSlots = func(snapInfo *snap.Info) {}
	logger.SimpleSetup(nil)
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintf(os.Stderr, "cannot snap-exec: %s\n", err)
		os.Exit(1)
	}
}

func parseArgs(args []string) (app string, appArgs []string, err error) {
	parser := flags.NewParser(&opts, flags.HelpFlag|flags.PassDoubleDash|flags.PassAfterNonOption)
	rest, err := parser.ParseArgs(args)
	if err != nil {
		return "", nil, err
	}
	if len(rest) == 0 {
		return "", nil, fmt.Errorf("need the application to run as argument")
	}

	// Catch some invalid parameter combinations, provide helpful errors
	if opts.Hook != "" && opts.Command != "" {
		return "", nil, fmt.Errorf("cannot use --hook and --command together")
	}
	if opts.Hook != "" && len(rest) > 1 {
		return "", nil, fmt.Errorf("too many arguments for hook %q: %s", opts.Hook, strings.Join(rest, " "))
	}

	return rest[0], rest[1:], nil
}

func run() error {
	snapTarget, extraArgs, err := parseArgs(os.Args[1:])
	if err != nil {
		return err
	}

	// the SNAP_REVISION is set by `snap run` - we can not (easily)
	// find it in `snap-exec` because `snap-exec` is run inside the
	// confinement and (generally) can not talk to snapd
	revision := os.Getenv("SNAP_REVISION")

	// Now actually handle the dispatching
	if opts.Hook != "" {
		return execHook(snapTarget, revision, opts.Hook)
	}

	return execApp(snapTarget, revision, opts.Command, extraArgs)
}

const defaultShell = "/bin/bash"

func findCommand(app *snap.AppInfo, command string) (string, error) {
	var cmd string
	switch command {
	case "shell":
		cmd = defaultShell
	case "complete":
		if app.Completer != "" {
			cmd = defaultShell
		}
	case "stop":
		cmd = app.StopCommand
	case "reload":
		cmd = app.ReloadCommand
	case "post-stop":
		cmd = app.PostStopCommand
	case "", "gdb", "gdbserver":
		cmd = app.Command
	default:
		return "", fmt.Errorf("cannot use %q command", command)
	}

	if cmd == "" {
		return "", fmt.Errorf("no %q command found for %q", command, app.Name)
	}
	return cmd, nil
}

func absoluteCommandChain(mountDir string, commandChain []string) []string {
	chain := make([]string, 0, len(commandChain))
	for _, element := range commandChain {
		chain = append(chain, filepath.Join(mountDir, element))
	}

	return chain
}

// expandEnvCmdArgs takes the string list of commandline arguments
// and expands any $VAR with the given var from the env argument.
func expandEnvCmdArgs(args []string, env osutil.Environment) []string {
	cmdArgs := make([]string, 0, len(args))
	for _, arg := range args {
		maybeExpanded := os.Expand(arg, func(varName string) string {
			return env[varName]
		})
		if maybeExpanded != "" {
			cmdArgs = append(cmdArgs, maybeExpanded)
		}
	}
	return cmdArgs
}

func completionHelper() (string, error) {
	exe, err := osReadlink("/proc/self/exe")
	if err != nil {
		return "", err
	}
	return filepath.Join(filepath.Dir(exe), "etelpmoc.sh"), nil
}

func execApp(snapTarget, revision, command string, args []string) error {
	if strings.ContainsRune(snapTarget, '+') {
		return fmt.Errorf("snap-exec cannot run a snap component without a hook specified (use --hook)")
	}

	rev, err := snap.ParseRevision(revision)
	if err != nil {
		return fmt.Errorf("cannot parse revision %q: %s", revision, err)
	}

	snapName, appName := snap.SplitSnapApp(snapTarget)
	info, err := snap.ReadInfo(snapName, &snap.SideInfo{
		Revision: rev,
	})
	if err != nil {
		return fmt.Errorf("cannot read info for %q: %s", snapName, err)
	}

	app := info.Apps[appName]
	if app == nil {
		return fmt.Errorf("cannot find app %q in %q", appName, snapName)
	}

	cmdAndArgs, err := findCommand(app, command)
	if err != nil {
		return err
	}

	// build the environment from the yaml, translating TMPDIR and
	// similar variables back from where they were hidden when
	// invoking the setuid snap-confine.
	env, err := osutil.OSEnvironmentUnescapeUnsafe(snapenv.PreservedUnsafePrefix)
	if err != nil {
		return err
	}
	for _, eenv := range app.EnvChain() {
		env.ExtendWithExpanded(eenv)
	}

	// this is a workaround for the lack of an environment backend in interfaces
	// where we want certain interfaces when connected to add environment
	// variables to plugging snap apps, but this is a lot simpler as a
	// work-around
	// we currently only handle the CUPS_SERVER environment variable, setting it
	// to /var/cups/ if that dir is a bind-mount - it should not be one
	// except in a strictly confined snap where we setup the bind mount from the
	// source cups slot snap to the plugging snap.
	var stVar, stVarCups syscall.Stat_t
	err1 := syscallStat(dirs.GlobalRootDir+"/var/", &stVar)
	err2 := syscallStat(dirs.GlobalRootDir+"/var/cups/", &stVarCups)
	if err1 == nil && err2 == nil && stVar.Dev != stVarCups.Dev {
		env["CUPS_SERVER"] = "/var/cups/cups.sock"
	}

	// strings.Split() is ok here because we validate all app fields and the
	// whitelist is pretty strict (see snap/validate.go:appContentWhitelist)
	// (see also overlord/snapstate/check_snap.go's normPath)
	tmpArgv := strings.Split(cmdAndArgs, " ")
	cmd := tmpArgv[0]
	cmdArgs := expandEnvCmdArgs(tmpArgv[1:], env)

	// run the command
	fullCmd := []string{filepath.Join(app.Snap.MountDir(), cmd)}
	switch command {
	case "shell":
		fullCmd[0] = defaultShell
		cmdArgs = nil
	case "complete":
		fullCmd[0] = defaultShell
		helper, err := completionHelper()
		if err != nil {
			return fmt.Errorf("cannot find completion helper: %v", err)
		}
		cmdArgs = []string{
			helper,
			filepath.Join(app.Snap.MountDir(), app.Completer),
		}
	case "gdb":
		fullCmd = append(fullCmd, fullCmd[0])
		fullCmd[0] = filepath.Join(dirs.CoreLibExecDir, "snap-gdb-shim")
	case "gdbserver":
		fullCmd = append(fullCmd, fullCmd[0])
		fullCmd[0] = filepath.Join(dirs.CoreLibExecDir, "snap-gdbserver-shim")
	}
	fullCmd = append(fullCmd, cmdArgs...)
	fullCmd = append(fullCmd, args...)

	fullCmd = append(absoluteCommandChain(app.Snap.MountDir(), app.CommandChain), fullCmd...)

	logger.StartupStageTimestamp("snap-exec to app")
	if err := syscallExec(fullCmd[0], fullCmd, env.ForExec()); err != nil {
		return fmt.Errorf("cannot exec %q: %s", fullCmd[0], err)
	}
	// this is never reached except in tests
	return nil
}

func getComponentInfo(name string, snapInfo *snap.Info) (*snap.ComponentInfo, error) {
	return snap.ReadCurrentComponentInfo(name, snapInfo)
}

func execHook(snapTarget string, revision, hookName string) error {
	snapName, componentName := snap.SplitSnapComponentInstanceName(snapTarget)

	rev, err := snap.ParseRevision(revision)
	if err != nil {
		return err
	}

	info, err := snap.ReadInfo(snapName, &snap.SideInfo{
		Revision: rev,
	})
	if err != nil {
		return err
	}

	var (
		hook     *snap.HookInfo
		mountDir string
	)

	if componentName == "" {
		hook = info.Hooks[hookName]
		mountDir = info.MountDir()
	} else {
		component, err := getComponentInfo(componentName, info)
		if err != nil {
			return err
		}
		hook = component.Hooks[hookName]
		mountDir = snap.ComponentMountDir(component.Component.ComponentName, component.Revision, info.InstanceName())
	}

	if hook == nil {
		return fmt.Errorf("cannot find hook %q in %q", hookName, snapName)
	}

	// build the environment
	// NOTE: we do not use OSEnvironmentUnescapeUnsafe, we do not
	// particurly want to transmit snapd exec environment details
	// to the hooks
	env, err := osutil.OSEnvironment()
	if err != nil {
		return err
	}
	for _, eenv := range hook.EnvChain() {
		env.ExtendWithExpanded(eenv)
	}

	hookPath := filepath.Join(mountDir, "meta", "hooks", hookName)

	// run the hook
	cmd := append(absoluteCommandChain(mountDir, hook.CommandChain), hookPath)
	return syscallExec(cmd[0], cmd, env.ForExec())
}