File: copy.go

package info (click to toggle)
golang-github-mendersoftware-mender-artifact 3.9.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,212 kB
  • sloc: sh: 128; makefile: 128
file content (335 lines) | stat: -rw-r--r-- 7,807 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
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
// Copyright 2021 Northern.tech AS
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

package cli

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"

	"github.com/urfave/cli"
)

var isimg = regexp.MustCompile(`\.(mender|sdimg|uefiimg|img)(:|$)`)

func Cat(c *cli.Context) (err error) {

	if c.NArg() != 1 {
		return cli.NewExitError(fmt.Sprintf("Got %d arguments, wants one", c.NArg()), 1)
	}
	if !isimg.MatchString(c.Args().First()) {
		return cli.NewExitError("The input image does not seem to be a valid image", 1)
	}

	privateKey, err := getKey(c)
	if err != nil {
		return cli.NewExitError("Unable to load key: "+err.Error(), 1)
	}

	r, err := virtualImage.OpenFile(privateKey, c.Args().First())
	defer func() {
		if r == nil {
			return
		}
		cerr := r.Close()
		if err == nil {
			err = cerr
		}
	}()
	if err != nil {
		return cli.NewExitError(fmt.Sprintf("failed to open the partition reader: err: %v", err), 1)
	}
	var w io.WriteCloser = os.Stdout
	if _, err = io.Copy(w, r); err != nil {
		return cli.NewExitError(
			fmt.Sprintf("failed to copy from: %s to stdout: err: %v", c.Args().First(), err),
			1,
		)
	}
	return nil
}

func Copy(c *cli.Context) (err error) {
	if c.String("compression") != "" {
		fmt.Fprintf(os.Stderr, "Warning: The compression flag is not respected for the copy"+
			" command.\nIf you wish to change the compression type, use the <modify> command.")
	}

	privateKey, err := getKey(c)
	if err != nil {
		return cli.NewExitError("Unable to load key: "+err.Error(), 1)
	}

	var r io.ReadCloser
	var w io.WriteCloser
	wclose := func(w io.Closer) {
		if w == nil {
			return
		}
		cerr := w.Close()
		if err == nil {
			err = cerr
		}
	}
	var vfile VPFile
	switch parseCLIOptions(c) {
	case copyin:
		r, err = os.Open(c.Args().First())
		defer r.Close()
		if err != nil {
			return cli.NewExitError(err, 1)
		}
		vfile, err = virtualImage.OpenFile(privateKey, c.Args().Get(1))
		defer wclose(vfile)
		if err != nil {
			return cli.NewExitError(err, 1)
		}
		if err = vfile.CopyTo(c.Args().First()); err != nil {
			return cli.NewExitError(err, 1)
		}
		return nil
	case copyinstdin:
		r = os.Stdin
		vfile, err = virtualImage.OpenFile(privateKey, c.Args().Get(1))
		defer wclose(vfile)
		if err != nil {
			return cli.NewExitError(err, 1)
		}
		w = vfile
	case copyout:
		vfile, err = virtualImage.OpenFile(privateKey, c.Args().First())
		defer wclose(vfile)
		if err != nil {
			return cli.NewExitError(err, 1)
		}
		if err = vfile.CopyFrom(c.Args().Get(1)); err != nil {
			return cli.NewExitError(fmt.Sprintf("%v", err), 1)
		}
		return nil
	case parseError:
		return cli.NewExitError(fmt.Sprintln("no artifact or sdimage provided"), 1)
	case argerror:
		return cli.NewExitError(fmt.Sprintf("got %d arguments, wants two", c.NArg()), 1)
	default:
		return cli.NewExitError("critical error", 1)
	}

	_, err = io.Copy(w, r)
	if err != nil {
		return cli.NewExitError(err, 1)
	}
	return nil
}

