Skip to content

Commit b021161

Browse files
loresusopoiana
authored andcommitted
update(cmd/internal): add a function to copy bytes in chunks
better memory footprint and solving gosec problem Signed-off-by: Lorenzo Susini <[email protected]>
1 parent c6585b1 commit b021161

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

cmd/internal/utils/extract.go

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package utils
1717
import (
1818
"archive/tar"
1919
"compress/gzip"
20+
"errors"
2021
"fmt"
2122
"io"
2223
"os"
@@ -32,10 +33,10 @@ func ExtractTarGz(gzipStream io.Reader, destDir string) error {
3233

3334
tarReader := tar.NewReader(uncompressedStream)
3435

35-
for true {
36+
for {
3637
header, err := tarReader.Next()
3738

38-
if err == io.EOF {
39+
if errors.Is(err, io.EOF) {
3940
break
4041
}
4142

@@ -45,16 +46,19 @@ func ExtractTarGz(gzipStream io.Reader, destDir string) error {
4546

4647
switch header.Typeflag {
4748
case tar.TypeDir:
48-
return fmt.Errorf("unexepected dir inside the archive. Expected to find only files without any tree structure.")
49+
return fmt.Errorf("unexepected dir inside the archive, expected to find only files without any tree structure")
4950
case tar.TypeReg:
50-
outFile, err := os.Create(filepath.Join(destDir, header.Name))
51+
outFile, err := os.Create(filepath.Clean(filepath.Join(destDir, filepath.Clean(header.Name))))
5152
if err != nil {
5253
return err
5354
}
54-
if _, err := io.Copy(outFile, tarReader); err != nil {
55+
if err := copyInChunks(outFile, tarReader); err != nil {
56+
return err
57+
}
58+
err = outFile.Close()
59+
if err != nil {
5560
return err
5661
}
57-
outFile.Close()
5862

5963
default:
6064
return fmt.Errorf("extractTarGz: uknown type: %b in %s", header.Typeflag, header.Name)
@@ -63,3 +67,17 @@ func ExtractTarGz(gzipStream io.Reader, destDir string) error {
6367

6468
return nil
6569
}
70+
71+
func copyInChunks(dst io.Writer, src io.Reader) error {
72+
for {
73+
_, err := io.CopyN(dst, src, 1024)
74+
if err != nil {
75+
if errors.Is(err, io.EOF) {
76+
break
77+
}
78+
return err
79+
}
80+
}
81+
82+
return nil
83+
}

0 commit comments

Comments
 (0)