-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathfile.go
341 lines (298 loc) · 8.85 KB
/
file.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright 2015 CoreOS, Inc.
//
// 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 util
import (
"encoding/hex"
"fmt"
"hash"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"strconv"
"syscall"
"github.com/coreos/ignition/internal/config/types"
"github.com/coreos/ignition/internal/log"
"github.com/coreos/ignition/internal/resource"
"github.com/coreos/ignition/internal/util"
)
const (
DefaultDirectoryPermissions os.FileMode = 0755
DefaultFilePermissions os.FileMode = 0644
)
type FetchOp struct {
Hash hash.Hash
Path string
Url url.URL
Mode *int
FetchOptions resource.FetchOptions
Overwrite *bool
Append bool
Node types.Node
}
// newHashedReader returns a new ReadCloser that also writes to the provided hash.
func newHashedReader(reader io.ReadCloser, hasher hash.Hash) io.ReadCloser {
return struct {
io.Reader
io.Closer
}{
Reader: io.TeeReader(reader, hasher),
Closer: reader,
}
}
// PrepareFetch converts a given logger, http client, and types.File into a
// FetchOp. This includes operations such as parsing the source URL, generating
// a hasher, and performing user/group name lookups. If an error is encountered,
// the issue will be logged and nil will be returned.
func (u Util) PrepareFetch(l *log.Logger, f types.File) *FetchOp {
var err error
var expectedSum []byte
// explicitly ignoring the error here because the config should already be
// validated by this point
uri, _ := url.Parse(f.Contents.Source)
hasher, err := util.GetHasher(f.Contents.Verification)
if err != nil {
l.Crit("Error verifying file %q: %v", f.Path, err)
return nil
}
if hasher != nil {
// explicitly ignoring the error here because the config should already
// be validated by this point
_, expectedSumString, _ := util.HashParts(f.Contents.Verification)
expectedSum, err = hex.DecodeString(expectedSumString)
if err != nil {
l.Crit("Error parsing verification string %q: %v", expectedSumString, err)
return nil
}
}
return &FetchOp{
Path: f.Path,
Hash: hasher,
Node: f.Node,
Url: *uri,
Mode: f.Mode,
Overwrite: f.Overwrite,
Append: f.Append,
FetchOptions: resource.FetchOptions{
Hash: hasher,
Compression: f.Contents.Compression,
ExpectedSum: expectedSum,
},
}
}
func (u Util) WriteLink(s types.Link) error {
path := u.JoinPath(s.Path)
if err := MkdirForFile(path); err != nil {
return err
}
if s.Hard {
targetPath := u.JoinPath(s.Target)
return os.Link(targetPath, path)
}
if err := os.Symlink(s.Target, path); err != nil {
return err
}
uid, gid, err := u.ResolveNodeUidAndGid(s.Node, 0, 0)
if err != nil {
return err
}
if err := os.Lchown(path, uid, gid); err != nil {
return err
}
return nil
}
// PerformFetch performs a fetch operation generated by PrepareFetch, retrieving
// the file and writing it to disk. Any encountered errors are returned.
func (u Util) PerformFetch(f *FetchOp) error {
var err error
path := u.JoinPath(string(f.Path))
if f.Overwrite != nil && *f.Overwrite == false {
// Both directories and links will fail to be created if the target path
// already exists. Because files are downloaded into a temporary file
// and then renamed to the target path, we don't have the same
// guarantees here. If the user explicitly doesn't want us to overwrite
// preexisting nodes, check the target path and fail if something's
// there.
_, err := os.Stat(path)
switch {
case os.IsNotExist(err):
break
case err != nil:
return err
default:
return fmt.Errorf("error creating %q: something else exists at that path", f.Path)
}
}
if f.Overwrite == nil && !f.Append {
// For files, overwrite defaults to true if append is false. If
// overwrite wasn't specified, delete the path.
err := os.RemoveAll(path)
if err != nil {
return err
}
}
if err := MkdirForFile(path); err != nil {
return err
}
// Create a temporary file in the same directory to ensure it's on the same filesystem
var tmp *os.File
if tmp, err = ioutil.TempFile(filepath.Dir(path), "tmp"); err != nil {
return err
}
defer tmp.Close()
// sometimes the following line will fail (the file might be renamed),
// but that's ok (we wanted to keep the file in that case).
defer os.Remove(tmp.Name())
err = u.Fetcher.Fetch(f.Url, tmp, f.FetchOptions)
if err != nil {
u.Crit("Error fetching file %q: %v", f.Path, err)
return err
}
if f.Append {
// Make sure that we're appending to a file
finfo, err := os.Lstat(path)
switch {
case os.IsNotExist(err):
// No problem, we'll create it.
break
case err != nil:
return err
default:
if !finfo.Mode().IsRegular() {
return fmt.Errorf("can only append to files: %q", f.Path)
}
}
// Default to the appended file's owner for the uid and gid
defaultUid, defaultGid, mode := getFileOwnerAndMode(path)
uid, gid, err := u.ResolveNodeUidAndGid(f.Node, defaultUid, defaultGid)
if err != nil {
return err
}
if f.Mode != nil {
mode = os.FileMode(*f.Mode)
}
targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, mode)
if err != nil {
return err
}
defer targetFile.Close()
if _, err = tmp.Seek(0, os.SEEK_SET); err != nil {
return err
}
if _, err = io.Copy(targetFile, tmp); err != nil {
return err
}
if err = os.Chown(targetFile.Name(), uid, gid); err != nil {
return err
}
if err = os.Chmod(targetFile.Name(), mode); err != nil {
return err
}
} else {
// XXX(vc): Note that we assume to be operating on the file we just wrote, this is only guaranteed
// by using syscall.Fchown() and syscall.Fchmod()
// Ensure the ownership and mode are as requested (since WriteFile can be affected by sticky bit)
mode := os.FileMode(0)
if f.Mode != nil {
mode = os.FileMode(*f.Mode)
}
uid, gid, err := u.ResolveNodeUidAndGid(f.Node, 0, 0)
if err != nil {
return err
}
if err = os.Chown(tmp.Name(), uid, gid); err != nil {
return err
}
if err = os.Chmod(tmp.Name(), mode); err != nil {
return err
}
if err = os.Rename(tmp.Name(), path); err != nil {
return err
}
}
return nil
}
// MkdirForFile helper creates the directory components of path.
func MkdirForFile(path string) error {
return os.MkdirAll(filepath.Dir(path), DefaultDirectoryPermissions)
}
// getFileOwner will return the uid and gid for the file at a given path. If the
// file doesn't exist, or some other error is encountered when running stat on
// the path, 0, 0, and 0 will be returned.
func getFileOwnerAndMode(path string) (int, int, os.FileMode) {
finfo, err := os.Stat(path)
if err != nil {
return 0, 0, 0
}
return int(finfo.Sys().(*syscall.Stat_t).Uid), int(finfo.Sys().(*syscall.Stat_t).Gid), finfo.Mode()
}
// ResolveNodeUidAndGid attempts to convert a types.Node into a concrete uid and
// gid. If the node has the User.ID field set, that's used for the uid. If the
// node has the User.Name field set, a username -> uid lookup is performed. If
// neither are set, it returns the passed in defaultUid. The logic is identical
// for gids with equivalent fields.
func (u Util) ResolveNodeUidAndGid(n types.Node, defaultUid, defaultGid int) (int, int, error) {
var err error
uid, gid := defaultUid, defaultGid
if n.User != nil {
if n.User.ID != nil {
uid = *n.User.ID
} else if n.User.Name != "" {
uid, err = u.getUserID(n.User.Name)
if err != nil {
return 0, 0, err
}
}
}
if n.Group != nil {
if n.Group.ID != nil {
gid = *n.Group.ID
} else if n.Group.Name != "" {
gid, err = u.getGroupID(n.Group.Name)
if err != nil {
return 0, 0, err
}
}
}
return uid, gid, nil
}
func (u Util) getUserID(name string) (int, error) {
usr, err := u.userLookup(name)
if err != nil {
return 0, fmt.Errorf("No such user %q: %v", name, err)
}
uid, err := strconv.ParseInt(usr.Uid, 0, 0)
if err != nil {
return 0, fmt.Errorf("Couldn't parse uid %q: %v", usr.Uid, err)
}
return int(uid), nil
}
func (u Util) getGroupID(name string) (int, error) {
g, err := u.groupLookup(name)
if err != nil {
return 0, fmt.Errorf("No such group %q: %v", name, err)
}
gid, err := strconv.ParseInt(g.Gid, 0, 0)
if err != nil {
return 0, fmt.Errorf("Couldn't parse gid %q: %v", g.Gid, err)
}
return int(gid), nil
}
func (u Util) DeletePathOnOverwrite(n types.Node) error {
if n.Overwrite == nil || !*n.Overwrite {
return nil
}
return os.RemoveAll(u.JoinPath(string(n.Path)))
}