unzip.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package zip
  2. import (
  3. "archive/zip"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. )
  10. // Unzip will decompress a zip archive, moving all files and folders
  11. // within the zip file (parameter 1) to an output directory (parameter 2).
  12. // Credits to https://golangcode.com/unzip-files-in-go/
  13. func Unzip(src string, dest string) ([]string, error) {
  14. var outFile *os.File
  15. var zipFile io.ReadCloser
  16. var filenames []string
  17. r, err := zip.OpenReader(src)
  18. if err != nil {
  19. return filenames, err
  20. }
  21. defer r.Close()
  22. clean := func() {
  23. if outFile != nil {
  24. outFile.Close()
  25. outFile = nil
  26. }
  27. if zipFile != nil {
  28. zipFile.Close()
  29. zipFile = nil
  30. }
  31. }
  32. for _, f := range r.File {
  33. zipFile, err = f.Open()
  34. if err != nil {
  35. return filenames, err
  36. }
  37. // Store filename/path for returning and using later on
  38. fpath := filepath.Join(dest, f.Name)
  39. // Check for ZipSlip. More Info: https://snyk.io/research/zip-slip-vulnerability#go
  40. if !strings.HasPrefix(fpath, filepath.Clean(dest)+string(os.PathSeparator)) {
  41. clean()
  42. return filenames, fmt.Errorf("%s: illegal file path", fpath)
  43. }
  44. filenames = append(filenames, fpath)
  45. if f.FileInfo().IsDir() {
  46. os.MkdirAll(fpath, os.ModePerm)
  47. clean()
  48. continue
  49. }
  50. if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
  51. clean()
  52. return filenames, err
  53. }
  54. outFile, err = os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
  55. if err != nil {
  56. clean()
  57. return filenames, err
  58. }
  59. _, err = io.Copy(outFile, zipFile)
  60. clean()
  61. if err != nil {
  62. return filenames, err
  63. }
  64. }
  65. return filenames, nil
  66. }