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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
|
package fastzip
import (
"bufio"
"context"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/klauspost/compress/zip"
"github.com/klauspost/compress/zstd"
"github.com/saracen/zipextra"
"golang.org/x/sync/errgroup"
)
var bufioWriterPool = sync.Pool{
New: func() interface{} {
return bufio.NewWriterSize(nil, 32*1024)
},
}
var (
defaultDecompressor = FlateDecompressor()
defaultZstdDecompressor = ZstdDecompressor()
)
// Extractor is an opinionated Zip file extractor.
//
// Files are extracted in parallel. Only regular files, symlinks and directories
// are supported. Files can only be extracted to the specified chroot directory.
//
// Access permissions, ownership (unix) and modification times are preserved.
type Extractor struct {
// This 2 fields are accessed via atomic operations
// They are at the start of the struct so they are properly 8 byte aligned
written, entries int64
zr *zip.Reader
closer io.Closer
m sync.Mutex
options extractorOptions
chroot string
}
// NewExtractor opens a zip file and returns a new extractor.
//
// Close() should be called to close the extractor's underlying zip.Reader
// when done.
func NewExtractor(filename, chroot string, opts ...ExtractorOption) (*Extractor, error) {
zr, err := zip.OpenReader(filename)
if err != nil {
return nil, err
}
return newExtractor(&zr.Reader, zr, chroot, opts)
}
// NewExtractor returns a new extractor, reading from the reader provided.
//
// The size of the archive should be provided.
//
// Unlike with NewExtractor(), calling Close() on the extractor is unnecessary.
func NewExtractorFromReader(r io.ReaderAt, size int64, chroot string, opts ...ExtractorOption) (*Extractor, error) {
zr, err := zip.NewReader(r, size)
if err != nil {
return nil, err
}
return newExtractor(zr, nil, chroot, opts)
}
func newExtractor(r *zip.Reader, c io.Closer, chroot string, opts []ExtractorOption) (*Extractor, error) {
var err error
if chroot, err = filepath.Abs(chroot); err != nil {
return nil, err
}
e := &Extractor{
chroot: chroot,
zr: r,
closer: c,
}
e.options.concurrency = runtime.GOMAXPROCS(0)
for _, o := range opts {
err := o(&e.options)
if err != nil {
return nil, err
}
}
e.RegisterDecompressor(zip.Deflate, defaultDecompressor)
e.RegisterDecompressor(zstd.ZipMethodWinZip, defaultZstdDecompressor)
return e, nil
}
// RegisterDecompressor allows custom decompressors for a specified method ID.
// The common methods Store and Deflate are built in.
func (e *Extractor) RegisterDecompressor(method uint16, dcomp zip.Decompressor) {
e.zr.RegisterDecompressor(method, dcomp)
}
// Files returns the file within the archive.
func (e *Extractor) Files() []*zip.File {
return e.zr.File
}
// Close closes the underlying ZipReader.
func (e *Extractor) Close() error {
if e.closer == nil {
return nil
}
return e.closer.Close()
}
// Written returns how many bytes and entries have been written to disk.
// Written can be called whilst extraction is in progress.
func (e *Extractor) Written() (bytes, entries int64) {
return atomic.LoadInt64(&e.written), atomic.LoadInt64(&e.entries)
}
// Extract extracts files, creates symlinks and directories from the
// archive.
func (e *Extractor) Extract(ctx context.Context) (err error) {
limiter := make(chan struct{}, e.options.concurrency)
wg, ctx := errgroup.WithContext(ctx)
defer func() {
if werr := wg.Wait(); werr != nil {
err = werr
}
}()
for i, file := range e.zr.File {
if file.Mode()&irregularModes != 0 {
continue
}
var path string
path, err = filepath.Abs(filepath.Join(e.chroot, file.Name))
if err != nil {
return err
}
if !strings.HasPrefix(path, e.chroot+string(filepath.Separator)) && path != e.chroot {
return fmt.Errorf("%s cannot be extracted outside of chroot (%s)", path, e.chroot)
}
if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
switch {
case file.Mode()&os.ModeSymlink != 0:
// defer the creation of symlinks
// this is to prevent a traversal vulnerability where a symlink is
// first created and then files are additional extracted into it
continue
case file.Mode().IsDir():
err = e.createDirectory(path, file)
default:
limiter <- struct{}{}
gf := e.zr.File[i]
wg.Go(func() error {
defer func() { <-limiter }()
err := e.createFile(ctx, path, gf)
if err == nil {
err = e.updateFileMetadata(path, gf)
}
return err
})
}
if err != nil {
return err
}
}
if err := wg.Wait(); err != nil {
return err
}
// handle deferred symlink creation and update directory metadata
// (otherwise modification dates are incorrect)
for _, file := range e.zr.File {
if file.Mode()&os.ModeSymlink == 0 && !file.Mode().IsDir() {
continue
}
path, err := filepath.Abs(filepath.Join(e.chroot, file.Name))
if err != nil {
return err
}
if file.Mode()&os.ModeSymlink != 0 {
if err := e.createSymlink(path, file); err != nil {
return err
}
continue
}
err = e.updateFileMetadata(path, file)
if err != nil {
return err
}
}
return nil
}
func (e *Extractor) createDirectory(path string, file *zip.File) error {
err := os.Mkdir(path, 0777)
if os.IsExist(err) {
err = nil
}
incOnSuccess(&e.entries, err)
return err
}
func (e *Extractor) createSymlink(path string, file *zip.File) error {
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
r, err := file.Open()
if err != nil {
return err
}
defer r.Close()
name, err := io.ReadAll(r)
if err != nil {
return err
}
if err := os.Symlink(string(name), path); err != nil {
return err
}
err = e.updateFileMetadata(path, file)
incOnSuccess(&e.entries, err)
return err
}
func (e *Extractor) createFile(ctx context.Context, path string, file *zip.File) (err error) {
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
r, err := file.Open()
if err != nil {
return err
}
defer dclose(r, &err)
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
defer dclose(f, &err)
bw := bufioWriterPool.Get().(*bufio.Writer)
defer bufioWriterPool.Put(bw)
bw.Reset(countWriter{f, &e.written, ctx})
if _, err = bw.ReadFrom(r); err != nil {
return err
}
err = bw.Flush()
incOnSuccess(&e.entries, err)
return err
}
func (e *Extractor) updateFileMetadata(path string, file *zip.File) error {
fields, err := zipextra.Parse(file.Extra)
if err != nil {
return err
}
if err := lchtimes(path, file.Mode(), time.Now(), file.Modified); err != nil {
return err
}
if err := lchmod(path, file.Mode()); err != nil {
return err
}
unixfield, ok := fields[zipextra.ExtraFieldUnixN]
if !ok {
return nil
}
unix, err := unixfield.InfoZIPNewUnix()
if err != nil {
return err
}
err = lchown(path, int(unix.Uid.Int64()), int(unix.Gid.Int64()))
if err == nil {
return nil
}
if e.options.chownErrorHandler == nil {
return nil
}
e.m.Lock()
defer e.m.Unlock()
return e.options.chownErrorHandler(file.Name, err)
}
|