You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IndexPack.java 38KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 2007-2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.transport;
  46. import java.io.EOFException;
  47. import java.io.File;
  48. import java.io.FileOutputStream;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.RandomAccessFile;
  52. import java.security.MessageDigest;
  53. import java.text.MessageFormat;
  54. import java.util.ArrayList;
  55. import java.util.Arrays;
  56. import java.util.List;
  57. import java.util.zip.CRC32;
  58. import java.util.zip.DataFormatException;
  59. import java.util.zip.Deflater;
  60. import java.util.zip.Inflater;
  61. import org.eclipse.jgit.JGitText;
  62. import org.eclipse.jgit.errors.CorruptObjectException;
  63. import org.eclipse.jgit.errors.MissingObjectException;
  64. import org.eclipse.jgit.lib.AnyObjectId;
  65. import org.eclipse.jgit.lib.Constants;
  66. import org.eclipse.jgit.lib.CoreConfig;
  67. import org.eclipse.jgit.lib.InflaterCache;
  68. import org.eclipse.jgit.lib.MutableObjectId;
  69. import org.eclipse.jgit.lib.ObjectChecker;
  70. import org.eclipse.jgit.lib.ObjectDatabase;
  71. import org.eclipse.jgit.lib.ObjectId;
  72. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  73. import org.eclipse.jgit.lib.ObjectLoader;
  74. import org.eclipse.jgit.lib.ObjectReader;
  75. import org.eclipse.jgit.lib.ObjectStream;
  76. import org.eclipse.jgit.lib.ProgressMonitor;
  77. import org.eclipse.jgit.lib.Repository;
  78. import org.eclipse.jgit.storage.file.PackIndexWriter;
  79. import org.eclipse.jgit.storage.file.PackLock;
  80. import org.eclipse.jgit.storage.pack.BinaryDelta;
  81. import org.eclipse.jgit.util.FileUtils;
  82. import org.eclipse.jgit.util.IO;
  83. import org.eclipse.jgit.util.NB;
  84. /** Indexes Git pack files for local use. */
  85. public class IndexPack {
  86. /**
  87. * Size of the internal stream buffer.
  88. * <p>
  89. * If callers are going to be supplying IndexPack a BufferedInputStream they
  90. * should use this buffer size as the size of the buffer for that
  91. * BufferedInputStream, and any other its may be wrapping. This way the
  92. * buffers will cascade efficiently and only the IndexPack buffer will be
  93. * receiving the bulk of the data stream.
  94. */
  95. public static final int BUFFER_SIZE = 8192;
  96. /**
  97. * Create an index pack instance to load a new pack into a repository.
  98. * <p>
  99. * The received pack data and generated index will be saved to temporary
  100. * files within the repository's <code>objects</code> directory. To use the
  101. * data contained within them call {@link #renameAndOpenPack()} once the
  102. * indexing is complete.
  103. *
  104. * @param db
  105. * the repository that will receive the new pack.
  106. * @param is
  107. * stream to read the pack data from. If the stream is buffered
  108. * use {@link #BUFFER_SIZE} as the buffer size for the stream.
  109. * @return a new index pack instance.
  110. * @throws IOException
  111. * a temporary file could not be created.
  112. */
  113. public static IndexPack create(final Repository db, final InputStream is)
  114. throws IOException {
  115. final String suffix = ".pack";
  116. final File objdir = db.getObjectsDirectory();
  117. final File tmp = File.createTempFile("incoming_", suffix, objdir);
  118. final String n = tmp.getName();
  119. final File base;
  120. base = new File(objdir, n.substring(0, n.length() - suffix.length()));
  121. final IndexPack ip = new IndexPack(db, is, base);
  122. ip.setIndexVersion(db.getConfig().get(CoreConfig.KEY)
  123. .getPackIndexVersion());
  124. return ip;
  125. }
  126. private static enum Source {
  127. /** Data is read from the incoming stream. */
  128. INPUT,
  129. /**
  130. * Data is read from the spooled pack file.
  131. * <p>
  132. * During streaming, some (or all) data might be saved into the spooled
  133. * pack file so it can be randomly accessed later.
  134. */
  135. FILE;
  136. }
  137. private final Repository repo;
  138. /**
  139. * Object database used for loading existing objects
  140. */
  141. private final ObjectDatabase objectDatabase;
  142. private InflaterStream inflater;
  143. private byte[] readBuffer;
  144. private final MessageDigest objectDigest;
  145. private final MutableObjectId tempObjectId;
  146. private InputStream in;
  147. private byte[] buf;
  148. private long bBase;
  149. private int bOffset;
  150. private int bAvail;
  151. private ObjectChecker objCheck;
  152. private boolean fixThin;
  153. private boolean keepEmpty;
  154. private boolean needBaseObjectIds;
  155. private int outputVersion;
  156. private final File dstPack;
  157. private final File dstIdx;
  158. private long objectCount;
  159. private PackedObjectInfo[] entries;
  160. /**
  161. * Every object contained within the incoming pack.
  162. * <p>
  163. * This is a subset of {@link #entries}, as thin packs can add additional
  164. * objects to {@code entries} by copying already existing objects from the
  165. * repository onto the end of the thin pack to make it self-contained.
  166. */
  167. private ObjectIdSubclassMap<ObjectId> newObjectIds;
  168. private int deltaCount;
  169. private int entryCount;
  170. private final CRC32 crc = new CRC32();
  171. private ObjectIdSubclassMap<DeltaChain> baseById;
  172. /**
  173. * Objects referenced by their name from deltas, that aren't in this pack.
  174. * <p>
  175. * This is the set of objects that were copied onto the end of this pack to
  176. * make it complete. These objects were not transmitted by the remote peer,
  177. * but instead were assumed to already exist in the local repository.
  178. */
  179. private ObjectIdSubclassMap<ObjectId> baseObjectIds;
  180. private LongMap<UnresolvedDelta> baseByPos;
  181. /** Blobs whose contents need to be double-checked after indexing. */
  182. private List<PackedObjectInfo> deferredCheckBlobs;
  183. private MessageDigest packDigest;
  184. private RandomAccessFile packOut;
  185. private byte[] packcsum;
  186. /** If {@link #fixThin} this is the last byte of the original checksum. */
  187. private long originalEOF;
  188. private ObjectReader readCurs;
  189. /**
  190. * Create a new pack indexer utility.
  191. *
  192. * @param db
  193. * @param src
  194. * stream to read the pack data from. If the stream is buffered
  195. * use {@link #BUFFER_SIZE} as the buffer size for the stream.
  196. * @param dstBase
  197. * @throws IOException
  198. * the output packfile could not be created.
  199. */
  200. public IndexPack(final Repository db, final InputStream src,
  201. final File dstBase) throws IOException {
  202. repo = db;
  203. objectDatabase = db.getObjectDatabase().newCachedDatabase();
  204. in = src;
  205. inflater = new InflaterStream();
  206. readCurs = objectDatabase.newReader();
  207. buf = new byte[BUFFER_SIZE];
  208. readBuffer = new byte[BUFFER_SIZE];
  209. objectDigest = Constants.newMessageDigest();
  210. tempObjectId = new MutableObjectId();
  211. packDigest = Constants.newMessageDigest();
  212. if (dstBase != null) {
  213. final File dir = dstBase.getParentFile();
  214. final String nam = dstBase.getName();
  215. dstPack = new File(dir, nam + ".pack");
  216. dstIdx = new File(dir, nam + ".idx");
  217. packOut = new RandomAccessFile(dstPack, "rw");
  218. packOut.setLength(0);
  219. } else {
  220. dstPack = null;
  221. dstIdx = null;
  222. }
  223. }
  224. /**
  225. * Set the pack index file format version this instance will create.
  226. *
  227. * @param version
  228. * the version to write. The special version 0 designates the
  229. * oldest (most compatible) format available for the objects.
  230. * @see PackIndexWriter
  231. */
  232. public void setIndexVersion(final int version) {
  233. outputVersion = version;
  234. }
  235. /**
  236. * Configure this index pack instance to make a thin pack complete.
  237. * <p>
  238. * Thin packs are sometimes used during network transfers to allow a delta
  239. * to be sent without a base object. Such packs are not permitted on disk.
  240. * They can be fixed by copying the base object onto the end of the pack.
  241. *
  242. * @param fix
  243. * true to enable fixing a thin pack.
  244. */
  245. public void setFixThin(final boolean fix) {
  246. fixThin = fix;
  247. }
  248. /**
  249. * Configure this index pack instance to keep an empty pack.
  250. * <p>
  251. * By default an empty pack (a pack with no objects) is not kept, as doing
  252. * so is completely pointless. With no objects in the pack there is no data
  253. * stored by it, so the pack is unnecessary.
  254. *
  255. * @param empty true to enable keeping an empty pack.
  256. */
  257. public void setKeepEmpty(final boolean empty) {
  258. keepEmpty = empty;
  259. }
  260. /**
  261. * Configure this index pack instance to keep track of new objects.
  262. * <p>
  263. * By default an index pack doesn't save the new objects that were created
  264. * when it was instantiated. Setting this flag to {@code true} allows the
  265. * caller to use {@link #getNewObjectIds()} to retrieve that list.
  266. *
  267. * @param b {@code true} to enable keeping track of new objects.
  268. */
  269. public void setNeedNewObjectIds(boolean b) {
  270. if (b)
  271. newObjectIds = new ObjectIdSubclassMap<ObjectId>();
  272. else
  273. newObjectIds = null;
  274. }
  275. private boolean needNewObjectIds() {
  276. return newObjectIds != null;
  277. }
  278. /**
  279. * Configure this index pack instance to keep track of the objects assumed
  280. * for delta bases.
  281. * <p>
  282. * By default an index pack doesn't save the objects that were used as delta
  283. * bases. Setting this flag to {@code true} will allow the caller to
  284. * use {@link #getBaseObjectIds()} to retrieve that list.
  285. *
  286. * @param b {@code true} to enable keeping track of delta bases.
  287. */
  288. public void setNeedBaseObjectIds(boolean b) {
  289. this.needBaseObjectIds = b;
  290. }
  291. /** @return the new objects that were sent by the user */
  292. public ObjectIdSubclassMap<ObjectId> getNewObjectIds() {
  293. if (newObjectIds != null)
  294. return newObjectIds;
  295. return new ObjectIdSubclassMap<ObjectId>();
  296. }
  297. /** @return set of objects the incoming pack assumed for delta purposes */
  298. public ObjectIdSubclassMap<ObjectId> getBaseObjectIds() {
  299. if (baseObjectIds != null)
  300. return baseObjectIds;
  301. return new ObjectIdSubclassMap<ObjectId>();
  302. }
  303. /**
  304. * Configure the checker used to validate received objects.
  305. * <p>
  306. * Usually object checking isn't necessary, as Git implementations only
  307. * create valid objects in pack files. However, additional checking may be
  308. * useful if processing data from an untrusted source.
  309. *
  310. * @param oc
  311. * the checker instance; null to disable object checking.
  312. */
  313. public void setObjectChecker(final ObjectChecker oc) {
  314. objCheck = oc;
  315. }
  316. /**
  317. * Configure the checker used to validate received objects.
  318. * <p>
  319. * Usually object checking isn't necessary, as Git implementations only
  320. * create valid objects in pack files. However, additional checking may be
  321. * useful if processing data from an untrusted source.
  322. * <p>
  323. * This is shorthand for:
  324. *
  325. * <pre>
  326. * setObjectChecker(on ? new ObjectChecker() : null);
  327. * </pre>
  328. *
  329. * @param on
  330. * true to enable the default checker; false to disable it.
  331. */
  332. public void setObjectChecking(final boolean on) {
  333. setObjectChecker(on ? new ObjectChecker() : null);
  334. }
  335. /**
  336. * Consume data from the input stream until the packfile is indexed.
  337. *
  338. * @param progress
  339. * progress feedback
  340. *
  341. * @throws IOException
  342. */
  343. public void index(final ProgressMonitor progress) throws IOException {
  344. progress.start(2 /* tasks */);
  345. try {
  346. try {
  347. readPackHeader();
  348. entries = new PackedObjectInfo[(int) objectCount];
  349. baseById = new ObjectIdSubclassMap<DeltaChain>();
  350. baseByPos = new LongMap<UnresolvedDelta>();
  351. deferredCheckBlobs = new ArrayList<PackedObjectInfo>();
  352. progress.beginTask(JGitText.get().receivingObjects,
  353. (int) objectCount);
  354. for (int done = 0; done < objectCount; done++) {
  355. indexOneObject();
  356. progress.update(1);
  357. if (progress.isCancelled())
  358. throw new IOException(JGitText.get().downloadCancelled);
  359. }
  360. readPackFooter();
  361. endInput();
  362. if (!deferredCheckBlobs.isEmpty())
  363. doDeferredCheckBlobs();
  364. progress.endTask();
  365. if (deltaCount > 0) {
  366. if (packOut == null)
  367. throw new IOException(JGitText.get().needPackOut);
  368. resolveDeltas(progress);
  369. if (entryCount < objectCount) {
  370. if (!fixThin) {
  371. throw new IOException(MessageFormat.format(
  372. JGitText.get().packHasUnresolvedDeltas, (objectCount - entryCount)));
  373. }
  374. fixThinPack(progress);
  375. }
  376. }
  377. if (packOut != null && (keepEmpty || entryCount > 0))
  378. packOut.getChannel().force(true);
  379. packDigest = null;
  380. baseById = null;
  381. baseByPos = null;
  382. if (dstIdx != null && (keepEmpty || entryCount > 0))
  383. writeIdx();
  384. } finally {
  385. try {
  386. if (readCurs != null)
  387. readCurs.release();
  388. } finally {
  389. readCurs = null;
  390. }
  391. try {
  392. inflater.release();
  393. } finally {
  394. inflater = null;
  395. objectDatabase.close();
  396. }
  397. progress.endTask();
  398. if (packOut != null)
  399. packOut.close();
  400. }
  401. if (keepEmpty || entryCount > 0) {
  402. if (dstPack != null)
  403. dstPack.setReadOnly();
  404. if (dstIdx != null)
  405. dstIdx.setReadOnly();
  406. }
  407. } catch (IOException err) {
  408. if (dstPack != null)
  409. FileUtils.delete(dstPack);
  410. if (dstIdx != null)
  411. FileUtils.delete(dstIdx);
  412. throw err;
  413. }
  414. }
  415. private void resolveDeltas(final ProgressMonitor progress)
  416. throws IOException {
  417. progress.beginTask(JGitText.get().resolvingDeltas, deltaCount);
  418. final int last = entryCount;
  419. for (int i = 0; i < last; i++) {
  420. final int before = entryCount;
  421. resolveDeltas(entries[i]);
  422. progress.update(entryCount - before);
  423. if (progress.isCancelled())
  424. throw new IOException(JGitText.get().downloadCancelledDuringIndexing);
  425. }
  426. progress.endTask();
  427. }
  428. private void resolveDeltas(final PackedObjectInfo oe) throws IOException {
  429. UnresolvedDelta children = firstChildOf(oe);
  430. if (children == null)
  431. return;
  432. DeltaVisit visit = new DeltaVisit();
  433. visit.nextChild = children;
  434. crc.reset();
  435. position(oe.getOffset());
  436. int c = readFrom(Source.FILE);
  437. final int typeCode = (c >> 4) & 7;
  438. long sz = c & 15;
  439. int shift = 4;
  440. while ((c & 0x80) != 0) {
  441. c = readFrom(Source.FILE);
  442. sz += (c & 0x7f) << shift;
  443. shift += 7;
  444. }
  445. switch (typeCode) {
  446. case Constants.OBJ_COMMIT:
  447. case Constants.OBJ_TREE:
  448. case Constants.OBJ_BLOB:
  449. case Constants.OBJ_TAG:
  450. visit.data = inflateAndReturn(Source.FILE, sz);
  451. break;
  452. default:
  453. throw new IOException(MessageFormat.format(
  454. JGitText.get().unknownObjectType, typeCode));
  455. }
  456. if (oe.getCRC() != (int) crc.getValue()) {
  457. throw new IOException(MessageFormat.format(
  458. JGitText.get().corruptionDetectedReReadingAt,
  459. oe.getOffset()));
  460. }
  461. resolveDeltas(visit.next(), typeCode);
  462. }
  463. private void resolveDeltas(DeltaVisit visit, final int type)
  464. throws IOException {
  465. do {
  466. final long pos = visit.delta.position;
  467. crc.reset();
  468. position(pos);
  469. int c = readFrom(Source.FILE);
  470. final int typeCode = (c >> 4) & 7;
  471. long sz = c & 15;
  472. int shift = 4;
  473. while ((c & 0x80) != 0) {
  474. c = readFrom(Source.FILE);
  475. sz += (c & 0x7f) << shift;
  476. shift += 7;
  477. }
  478. switch (typeCode) {
  479. case Constants.OBJ_OFS_DELTA: {
  480. c = readFrom(Source.FILE) & 0xff;
  481. while ((c & 128) != 0)
  482. c = readFrom(Source.FILE) & 0xff;
  483. visit.data = BinaryDelta.apply(visit.parent.data, inflateAndReturn(Source.FILE, sz));
  484. break;
  485. }
  486. case Constants.OBJ_REF_DELTA: {
  487. crc.update(buf, fill(Source.FILE, 20), 20);
  488. use(20);
  489. visit.data = BinaryDelta.apply(visit.parent.data, inflateAndReturn(Source.FILE, sz));
  490. break;
  491. }
  492. default:
  493. throw new IOException(MessageFormat.format(JGitText.get().unknownObjectType, typeCode));
  494. }
  495. final int crc32 = (int) crc.getValue();
  496. if (visit.delta.crc != crc32)
  497. throw new IOException(MessageFormat.format(JGitText.get().corruptionDetectedReReadingAt, pos));
  498. objectDigest.update(Constants.encodedTypeString(type));
  499. objectDigest.update((byte) ' ');
  500. objectDigest.update(Constants.encodeASCII(visit.data.length));
  501. objectDigest.update((byte) 0);
  502. objectDigest.update(visit.data);
  503. tempObjectId.fromRaw(objectDigest.digest(), 0);
  504. verifySafeObject(tempObjectId, type, visit.data);
  505. PackedObjectInfo oe;
  506. oe = new PackedObjectInfo(pos, crc32, tempObjectId);
  507. addObjectAndTrack(oe);
  508. visit.nextChild = firstChildOf(oe);
  509. visit = visit.next();
  510. } while (visit != null);
  511. }
  512. private UnresolvedDelta removeBaseById(final AnyObjectId id){
  513. final DeltaChain d = baseById.get(id);
  514. return d != null ? d.remove() : null;
  515. }
  516. private static UnresolvedDelta reverse(UnresolvedDelta c) {
  517. UnresolvedDelta tail = null;
  518. while (c != null) {
  519. final UnresolvedDelta n = c.next;
  520. c.next = tail;
  521. tail = c;
  522. c = n;
  523. }
  524. return tail;
  525. }
  526. private UnresolvedDelta firstChildOf(PackedObjectInfo oe) {
  527. UnresolvedDelta a = reverse(removeBaseById(oe));
  528. UnresolvedDelta b = reverse(baseByPos.remove(oe.getOffset()));
  529. if (a == null)
  530. return b;
  531. if (b == null)
  532. return a;
  533. UnresolvedDelta first = null;
  534. UnresolvedDelta last = null;
  535. while (a != null || b != null) {
  536. UnresolvedDelta curr;
  537. if (b == null || (a != null && a.position < b.position)) {
  538. curr = a;
  539. a = a.next;
  540. } else {
  541. curr = b;
  542. b = b.next;
  543. }
  544. if (last != null)
  545. last.next = curr;
  546. else
  547. first = curr;
  548. last = curr;
  549. curr.next = null;
  550. }
  551. return first;
  552. }
  553. private void fixThinPack(final ProgressMonitor progress) throws IOException {
  554. growEntries();
  555. if (needBaseObjectIds)
  556. baseObjectIds = new ObjectIdSubclassMap<ObjectId>();
  557. packDigest.reset();
  558. originalEOF = packOut.length() - 20;
  559. final Deflater def = new Deflater(Deflater.DEFAULT_COMPRESSION, false);
  560. final List<DeltaChain> missing = new ArrayList<DeltaChain>(64);
  561. long end = originalEOF;
  562. for (final DeltaChain baseId : baseById) {
  563. if (baseId.head == null)
  564. continue;
  565. if (needBaseObjectIds)
  566. baseObjectIds.add(baseId);
  567. final ObjectLoader ldr;
  568. try {
  569. ldr = readCurs.open(baseId);
  570. } catch (MissingObjectException notFound) {
  571. missing.add(baseId);
  572. continue;
  573. }
  574. final DeltaVisit visit = new DeltaVisit();
  575. visit.data = ldr.getCachedBytes(Integer.MAX_VALUE);
  576. final int typeCode = ldr.getType();
  577. final PackedObjectInfo oe;
  578. crc.reset();
  579. packOut.seek(end);
  580. writeWhole(def, typeCode, visit.data);
  581. oe = new PackedObjectInfo(end, (int) crc.getValue(), baseId);
  582. entries[entryCount++] = oe;
  583. end = packOut.getFilePointer();
  584. visit.nextChild = firstChildOf(oe);
  585. resolveDeltas(visit.next(), typeCode);
  586. if (progress.isCancelled())
  587. throw new IOException(JGitText.get().downloadCancelledDuringIndexing);
  588. }
  589. def.end();
  590. for (final DeltaChain base : missing) {
  591. if (base.head != null)
  592. throw new MissingObjectException(base, "delta base");
  593. }
  594. if (end - originalEOF < 20) {
  595. // Ugly corner case; if what we appended on to complete deltas
  596. // doesn't completely cover the SHA-1 we have to truncate off
  597. // we need to shorten the file, otherwise we will include part
  598. // of the old footer as object content.
  599. packOut.setLength(end);
  600. }
  601. fixHeaderFooter(packcsum, packDigest.digest());
  602. }
  603. private void writeWhole(final Deflater def, final int typeCode,
  604. final byte[] data) throws IOException {
  605. int sz = data.length;
  606. int hdrlen = 0;
  607. buf[hdrlen++] = (byte) ((typeCode << 4) | sz & 15);
  608. sz >>>= 4;
  609. while (sz > 0) {
  610. buf[hdrlen - 1] |= 0x80;
  611. buf[hdrlen++] = (byte) (sz & 0x7f);
  612. sz >>>= 7;
  613. }
  614. packDigest.update(buf, 0, hdrlen);
  615. crc.update(buf, 0, hdrlen);
  616. packOut.write(buf, 0, hdrlen);
  617. def.reset();
  618. def.setInput(data);
  619. def.finish();
  620. while (!def.finished()) {
  621. final int datlen = def.deflate(buf);
  622. packDigest.update(buf, 0, datlen);
  623. crc.update(buf, 0, datlen);
  624. packOut.write(buf, 0, datlen);
  625. }
  626. }
  627. private void fixHeaderFooter(final byte[] origcsum, final byte[] tailcsum)
  628. throws IOException {
  629. final MessageDigest origDigest = Constants.newMessageDigest();
  630. final MessageDigest tailDigest = Constants.newMessageDigest();
  631. long origRemaining = originalEOF;
  632. packOut.seek(0);
  633. bAvail = 0;
  634. bOffset = 0;
  635. fill(Source.FILE, 12);
  636. {
  637. final int origCnt = (int) Math.min(bAvail, origRemaining);
  638. origDigest.update(buf, 0, origCnt);
  639. origRemaining -= origCnt;
  640. if (origRemaining == 0)
  641. tailDigest.update(buf, origCnt, bAvail - origCnt);
  642. }
  643. NB.encodeInt32(buf, 8, entryCount);
  644. packOut.seek(0);
  645. packOut.write(buf, 0, 12);
  646. packOut.seek(bAvail);
  647. packDigest.reset();
  648. packDigest.update(buf, 0, bAvail);
  649. for (;;) {
  650. final int n = packOut.read(buf);
  651. if (n < 0)
  652. break;
  653. if (origRemaining != 0) {
  654. final int origCnt = (int) Math.min(n, origRemaining);
  655. origDigest.update(buf, 0, origCnt);
  656. origRemaining -= origCnt;
  657. if (origRemaining == 0)
  658. tailDigest.update(buf, origCnt, n - origCnt);
  659. } else
  660. tailDigest.update(buf, 0, n);
  661. packDigest.update(buf, 0, n);
  662. }
  663. if (!Arrays.equals(origDigest.digest(), origcsum)
  664. || !Arrays.equals(tailDigest.digest(), tailcsum))
  665. throw new IOException(JGitText.get().packCorruptedWhileWritingToFilesystem);
  666. packcsum = packDigest.digest();
  667. packOut.write(packcsum);
  668. }
  669. private void growEntries() {
  670. final PackedObjectInfo[] ne;
  671. ne = new PackedObjectInfo[(int) objectCount + baseById.size()];
  672. System.arraycopy(entries, 0, ne, 0, entryCount);
  673. entries = ne;
  674. }
  675. private void writeIdx() throws IOException {
  676. Arrays.sort(entries, 0, entryCount);
  677. List<PackedObjectInfo> list = Arrays.asList(entries);
  678. if (entryCount < entries.length)
  679. list = list.subList(0, entryCount);
  680. final FileOutputStream os = new FileOutputStream(dstIdx);
  681. try {
  682. final PackIndexWriter iw;
  683. if (outputVersion <= 0)
  684. iw = PackIndexWriter.createOldestPossible(os, list);
  685. else
  686. iw = PackIndexWriter.createVersion(os, outputVersion);
  687. iw.write(list, packcsum);
  688. os.getChannel().force(true);
  689. } finally {
  690. os.close();
  691. }
  692. }
  693. private void readPackHeader() throws IOException {
  694. final int hdrln = Constants.PACK_SIGNATURE.length + 4 + 4;
  695. final int p = fill(Source.INPUT, hdrln);
  696. for (int k = 0; k < Constants.PACK_SIGNATURE.length; k++)
  697. if (buf[p + k] != Constants.PACK_SIGNATURE[k])
  698. throw new IOException(JGitText.get().notAPACKFile);
  699. final long vers = NB.decodeUInt32(buf, p + 4);
  700. if (vers != 2 && vers != 3)
  701. throw new IOException(MessageFormat.format(JGitText.get().unsupportedPackVersion, vers));
  702. objectCount = NB.decodeUInt32(buf, p + 8);
  703. use(hdrln);
  704. }
  705. private void readPackFooter() throws IOException {
  706. sync();
  707. final byte[] cmpcsum = packDigest.digest();
  708. final int c = fill(Source.INPUT, 20);
  709. packcsum = new byte[20];
  710. System.arraycopy(buf, c, packcsum, 0, 20);
  711. use(20);
  712. if (packOut != null)
  713. packOut.write(packcsum);
  714. if (!Arrays.equals(cmpcsum, packcsum))
  715. throw new CorruptObjectException(JGitText.get().corruptObjectPackfileChecksumIncorrect);
  716. }
  717. // Cleanup all resources associated with our input parsing.
  718. private void endInput() {
  719. in = null;
  720. }
  721. // Read one entire object or delta from the input.
  722. private void indexOneObject() throws IOException {
  723. final long pos = position();
  724. crc.reset();
  725. int c = readFrom(Source.INPUT);
  726. final int typeCode = (c >> 4) & 7;
  727. long sz = c & 15;
  728. int shift = 4;
  729. while ((c & 0x80) != 0) {
  730. c = readFrom(Source.INPUT);
  731. sz += (c & 0x7f) << shift;
  732. shift += 7;
  733. }
  734. switch (typeCode) {
  735. case Constants.OBJ_COMMIT:
  736. case Constants.OBJ_TREE:
  737. case Constants.OBJ_BLOB:
  738. case Constants.OBJ_TAG:
  739. whole(typeCode, pos, sz);
  740. break;
  741. case Constants.OBJ_OFS_DELTA: {
  742. c = readFrom(Source.INPUT);
  743. long ofs = c & 127;
  744. while ((c & 128) != 0) {
  745. ofs += 1;
  746. c = readFrom(Source.INPUT);
  747. ofs <<= 7;
  748. ofs += (c & 127);
  749. }
  750. final long base = pos - ofs;
  751. final UnresolvedDelta n;
  752. inflateAndSkip(Source.INPUT, sz);
  753. n = new UnresolvedDelta(pos, (int) crc.getValue());
  754. n.next = baseByPos.put(base, n);
  755. deltaCount++;
  756. break;
  757. }
  758. case Constants.OBJ_REF_DELTA: {
  759. c = fill(Source.INPUT, 20);
  760. crc.update(buf, c, 20);
  761. final ObjectId base = ObjectId.fromRaw(buf, c);
  762. use(20);
  763. DeltaChain r = baseById.get(base);
  764. if (r == null) {
  765. r = new DeltaChain(base);
  766. baseById.add(r);
  767. }
  768. inflateAndSkip(Source.INPUT, sz);
  769. r.add(new UnresolvedDelta(pos, (int) crc.getValue()));
  770. deltaCount++;
  771. break;
  772. }
  773. default:
  774. throw new IOException(MessageFormat.format(JGitText.get().unknownObjectType, typeCode));
  775. }
  776. }
  777. private void whole(final int type, final long pos, final long sz)
  778. throws IOException {
  779. objectDigest.update(Constants.encodedTypeString(type));
  780. objectDigest.update((byte) ' ');
  781. objectDigest.update(Constants.encodeASCII(sz));
  782. objectDigest.update((byte) 0);
  783. boolean checkContentLater = false;
  784. if (type == Constants.OBJ_BLOB) {
  785. InputStream inf = inflate(Source.INPUT, sz);
  786. long cnt = 0;
  787. while (cnt < sz) {
  788. int r = inf.read(readBuffer);
  789. if (r <= 0)
  790. break;
  791. objectDigest.update(readBuffer, 0, r);
  792. cnt += r;
  793. }
  794. inf.close();
  795. tempObjectId.fromRaw(objectDigest.digest(), 0);
  796. checkContentLater = readCurs.has(tempObjectId);
  797. } else {
  798. final byte[] data = inflateAndReturn(Source.INPUT, sz);
  799. objectDigest.update(data);
  800. tempObjectId.fromRaw(objectDigest.digest(), 0);
  801. verifySafeObject(tempObjectId, type, data);
  802. }
  803. final int crc32 = (int) crc.getValue();
  804. PackedObjectInfo obj = new PackedObjectInfo(pos, crc32, tempObjectId);
  805. addObjectAndTrack(obj);
  806. if (checkContentLater)
  807. deferredCheckBlobs.add(obj);
  808. }
  809. private void verifySafeObject(final AnyObjectId id, final int type,
  810. final byte[] data) throws IOException {
  811. if (objCheck != null) {
  812. try {
  813. objCheck.check(type, data);
  814. } catch (CorruptObjectException e) {
  815. throw new IOException(MessageFormat.format(JGitText.get().invalidObject
  816. , Constants.typeString(type) , id.name() , e.getMessage()));
  817. }
  818. }
  819. try {
  820. final ObjectLoader ldr = readCurs.open(id, type);
  821. final byte[] existingData = ldr.getCachedBytes(data.length);
  822. if (!Arrays.equals(data, existingData)) {
  823. throw new IOException(MessageFormat.format(JGitText.get().collisionOn, id.name()));
  824. }
  825. } catch (MissingObjectException notLocal) {
  826. // This is OK, we don't have a copy of the object locally
  827. // but the API throws when we try to read it as usually its
  828. // an error to read something that doesn't exist.
  829. }
  830. }
  831. private void doDeferredCheckBlobs() throws IOException {
  832. final byte[] curBuffer = new byte[readBuffer.length];
  833. for (PackedObjectInfo obj : deferredCheckBlobs) {
  834. position(obj.getOffset());
  835. int c = readFrom(Source.FILE);
  836. final int type = (c >> 4) & 7;
  837. long sz = c & 15;
  838. int shift = 4;
  839. while ((c & 0x80) != 0) {
  840. c = readFrom(Source.FILE);
  841. sz += (c & 0x7f) << shift;
  842. shift += 7;
  843. }
  844. if (type != Constants.OBJ_BLOB)
  845. throw new IOException(MessageFormat.format(
  846. JGitText.get().unknownObjectType, type));
  847. ObjectStream cur = readCurs.open(obj, type).openStream();
  848. try {
  849. if (cur.getSize() != sz)
  850. throw new IOException(MessageFormat.format(
  851. JGitText.get().collisionOn, obj.name()));
  852. InputStream pck = inflate(Source.FILE, sz);
  853. while (0 < sz) {
  854. int n = (int) Math.min(readBuffer.length, sz);
  855. IO.readFully(cur, curBuffer, 0, n);
  856. IO.readFully(pck, readBuffer, 0, n);
  857. for (int i = 0; i < n; i++) {
  858. if (curBuffer[i] != readBuffer[i])
  859. throw new IOException(MessageFormat.format(JGitText
  860. .get().collisionOn, obj.name()));
  861. }
  862. sz -= n;
  863. }
  864. pck.close();
  865. } finally {
  866. cur.close();
  867. }
  868. }
  869. }
  870. // Current position of {@link #bOffset} within the entire file.
  871. private long position() {
  872. return bBase + bOffset;
  873. }
  874. private void position(final long pos) throws IOException {
  875. packOut.seek(pos);
  876. bBase = pos;
  877. bOffset = 0;
  878. bAvail = 0;
  879. }
  880. // Consume exactly one byte from the buffer and return it.
  881. private int readFrom(final Source src) throws IOException {
  882. if (bAvail == 0)
  883. fill(src, 1);
  884. bAvail--;
  885. final int b = buf[bOffset++] & 0xff;
  886. crc.update(b);
  887. return b;
  888. }
  889. // Consume cnt bytes from the buffer.
  890. private void use(final int cnt) {
  891. bOffset += cnt;
  892. bAvail -= cnt;
  893. }
  894. // Ensure at least need bytes are available in in {@link #buf}.
  895. private int fill(final Source src, final int need) throws IOException {
  896. while (bAvail < need) {
  897. int next = bOffset + bAvail;
  898. int free = buf.length - next;
  899. if (free + bAvail < need) {
  900. switch(src){
  901. case INPUT:
  902. sync();
  903. break;
  904. case FILE:
  905. if (bAvail > 0)
  906. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  907. bOffset = 0;
  908. break;
  909. }
  910. next = bAvail;
  911. free = buf.length - next;
  912. }
  913. switch(src){
  914. case INPUT:
  915. next = in.read(buf, next, free);
  916. break;
  917. case FILE:
  918. next = packOut.read(buf, next, free);
  919. break;
  920. }
  921. if (next <= 0)
  922. throw new EOFException(JGitText.get().packfileIsTruncated);
  923. bAvail += next;
  924. }
  925. return bOffset;
  926. }
  927. // Store consumed bytes in {@link #buf} up to {@link #bOffset}.
  928. private void sync() throws IOException {
  929. packDigest.update(buf, 0, bOffset);
  930. if (packOut != null)
  931. packOut.write(buf, 0, bOffset);
  932. if (bAvail > 0)
  933. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  934. bBase += bOffset;
  935. bOffset = 0;
  936. }
  937. private void inflateAndSkip(final Source src, final long inflatedSize)
  938. throws IOException {
  939. final InputStream inf = inflate(src, inflatedSize);
  940. IO.skipFully(inf, inflatedSize);
  941. inf.close();
  942. }
  943. private byte[] inflateAndReturn(final Source src, final long inflatedSize)
  944. throws IOException {
  945. final byte[] dst = new byte[(int) inflatedSize];
  946. final InputStream inf = inflate(src, inflatedSize);
  947. IO.readFully(inf, dst, 0, dst.length);
  948. inf.close();
  949. return dst;
  950. }
  951. private InputStream inflate(final Source src, final long inflatedSize)
  952. throws IOException {
  953. inflater.open(src, inflatedSize);
  954. return inflater;
  955. }
  956. private static class DeltaChain extends ObjectId {
  957. UnresolvedDelta head;
  958. DeltaChain(final AnyObjectId id) {
  959. super(id);
  960. }
  961. UnresolvedDelta remove() {
  962. final UnresolvedDelta r = head;
  963. if (r != null)
  964. head = null;
  965. return r;
  966. }
  967. void add(final UnresolvedDelta d) {
  968. d.next = head;
  969. head = d;
  970. }
  971. }
  972. private static class UnresolvedDelta {
  973. final long position;
  974. final int crc;
  975. UnresolvedDelta next;
  976. UnresolvedDelta(final long headerOffset, final int crc32) {
  977. position = headerOffset;
  978. crc = crc32;
  979. }
  980. }
  981. private static class DeltaVisit {
  982. final UnresolvedDelta delta;
  983. byte[] data;
  984. DeltaVisit parent;
  985. UnresolvedDelta nextChild;
  986. DeltaVisit() {
  987. this.delta = null; // At the root of the stack we have a base.
  988. }
  989. DeltaVisit(DeltaVisit parent) {
  990. this.parent = parent;
  991. this.delta = parent.nextChild;
  992. parent.nextChild = delta.next;
  993. }
  994. DeltaVisit next() {
  995. // If our parent has no more children, discard it.
  996. if (parent != null && parent.nextChild == null) {
  997. parent.data = null;
  998. parent = parent.parent;
  999. }
  1000. if (nextChild != null)
  1001. return new DeltaVisit(this);
  1002. // If we have no child ourselves, our parent must (if it exists),
  1003. // due to the discard rule above. With no parent, we are done.
  1004. if (parent != null)
  1005. return new DeltaVisit(parent);
  1006. return null;
  1007. }
  1008. }
  1009. /**
  1010. * Rename the pack to it's final name and location and open it.
  1011. * <p>
  1012. * If the call completes successfully the repository this IndexPack instance
  1013. * was created with will have the objects in the pack available for reading
  1014. * and use, without needing to scan for packs.
  1015. *
  1016. * @throws IOException
  1017. * The pack could not be inserted into the repository's objects
  1018. * directory. The pack no longer exists on disk, as it was
  1019. * removed prior to throwing the exception to the caller.
  1020. */
  1021. public void renameAndOpenPack() throws IOException {
  1022. renameAndOpenPack(null);
  1023. }
  1024. /**
  1025. * Rename the pack to it's final name and location and open it.
  1026. * <p>
  1027. * If the call completes successfully the repository this IndexPack instance
  1028. * was created with will have the objects in the pack available for reading
  1029. * and use, without needing to scan for packs.
  1030. *
  1031. * @param lockMessage
  1032. * message to place in the pack-*.keep file. If null, no lock
  1033. * will be created, and this method returns null.
  1034. * @return the pack lock object, if lockMessage is not null.
  1035. * @throws IOException
  1036. * The pack could not be inserted into the repository's objects
  1037. * directory. The pack no longer exists on disk, as it was
  1038. * removed prior to throwing the exception to the caller.
  1039. */
  1040. public PackLock renameAndOpenPack(final String lockMessage)
  1041. throws IOException {
  1042. if (!keepEmpty && entryCount == 0) {
  1043. cleanupTemporaryFiles();
  1044. return null;
  1045. }
  1046. final MessageDigest d = Constants.newMessageDigest();
  1047. final byte[] oeBytes = new byte[Constants.OBJECT_ID_LENGTH];
  1048. for (int i = 0; i < entryCount; i++) {
  1049. final PackedObjectInfo oe = entries[i];
  1050. oe.copyRawTo(oeBytes, 0);
  1051. d.update(oeBytes);
  1052. }
  1053. final String name = ObjectId.fromRaw(d.digest()).name();
  1054. final File packDir = new File(repo.getObjectsDirectory(), "pack");
  1055. final File finalPack = new File(packDir, "pack-" + name + ".pack");
  1056. final File finalIdx = new File(packDir, "pack-" + name + ".idx");
  1057. final PackLock keep = new PackLock(finalPack, repo.getFS());
  1058. if (!packDir.exists() && !packDir.mkdir() && !packDir.exists()) {
  1059. // The objects/pack directory isn't present, and we are unable
  1060. // to create it. There is no way to move this pack in.
  1061. //
  1062. cleanupTemporaryFiles();
  1063. throw new IOException(MessageFormat.format(JGitText.get().cannotCreateDirectory, packDir.getAbsolutePath()));
  1064. }
  1065. if (finalPack.exists()) {
  1066. // If the pack is already present we should never replace it.
  1067. //
  1068. cleanupTemporaryFiles();
  1069. return null;
  1070. }
  1071. if (lockMessage != null) {
  1072. // If we have a reason to create a keep file for this pack, do
  1073. // so, or fail fast and don't put the pack in place.
  1074. //
  1075. try {
  1076. if (!keep.lock(lockMessage))
  1077. throw new IOException(MessageFormat.format(JGitText.get().cannotLockPackIn, finalPack));
  1078. } catch (IOException e) {
  1079. cleanupTemporaryFiles();
  1080. throw e;
  1081. }
  1082. }
  1083. if (!dstPack.renameTo(finalPack)) {
  1084. cleanupTemporaryFiles();
  1085. keep.unlock();
  1086. throw new IOException(MessageFormat.format(JGitText.get().cannotMovePackTo, finalPack));
  1087. }
  1088. if (!dstIdx.renameTo(finalIdx)) {
  1089. cleanupTemporaryFiles();
  1090. keep.unlock();
  1091. if (!finalPack.delete())
  1092. finalPack.deleteOnExit();
  1093. throw new IOException(MessageFormat.format(JGitText.get().cannotMoveIndexTo, finalIdx));
  1094. }
  1095. try {
  1096. repo.openPack(finalPack, finalIdx);
  1097. } catch (IOException err) {
  1098. keep.unlock();
  1099. FileUtils.delete(finalPack);
  1100. FileUtils.delete(finalIdx);
  1101. throw err;
  1102. }
  1103. return lockMessage != null ? keep : null;
  1104. }
  1105. private void cleanupTemporaryFiles() {
  1106. if (!dstIdx.delete())
  1107. dstIdx.deleteOnExit();
  1108. if (!dstPack.delete())
  1109. dstPack.deleteOnExit();
  1110. }
  1111. private void addObjectAndTrack(PackedObjectInfo oe) {
  1112. entries[entryCount++] = oe;
  1113. if (needNewObjectIds())
  1114. newObjectIds.add(oe);
  1115. }
  1116. private class InflaterStream extends InputStream {
  1117. private final Inflater inf;
  1118. private final byte[] skipBuffer;
  1119. private Source src;
  1120. private long expectedSize;
  1121. private long actualSize;
  1122. private int p;
  1123. InflaterStream() {
  1124. inf = InflaterCache.get();
  1125. skipBuffer = new byte[512];
  1126. }
  1127. void release() {
  1128. inf.reset();
  1129. InflaterCache.release(inf);
  1130. }
  1131. void open(Source source, long inflatedSize) throws IOException {
  1132. src = source;
  1133. expectedSize = inflatedSize;
  1134. actualSize = 0;
  1135. p = fill(src, 24);
  1136. inf.setInput(buf, p, bAvail);
  1137. }
  1138. @Override
  1139. public long skip(long toSkip) throws IOException {
  1140. long n = 0;
  1141. while (n < toSkip) {
  1142. final int cnt = (int) Math.min(skipBuffer.length, toSkip - n);
  1143. final int r = read(skipBuffer, 0, cnt);
  1144. if (r <= 0)
  1145. break;
  1146. n += r;
  1147. }
  1148. return n;
  1149. }
  1150. @Override
  1151. public int read() throws IOException {
  1152. int n = read(skipBuffer, 0, 1);
  1153. return n == 1 ? skipBuffer[0] & 0xff : -1;
  1154. }
  1155. @Override
  1156. public int read(byte[] dst, int pos, int cnt) throws IOException {
  1157. try {
  1158. int n = 0;
  1159. while (n < cnt) {
  1160. int r = inf.inflate(dst, pos + n, cnt - n);
  1161. if (r == 0) {
  1162. if (inf.finished())
  1163. break;
  1164. if (inf.needsInput()) {
  1165. crc.update(buf, p, bAvail);
  1166. use(bAvail);
  1167. p = fill(src, 24);
  1168. inf.setInput(buf, p, bAvail);
  1169. } else {
  1170. throw new CorruptObjectException(
  1171. MessageFormat
  1172. .format(
  1173. JGitText.get().packfileCorruptionDetected,
  1174. JGitText.get().unknownZlibError));
  1175. }
  1176. } else {
  1177. n += r;
  1178. }
  1179. }
  1180. actualSize += n;
  1181. return 0 < n ? n : -1;
  1182. } catch (DataFormatException dfe) {
  1183. throw new CorruptObjectException(MessageFormat.format(JGitText
  1184. .get().packfileCorruptionDetected, dfe.getMessage()));
  1185. }
  1186. }
  1187. @Override
  1188. public void close() throws IOException {
  1189. // We need to read here to enter the loop above and pump the
  1190. // trailing checksum into the Inflater. It should return -1 as the
  1191. // caller was supposed to consume all content.
  1192. //
  1193. if (read(skipBuffer) != -1 || actualSize != expectedSize) {
  1194. throw new CorruptObjectException(MessageFormat.format(JGitText
  1195. .get().packfileCorruptionDetected,
  1196. JGitText.get().wrongDecompressedLength));
  1197. }
  1198. int used = bAvail - inf.getRemaining();
  1199. if (0 < used) {
  1200. crc.update(buf, p, used);
  1201. use(used);
  1202. }
  1203. inf.reset();
  1204. }
  1205. }
  1206. }