refactor(code): Cleaned-up the code base
This commit is contained in:
50
lib/boxstore/zip.go
Normal file
50
lib/boxstore/zip.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package boxstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func AddFileToZip(zipWriter *zip.Writer, boxID string, filename string) error {
|
||||
path, ok := SafeBoxFilePath(boxID, filename)
|
||||
if !ok {
|
||||
return fmt.Errorf("Invalid file")
|
||||
}
|
||||
if err := ensureRegularFile(path); err != nil {
|
||||
return err
|
||||
}
|
||||
zipName, ok := safeZipEntryName(filename)
|
||||
if !ok {
|
||||
return fmt.Errorf("Invalid zip entry")
|
||||
}
|
||||
|
||||
source, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer source.Close()
|
||||
|
||||
destination, err := zipWriter.Create(zipName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = io.Copy(destination, source)
|
||||
return err
|
||||
}
|
||||
func safeZipEntryName(filename string) (string, bool) {
|
||||
filename = strings.TrimSpace(filename)
|
||||
if filename == "" || filepath.IsAbs(filename) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
cleaned := filepath.ToSlash(filepath.Clean(filename))
|
||||
if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") || strings.HasPrefix(cleaned, "/") {
|
||||
return "", false
|
||||
}
|
||||
return cleaned, true
|
||||
}
|
||||
Reference in New Issue
Block a user