github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/archive/zip/writer.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package zip
     6  
     7  import (
     8  	"bufio"
     9  	"encoding/binary"
    10  	"errors"
    11  	"hash"
    12  	"hash/crc32"
    13  	"io"
    14  )
    15  
    16  // TODO(adg): support zip file comments
    17  
    18  // Writer implements a zip file writer.
    19  type Writer struct {
    20  	cw          *countWriter
    21  	dir         []*header
    22  	last        *fileWriter
    23  	closed      bool
    24  	compressors map[uint16]Compressor
    25  }
    26  
    27  type header struct {
    28  	*FileHeader
    29  	offset uint64
    30  }
    31  
    32  // NewWriter returns a new Writer writing a zip file to w.
    33  func NewWriter(w io.Writer) *Writer {
    34  	return &Writer{cw: &countWriter{w: bufio.NewWriter(w)}}
    35  }
    36  
    37  // SetOffset sets the offset of the beginning of the zip data within the
    38  // underlying writer. It should be used when the zip data is appended to an
    39  // existing file, such as a binary executable.
    40  // It must be called before any data is written.
    41  func (w *Writer) SetOffset(n int64) {
    42  	if w.cw.count != 0 {
    43  		panic("zip: SetOffset called after data was written")
    44  	}
    45  	w.cw.count = n
    46  }
    47  
    48  // Flush flushes any buffered data to the underlying writer.
    49  // Calling Flush is not normally necessary; calling Close is sufficient.
    50  func (w *Writer) Flush() error {
    51  	return w.cw.w.(*bufio.Writer).Flush()
    52  }
    53  
    54  // Close finishes writing the zip file by writing the central directory.
    55  // It does not (and cannot) close the underlying writer.
    56  func (w *Writer) Close() error {
    57  	if w.last != nil && !w.last.closed {
    58  		if err := w.last.close(); err != nil {
    59  			return err
    60  		}
    61  		w.last = nil
    62  	}
    63  	if w.closed {
    64  		return errors.New("zip: writer closed twice")
    65  	}
    66  	w.closed = true
    67  
    68  	// write central directory
    69  	start := w.cw.count
    70  	for _, h := range w.dir {
    71  		var buf [directoryHeaderLen]byte
    72  		b := writeBuf(buf[:])
    73  		b.uint32(uint32(directoryHeaderSignature))
    74  		b.uint16(h.CreatorVersion)
    75  		b.uint16(h.ReaderVersion)
    76  		b.uint16(h.Flags)
    77  		b.uint16(h.Method)
    78  		b.uint16(h.ModifiedTime)
    79  		b.uint16(h.ModifiedDate)
    80  		b.uint32(h.CRC32)
    81  		if h.isZip64() || h.offset >= uint32max {
    82  			// the file needs a zip64 header. store maxint in both
    83  			// 32 bit size fields (and offset later) to signal that the
    84  			// zip64 extra header should be used.
    85  			b.uint32(uint32max) // compressed size
    86  			b.uint32(uint32max) // uncompressed size
    87  
    88  			// append a zip64 extra block to Extra
    89  			var buf [28]byte // 2x uint16 + 3x uint64
    90  			eb := writeBuf(buf[:])
    91  			eb.uint16(zip64ExtraId)
    92  			eb.uint16(24) // size = 3x uint64
    93  			eb.uint64(h.UncompressedSize64)
    94  			eb.uint64(h.CompressedSize64)
    95  			eb.uint64(h.offset)
    96  			h.Extra = append(h.Extra, buf[:]...)
    97  		} else {
    98  			b.uint32(h.CompressedSize)
    99  			b.uint32(h.UncompressedSize)
   100  		}
   101  
   102  		// use Extended Timestamp Extra Field.
   103  		if h.ModifiedTime != 0 || h.ModifiedDate != 0 {
   104  			mt := uint32(h.ModTime().Unix())
   105  			var mbuf [9]byte // 2x uint16 + uint8 + uint32
   106  			eb := writeBuf(mbuf[:])
   107  			eb.uint16(exttsExtraId)
   108  			eb.uint16(5)  // size = uint8 + uint32
   109  			eb.uint8(1)   // flags = modtime
   110  			eb.uint32(mt) // ModTime
   111  			h.Extra = append(h.Extra, mbuf[:]...)
   112  		}
   113  
   114  		b.uint16(uint16(len(h.Name)))
   115  		b.uint16(uint16(len(h.Extra)))
   116  		b.uint16(uint16(len(h.Comment)))
   117  		b = b[4:] // skip disk number start and internal file attr (2x uint16)
   118  		b.uint32(h.ExternalAttrs)
   119  		if h.offset > uint32max {
   120  			b.uint32(uint32max)
   121  		} else {
   122  			b.uint32(uint32(h.offset))
   123  		}
   124  		if _, err := w.cw.Write(buf[:]); err != nil {
   125  			return err
   126  		}
   127  		if _, err := io.WriteString(w.cw, h.Name); err != nil {
   128  			return err
   129  		}
   130  		if _, err := w.cw.Write(h.Extra); err != nil {
   131  			return err
   132  		}
   133  		if _, err := io.WriteString(w.cw, h.Comment); err != nil {
   134  			return err
   135  		}
   136  	}
   137  	end := w.cw.count
   138  
   139  	records := uint64(len(w.dir))
   140  	size := uint64(end - start)
   141  	offset := uint64(start)
   142  
   143  	if records > uint16max || size > uint32max || offset > uint32max {
   144  		var buf [directory64EndLen + directory64LocLen]byte
   145  		b := writeBuf(buf[:])
   146  
   147  		// zip64 end of central directory record
   148  		b.uint32(directory64EndSignature)
   149  		b.uint64(directory64EndLen - 12) // length minus signature (uint32) and length fields (uint64)
   150  		b.uint16(zipVersion45)           // version made by
   151  		b.uint16(zipVersion45)           // version needed to extract
   152  		b.uint32(0)                      // number of this disk
   153  		b.uint32(0)                      // number of the disk with the start of the central directory
   154  		b.uint64(records)                // total number of entries in the central directory on this disk
   155  		b.uint64(records)                // total number of entries in the central directory
   156  		b.uint64(size)                   // size of the central directory
   157  		b.uint64(offset)                 // offset of start of central directory with respect to the starting disk number
   158  
   159  		// zip64 end of central directory locator
   160  		b.uint32(directory64LocSignature)
   161  		b.uint32(0)           // number of the disk with the start of the zip64 end of central directory
   162  		b.uint64(uint64(end)) // relative offset of the zip64 end of central directory record
   163  		b.uint32(1)           // total number of disks
   164  
   165  		if _, err := w.cw.Write(buf[:]); err != nil {
   166  			return err
   167  		}
   168  
   169  		// store max values in the regular end record to signal that
   170  		// that the zip64 values should be used instead
   171  		records = uint16max
   172  		size = uint32max
   173  		offset = uint32max
   174  	}
   175  
   176  	// write end record
   177  	var buf [directoryEndLen]byte
   178  	b := writeBuf(buf[:])
   179  	b.uint32(uint32(directoryEndSignature))
   180  	b = b[4:]                 // skip over disk number and first disk number (2x uint16)
   181  	b.uint16(uint16(records)) // number of entries this disk
   182  	b.uint16(uint16(records)) // number of entries total
   183  	b.uint32(uint32(size))    // size of directory
   184  	b.uint32(uint32(offset))  // start of directory
   185  	// skipped size of comment (always zero)
   186  	if _, err := w.cw.Write(buf[:]); err != nil {
   187  		return err
   188  	}
   189  
   190  	return w.cw.w.(*bufio.Writer).Flush()
   191  }
   192  
   193  // Create adds a file to the zip file using the provided name.
   194  // It returns a Writer to which the file contents should be written.
   195  // The name must be a relative path: it must not start with a drive
   196  // letter (e.g. C:) or leading slash, and only forward slashes are
   197  // allowed.
   198  // The file's contents must be written to the io.Writer before the next
   199  // call to Create, CreateHeader, or Close.
   200  func (w *Writer) Create(name string) (io.Writer, error) {
   201  	header := &FileHeader{
   202  		Name:   name,
   203  		Method: Deflate,
   204  	}
   205  	return w.CreateHeader(header)
   206  }
   207  
   208  // CreateHeader adds a file to the zip file using the provided FileHeader
   209  // for the file metadata.
   210  // It returns a Writer to which the file contents should be written.
   211  //
   212  // The file's contents must be written to the io.Writer before the next
   213  // call to Create, CreateHeader, or Close. The provided FileHeader fh
   214  // must not be modified after a call to CreateHeader.
   215  func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error) {
   216  	if w.last != nil && !w.last.closed {
   217  		if err := w.last.close(); err != nil {
   218  			return nil, err
   219  		}
   220  	}
   221  	if len(w.dir) > 0 && w.dir[len(w.dir)-1].FileHeader == fh {
   222  		// See https://golang.org/issue/11144 confusion.
   223  		return nil, errors.New("archive/zip: invalid duplicate FileHeader")
   224  	}
   225  
   226  	fh.Flags |= 0x8 // we will write a data descriptor
   227  
   228  	fh.CreatorVersion = fh.CreatorVersion&0xff00 | zipVersion20 // preserve compatibility byte
   229  	fh.ReaderVersion = zipVersion20
   230  
   231  	fw := &fileWriter{
   232  		zipw:      w.cw,
   233  		compCount: &countWriter{w: w.cw},
   234  		crc32:     crc32.NewIEEE(),
   235  	}
   236  	comp := w.compressor(fh.Method)
   237  	if comp == nil {
   238  		return nil, ErrAlgorithm
   239  	}
   240  	var err error
   241  	fw.comp, err = comp(fw.compCount)
   242  	if err != nil {
   243  		return nil, err
   244  	}
   245  	fw.rawCount = &countWriter{w: fw.comp}
   246  
   247  	h := &header{
   248  		FileHeader: fh,
   249  		offset:     uint64(w.cw.count),
   250  	}
   251  	w.dir = append(w.dir, h)
   252  	fw.header = h
   253  
   254  	if err := writeHeader(w.cw, fh); err != nil {
   255  		return nil, err
   256  	}
   257  
   258  	w.last = fw
   259  	return fw, nil
   260  }
   261  
   262  func writeHeader(w io.Writer, h *FileHeader) error {
   263  	var buf [fileHeaderLen]byte
   264  	b := writeBuf(buf[:])
   265  	b.uint32(uint32(fileHeaderSignature))
   266  	b.uint16(h.ReaderVersion)
   267  	b.uint16(h.Flags)
   268  	b.uint16(h.Method)
   269  	b.uint16(h.ModifiedTime)
   270  	b.uint16(h.ModifiedDate)
   271  	b.uint32(0) // since we are writing a data descriptor crc32,
   272  	b.uint32(0) // compressed size,
   273  	b.uint32(0) // and uncompressed size should be zero
   274  	b.uint16(uint16(len(h.Name)))
   275  	b.uint16(uint16(len(h.Extra)))
   276  	if _, err := w.Write(buf[:]); err != nil {
   277  		return err
   278  	}
   279  	if _, err := io.WriteString(w, h.Name); err != nil {
   280  		return err
   281  	}
   282  	_, err := w.Write(h.Extra)
   283  	return err
   284  }
   285  
   286  // RegisterCompressor registers or overrides a custom compressor for a specific
   287  // method ID. If a compressor for a given method is not found, Writer will
   288  // default to looking up the compressor at the package level.
   289  func (w *Writer) RegisterCompressor(method uint16, comp Compressor) {
   290  	if w.compressors == nil {
   291  		w.compressors = make(map[uint16]Compressor)
   292  	}
   293  	w.compressors[method] = comp
   294  }
   295  
   296  func (w *Writer) compressor(method uint16) Compressor {
   297  	comp := w.compressors[method]
   298  	if comp == nil {
   299  		comp = compressor(method)
   300  	}
   301  	return comp
   302  }
   303  
   304  type fileWriter struct {
   305  	*header
   306  	zipw      io.Writer
   307  	rawCount  *countWriter
   308  	comp      io.WriteCloser
   309  	compCount *countWriter
   310  	crc32     hash.Hash32
   311  	closed    bool
   312  }
   313  
   314  func (w *fileWriter) Write(p []byte) (int, error) {
   315  	if w.closed {
   316  		return 0, errors.New("zip: write to closed file")
   317  	}
   318  	w.crc32.Write(p)
   319  	return w.rawCount.Write(p)
   320  }
   321  
   322  func (w *fileWriter) close() error {
   323  	if w.closed {
   324  		return errors.New("zip: file closed twice")
   325  	}
   326  	w.closed = true
   327  	if err := w.comp.Close(); err != nil {
   328  		return err
   329  	}
   330  
   331  	// update FileHeader
   332  	fh := w.header.FileHeader
   333  	fh.CRC32 = w.crc32.Sum32()
   334  	fh.CompressedSize64 = uint64(w.compCount.count)
   335  	fh.UncompressedSize64 = uint64(w.rawCount.count)
   336  
   337  	if fh.isZip64() {
   338  		fh.CompressedSize = uint32max
   339  		fh.UncompressedSize = uint32max
   340  		fh.ReaderVersion = zipVersion45 // requires 4.5 - File uses ZIP64 format extensions
   341  	} else {
   342  		fh.CompressedSize = uint32(fh.CompressedSize64)
   343  		fh.UncompressedSize = uint32(fh.UncompressedSize64)
   344  	}
   345  
   346  	// Write data descriptor. This is more complicated than one would
   347  	// think, see e.g. comments in zipfile.c:putextended() and
   348  	// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7073588.
   349  	// The approach here is to write 8 byte sizes if needed without
   350  	// adding a zip64 extra in the local header (too late anyway).
   351  	var buf []byte
   352  	if fh.isZip64() {
   353  		buf = make([]byte, dataDescriptor64Len)
   354  	} else {
   355  		buf = make([]byte, dataDescriptorLen)
   356  	}
   357  	b := writeBuf(buf)
   358  	b.uint32(dataDescriptorSignature) // de-facto standard, required by OS X
   359  	b.uint32(fh.CRC32)
   360  	if fh.isZip64() {
   361  		b.uint64(fh.CompressedSize64)
   362  		b.uint64(fh.UncompressedSize64)
   363  	} else {
   364  		b.uint32(fh.CompressedSize)
   365  		b.uint32(fh.UncompressedSize)
   366  	}
   367  	_, err := w.zipw.Write(buf)
   368  	return err
   369  }
   370  
   371  type countWriter struct {
   372  	w     io.Writer
   373  	count int64
   374  }
   375  
   376  func (w *countWriter) Write(p []byte) (int, error) {
   377  	n, err := w.w.Write(p)
   378  	w.count += int64(n)
   379  	return n, err
   380  }
   381  
   382  type nopCloser struct {
   383  	io.Writer
   384  }
   385  
   386  func (w nopCloser) Close() error {
   387  	return nil
   388  }
   389  
   390  type writeBuf []byte
   391  
   392  func (b *writeBuf) uint8(v uint8) {
   393  	(*b)[0] = v
   394  	*b = (*b)[1:]
   395  }
   396  
   397  func (b *writeBuf) uint16(v uint16) {
   398  	binary.LittleEndian.PutUint16(*b, v)
   399  	*b = (*b)[2:]
   400  }
   401  
   402  func (b *writeBuf) uint32(v uint32) {
   403  	binary.LittleEndian.PutUint32(*b, v)
   404  	*b = (*b)[4:]
   405  }
   406  
   407  func (b *writeBuf) uint64(v uint64) {
   408  	binary.LittleEndian.PutUint64(*b, v)
   409  	*b = (*b)[8:]
   410  }