View Javadoc
1   /*
2    * Copyright (C) 2010, Google Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.internal.storage.file;
45  
46  import static org.junit.Assert.assertArrayEquals;
47  import static org.junit.Assert.assertEquals;
48  import static org.junit.Assert.assertFalse;
49  import static org.junit.Assert.assertNotNull;
50  import static org.junit.Assert.assertNull;
51  import static org.junit.Assert.assertTrue;
52  import static org.junit.Assert.fail;
53  
54  import java.io.ByteArrayInputStream;
55  import java.io.ByteArrayOutputStream;
56  import java.io.File;
57  import java.io.FileOutputStream;
58  import java.io.IOException;
59  import java.security.MessageDigest;
60  import java.text.MessageFormat;
61  import java.util.ArrayList;
62  import java.util.Arrays;
63  import java.util.Collections;
64  import java.util.List;
65  import java.util.zip.Deflater;
66  
67  import org.eclipse.jgit.errors.LargeObjectException;
68  import org.eclipse.jgit.internal.JGitText;
69  import org.eclipse.jgit.internal.storage.pack.DeltaEncoder;
70  import org.eclipse.jgit.internal.storage.pack.PackExt;
71  import org.eclipse.jgit.junit.JGitTestUtil;
72  import org.eclipse.jgit.junit.LocalDiskRepositoryTestCase;
73  import org.eclipse.jgit.junit.TestRepository;
74  import org.eclipse.jgit.junit.TestRng;
75  import org.eclipse.jgit.lib.Constants;
76  import org.eclipse.jgit.lib.NullProgressMonitor;
77  import org.eclipse.jgit.lib.ObjectId;
78  import org.eclipse.jgit.lib.ObjectInserter;
79  import org.eclipse.jgit.lib.ObjectLoader;
80  import org.eclipse.jgit.lib.ObjectStream;
81  import org.eclipse.jgit.lib.Repository;
82  import org.eclipse.jgit.revwalk.RevBlob;
83  import org.eclipse.jgit.storage.file.WindowCacheConfig;
84  import org.eclipse.jgit.transport.PackParser;
85  import org.eclipse.jgit.transport.PackedObjectInfo;
86  import org.eclipse.jgit.util.IO;
87  import org.eclipse.jgit.util.NB;
88  import org.eclipse.jgit.util.TemporaryBuffer;
89  import org.junit.After;
90  import org.junit.Before;
91  import org.junit.Test;
92  
93  public class PackFileTest extends LocalDiskRepositoryTestCase {
94  	private int streamThreshold = 16 * 1024;
95  
96  	private TestRng rng;
97  
98  	private FileRepository repo;
99  
100 	private TestRepository<Repository> tr;
101 
102 	private WindowCursor wc;
103 
104 	private TestRng getRng() {
105 		if (rng == null)
106 			rng = new TestRng(JGitTestUtil.getName());
107 		return rng;
108 	}
109 
110 	@Override
111 	@Before
112 	public void setUp() throws Exception {
113 		super.setUp();
114 
115 		WindowCacheConfig cfg = new WindowCacheConfig();
116 		cfg.setStreamFileThreshold(streamThreshold);
117 		cfg.install();
118 
119 		repo = createBareRepository();
120 		tr = new TestRepository<>(repo);
121 		wc = (WindowCursor) repo.newObjectReader();
122 	}
123 
124 	@Override
125 	@After
126 	public void tearDown() throws Exception {
127 		if (wc != null)
128 			wc.close();
129 		new WindowCacheConfig().install();
130 		super.tearDown();
131 	}
132 
133 	@Test
134 	public void testWhole_SmallObject() throws Exception {
135 		final int type = Constants.OBJ_BLOB;
136 		byte[] data = getRng().nextBytes(300);
137 		RevBlob id = tr.blob(data);
138 		tr.branch("master").commit().add("A", id).create();
139 		tr.packAndPrune();
140 		assertTrue("has blob", wc.has(id));
141 
142 		ObjectLoader ol = wc.open(id);
143 		assertNotNull("created loader", ol);
144 		assertEquals(type, ol.getType());
145 		assertEquals(data.length, ol.getSize());
146 		assertFalse("is not large", ol.isLarge());
147 		assertTrue("same content", Arrays.equals(data, ol.getCachedBytes()));
148 
149 		try (ObjectStream in = ol.openStream()) {
150 			assertNotNull("have stream", in);
151 			assertEquals(type, in.getType());
152 			assertEquals(data.length, in.getSize());
153 			byte[] data2 = new byte[data.length];
154 			IO.readFully(in, data2, 0, data.length);
155 			assertTrue("same content", Arrays.equals(data2, data));
156 			assertEquals("stream at EOF", -1, in.read());
157 		}
158 	}
159 
160 	@Test
161 	public void testWhole_LargeObject() throws Exception {
162 		final int type = Constants.OBJ_BLOB;
163 		byte[] data = getRng().nextBytes(streamThreshold + 5);
164 		RevBlob id = tr.blob(data);
165 		tr.branch("master").commit().add("A", id).create();
166 		tr.packAndPrune();
167 		assertTrue("has blob", wc.has(id));
168 
169 		ObjectLoader ol = wc.open(id);
170 		assertNotNull("created loader", ol);
171 		assertEquals(type, ol.getType());
172 		assertEquals(data.length, ol.getSize());
173 		assertTrue("is large", ol.isLarge());
174 		try {
175 			ol.getCachedBytes();
176 			fail("Should have thrown LargeObjectException");
177 		} catch (LargeObjectException tooBig) {
178 			assertEquals(MessageFormat.format(
179 					JGitText.get().largeObjectException, id.name()), tooBig
180 					.getMessage());
181 		}
182 
183 		try (ObjectStream in = ol.openStream()) {
184 			assertNotNull("have stream", in);
185 			assertEquals(type, in.getType());
186 			assertEquals(data.length, in.getSize());
187 			byte[] data2 = new byte[data.length];
188 			IO.readFully(in, data2, 0, data.length);
189 			assertTrue("same content", Arrays.equals(data2, data));
190 			assertEquals("stream at EOF", -1, in.read());
191 		}
192 	}
193 
194 	@Test
195 	public void testDelta_SmallObjectChain() throws Exception {
196 		try (ObjectInserter.Formatter fmt = new ObjectInserter.Formatter()) {
197 			byte[] data0 = new byte[512];
198 			Arrays.fill(data0, (byte) 0xf3);
199 			ObjectId id0 = fmt.idFor(Constants.OBJ_BLOB, data0);
200 
201 			TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(64 * 1024);
202 			packHeader(pack, 4);
203 			objectHeader(pack, Constants.OBJ_BLOB, data0.length);
204 			deflate(pack, data0);
205 
206 			byte[] data1 = clone(0x01, data0);
207 			byte[] delta1 = delta(data0, data1);
208 			ObjectId id1 = fmt.idFor(Constants.OBJ_BLOB, data1);
209 			objectHeader(pack, Constants.OBJ_REF_DELTA, delta1.length);
210 			id0.copyRawTo(pack);
211 			deflate(pack, delta1);
212 
213 			byte[] data2 = clone(0x02, data1);
214 			byte[] delta2 = delta(data1, data2);
215 			ObjectId id2 = fmt.idFor(Constants.OBJ_BLOB, data2);
216 			objectHeader(pack, Constants.OBJ_REF_DELTA, delta2.length);
217 			id1.copyRawTo(pack);
218 			deflate(pack, delta2);
219 
220 			byte[] data3 = clone(0x03, data2);
221 			byte[] delta3 = delta(data2, data3);
222 			ObjectId id3 = fmt.idFor(Constants.OBJ_BLOB, data3);
223 			objectHeader(pack, Constants.OBJ_REF_DELTA, delta3.length);
224 			id2.copyRawTo(pack);
225 			deflate(pack, delta3);
226 
227 			digest(pack);
228 			PackParser ip = index(pack.toByteArray());
229 			ip.setAllowThin(true);
230 			ip.parse(NullProgressMonitor.INSTANCE);
231 
232 			assertTrue("has blob", wc.has(id3));
233 
234 			ObjectLoader ol = wc.open(id3);
235 			assertNotNull("created loader", ol);
236 			assertEquals(Constants.OBJ_BLOB, ol.getType());
237 			assertEquals(data3.length, ol.getSize());
238 			assertFalse("is large", ol.isLarge());
239 			assertNotNull(ol.getCachedBytes());
240 			assertArrayEquals(data3, ol.getCachedBytes());
241 
242 			try (ObjectStream in = ol.openStream()) {
243 				assertNotNull("have stream", in);
244 				assertEquals(Constants.OBJ_BLOB, in.getType());
245 				assertEquals(data3.length, in.getSize());
246 				byte[] act = new byte[data3.length];
247 				IO.readFully(in, act, 0, data3.length);
248 				assertTrue("same content", Arrays.equals(act, data3));
249 				assertEquals("stream at EOF", -1, in.read());
250 			}
251 		}
252 	}
253 
254 	@Test
255 	public void testDelta_FailsOver2GiB() throws Exception {
256 		try (ObjectInserter.Formatter fmt = new ObjectInserter.Formatter()) {
257 			byte[] base = new byte[] { 'a' };
258 			ObjectId idA = fmt.idFor(Constants.OBJ_BLOB, base);
259 			ObjectId idB = fmt.idFor(Constants.OBJ_BLOB, new byte[] { 'b' });
260 
261 			PackedObjectInfo a = new PackedObjectInfo(idA);
262 			PackedObjectInfo b = new PackedObjectInfo(idB);
263 
264 			TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(64 * 1024);
265 			packHeader(pack, 2);
266 			a.setOffset(pack.length());
267 			objectHeader(pack, Constants.OBJ_BLOB, base.length);
268 			deflate(pack, base);
269 
270 			ByteArrayOutputStream tmp = new ByteArrayOutputStream();
271 			DeltaEncoder de = new DeltaEncoder(tmp, base.length, 3L << 30);
272 			de.copy(0, 1);
273 			byte[] delta = tmp.toByteArray();
274 			b.setOffset(pack.length());
275 			objectHeader(pack, Constants.OBJ_REF_DELTA, delta.length);
276 			idA.copyRawTo(pack);
277 			deflate(pack, delta);
278 			byte[] footer = digest(pack);
279 
280 			File dir = new File(repo.getObjectDatabase().getDirectory(),
281 					"pack");
282 			File packName = new File(dir, idA.name() + ".pack");
283 			File idxName = new File(dir, idA.name() + ".idx");
284 
285 			try (FileOutputStream f = new FileOutputStream(packName)) {
286 				f.write(pack.toByteArray());
287 			}
288 
289 			try (FileOutputStream f = new FileOutputStream(idxName)) {
290 				List<PackedObjectInfo> list = new ArrayList<>();
291 				list.add(a);
292 				list.add(b);
293 				Collections.sort(list);
294 				new PackIndexWriterV1(f).write(list, footer);
295 			}
296 
297 			PackFile packFile = new PackFile(packName, PackExt.INDEX.getBit());
298 			try {
299 				packFile.get(wc, b);
300 				fail("expected LargeObjectException.ExceedsByteArrayLimit");
301 			} catch (LargeObjectException.ExceedsByteArrayLimit bad) {
302 				assertNull(bad.getObjectId());
303 			} finally {
304 				packFile.close();
305 			}
306 		}
307 	}
308 
309 	@Test
310 	public void testConfigurableStreamFileThreshold() throws Exception {
311 		byte[] data = getRng().nextBytes(300);
312 		RevBlob id = tr.blob(data);
313 		tr.branch("master").commit().add("A", id).create();
314 		tr.packAndPrune();
315 		assertTrue("has blob", wc.has(id));
316 
317 		ObjectLoader ol = wc.open(id);
318 		try (ObjectStream in = ol.openStream()) {
319 			assertTrue(in instanceof ObjectStream.SmallStream);
320 			assertEquals(300, in.available());
321 		}
322 
323 		wc.setStreamFileThreshold(299);
324 		ol = wc.open(id);
325 		try (ObjectStream in = ol.openStream()) {
326 			assertTrue(in instanceof ObjectStream.Filter);
327 			assertEquals(1, in.available());
328 		}
329 	}
330 
331 	private static byte[] clone(int first, byte[] base) {
332 		byte[] r = new byte[base.length];
333 		System.arraycopy(base, 1, r, 1, r.length - 1);
334 		r[0] = (byte) first;
335 		return r;
336 	}
337 
338 	private static byte[] delta(byte[] base, byte[] dest) throws IOException {
339 		ByteArrayOutputStream tmp = new ByteArrayOutputStream();
340 		DeltaEncoder de = new DeltaEncoder(tmp, base.length, dest.length);
341 		de.insert(dest, 0, 1);
342 		de.copy(1, base.length - 1);
343 		return tmp.toByteArray();
344 	}
345 
346 	private static void packHeader(TemporaryBuffer.Heap pack, int cnt)
347 			throws IOException {
348 		final byte[] hdr = new byte[8];
349 		NB.encodeInt32(hdr, 0, 2);
350 		NB.encodeInt32(hdr, 4, cnt);
351 		pack.write(Constants.PACK_SIGNATURE);
352 		pack.write(hdr, 0, 8);
353 	}
354 
355 	private static void objectHeader(TemporaryBuffer.Heap pack, int type, int sz)
356 			throws IOException {
357 		byte[] buf = new byte[8];
358 		int nextLength = sz >>> 4;
359 		buf[0] = (byte) ((nextLength > 0 ? 0x80 : 0x00) | (type << 4) | (sz & 0x0F));
360 		sz = nextLength;
361 		int n = 1;
362 		while (sz > 0) {
363 			nextLength >>>= 7;
364 			buf[n++] = (byte) ((nextLength > 0 ? 0x80 : 0x00) | (sz & 0x7F));
365 			sz = nextLength;
366 		}
367 		pack.write(buf, 0, n);
368 	}
369 
370 	private static void deflate(TemporaryBuffer.Heap pack, byte[] content)
371 			throws IOException {
372 		final Deflater deflater = new Deflater();
373 		final byte[] buf = new byte[128];
374 		deflater.setInput(content, 0, content.length);
375 		deflater.finish();
376 		do {
377 			final int n = deflater.deflate(buf, 0, buf.length);
378 			if (n > 0)
379 				pack.write(buf, 0, n);
380 		} while (!deflater.finished());
381 		deflater.end();
382 	}
383 
384 	private static byte[] digest(TemporaryBuffer.Heap buf)
385 			throws IOException {
386 		MessageDigest md = Constants.newMessageDigest();
387 		md.update(buf.toByteArray());
388 		byte[] footer = md.digest();
389 		buf.write(footer);
390 		return footer;
391 	}
392 
393 	private ObjectInserter inserter;
394 
395 	@After
396 	public void release() {
397 		if (inserter != null) {
398 			inserter.close();
399 		}
400 	}
401 
402 	private PackParser index(byte[] raw) throws IOException {
403 		if (inserter == null)
404 			inserter = repo.newObjectInserter();
405 		return inserter.newPackParser(new ByteArrayInputStream(raw));
406 	}
407 }