Source File
struct.go
Belonging Package
archive/zip
// Copyright 2010 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file./*Package zip provides support for reading and writing ZIP archives.See the [ZIP specification] for details.This package does not support disk spanning.A note about ZIP64:To be backwards compatible the FileHeader has both 32 and 64 bit Sizefields. The 64 bit fields will always contain the correct value andfor normal archives both fields will be the same. For files requiringthe ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bitfields must be used instead.[ZIP specification]: https://support.pkware.com/pkzip/appnote*/package zipimport ()// Compression methods.const (Store uint16 = 0 // no compressionDeflate uint16 = 8 // DEFLATE compressed)const (fileHeaderSignature = 0x04034b50directoryHeaderSignature = 0x02014b50directoryEndSignature = 0x06054b50directory64LocSignature = 0x07064b50directory64EndSignature = 0x06064b50dataDescriptorSignature = 0x08074b50 // de-facto standard; required by OS X FinderfileHeaderLen = 30 // + filename + extradirectoryHeaderLen = 46 // + filename + extra + commentdirectoryEndLen = 22 // + commentdataDescriptorLen = 16 // four uint32: descriptor signature, crc32, compressed size, sizedataDescriptor64Len = 24 // two uint32: signature, crc32 | two uint64: compressed size, sizedirectory64LocLen = 20 //directory64EndLen = 56 // + extra// Constants for the first byte in CreatorVersion.creatorFAT = 0creatorUnix = 3creatorNTFS = 11creatorVFAT = 14creatorMacOSX = 19// Version numbers.zipVersion20 = 20 // 2.0zipVersion45 = 45 // 4.5 (reads and writes zip64 archives)// Limits for non zip64 files.uint16max = (1 << 16) - 1uint32max = (1 << 32) - 1// Extra header IDs.//// IDs 0..31 are reserved for official use by PKWARE.// IDs above that range are defined by third-party vendors.// Since ZIP lacked high precision timestamps (nor an official specification// of the timezone used for the date fields), many competing extra fields// have been invented. Pervasive use effectively makes them "official".//// See http://mdfs.net/Docs/Comp/Archiving/Zip/ExtraFieldzip64ExtraID = 0x0001 // Zip64 extended informationntfsExtraID = 0x000a // NTFSunixExtraID = 0x000d // UNIXextTimeExtraID = 0x5455 // Extended timestampinfoZipUnixExtraID = 0x5855 // Info-ZIP Unix extension)// FileHeader describes a file within a ZIP file.// See the [ZIP specification] for details.//// [ZIP specification]: https://support.pkware.com/pkzip/appnotetype FileHeader struct {// Name is the name of the file.//// It must be a relative path, not start with a drive letter (such as "C:"),// and must use forward slashes instead of back slashes. A trailing slash// indicates that this file is a directory and should have no data.Name string// Comment is any arbitrary user-defined string shorter than 64KiB.Comment string// NonUTF8 indicates that Name and Comment are not encoded in UTF-8.//// By specification, the only other encoding permitted should be CP-437,// but historically many ZIP readers interpret Name and Comment as whatever// the system's local character encoding happens to be.//// This flag should only be set if the user intends to encode a non-portable// ZIP file for a specific localized region. Otherwise, the Writer// automatically sets the ZIP format's UTF-8 flag for valid UTF-8 strings.NonUTF8 boolCreatorVersion uint16ReaderVersion uint16Flags uint16// Method is the compression method. If zero, Store is used.Method uint16// Modified is the modified time of the file.//// When reading, an extended timestamp is preferred over the legacy MS-DOS// date field, and the offset between the times is used as the timezone.// If only the MS-DOS date is present, the timezone is assumed to be UTC.//// When writing, an extended timestamp (which is timezone-agnostic) is// always emitted. The legacy MS-DOS date field is encoded according to the// location of the Modified time.Modified time.Time// ModifiedTime is an MS-DOS-encoded time.//// Deprecated: Use Modified instead.ModifiedTime uint16// ModifiedDate is an MS-DOS-encoded date.//// Deprecated: Use Modified instead.ModifiedDate uint16// CRC32 is the CRC32 checksum of the file content.CRC32 uint32// CompressedSize is the compressed size of the file in bytes.// If either the uncompressed or compressed size of the file// does not fit in 32 bits, CompressedSize is set to ^uint32(0).//// Deprecated: Use CompressedSize64 instead.CompressedSize uint32// UncompressedSize is the uncompressed size of the file in bytes.// If either the uncompressed or compressed size of the file// does not fit in 32 bits, UncompressedSize is set to ^uint32(0).//// Deprecated: Use UncompressedSize64 instead.UncompressedSize uint32// CompressedSize64 is the compressed size of the file in bytes.CompressedSize64 uint64// UncompressedSize64 is the uncompressed size of the file in bytes.UncompressedSize64 uint64// Extra are the extensible data fields. The writer automatically includes// the appropriate Zip64 field if necessary, and [Writer.Close] appends the// Central Directory version of the Zip64 field to Extra.Extra []byteExternalAttrs uint32 // Meaning depends on CreatorVersion}// FileInfo returns an fs.FileInfo for the [FileHeader].func ( *FileHeader) () fs.FileInfo {return headerFileInfo{}}// headerFileInfo implements [fs.FileInfo].type headerFileInfo struct {fh *FileHeader}func ( headerFileInfo) () string { return path.Base(.fh.Name) }func ( headerFileInfo) () int64 {if .fh.UncompressedSize64 > 0 {return int64(.fh.UncompressedSize64)}return int64(.fh.UncompressedSize)}func ( headerFileInfo) () bool { return .Mode().IsDir() }func ( headerFileInfo) () time.Time {if .fh.Modified.IsZero() {return .fh.ModTime()}return .fh.Modified.UTC()}func ( headerFileInfo) () fs.FileMode { return .fh.Mode() }func ( headerFileInfo) () fs.FileMode { return .fh.Mode().Type() }func ( headerFileInfo) () any { return .fh }func ( headerFileInfo) () (fs.FileInfo, error) { return , nil }func ( headerFileInfo) () string {return fs.FormatFileInfo()}// FileInfoHeader creates a partially-populated [FileHeader] from an// fs.FileInfo.// Because fs.FileInfo's Name method returns only the base name of// the file it describes, it may be necessary to modify the Name field// of the returned header to provide the full path name of the file.// If compression is desired, callers should set the FileHeader.Method// field; it is unset by default.func ( fs.FileInfo) (*FileHeader, error) {:= .Size():= &FileHeader{Name: .Name(),UncompressedSize64: uint64(),}.SetModTime(.ModTime()).SetMode(.Mode())if .UncompressedSize64 > uint32max {.UncompressedSize = uint32max} else {.UncompressedSize = uint32(.UncompressedSize64)}return , nil}type directoryEnd struct {diskNbr uint32 // unuseddirDiskNbr uint32 // unuseddirRecordsThisDisk uint64 // unuseddirectoryRecords uint64directorySize uint64directoryOffset uint64 // relative to filecommentLen uint16comment string}// timeZone returns a *time.Location based on the provided offset.// If the offset is non-sensible, then this uses an offset of zero.func ( time.Duration) *time.Location {const (= -12 * time.Hour // E.g., Baker island at -12:00= +14 * time.Hour // E.g., Line island at +14:00= 15 * time.Minute // E.g., Nepal at +5:45)= .Round()if < || < {= 0}return time.FixedZone("", int(/time.Second))}// msDosTimeToTime converts an MS-DOS date and time into a time.Time.// The resolution is 2s.// See: https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-dosdatetimetofiletimefunc (, uint16) time.Time {return time.Date(// date bits 0-4: day of month; 5-8: month; 9-15: years since 1980int(>>9+1980),time.Month(>>5&0xf),int(&0x1f),// time bits 0-4: second/2; 5-10: minute; 11-15: hourint(>>11),int(>>5&0x3f),int(&0x1f*2),0, // nanosecondstime.UTC,)}// timeToMsDosTime converts a time.Time to an MS-DOS date and time.// The resolution is 2s.// See: https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-filetimetodosdatetimefunc ( time.Time) ( uint16, uint16) {= uint16(.Day() + int(.Month())<<5 + (.Year()-1980)<<9)= uint16(.Second()/2 + .Minute()<<5 + .Hour()<<11)return}// ModTime returns the modification time in UTC using the legacy// [ModifiedDate] and [ModifiedTime] fields.//// Deprecated: Use [Modified] instead.func ( *FileHeader) () time.Time {return msDosTimeToTime(.ModifiedDate, .ModifiedTime)}// SetModTime sets the [Modified], [ModifiedTime], and [ModifiedDate] fields// to the given time in UTC.//// Deprecated: Use [Modified] instead.func ( *FileHeader) ( time.Time) {= .UTC() // Convert to UTC for compatibility.Modified =.ModifiedDate, .ModifiedTime = timeToMsDosTime()}const (// Unix constants. The specification doesn't mention them,// but these seem to be the values agreed on by tools.s_IFMT = 0xf000s_IFSOCK = 0xc000s_IFLNK = 0xa000s_IFREG = 0x8000s_IFBLK = 0x6000s_IFDIR = 0x4000s_IFCHR = 0x2000s_IFIFO = 0x1000s_ISUID = 0x800s_ISGID = 0x400s_ISVTX = 0x200msdosDir = 0x10msdosReadOnly = 0x01)// Mode returns the permission and mode bits for the [FileHeader].func ( *FileHeader) () ( fs.FileMode) {switch .CreatorVersion >> 8 {case creatorUnix, creatorMacOSX:= unixModeToFileMode(.ExternalAttrs >> 16)case creatorNTFS, creatorVFAT, creatorFAT:= msdosModeToFileMode(.ExternalAttrs)}if len(.Name) > 0 && .Name[len(.Name)-1] == '/' {|= fs.ModeDir}return}// SetMode changes the permission and mode bits for the [FileHeader].func ( *FileHeader) ( fs.FileMode) {.CreatorVersion = .CreatorVersion&0xff | creatorUnix<<8.ExternalAttrs = fileModeToUnixMode() << 16// set MSDOS attributes too, as the original zip does.if &fs.ModeDir != 0 {.ExternalAttrs |= msdosDir}if &0200 == 0 {.ExternalAttrs |= msdosReadOnly}}func ( *FileHeader) () bool {return .Flags&0x8 != 0}func ( uint32) ( fs.FileMode) {if &msdosDir != 0 {= fs.ModeDir | 0777} else {= 0666}if &msdosReadOnly != 0 {&^= 0222}return}func ( fs.FileMode) uint32 {var uint32switch & fs.ModeType {default:= s_IFREGcase fs.ModeDir:= s_IFDIRcase fs.ModeSymlink:= s_IFLNKcase fs.ModeNamedPipe:= s_IFIFOcase fs.ModeSocket:= s_IFSOCKcase fs.ModeDevice:= s_IFBLKcase fs.ModeDevice | fs.ModeCharDevice:= s_IFCHR}if &fs.ModeSetuid != 0 {|= s_ISUID}if &fs.ModeSetgid != 0 {|= s_ISGID}if &fs.ModeSticky != 0 {|= s_ISVTX}return | uint32(&0777)}func ( uint32) fs.FileMode {:= fs.FileMode( & 0777)switch & s_IFMT {case s_IFBLK:|= fs.ModeDevicecase s_IFCHR:|= fs.ModeDevice | fs.ModeCharDevicecase s_IFDIR:|= fs.ModeDircase s_IFIFO:|= fs.ModeNamedPipecase s_IFLNK:|= fs.ModeSymlinkcase s_IFREG:// nothing to docase s_IFSOCK:|= fs.ModeSocket}if &s_ISGID != 0 {|= fs.ModeSetgid}if &s_ISUID != 0 {|= fs.ModeSetuid}if &s_ISVTX != 0 {|= fs.ModeSticky}return}
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64)