1// Copyright 2016 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package zip
16
17import (
18	"errors"
19	"io"
20)
21
22const DataDescriptorFlag = 0x8
23const ExtendedTimeStampTag = 0x5455
24
25func (w *Writer) CopyFrom(orig *File, newName string) error {
26	if w.last != nil && !w.last.closed {
27		if err := w.last.close(); err != nil {
28			return err
29		}
30		w.last = nil
31	}
32
33	fileHeader := orig.FileHeader
34	fileHeader.Name = newName
35	fh := &fileHeader
36
37	// In some cases, we need strip the extras if it change between Central Directory
38	// and Local File Header.
39	fh.Extra = stripExtras(fh.Extra)
40
41	h := &header{
42		FileHeader: fh,
43		offset:     uint64(w.cw.count),
44	}
45	w.dir = append(w.dir, h)
46	if !fh.isZip64() {
47		// Some writers will generate 64 bit sizes and set 32 bit fields to
48		// uint32max even if the actual size fits in 32 bit. So we should
49		// make sure CompressedSize contains the correct value in such
50		// cases. With out the two lines below we would be writing invalid(-1)
51		// sizes in such case.
52		fh.CompressedSize = uint32(fh.CompressedSize64)
53		fh.UncompressedSize = uint32(fh.UncompressedSize64)
54	}
55
56	if err := writeHeader(w.cw, fh); err != nil {
57		return err
58	}
59	dataOffset, err := orig.DataOffset()
60	if err != nil {
61		return err
62	}
63	io.Copy(w.cw, io.NewSectionReader(orig.zipr, dataOffset, int64(orig.CompressedSize64)))
64
65	if orig.hasDataDescriptor() {
66		// Write data descriptor.
67		var buf []byte
68		if fh.isZip64() {
69			buf = make([]byte, dataDescriptor64Len)
70		} else {
71			buf = make([]byte, dataDescriptorLen)
72		}
73		b := writeBuf(buf)
74		b.uint32(dataDescriptorSignature)
75		b.uint32(fh.CRC32)
76		if fh.isZip64() {
77			b.uint64(fh.CompressedSize64)
78			b.uint64(fh.UncompressedSize64)
79		} else {
80			b.uint32(fh.CompressedSize)
81			b.uint32(fh.UncompressedSize)
82		}
83		_, err = w.cw.Write(buf)
84	}
85	return err
86}
87
88// The zip64 extras change between the Central Directory and Local File Header, while we use
89// the same structure for both. The Local File Haeder is taken care of by us writing a data
90// descriptor with the zip64 values. The Central Directory Entry is written by Close(), where
91// the zip64 extra is automatically created and appended when necessary.
92//
93// The extended-timestamp extra block changes between the Central Directory Header and Local
94// File Header.
95// Extended-Timestamp extra(LFH): <tag-size-flag-modtime-actime-changetime>
96// Extended-Timestamp extra(CDH): <tag-size-flag-modtime>
97func stripExtras(input []byte) []byte {
98	ret := []byte{}
99
100	for len(input) >= 4 {
101		r := readBuf(input)
102		tag := r.uint16()
103		size := r.uint16()
104		if int(size) > len(r) {
105			break
106		}
107		if tag != zip64ExtraId && tag != ExtendedTimeStampTag {
108			ret = append(ret, input[:4+size]...)
109		}
110		input = input[4+size:]
111	}
112
113	// Keep any trailing data
114	ret = append(ret, input...)
115
116	return ret
117}
118
119// CreateCompressedHeader adds a file to the zip file using the provied
120// FileHeader for the file metadata.
121// It returns a Writer to which the already compressed file contents
122// should be written.
123//
124// The UncompressedSize64 and CRC32 entries in the FileHeader must be filled
125// out already.
126//
127// The file's contents must be written to the io.Writer before the next
128// call to Create, CreateHeader, CreateCompressedHeader, or Close. The
129// provided FileHeader fh must not be modified after a call to
130// CreateCompressedHeader
131func (w *Writer) CreateCompressedHeader(fh *FileHeader) (io.WriteCloser, error) {
132	if w.last != nil && !w.last.closed {
133		if err := w.last.close(); err != nil {
134			return nil, err
135		}
136	}
137	if len(w.dir) > 0 && w.dir[len(w.dir)-1].FileHeader == fh {
138		// See https://golang.org/issue/11144 confusion.
139		return nil, errors.New("archive/zip: invalid duplicate FileHeader")
140	}
141
142	fh.Flags |= DataDescriptorFlag // we will write a data descriptor
143
144	fh.CreatorVersion = fh.CreatorVersion&0xff00 | zipVersion20 // preserve compatibility byte
145	fh.ReaderVersion = zipVersion20
146
147	fw := &compressedFileWriter{
148		fileWriter{
149			zipw:      w.cw,
150			compCount: &countWriter{w: w.cw},
151		},
152	}
153
154	h := &header{
155		FileHeader: fh,
156		offset:     uint64(w.cw.count),
157	}
158	w.dir = append(w.dir, h)
159	fw.header = h
160
161	if err := writeHeader(w.cw, fh); err != nil {
162		return nil, err
163	}
164
165	w.last = &fw.fileWriter
166	return fw, nil
167}
168
169// Updated version of CreateHeader that doesn't enforce writing a data descriptor
170func (w *Writer) CreateHeaderAndroid(fh *FileHeader) (io.Writer, error) {
171	writeDataDescriptor := fh.Method != Store
172	if writeDataDescriptor {
173		fh.Flags &= DataDescriptorFlag
174	} else {
175		fh.Flags &= ^uint16(DataDescriptorFlag)
176	}
177	return w.createHeaderImpl(fh)
178}
179
180type compressedFileWriter struct {
181	fileWriter
182}
183
184func (w *compressedFileWriter) Write(p []byte) (int, error) {
185	if w.closed {
186		return 0, errors.New("zip: write to closed file")
187	}
188	return w.compCount.Write(p)
189}
190
191func (w *compressedFileWriter) Close() error {
192	if w.closed {
193		return errors.New("zip: file closed twice")
194	}
195	w.closed = true
196
197	// update FileHeader
198	fh := w.header.FileHeader
199	fh.CompressedSize64 = uint64(w.compCount.count)
200
201	if fh.isZip64() {
202		fh.CompressedSize = uint32max
203		fh.UncompressedSize = uint32max
204		fh.ReaderVersion = zipVersion45 // requires 4.5 - File uses ZIP64 format extensions
205	} else {
206		fh.CompressedSize = uint32(fh.CompressedSize64)
207		fh.UncompressedSize = uint32(fh.UncompressedSize64)
208	}
209
210	// Write data descriptor. This is more complicated than one would
211	// think, see e.g. comments in zipfile.c:putextended() and
212	// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7073588.
213	// The approach here is to write 8 byte sizes if needed without
214	// adding a zip64 extra in the local header (too late anyway).
215	var buf []byte
216	if fh.isZip64() {
217		buf = make([]byte, dataDescriptor64Len)
218	} else {
219		buf = make([]byte, dataDescriptorLen)
220	}
221	b := writeBuf(buf)
222	b.uint32(dataDescriptorSignature) // de-facto standard, required by OS X
223	b.uint32(fh.CRC32)
224	if fh.isZip64() {
225		b.uint64(fh.CompressedSize64)
226		b.uint64(fh.UncompressedSize64)
227	} else {
228		b.uint32(fh.CompressedSize)
229		b.uint32(fh.UncompressedSize)
230	}
231	_, err := w.zipw.Write(buf)
232	return err
233}
234