forked from snapcore/snapd
/
api_sideload_n_try.go
253 lines (213 loc) · 7.14 KB
/
api_sideload_n_try.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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2015-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 daemon
import (
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"os"
"path/filepath"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/asserts/snapasserts"
"github.com/snapcore/snapd/client"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord/assertstate"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/snapfile"
)
const maxReadBuflen = 1024 * 1024
func sideloadOrTrySnap(c *Command, body io.ReadCloser, boundary string, user *auth.UserState) Response {
route := c.d.router.Get(stateChangeCmd.Path)
if route == nil {
return InternalError("cannot find route for change")
}
// POSTs to sideload snaps must be a multipart/form-data file upload.
form, err := multipart.NewReader(body, boundary).ReadForm(maxReadBuflen)
if err != nil {
return BadRequest("cannot read POST form: %v", err)
}
dangerousOK := isTrue(form, "dangerous")
flags, err := modeFlags(isTrue(form, "devmode"), isTrue(form, "jailmode"), isTrue(form, "classic"))
if err != nil {
return BadRequest(err.Error())
}
if len(form.Value["action"]) > 0 && form.Value["action"][0] == "try" {
if len(form.Value["snap-path"]) == 0 {
return BadRequest("need 'snap-path' value in form")
}
return trySnap(c.d.overlord.State(), form.Value["snap-path"][0], flags)
}
flags.RemoveSnapPath = true
flags.Unaliased = isTrue(form, "unaliased")
flags.IgnoreRunning = isTrue(form, "ignore-running")
// find the file for the "snap" form field
var snapBody multipart.File
var origPath string
out:
for name, fheaders := range form.File {
if name != "snap" {
continue
}
for _, fheader := range fheaders {
snapBody, err = fheader.Open()
origPath = fheader.Filename
if err != nil {
return BadRequest(`cannot open uploaded "snap" file: %v`, err)
}
defer snapBody.Close()
break out
}
}
defer form.RemoveAll()
if snapBody == nil {
return BadRequest(`cannot find "snap" file field in provided multipart/form-data payload`)
}
// we are in charge of the tempfile life cycle until we hand it off to the change
changeTriggered := false
// if you change this prefix, look for it in the tests
// also see localInstallCleanup in snapstate/snapmgr.go
tmpf, err := ioutil.TempFile(dirs.SnapBlobDir, dirs.LocalInstallBlobTempPrefix)
if err != nil {
return InternalError("cannot create temporary file: %v", err)
}
tempPath := tmpf.Name()
defer func() {
if !changeTriggered {
os.Remove(tempPath)
}
}()
if _, err := io.Copy(tmpf, snapBody); err != nil {
return InternalError("cannot copy request into temporary file: %v", err)
}
tmpf.Sync()
if len(form.Value["snap-path"]) > 0 {
origPath = form.Value["snap-path"][0]
}
var instanceName string
if len(form.Value["name"]) > 0 {
// caller has specified desired instance name
instanceName = form.Value["name"][0]
if err := snap.ValidateInstanceName(instanceName); err != nil {
return BadRequest(err.Error())
}
}
st := c.d.overlord.State()
st.Lock()
defer st.Unlock()
var snapName string
var sideInfo *snap.SideInfo
if !dangerousOK {
si, err := snapasserts.DeriveSideInfo(tempPath, assertstate.DB(st))
switch {
case err == nil:
snapName = si.RealName
sideInfo = si
case asserts.IsNotFound(err):
// with devmode we try to find assertions but it's ok
// if they are not there (implies --dangerous)
if !isTrue(form, "devmode") {
msg := "cannot find signatures with metadata for snap"
if origPath != "" {
msg = fmt.Sprintf("%s %q", msg, origPath)
}
return BadRequest(msg)
}
// TODO: set a warning if devmode
default:
return BadRequest(err.Error())
}
}
if snapName == "" {
// potentially dangerous but dangerous or devmode params were set
info, err := unsafeReadSnapInfo(tempPath)
if err != nil {
return BadRequest("cannot read snap file: %v", err)
}
snapName = info.SnapName()
sideInfo = &snap.SideInfo{RealName: snapName}
}
if instanceName != "" {
requestedSnapName := snap.InstanceSnap(instanceName)
if requestedSnapName != snapName {
return BadRequest(fmt.Sprintf("instance name %q does not match snap name %q", instanceName, snapName))
}
} else {
instanceName = snapName
}
msg := fmt.Sprintf(i18n.G("Install %q snap from file"), instanceName)
if origPath != "" {
msg = fmt.Sprintf(i18n.G("Install %q snap from file %q"), instanceName, origPath)
}
tset, _, err := snapstateInstallPath(st, sideInfo, tempPath, instanceName, "", flags)
if err != nil {
return errToResponse(err, []string{snapName}, InternalError, "cannot install snap file: %v")
}
chg := newChange(st, "install-snap", msg, []*state.TaskSet{tset}, []string{instanceName})
chg.Set("api-data", map[string]string{"snap-name": instanceName})
ensureStateSoon(st)
// only when the unlock succeeds (as opposed to panicing) is the handoff done
// but this is good enough
changeTriggered = true
return AsyncResponse(nil, chg.ID())
}
func trySnap(st *state.State, trydir string, flags snapstate.Flags) Response {
st.Lock()
defer st.Unlock()
if !filepath.IsAbs(trydir) {
return BadRequest("cannot try %q: need an absolute path", trydir)
}
if !osutil.IsDirectory(trydir) {
return BadRequest("cannot try %q: not a snap directory", trydir)
}
// the developer asked us to do this with a trusted snap dir
info, err := unsafeReadSnapInfo(trydir)
if _, ok := err.(snap.NotSnapError); ok {
return &apiError{
Status: 400,
Message: err.Error(),
Kind: client.ErrorKindNotSnap,
}
}
if err != nil {
return BadRequest("cannot read snap info for %s: %s", trydir, err)
}
tset, err := snapstateTryPath(st, info.InstanceName(), trydir, flags)
if err != nil {
return errToResponse(err, []string{info.InstanceName()}, BadRequest, "cannot try %s: %s", trydir)
}
msg := fmt.Sprintf(i18n.G("Try %q snap from %s"), info.InstanceName(), trydir)
chg := newChange(st, "try-snap", msg, []*state.TaskSet{tset}, []string{info.InstanceName()})
chg.Set("api-data", map[string]string{"snap-name": info.InstanceName()})
ensureStateSoon(st)
return AsyncResponse(nil, chg.ID())
}
var unsafeReadSnapInfo = unsafeReadSnapInfoImpl
func unsafeReadSnapInfoImpl(snapPath string) (*snap.Info, error) {
// Condider using DeriveSideInfo before falling back to this!
snapf, err := snapfile.Open(snapPath)
if err != nil {
return nil, err
}
return snap.ReadInfoFromSnapFile(snapf, nil)
}