package zip
import (
)
var zipinsecurepath = godebug.New("zipinsecurepath")
var (
ErrFormat = errors.New("zip: not a valid zip file")
ErrAlgorithm = errors.New("zip: unsupported compression algorithm")
ErrChecksum = errors.New("zip: checksum error")
ErrInsecurePath = errors.New("zip: insecure file path")
)
type Reader struct {
r io.ReaderAt
File []*File
Comment string
decompressors map[uint16]Decompressor
baseOffset int64
fileListOnce sync.Once
fileList []fileListEntry
}
type ReadCloser struct {
f *os.File
Reader
}
type File struct {
FileHeader
zip *Reader
zipr io.ReaderAt
headerOffset int64
}
func ( string) (*ReadCloser, error) {
, := os.Open()
if != nil {
return nil,
}
, := .Stat()
if != nil {
.Close()
return nil,
}
:= new(ReadCloser)
if = .init(, .Size()); != nil && != ErrInsecurePath {
.Close()
return nil,
}
.f =
return ,
}
func ( io.ReaderAt, int64) (*Reader, error) {
if < 0 {
return nil, errors.New("zip: size cannot be negative")
}
:= new(Reader)
var error
if = .init(, ); != nil && != ErrInsecurePath {
return nil,
}
return ,
}
func ( *Reader) ( io.ReaderAt, int64) error {
, , := readDirectoryEnd(, )
if != nil {
return
}
.r =
.baseOffset =
if .directorySize < uint64() && (uint64()-.directorySize)/30 >= .directoryRecords {
.File = make([]*File, 0, .directoryRecords)
}
.Comment = .comment
:= io.NewSectionReader(, 0, )
if _, = .Seek(.baseOffset+int64(.directoryOffset), io.SeekStart); != nil {
return
}
:= bufio.NewReader()
for {
:= &File{zip: , zipr: }
= readDirectoryHeader(, )
if == ErrFormat || == io.ErrUnexpectedEOF {
break
}
if != nil {
return
}
.headerOffset += .baseOffset
.File = append(.File, )
}
if uint16(len(.File)) != uint16(.directoryRecords) {
return
}
if zipinsecurepath.Value() == "0" {
for , := range .File {
if .Name == "" {
continue
}
if !filepath.IsLocal(.Name) || strings.Contains(.Name, `\`) {
zipinsecurepath.IncNonDefault()
return ErrInsecurePath
}
}
}
return nil
}
func ( *Reader) ( uint16, Decompressor) {
if .decompressors == nil {
.decompressors = make(map[uint16]Decompressor)
}
.decompressors[] =
}
func ( *Reader) ( uint16) Decompressor {
:= .decompressors[]
if == nil {
= decompressor()
}
return
}
func ( *ReadCloser) () error {
return .f.Close()
}
func ( *File) () ( int64, error) {
, := .findBodyOffset()
if != nil {
return
}
return .headerOffset + , nil
}
func ( *File) () (io.ReadCloser, error) {
, := .findBodyOffset()
if != nil {
return nil,
}
if strings.HasSuffix(.Name, "/") {
if .UncompressedSize64 != 0 {
return &dirReader{ErrFormat}, nil
} else {
return &dirReader{io.EOF}, nil
}
}
:= int64(.CompressedSize64)
:= io.NewSectionReader(.zipr, .headerOffset+, )
:= .zip.decompressor(.Method)
if == nil {
return nil, ErrAlgorithm
}
var io.ReadCloser = ()
var io.Reader
if .hasDataDescriptor() {
= io.NewSectionReader(.zipr, .headerOffset++, dataDescriptorLen)
}
= &checksumReader{
rc: ,
hash: crc32.NewIEEE(),
f: ,
desr: ,
}
return , nil
}
func ( *File) () (io.Reader, error) {
, := .findBodyOffset()
if != nil {
return nil,
}
:= io.NewSectionReader(.zipr, .headerOffset+, int64(.CompressedSize64))
return , nil
}
type dirReader struct {
err error
}
func ( *dirReader) ([]byte) (int, error) {
return 0, .err
}
func ( *dirReader) () error {
return nil
}
type checksumReader struct {
rc io.ReadCloser
hash hash.Hash32
nread uint64
f *File
desr io.Reader
err error
}
func ( *checksumReader) () (fs.FileInfo, error) {
return headerFileInfo{&.f.FileHeader}, nil
}
func ( *checksumReader) ( []byte) ( int, error) {
if .err != nil {
return 0, .err
}
, = .rc.Read()
.hash.Write([:])
.nread += uint64()
if .nread > .f.UncompressedSize64 {
return 0, ErrFormat
}
if == nil {
return
}
if == io.EOF {
if .nread != .f.UncompressedSize64 {
return 0, io.ErrUnexpectedEOF
}
if .desr != nil {
if := readDataDescriptor(.desr, .f); != nil {
if == io.EOF {
= io.ErrUnexpectedEOF
} else {
=
}
} else if .hash.Sum32() != .f.CRC32 {
= ErrChecksum
}
} else {
if .f.CRC32 != 0 && .hash.Sum32() != .f.CRC32 {
= ErrChecksum
}
}
}
.err =
return
}
func ( *checksumReader) () error { return .rc.Close() }
func ( *File) () (int64, error) {
var [fileHeaderLen]byte
if , := .zipr.ReadAt([:], .headerOffset); != nil {
return 0,
}
:= readBuf([:])
if := .uint32(); != fileHeaderSignature {
return 0, ErrFormat
}
= [22:]
:= int(.uint16())
:= int(.uint16())
return int64(fileHeaderLen + + ), nil
}
func ( *File, io.Reader) error {
var [directoryHeaderLen]byte
if , := io.ReadFull(, [:]); != nil {
return
}
:= readBuf([:])
if := .uint32(); != directoryHeaderSignature {
return ErrFormat
}
.CreatorVersion = .uint16()
.ReaderVersion = .uint16()
.Flags = .uint16()
.Method = .uint16()
.ModifiedTime = .uint16()
.ModifiedDate = .uint16()
.CRC32 = .uint32()
.CompressedSize = .uint32()
.UncompressedSize = .uint32()
.CompressedSize64 = uint64(.CompressedSize)
.UncompressedSize64 = uint64(.UncompressedSize)
:= int(.uint16())
:= int(.uint16())
:= int(.uint16())
= [4:]
.ExternalAttrs = .uint32()
.headerOffset = int64(.uint32())
:= make([]byte, ++)
if , := io.ReadFull(, ); != nil {
return
}
.Name = string([:])
.Extra = [ : +]
.Comment = string([+:])
, := detectUTF8(.Name)
, := detectUTF8(.Comment)
switch {
case ! || !:
.NonUTF8 = true
case ! && !:
.NonUTF8 = false
default:
.NonUTF8 = .Flags&0x800 == 0
}
var time.Time
:
for := readBuf(.Extra); len() >= 4; {
:= .uint16()
:= int(.uint16())
if len() < {
break
}
:= .sub()
switch {
case zip64ExtraID:
if .UncompressedSize == ^uint32(0) {
if len() < 8 {
return ErrFormat
}
.UncompressedSize64 = .uint64()
}
if .CompressedSize == ^uint32(0) {
if len() < 8 {
return ErrFormat
}
.CompressedSize64 = .uint64()
}
if .headerOffset == int64(^uint32(0)) {
if len() < 8 {
return ErrFormat
}
.headerOffset = int64(.uint64())
}
case ntfsExtraID:
if len() < 4 {
continue
}
.uint32()
for len() >= 4 {
:= .uint16()
:= int(.uint16())
if len() < {
continue
}
:= .sub()
if != 1 || != 24 {
continue
}
const = 1e7
:= int64(.uint64())
:= /
:= (1e9 / ) * ( % )
:= time.Date(1601, time.January, 1, 0, 0, 0, 0, time.UTC)
= time.Unix(.Unix()+, )
}
case unixExtraID, infoZipUnixExtraID:
if len() < 8 {
continue
}
.uint32()
:= int64(.uint32())
= time.Unix(, 0)
case extTimeExtraID:
if len() < 5 || .uint8()&1 == 0 {
continue
}
:= int64(.uint32())
= time.Unix(, 0)
}
}
:= msDosTimeToTime(.ModifiedDate, .ModifiedTime)
.Modified =
if !.IsZero() {
.Modified = .UTC()
if .ModifiedTime != 0 || .ModifiedDate != 0 {
.Modified = .In(timeZone(.Sub()))
}
}
return nil
}
func ( io.Reader, *File) error {
var [dataDescriptorLen]byte
if , := io.ReadFull(, [:4]); != nil {
return
}
:= 0
:= readBuf([:4])
if .uint32() != dataDescriptorSignature {
+= 4
}
if , := io.ReadFull(, [:12]); != nil {
return
}
:= readBuf([:12])
if .uint32() != .CRC32 {
return ErrChecksum
}
return nil
}
func ( io.ReaderAt, int64) ( *directoryEnd, int64, error) {
var []byte
var int64
for , := range []int64{1024, 65 * 1024} {
if > {
=
}
= make([]byte, int())
if , := .ReadAt(, -); != nil && != io.EOF {
return nil, 0,
}
if := findSignatureInBlock(); >= 0 {
= [:]
= - + int64()
break
}
if == 1 || == {
return nil, 0, ErrFormat
}
}
:= readBuf([4:])
:= &directoryEnd{
diskNbr: uint32(.uint16()),
dirDiskNbr: uint32(.uint16()),
dirRecordsThisDisk: uint64(.uint16()),
directoryRecords: uint64(.uint16()),
directorySize: uint64(.uint32()),
directoryOffset: uint64(.uint32()),
commentLen: .uint16(),
}
:= int(.commentLen)
if > len() {
return nil, 0, errors.New("zip: invalid comment length")
}
.comment = string([:])
if .directoryRecords == 0xffff || .directorySize == 0xffffffff || .directoryOffset == 0xffffffff {
, := findDirectory64End(, )
if == nil && >= 0 {
=
= readDirectory64End(, , )
}
if != nil {
return nil, 0,
}
}
:= uint64(1<<63 - 1)
if .directorySize > || .directoryOffset > {
return nil, 0, ErrFormat
}
= - int64(.directorySize) - int64(.directoryOffset)
if := + int64(.directoryOffset); < 0 || >= {
return nil, 0, ErrFormat
}
if > 0 {
:= int64(.directoryOffset)
:= io.NewSectionReader(, , -)
if readDirectoryHeader(&File{}, ) == nil {
= 0
}
}
return , , nil
}
func ( io.ReaderAt, int64) (int64, error) {
:= - directory64LocLen
if < 0 {
return -1, nil
}
:= make([]byte, directory64LocLen)
if , := .ReadAt(, ); != nil {
return -1,
}
:= readBuf()
if := .uint32(); != directory64LocSignature {
return -1, nil
}
if .uint32() != 0 {
return -1, nil
}
:= .uint64()
if .uint32() != 1 {
return -1, nil
}
return int64(), nil
}
func ( io.ReaderAt, int64, *directoryEnd) ( error) {
:= make([]byte, directory64EndLen)
if , := .ReadAt(, ); != nil {
return
}
:= readBuf()
if := .uint32(); != directory64EndSignature {
return ErrFormat
}
= [12:]
.diskNbr = .uint32()
.dirDiskNbr = .uint32()
.dirRecordsThisDisk = .uint64()
.directoryRecords = .uint64()
.directorySize = .uint64()
.directoryOffset = .uint64()
return nil
}
func ( []byte) int {
for := len() - directoryEndLen; >= 0; -- {
if [] == 'P' && [+1] == 'K' && [+2] == 0x05 && [+3] == 0x06 {
:= int([+directoryEndLen-2]) | int([+directoryEndLen-1])<<8
if +directoryEndLen+ > len() {
return -1
}
return
}
}
return -1
}
type readBuf []byte
func ( *readBuf) () uint8 {
:= (*)[0]
* = (*)[1:]
return
}
func ( *readBuf) () uint16 {
:= binary.LittleEndian.Uint16(*)
* = (*)[2:]
return
}
func ( *readBuf) () uint32 {
:= binary.LittleEndian.Uint32(*)
* = (*)[4:]
return
}
func ( *readBuf) () uint64 {
:= binary.LittleEndian.Uint64(*)
* = (*)[8:]
return
}
func ( *readBuf) ( int) readBuf {
:= (*)[:]
* = (*)[:]
return
}
type fileListEntry struct {
name string
file *File
isDir bool
isDup bool
}
type fileInfoDirEntry interface {
fs.FileInfo
fs.DirEntry
}
func ( *fileListEntry) () (fileInfoDirEntry, error) {
if .isDup {
return nil, errors.New(.name + ": duplicate entries in zip file")
}
if !.isDir {
return headerFileInfo{&.file.FileHeader}, nil
}
return , nil
}
func ( *fileListEntry) () string { , , := split(.name); return }
func ( *fileListEntry) () int64 { return 0 }
func ( *fileListEntry) () fs.FileMode { return fs.ModeDir | 0555 }
func ( *fileListEntry) () fs.FileMode { return fs.ModeDir }
func ( *fileListEntry) () bool { return true }
func ( *fileListEntry) () any { return nil }
func ( *fileListEntry) () time.Time {
if .file == nil {
return time.Time{}
}
return .file.FileHeader.Modified.UTC()
}
func ( *fileListEntry) () (fs.FileInfo, error) { return , nil }
func ( *fileListEntry) () string {
return fs.FormatDirEntry()
}
func ( string) string {
= strings.ReplaceAll(, `\`, `/`)
:= path.Clean()
= strings.TrimPrefix(, "/")
for strings.HasPrefix(, "../") {
= [len("../"):]
}
return
}
func ( *Reader) () {
.fileListOnce.Do(func() {
.fileList = make([]fileListEntry, 0, len(.File))
:= make(map[string]int)
:= make(map[string]int)
:= make(map[string]bool)
for , := range .File {
:= len(.Name) > 0 && .Name[len(.Name)-1] == '/'
:= toValidName(.Name)
if == "" {
continue
}
if , := []; {
.fileList[].isDup = true
continue
}
if , := []; {
.fileList[].isDup = true
continue
}
:=
for {
if := strings.LastIndex(, "/"); < 0 {
break
} else {
= [:]
}
if [] {
break
}
[] = true
}
:= len(.fileList)
:= fileListEntry{
name: ,
file: ,
isDir: ,
}
.fileList = append(.fileList, )
if {
[] =
} else {
[] =
}
}
for := range {
if , := []; ! {
if , := []; {
.fileList[].isDup = true
} else {
:= fileListEntry{
name: ,
file: nil,
isDir: true,
}
.fileList = append(.fileList, )
}
}
}
slices.SortFunc(.fileList, func(, fileListEntry) int {
return fileEntryCompare(.name, .name)
})
})
}
func (, string) int {
, , := split()
, , := split()
if != {
return strings.Compare(, )
}
return strings.Compare(, )
}
func ( *Reader) ( string) (fs.File, error) {
.initFileList()
if !fs.ValidPath() {
return nil, &fs.PathError{Op: "open", Path: , Err: fs.ErrInvalid}
}
:= .openLookup()
if == nil {
return nil, &fs.PathError{Op: "open", Path: , Err: fs.ErrNotExist}
}
if .isDir {
return &openDir{, .openReadDir(), 0}, nil
}
, := .file.Open()
if != nil {
return nil,
}
return .(fs.File), nil
}
func ( string) (, string, bool) {
, = strings.CutSuffix(, "/")
:= strings.LastIndexByte(, '/')
if < 0 {
return ".", ,
}
return [:], [+1:],
}
var dotFile = &fileListEntry{name: "./", isDir: true}
func ( *Reader) ( string) *fileListEntry {
if == "." {
return dotFile
}
, , := split()
:= .fileList
, := slices.BinarySearchFunc(, , func( fileListEntry, string) ( int) {
, , := split(.name)
if != {
return strings.Compare(, )
}
return strings.Compare(, )
})
if < len() {
:= [].name
if == || len() == len()+1 && [len()] == '/' && [:len()] == {
return &[]
}
}
return nil
}
func ( *Reader) ( string) []fileListEntry {
:= .fileList
, := slices.BinarySearchFunc(, , func( fileListEntry, string) int {
, , := split(.name)
if != {
return strings.Compare(, )
}
return +1
})
, := slices.BinarySearchFunc(, , func( fileListEntry, string) int {
, , := split(.name)
if != {
return strings.Compare(, )
}
return -1
})
return [:]
}
type openDir struct {
e *fileListEntry
files []fileListEntry
offset int
}
func ( *openDir) () error { return nil }
func ( *openDir) () (fs.FileInfo, error) { return .e.stat() }
func ( *openDir) ([]byte) (int, error) {
return 0, &fs.PathError{Op: "read", Path: .e.name, Err: errors.New("is a directory")}
}
func ( *openDir) ( int) ([]fs.DirEntry, error) {
:= len(.files) - .offset
if > 0 && > {
=
}
if == 0 {
if <= 0 {
return nil, nil
}
return nil, io.EOF
}
:= make([]fs.DirEntry, )
for := range {
, := .files[.offset+].stat()
if != nil {
return nil,
} else if .Name() == "." || !fs.ValidPath(.Name()) {
return nil, &fs.PathError{
Op: "readdir",
Path: .e.name,
Err: fmt.Errorf("invalid file name: %v", .files[.offset+].name),
}
}
[] =
}
.offset +=
return , nil
}