// Install installs a file from the host filesystem or directory onto either
// a mender artifact, or an sdimg.
func Install(c *cli.Context) (err error) {

	privateKey, err := getKey(c)
	if err != nil {
		return cli.NewExitError("Unable to load key: "+err.Error(), 1)
	}

	wclose := func(w io.Closer) {
		if w == nil {
			return
		}
		cerr := w.Close()
		if err == nil {
			err = cerr
		}
	}
	switch parseCLIOptions(c) {
	case copyin:
		directory := c.Bool("directory")
		var perm os.FileMode
		if c.Int("mode") == 0 && !directory {
			return cli.NewExitError("File permissions needs to be set, if you are simply copying,"+
				" the cp command should fit your needs", 1)
		}
		perm = os.FileMode(c.Int("mode"))
		if directory {
			vdir, err := virtualImage.OpenDir(privateKey, c.Args().First())
			defer wclose(vdir)
			if err != nil {
				return cli.NewExitError(err, 1)
			}

			if err = vdir.Create(); err != nil {
				return cli.NewExitError(err, 1)
			}
			return nil
		}
		f, err := os.Open(c.Args().First())
		defer f.Close()
		if err != nil {
			return cli.NewExitError(fmt.Sprintf("%v", err), 1)
		}

		tfName, err := createTmpFileWithPerm(f, perm)
		if err != nil {
			return cli.NewExitError(fmt.Sprintf("%v", err), 1)
		}

		Log.Debugf("Created tempfile: %s", tfName)
		defer func() {
			lerr := os.RemoveAll(filepath.Dir(tfName))
			if lerr != nil {
				Log.Warnf("Failed to remove tmpdir with: %v", lerr)
			}
		}()

		vfile, err := virtualImage.OpenFile(privateKey, c.Args().Get(1))
		defer wclose(vfile)
		if err != nil {
			return cli.NewExitError(fmt.Sprintf("%v", err), 1)
		}

		if err = vfile.CopyTo(tfName); err != nil {
			return cli.NewExitError(err, 1)
		}
		return nil
	case parseError:
		return cli.NewExitError("No artifact or sdimg provided", 1)
	case argerror:
		return cli.NewExitError(fmt.Sprintf("Wrong number of arguments, got %d", c.NArg()), 1)
	default:
		return cli.NewExitError("Unrecognized parse error", 1)
	}
}

func Remove(c *cli.Context) (err error) {
	wclose := func(w io.Closer) {
		if w == nil {
			return
		}
		cerr := w.Close()
		if err == nil {
			err = cerr
		}
	}

	privateKey, err := getKey(c)
	if err != nil {
		return cli.NewExitError("Unable to load key: "+err.Error(), 1)
	}

	if c.NArg() != 1 {
		return cli.NewExitError(fmt.Sprintf("Got %d arguments, wants one", c.NArg()), 1)
	}
	if !isimg.MatchString(c.Args().First()) {
		return cli.NewExitError("The input image does not have a valid extension", 1)
	}
	f, err := virtualImage.OpenFile(privateKey, c.Args().First())
	defer wclose(f)
	if err != nil {
		return cli.NewExitError(fmt.Sprintf("failed to open the partition reader: err: %v", err), 1)
	}
	return f.Delete(c.Bool("recursive"))
}

// enumerate cli-options
const (
	copyin = iota
	copyinstdin
	copyout
	parseError
	argerror
)

func parseCLIOptions(c *cli.Context) int {

	// If the -d flag is passed, parse for installing a directory
	if c.Bool("directory") {
		if c.NArg() != 1 {
			return argerror
		}
		if !isimg.MatchString(c.Args().First()) {
			return parseError
		}
		return copyin
	}

	if c.NArg() != 2 {
		return argerror
	}

	// If the first argument is '-', read from stdin
	if c.Args().First() == "-" {
		// Read from stdin
		if !isimg.MatchString(c.Args().Get(1)) {
			return parseError
		}
		return copyinstdin
	}

	switch {

	case isimg.MatchString(c.Args().First()):
		return copyout

	case isimg.MatchString(c.Args().Get(1)):
		return copyin

	default:
		return parseError
	}
}

// createTmpFileWithPerm Takes a file, and creates a temp-file copy of the
// current file, with the permissions given by perm.
func createTmpFileWithPerm(f *os.File, perm os.FileMode) (string, error) {

	td, err := ioutil.TempDir("", "mender-artifact-install")
	if err != nil {
		return "", err
	}

	tf, err := os.OpenFile(filepath.Join(td,
		filepath.Base(f.Name())), os.O_CREATE|os.O_WRONLY, perm)
	if err != nil {
		return "", err
	}

	_, err = io.Copy(tf, f)
	if err != nil {
		return "", err
	}

	// override umask
	err = tf.Chmod(perm)
	if err != nil {
		return "", err
	}

	name := tf.Name()
	Log.Debugf("Tempfile name: %s\n", name)

	s, _ := tf.Stat()
	err = tf.Close()
	if err != nil {
		return "", err
	}

	if s != nil {
		Log.Debugf("The tempfile: %s got permissions: %v\noriginal-permissions: %s\n",
			name, s.Mode(), perm)
	}

	return name, nil
}