forked from folbricht/desync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
untar.go
305 lines (278 loc) · 7.08 KB
/
untar.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
// +build !windows
package desync
import (
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"syscall"
"golang.org/x/sync/errgroup"
"github.com/pkg/errors"
"github.com/pkg/xattr"
)
// UntarOptions are used to influence the behaviour of untar
type UntarOptions struct {
NoSameOwner bool
NoSamePermissions bool
}
// UnTar implements the untar command, decoding a catar file and writing the
// contained tree to a target directory.
func UnTar(ctx context.Context, r io.Reader, dst string, opts UntarOptions) error {
dec := NewArchiveDecoder(r)
loop:
for {
// See if we're meant to stop
select {
case <-ctx.Done():
return Interrupted{}
default:
}
c, err := dec.Next()
if err != nil {
return err
}
switch n := c.(type) {
case NodeDirectory:
err = makeDir(dst, n, opts)
case NodeFile:
err = makeFile(dst, n, opts)
case NodeDevice:
err = makeDevice(dst, n, opts)
case NodeSymlink:
err = makeSymlink(dst, n, opts)
case nil:
break loop
default:
err = fmt.Errorf("unsupported type %s", reflect.TypeOf(c))
}
if err != nil {
return err
}
}
return nil
}
func makeDir(base string, n NodeDirectory, opts UntarOptions) error {
dst := filepath.Join(base, n.Name)
// Let's see if there is a dir with the same name already
if info, err := os.Stat(dst); err == nil {
if !info.IsDir() {
return fmt.Errorf("%s exists and is not a directory", dst)
}
} else {
// Stat error'ed out, presumably because the dir doesn't exist. Create it.
if err := os.Mkdir(dst, 0777); err != nil {
return err
}
}
// The dir exists now, fix the UID/GID if needed
if !opts.NoSameOwner {
if err := os.Chown(dst, n.UID, n.GID); err != nil {
return err
}
if n.Xattrs != nil {
for key, value := range n.Xattrs {
if err := xattr.LSet(dst, key, []byte(value)); err != nil {
return err
}
}
}
}
if !opts.NoSamePermissions {
if err := syscall.Chmod(dst, uint32(n.Mode)); err != nil {
return err
}
}
return os.Chtimes(dst, n.MTime, n.MTime)
}
func makeFile(base string, n NodeFile, opts UntarOptions) error {
dst := filepath.Join(base, n.Name)
f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
return err
}
defer f.Close()
if _, err = io.Copy(f, n.Data); err != nil {
return err
}
if !opts.NoSameOwner {
if err = f.Chown(n.UID, n.GID); err != nil {
return err
}
if n.Xattrs != nil {
for key, value := range n.Xattrs {
if err := xattr.LSet(dst, key, []byte(value)); err != nil {
return err
}
}
}
}
if !opts.NoSamePermissions {
if err := syscall.Chmod(dst, uint32(n.Mode)); err != nil {
return err
}
}
return os.Chtimes(dst, n.MTime, n.MTime)
}
func makeSymlink(base string, n NodeSymlink, opts UntarOptions) error {
dst := filepath.Join(base, n.Name)
if err := syscall.Unlink(dst); err != nil && !os.IsNotExist(err) {
return err
}
if err := os.Symlink(n.Target, dst); err != nil {
return err
}
// TODO: On Linux, the permissions of the link don't matter so we don't
// set them here. But they do matter somewhat on Mac, so should probably
// add some Mac-specific logic for that here.
// fchmodat() with flag AT_SYMLINK_NOFOLLOW
if !opts.NoSameOwner {
if err := os.Lchown(dst, n.UID, n.GID); err != nil {
return err
}
if n.Xattrs != nil {
for key, value := range n.Xattrs {
if err := xattr.LSet(dst, key, []byte(value)); err != nil {
return err
}
}
}
}
return nil
}
func makeDevice(base string, n NodeDevice, opts UntarOptions) error {
dst := filepath.Join(base, n.Name)
if err := syscall.Unlink(dst); err != nil && !os.IsNotExist(err) {
return err
}
if err := syscall.Mknod(dst, 0666, int(mkdev(n.Major, n.Minor))); err != nil {
return errors.Wrapf(err, "mknod %s", dst)
}
if !opts.NoSameOwner {
if err := os.Chown(dst, n.UID, n.GID); err != nil {
return err
}
if n.Xattrs != nil {
for key, value := range n.Xattrs {
if err := xattr.LSet(dst, key, []byte(value)); err != nil {
return err
}
}
}
}
if !opts.NoSamePermissions {
if err := syscall.Chmod(dst, uint32(n.Mode)); err != nil {
return errors.Wrapf(err, "chmod %s", dst)
}
}
return os.Chtimes(dst, n.MTime, n.MTime)
}
func mkdev(major, minor uint64) uint64 {
dev := (major & 0x00000fff) << 8
dev |= (major & 0xfffff000) << 32
dev |= (minor & 0x000000ff) << 0
dev |= (minor & 0xffffff00) << 12
return dev
}
// UnTarIndex takes an index file (of a chunked catar), re-assembles the catar
// and decodes it on-the-fly into the target directory 'dst'. Uses n gorountines
// to retrieve and decompress the chunks.
func UnTarIndex(ctx context.Context, dst string, index Index, s Store, n int, opts UntarOptions, pb ProgressBar) error {
type requestJob struct {
chunk IndexChunk // requested chunk
data chan ([]byte) // channel for the (decompressed) chunk
}
var (
req = make(chan requestJob)
assemble = make(chan chan []byte, n)
)
g, ctx := errgroup.WithContext(ctx)
// Initialize and start progress bar if one was provided
if pb != nil {
pb.SetTotal(len(index.Chunks))
pb.Start()
defer pb.Finish()
}
// Use a pipe as input to untar and write the chunks into that (in the right
// order of course)
r, w := io.Pipe()
// Workers - getting chunks from the store
for i := 0; i < n; i++ {
g.Go(func() error {
for r := range req {
// Pull the chunk from the store
chunk, err := s.GetChunk(r.chunk.ID)
if err != nil {
close(r.data)
return err
}
b, err := chunk.Uncompressed()
if err != nil {
close(r.data)
return err
}
// Might as well verify the chunk size while we're at it
if r.chunk.Size != uint64(len(b)) {
close(r.data)
return fmt.Errorf("unexpected size for chunk %s", r.chunk.ID)
}
r.data <- b
close(r.data)
}
return nil
})
}
// Feeder - requesting chunks from the workers and handing a result data channel
// to the assembler
g.Go(func() error {
loop:
for _, c := range index.Chunks {
data := make(chan []byte, 1)
select {
case <-ctx.Done():
break loop
case req <- requestJob{chunk: c, data: data}: // request the chunk
assemble <- data // and hand over the data channel to the assembler
}
}
close(req) // tell the workers this is it
close(assemble) // tell the assembler we're done
return nil
})
// Assember - Read from data channels push the chunks into the pipe that untar reads from
g.Go(func() error {
loop:
for {
select {
case data := <-assemble:
if data == nil {
break loop
}
if pb != nil {
pb.Increment()
}
b := <-data
if _, err := io.Copy(w, bytes.NewReader(b)); err != nil {
return err
}
case <-ctx.Done():
break loop
}
}
w.Close() // No more chunks to come, stop the untar
return nil
})
// UnTar - Read from the pipe that Assembler pushes into
g.Go(func() error {
err := UnTar(ctx, r, dst, opts)
if err != nil {
// If an error has occurred during the UnTar, we need to stop the Assembler.
// If we don't, then it would stall on writing to the pipe.
r.CloseWithError(err)
}
return err
})
return g.Wait()
}