File: cmdutil.go

package info (click to toggle)
snapd 2.71-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 79,536 kB
  • sloc: ansic: 16,114; sh: 16,105; python: 9,941; makefile: 1,890; exp: 190; awk: 40; xml: 22
file content (171 lines) | stat: -rw-r--r-- 4,841 bytes parent folder | download | duplicates (2)
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
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2019-2020 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 snapdtool

import (
	"bufio"
	"bytes"
	"debug/elf"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/snapcore/snapd/dirs"
	"github.com/snapcore/snapd/osutil"
)

var elfInterp = func(cmd string) (string, error) {
	el, err := elf.Open(cmd)
	if err != nil {
		return "", err
	}
	defer el.Close()

	for _, prog := range el.Progs {
		if prog.Type == elf.PT_INTERP {
			r := prog.Open()
			interp, err := io.ReadAll(r)
			if err != nil {
				return "", nil
			}

			return string(bytes.Trim(interp, "\x00")), nil
		}
	}

	return "", fmt.Errorf("cannot find PT_INTERP header")
}

func parseLdSoConf(root string, confPath string) []string {
	f, err := os.Open(filepath.Join(root, confPath))
	if err != nil {
		return nil
	}
	defer f.Close()

	var out []string
	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		line := scanner.Text()
		switch {
		case strings.HasPrefix(line, "#"):
			// nothing
		case strings.TrimSpace(line) == "":
			// nothing
		case strings.HasPrefix(line, "include "):
			l := strings.SplitN(line, "include ", 2)
			files, err := filepath.Glob(filepath.Join(root, l[1]))
			if err != nil {
				return nil
			}
			for _, f := range files {
				out = append(out, parseLdSoConf(root, f[len(root):])...)
			}
		default:
			out = append(out, filepath.Join(root, line))
		}

	}
	if err := scanner.Err(); err != nil {
		return nil
	}

	return out
}

// CommandFromSystemSnap runs a command from the snapd/core snap
// using the proper interpreter and library paths if needed.
//
// Files from core need this hack. Files from snapd are executed normally unless
// the snapd snap is not mounted under /snap.
//
// At the moment it can only run ELF files, expects a standard ld.so
// interpreter, and can't handle RPATH.
func CommandFromSystemSnap(name string, cmdArgs ...string) (*exec.Cmd, error) {
	from := "snapd"
	root := filepath.Join(dirs.SnapMountDir, "/snapd/current")
	if !osutil.FileExists(root) {
		from = "core"
		root = filepath.Join(dirs.SnapMountDir, "/core/current")
	}

	cmdPath := filepath.Join(root, name)

	if from == "snapd" {
		// the elf interpreter invoked by the binary will work if snaps are mounted at /snap
		// or /snap/snapd/current resolves to <mount dir>/snapd/current so that the interpreter
		// locations are correct, otherwise we need to set up a command to invoke it directly
		snapdCurrentDir := filepath.Join(dirs.GlobalRootDir, "snap/snapd/current")
		if match, err := osutil.ComparePathsByDeviceInode(root, snapdCurrentDir); err == nil && match {
			return exec.Command(cmdPath, cmdArgs...), nil
		}

		interp, err := elfInterp(cmdPath)
		if err != nil {
			return nil, err
		}

		slashSnapPrefix := filepath.Join(dirs.GlobalRootDir, "snap") + "/"
		interp = filepath.Join(dirs.SnapMountDir, strings.TrimPrefix(interp, slashSnapPrefix))
		// all libraries are at the same path as the interpreter
		ldLibraryPathForSnapd := filepath.Dir(interp)

		ldSoArgs := []string{"--library-path", ldLibraryPathForSnapd, cmdPath}
		allArgs := append(ldSoArgs, cmdArgs...)
		return exec.Command(interp, allArgs...), nil
	}

	// We are trying to execute files from core snap. They need
	// run with a their interpreter and library paths

	interp, err := elfInterp(cmdPath)
	if err != nil {
		return nil, err
	}
	coreLdSo := filepath.Join(root, interp)
	// we cannot use EvalSymlink here because we need to resolve
	// relative and an absolute symlinks differently. A absolute
	// symlink is relative to root of the snapd/core snap.
	seen := map[string]bool{}
	for osutil.IsSymlink(coreLdSo) {
		link, err := os.Readlink(coreLdSo)
		if err != nil {
			return nil, err
		}
		if filepath.IsAbs(link) {
			coreLdSo = filepath.Join(root, link)
		} else {
			coreLdSo = filepath.Join(filepath.Dir(coreLdSo), link)
		}
		if seen[coreLdSo] {
			return nil, fmt.Errorf("cannot run command from %s: symlink cycle found", from)
		}
		seen[coreLdSo] = true
	}

	ldLibraryPathForCore := parseLdSoConf(root, "/etc/ld.so.conf")

	ldSoArgs := []string{"--library-path", strings.Join(ldLibraryPathForCore, ":"), cmdPath}
	allArgs := append(ldSoArgs, cmdArgs...)
	return exec.Command(coreLdSo, allArgs...), nil
}