-
Notifications
You must be signed in to change notification settings - Fork 0
/
archives.go
96 lines (77 loc) · 2.01 KB
/
archives.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
/*
Copyright © 2023 Patrick Hermann [email protected]
*/
package cli
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
sthingsBase "github.com/stuttgart-things/sthingsBase"
)
func UnZipArchive(source, destination string) error {
// 1. OPEN THE ZIP FILE
reader, err := zip.OpenReader(source)
if err != nil {
return err
}
defer reader.Close()
// 2. GET THE ABSOLUTE DESTINATION PATH
destination, err = filepath.Abs(destination)
if err != nil {
return err
}
// 3. ITERATE OVER ZIP FILES INSIDE THE ARCHIVE AND UNZIP EACH OF THEM
for _, f := range reader.File {
err := unzipFile(f, destination)
if err != nil {
return err
}
}
return nil
}
func unzipFile(f *zip.File, destination string) error {
// 4. CHECK IF FILE PATHS ARE NOT VULNERABLE TO ZIP SLIP
filePath := filepath.Join(destination, f.Name)
if !strings.HasPrefix(filePath, filepath.Clean(destination)+string(os.PathSeparator)) {
return fmt.Errorf("invalid file path: %s", filePath)
}
// 5. CREATE DIRECTORY TREE
if f.FileInfo().IsDir() {
if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
return err
}
return nil
}
if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return err
}
// 6. CREATE A DESTINATION FILE FOR UNZIPPED CONTENT
destinationFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer destinationFile.Close()
// 7. UNZIP THE CONTENT OF A FILE AND COPY IT TO THE DESTINATION FILE
zippedFile, err := f.Open()
if err != nil {
return err
}
defer zippedFile.Close()
if _, err := io.Copy(destinationFile, zippedFile); err != nil {
return err
}
return nil
}
func ExtractTarGzArchive(archiveFilePath, extractionFilePath string, extractFileMode int) {
tarExtractArgs := []string{
"-zxvf",
archiveFilePath,
"-C",
extractionFilePath,
}
sthingsBase.CreateNestedDirectoryStructure(extractionFilePath, extractFileMode)
sthingsBase.GetExternalProcessOutputToVar("tar", tarExtractArgs)
}