-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathutil.go
417 lines (342 loc) · 8.09 KB
/
util.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package libbuildpack
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
backoff "github.com/cenkalti/backoff/v4"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func MoveDirectory(srcDir, destDir string) error {
destExists, _ := FileExists(destDir)
if !destExists {
return os.Rename(srcDir, destDir)
}
files, err := ioutil.ReadDir(srcDir)
if err != nil {
return err
}
for _, f := range files {
src := filepath.Join(srcDir, f.Name())
dest := filepath.Join(destDir, f.Name())
if exists, err := FileExists(dest); err != nil {
return err
} else if !exists {
if m := f.Mode(); m&os.ModeSymlink != 0 {
if err = moveSymlinks(src, dest); err != nil {
return err
}
}
if err = os.Rename(src, dest); err != nil {
return err
}
} else {
if f.IsDir() {
if err = MoveDirectory(src, dest); err != nil {
return err
}
}
}
}
return nil
}
// CopyDirectory copies srcDir to destDir
func CopyDirectory(srcDir, destDir string) error {
destExists, _ := FileExists(destDir)
if !destExists {
return errors.New("destination dir must exist")
}
files, err := ioutil.ReadDir(srcDir)
if err != nil {
return err
}
for _, f := range files {
src := filepath.Join(srcDir, f.Name())
dest := filepath.Join(destDir, f.Name())
if m := f.Mode(); m&os.ModeSymlink != 0 {
if err = moveSymlinks(src, dest); err != nil {
return err
}
} else if f.IsDir() {
err = os.MkdirAll(dest, f.Mode())
if err != nil {
return err
}
if err := CopyDirectory(src, dest); err != nil {
return err
}
} else {
rc, err := os.Open(src)
if err != nil {
return err
}
err = writeToFile(rc, dest, f.Mode())
if err != nil {
rc.Close()
return err
}
rc.Close()
}
}
return nil
}
func moveSymlinks(src, dest string) error {
target, err := os.Readlink(src)
if err != nil {
return fmt.Errorf("Error while reading symlink '%s': %v", src, err)
}
if err := os.Symlink(target, dest); err != nil {
return fmt.Errorf("Error while creating '%s' as symlink to '%s': %v", dest, target, err)
}
return nil
}
// ExtractZip extracts zipfile to destDir
func ExtractZip(zipfile, destDir string) error {
r, err := zip.OpenReader(zipfile)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
path := filepath.Join(destDir, filepath.Clean(f.Name))
rc, err := f.Open()
if err != nil {
return err
}
if f.FileInfo().IsDir() {
err = os.MkdirAll(path, f.Mode())
} else {
err = writeToFile(rc, path, f.Mode())
}
rc.Close()
if err != nil {
return err
}
}
return nil
}
func ExtractTarXz(tarfile, destDir string) error {
file, err := os.Open(tarfile)
if err != nil {
return err
}
defer file.Close()
xz := xzReader(file)
defer xz.Close()
return extractTar(xz, destDir)
}
func xzReader(r io.Reader) io.ReadCloser {
rpipe, wpipe := io.Pipe()
cmd := exec.Command("xz", "--decompress", "--stdout")
cmd.Stdin = r
cmd.Stdout = wpipe
go func() {
err := cmd.Run()
wpipe.CloseWithError(err)
}()
return rpipe
}
// Gets the buildpack directory
func GetBuildpackDir() (string, error) {
var err error
bpDir := os.Getenv("BUILDPACK_DIR")
if bpDir == "" {
bpDir, err = filepath.Abs(filepath.Join(filepath.Dir(os.Args[0]), ".."))
if err != nil {
return "", err
}
}
return bpDir, nil
}
// ExtractTarGz extracts tar.gz to destDir
func ExtractTarGz(tarfile, destDir string) error {
file, err := os.Open(tarfile)
if err != nil {
return err
}
defer file.Close()
gz, err := gzip.NewReader(file)
if err != nil {
return err
}
defer gz.Close()
return extractTar(gz, destDir)
}
// CopyFile copies source file to destFile, creating all intermediate directories in destFile
func CopyFile(source, destFile string) error {
fh, err := os.Open(source)
if err != nil {
return err
}
fileInfo, err := fh.Stat()
if err != nil {
return err
}
defer fh.Close()
return writeToFile(fh, destFile, fileInfo.Mode())
}
func FileExists(file string) (bool, error) {
_, err := os.Stat(file)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
}
func RandString(n int) string {
letterRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func extractTar(src io.Reader, destDir string) error {
tr := tar.NewReader(src)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
path := filepath.Join(destDir, cleanPath(hdr.Name))
fi := hdr.FileInfo()
if fi.IsDir() {
if err := os.MkdirAll(path, hdr.FileInfo().Mode()); err != nil {
return err
}
} else if hdr.Typeflag == tar.TypeSymlink {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
if filepath.IsAbs(hdr.Linkname) {
return fmt.Errorf("cannot link to an absolute path when extracting archives")
}
fullLink, err := filepath.Abs(filepath.Join(filepath.Dir(path), hdr.Linkname))
if err != nil {
return err
}
fullDest, err := filepath.Abs(destDir)
if err != nil {
return err
}
// check that the relative link does not escape the destination dir
if !strings.HasPrefix(fullLink, fullDest) {
return fmt.Errorf("cannot link outside of the destination diretory when extracting archives")
}
if err = os.Symlink(hdr.Linkname, path); err != nil {
return err
}
} else if hdr.Typeflag == tar.TypeLink {
originalPath := filepath.Join(destDir, cleanPath(hdr.Linkname))
file, err := os.Open(originalPath)
if err != nil {
return err
}
if err := writeToFile(file, path, hdr.FileInfo().Mode()); err != nil {
return err
}
} else {
if err := writeToFile(tr, path, hdr.FileInfo().Mode()); err != nil {
return err
}
}
}
return nil
}
func filterURI(rawURL string) (string, error) {
unsafeURL, err := url.Parse(rawURL)
if err != nil {
return "", err
}
var safeURL string
if unsafeURL.User == nil {
safeURL = rawURL
return safeURL, nil
}
redactedUserInfo := url.UserPassword("-redacted-", "-redacted-")
unsafeURL.User = redactedUserInfo
safeURL = unsafeURL.String()
return safeURL, nil
}
func CheckSha256(filePath, expectedSha256 string) error {
content, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
sum := sha256.Sum256(content)
actualSha256 := hex.EncodeToString(sum[:])
if actualSha256 != expectedSha256 {
return fmt.Errorf("dependency sha256 mismatch: expected sha256 %s, actual sha256 %s", expectedSha256, actualSha256)
}
return nil
}
func downloadFile(url string, destFile string, retryTimeLimit time.Duration, retryTimeInitialInterval time.Duration, logger *Logger) error {
bo := backoff.NewExponentialBackOff()
bo.MaxElapsedTime = retryTimeLimit
bo.InitialInterval = retryTimeInitialInterval
var resp *http.Response
var err error
operation := func() error {
resp, err = http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return fmt.Errorf("%s", resp.Status)
}
return writeToFile(resp.Body, destFile, 0666)
}
notify := func(err error, duration time.Duration) {
logger.Info("error: %v, retrying in %v...", err, duration)
}
err = backoff.RetryNotify(operation, bo, notify)
if err != nil {
return fmt.Errorf("could not download: %s", err)
}
return nil
}
func writeToFile(source io.Reader, destFile string, mode os.FileMode) error {
err := os.MkdirAll(filepath.Dir(destFile), 0755)
if err != nil {
return err
}
fh, err := os.OpenFile(destFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return err
}
defer fh.Close()
_, err = io.Copy(fh, source)
if err != nil {
return err
}
return nil
}
func cleanPath(path string) string {
if path == "" {
return ""
}
path = filepath.Clean(path)
if !filepath.IsAbs(path) {
path = filepath.Clean(string(os.PathSeparator) + path)
path, _ = filepath.Rel(string(os.PathSeparator), path)
}
return filepath.Clean(path)
}