extractFile extracts the provided zipFile into "basePath/zipFileName" path, creating all the necessary path directories.
(zipFile *zip.File, basePath string)
| 37 | // extractFile extracts the provided zipFile into "basePath/zipFileName" path, |
| 38 | // creating all the necessary path directories. |
| 39 | func extractFile(zipFile *zip.File, basePath string) error { |
| 40 | path := filepath.Join(basePath, zipFile.Name) |
| 41 | |
| 42 | // check for Zip Slip |
| 43 | if !strings.HasPrefix(path, basePath) { |
| 44 | return fmt.Errorf("invalid file path: %s", path) |
| 45 | } |
| 46 | |
| 47 | r, err := zipFile.Open() |
| 48 | if err != nil { |
| 49 | return err |
| 50 | } |
| 51 | defer r.Close() |
| 52 | |
| 53 | // allow only dirs or regular files |
| 54 | if zipFile.FileInfo().IsDir() { |
| 55 | if err := os.MkdirAll(path, os.ModePerm); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | } else if zipFile.FileInfo().Mode().IsRegular() { |
| 59 | // ensure that the file path directories are created |
| 60 | if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil { |
| 61 | return err |
| 62 | } |
| 63 | |
| 64 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, zipFile.Mode()) |
| 65 | if err != nil { |
| 66 | return err |
| 67 | } |
| 68 | defer f.Close() |
| 69 | |
| 70 | _, err = io.Copy(f, r) |
| 71 | if err != nil { |
| 72 | return err |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | return nil |
| 77 | } |