PackParser.java

  1. /*
  2.  * Copyright (C) 2008-2011, Google Inc.
  3.  * Copyright (C) 2007-2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4.  * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
  5.  *
  6.  * This program and the accompanying materials are made available under the
  7.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  8.  * https://www.eclipse.org/org/documents/edl-v10.php.
  9.  *
  10.  * SPDX-License-Identifier: BSD-3-Clause
  11.  */

  12. package org.eclipse.jgit.transport;

  13. import java.io.EOFException;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.security.MessageDigest;
  17. import java.text.MessageFormat;
  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Comparator;
  21. import java.util.List;
  22. import java.util.concurrent.TimeUnit;
  23. import java.util.zip.DataFormatException;
  24. import java.util.zip.Inflater;

  25. import org.eclipse.jgit.errors.CorruptObjectException;
  26. import org.eclipse.jgit.errors.MissingObjectException;
  27. import org.eclipse.jgit.errors.TooLargeObjectInPackException;
  28. import org.eclipse.jgit.internal.JGitText;
  29. import org.eclipse.jgit.internal.storage.pack.BinaryDelta;
  30. import org.eclipse.jgit.lib.AnyObjectId;
  31. import org.eclipse.jgit.lib.BatchingProgressMonitor;
  32. import org.eclipse.jgit.lib.BlobObjectChecker;
  33. import org.eclipse.jgit.lib.Constants;
  34. import org.eclipse.jgit.lib.InflaterCache;
  35. import org.eclipse.jgit.lib.MutableObjectId;
  36. import org.eclipse.jgit.lib.NullProgressMonitor;
  37. import org.eclipse.jgit.lib.ObjectChecker;
  38. import org.eclipse.jgit.lib.ObjectDatabase;
  39. import org.eclipse.jgit.lib.ObjectId;
  40. import org.eclipse.jgit.lib.ObjectIdOwnerMap;
  41. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  42. import org.eclipse.jgit.lib.ObjectLoader;
  43. import org.eclipse.jgit.lib.ObjectReader;
  44. import org.eclipse.jgit.lib.ObjectStream;
  45. import org.eclipse.jgit.lib.ProgressMonitor;
  46. import org.eclipse.jgit.util.BlockList;
  47. import org.eclipse.jgit.util.IO;
  48. import org.eclipse.jgit.util.LongMap;
  49. import org.eclipse.jgit.util.NB;
  50. import org.eclipse.jgit.util.sha1.SHA1;

  51. /**
  52.  * Parses a pack stream and imports it for an
  53.  * {@link org.eclipse.jgit.lib.ObjectInserter}.
  54.  * <p>
  55.  * Applications can acquire an instance of a parser from ObjectInserter's
  56.  * {@link org.eclipse.jgit.lib.ObjectInserter#newPackParser(InputStream)}
  57.  * method.
  58.  * <p>
  59.  * Implementations of {@link org.eclipse.jgit.lib.ObjectInserter} should
  60.  * subclass this type and provide their own logic for the various {@code on*()}
  61.  * event methods declared to be abstract.
  62.  */
  63. public abstract class PackParser {
  64.     /** Size of the internal stream buffer. */
  65.     private static final int BUFFER_SIZE = 8192;

  66.     /** Location data is being obtained from. */
  67.     public enum Source {
  68.         /** Data is read from the incoming stream. */
  69.         INPUT,

  70.         /** Data is read back from the database's buffers. */
  71.         DATABASE;
  72.     }

  73.     /** Object database used for loading existing objects. */
  74.     private final ObjectDatabase objectDatabase;

  75.     private InflaterStream inflater;

  76.     private byte[] tempBuffer;

  77.     private byte[] hdrBuf;

  78.     private final SHA1 objectHasher = SHA1.newInstance();
  79.     private final MutableObjectId tempObjectId;

  80.     private InputStream in;

  81.     byte[] buf;

  82.     /** Position in the input stream of {@code buf[0]}. */
  83.     private long bBase;

  84.     private int bOffset;

  85.     int bAvail;

  86.     private ObjectChecker objCheck;

  87.     private boolean allowThin;

  88.     private boolean checkObjectCollisions;

  89.     private boolean needBaseObjectIds;

  90.     private boolean checkEofAfterPackFooter;

  91.     private boolean expectDataAfterPackFooter;

  92.     private long expectedObjectCount;

  93.     private PackedObjectInfo[] entries;

  94.     /**
  95.      * Every object contained within the incoming pack.
  96.      * <p>
  97.      * This is a subset of {@link #entries}, as thin packs can add additional
  98.      * objects to {@code entries} by copying already existing objects from the
  99.      * repository onto the end of the thin pack to make it self-contained.
  100.      */
  101.     private ObjectIdSubclassMap<ObjectId> newObjectIds;

  102.     private int deltaCount;

  103.     private int entryCount;

  104.     private ObjectIdOwnerMap<DeltaChain> baseById;

  105.     /**
  106.      * Objects referenced by their name from deltas, that aren't in this pack.
  107.      * <p>
  108.      * This is the set of objects that were copied onto the end of this pack to
  109.      * make it complete. These objects were not transmitted by the remote peer,
  110.      * but instead were assumed to already exist in the local repository.
  111.      */
  112.     private ObjectIdSubclassMap<ObjectId> baseObjectIds;

  113.     private LongMap<UnresolvedDelta> baseByPos;

  114.     /** Objects need to be double-checked for collision after indexing. */
  115.     private BlockList<PackedObjectInfo> collisionCheckObjs;

  116.     private MessageDigest packDigest;

  117.     private ObjectReader readCurs;

  118.     /** Message to protect the pack data from garbage collection. */
  119.     private String lockMessage;

  120.     /** Git object size limit */
  121.     private long maxObjectSizeLimit;

  122.     private final ReceivedPackStatistics.Builder stats =
  123.             new ReceivedPackStatistics.Builder();

  124.     /**
  125.      * Initialize a pack parser.
  126.      *
  127.      * @param odb
  128.      *            database the parser will write its objects into.
  129.      * @param src
  130.      *            the stream the parser will read.
  131.      */
  132.     protected PackParser(ObjectDatabase odb, InputStream src) {
  133.         objectDatabase = odb.newCachedDatabase();
  134.         in = src;

  135.         inflater = new InflaterStream();
  136.         readCurs = objectDatabase.newReader();
  137.         buf = new byte[BUFFER_SIZE];
  138.         tempBuffer = new byte[BUFFER_SIZE];
  139.         hdrBuf = new byte[64];
  140.         tempObjectId = new MutableObjectId();
  141.         packDigest = Constants.newMessageDigest();
  142.         checkObjectCollisions = true;
  143.     }

  144.     /**
  145.      * Whether a thin pack (missing base objects) is permitted.
  146.      *
  147.      * @return {@code true} if a thin pack (missing base objects) is permitted.
  148.      */
  149.     public boolean isAllowThin() {
  150.         return allowThin;
  151.     }

  152.     /**
  153.      * Configure this index pack instance to allow a thin pack.
  154.      * <p>
  155.      * Thin packs are sometimes used during network transfers to allow a delta
  156.      * to be sent without a base object. Such packs are not permitted on disk.
  157.      *
  158.      * @param allow
  159.      *            true to enable a thin pack.
  160.      */
  161.     public void setAllowThin(boolean allow) {
  162.         allowThin = allow;
  163.     }

  164.     /**
  165.      * Whether received objects are verified to prevent collisions.
  166.      *
  167.      * @return if true received objects are verified to prevent collisions.
  168.      * @since 4.1
  169.      */
  170.     protected boolean isCheckObjectCollisions() {
  171.         return checkObjectCollisions;
  172.     }

  173.     /**
  174.      * Enable checking for collisions with existing objects.
  175.      * <p>
  176.      * By default PackParser looks for each received object in the repository.
  177.      * If the object already exists, the existing object is compared
  178.      * byte-for-byte with the newly received copy to ensure they are identical.
  179.      * The receive is aborted with an exception if any byte differs. This check
  180.      * is necessary to prevent an evil attacker from supplying a replacement
  181.      * object into this repository in the event that a discovery enabling SHA-1
  182.      * collisions is made.
  183.      * <p>
  184.      * This check may be very costly to perform, and some repositories may have
  185.      * other ways to segregate newly received object data. The check is enabled
  186.      * by default, but can be explicitly disabled if the implementation can
  187.      * provide the same guarantee, or is willing to accept the risks associated
  188.      * with bypassing the check.
  189.      *
  190.      * @param check
  191.      *            true to enable collision checking (strongly encouraged).
  192.      * @since 4.1
  193.      */
  194.     protected void setCheckObjectCollisions(boolean check) {
  195.         checkObjectCollisions = check;
  196.     }

  197.     /**
  198.      * Configure this index pack instance to keep track of new objects.
  199.      * <p>
  200.      * By default an index pack doesn't save the new objects that were created
  201.      * when it was instantiated. Setting this flag to {@code true} allows the
  202.      * caller to use {@link #getNewObjectIds()} to retrieve that list.
  203.      *
  204.      * @param b
  205.      *            {@code true} to enable keeping track of new objects.
  206.      */
  207.     public void setNeedNewObjectIds(boolean b) {
  208.         if (b)
  209.             newObjectIds = new ObjectIdSubclassMap<>();
  210.         else
  211.             newObjectIds = null;
  212.     }

  213.     private boolean needNewObjectIds() {
  214.         return newObjectIds != null;
  215.     }

  216.     /**
  217.      * Configure this index pack instance to keep track of the objects assumed
  218.      * for delta bases.
  219.      * <p>
  220.      * By default an index pack doesn't save the objects that were used as delta
  221.      * bases. Setting this flag to {@code true} will allow the caller to use
  222.      * {@link #getBaseObjectIds()} to retrieve that list.
  223.      *
  224.      * @param b
  225.      *            {@code true} to enable keeping track of delta bases.
  226.      */
  227.     public void setNeedBaseObjectIds(boolean b) {
  228.         this.needBaseObjectIds = b;
  229.     }

  230.     /**
  231.      * Whether the EOF should be read from the input after the footer.
  232.      *
  233.      * @return true if the EOF should be read from the input after the footer.
  234.      */
  235.     public boolean isCheckEofAfterPackFooter() {
  236.         return checkEofAfterPackFooter;
  237.     }

  238.     /**
  239.      * Ensure EOF is read from the input stream after the footer.
  240.      *
  241.      * @param b
  242.      *            true if the EOF should be read; false if it is not checked.
  243.      */
  244.     public void setCheckEofAfterPackFooter(boolean b) {
  245.         checkEofAfterPackFooter = b;
  246.     }

  247.     /**
  248.      * Whether there is data expected after the pack footer.
  249.      *
  250.      * @return true if there is data expected after the pack footer.
  251.      */
  252.     public boolean isExpectDataAfterPackFooter() {
  253.         return expectDataAfterPackFooter;
  254.     }

  255.     /**
  256.      * Set if there is additional data in InputStream after pack.
  257.      *
  258.      * @param e
  259.      *            true if there is additional data in InputStream after pack.
  260.      *            This requires the InputStream to support the mark and reset
  261.      *            functions.
  262.      */
  263.     public void setExpectDataAfterPackFooter(boolean e) {
  264.         expectDataAfterPackFooter = e;
  265.     }

  266.     /**
  267.      * Get the new objects that were sent by the user
  268.      *
  269.      * @return the new objects that were sent by the user
  270.      */
  271.     public ObjectIdSubclassMap<ObjectId> getNewObjectIds() {
  272.         if (newObjectIds != null)
  273.             return newObjectIds;
  274.         return new ObjectIdSubclassMap<>();
  275.     }

  276.     /**
  277.      * Get set of objects the incoming pack assumed for delta purposes
  278.      *
  279.      * @return set of objects the incoming pack assumed for delta purposes
  280.      */
  281.     public ObjectIdSubclassMap<ObjectId> getBaseObjectIds() {
  282.         if (baseObjectIds != null)
  283.             return baseObjectIds;
  284.         return new ObjectIdSubclassMap<>();
  285.     }

  286.     /**
  287.      * Configure the checker used to validate received objects.
  288.      * <p>
  289.      * Usually object checking isn't necessary, as Git implementations only
  290.      * create valid objects in pack files. However, additional checking may be
  291.      * useful if processing data from an untrusted source.
  292.      *
  293.      * @param oc
  294.      *            the checker instance; null to disable object checking.
  295.      */
  296.     public void setObjectChecker(ObjectChecker oc) {
  297.         objCheck = oc;
  298.     }

  299.     /**
  300.      * Configure the checker used to validate received objects.
  301.      * <p>
  302.      * Usually object checking isn't necessary, as Git implementations only
  303.      * create valid objects in pack files. However, additional checking may be
  304.      * useful if processing data from an untrusted source.
  305.      * <p>
  306.      * This is shorthand for:
  307.      *
  308.      * <pre>
  309.      * setObjectChecker(on ? new ObjectChecker() : null);
  310.      * </pre>
  311.      *
  312.      * @param on
  313.      *            true to enable the default checker; false to disable it.
  314.      */
  315.     public void setObjectChecking(boolean on) {
  316.         setObjectChecker(on ? new ObjectChecker() : null);
  317.     }

  318.     /**
  319.      * Get the message to record with the pack lock.
  320.      *
  321.      * @return the message to record with the pack lock.
  322.      */
  323.     public String getLockMessage() {
  324.         return lockMessage;
  325.     }

  326.     /**
  327.      * Set the lock message for the incoming pack data.
  328.      *
  329.      * @param msg
  330.      *            if not null, the message to associate with the incoming data
  331.      *            while it is locked to prevent garbage collection.
  332.      */
  333.     public void setLockMessage(String msg) {
  334.         lockMessage = msg;
  335.     }

  336.     /**
  337.      * Set the maximum allowed Git object size.
  338.      * <p>
  339.      * If an object is larger than the given size the pack-parsing will throw an
  340.      * exception aborting the parsing.
  341.      *
  342.      * @param limit
  343.      *            the Git object size limit. If zero then there is not limit.
  344.      */
  345.     public void setMaxObjectSizeLimit(long limit) {
  346.         maxObjectSizeLimit = limit;
  347.     }

  348.     /**
  349.      * Get the number of objects in the stream.
  350.      * <p>
  351.      * The object count is only available after {@link #parse(ProgressMonitor)}
  352.      * has returned. The count may have been increased if the stream was a thin
  353.      * pack, and missing bases objects were appending onto it by the subclass.
  354.      *
  355.      * @return number of objects parsed out of the stream.
  356.      */
  357.     public int getObjectCount() {
  358.         return entryCount;
  359.     }

  360.     /**
  361.      * Get the information about the requested object.
  362.      * <p>
  363.      * The object information is only available after
  364.      * {@link #parse(ProgressMonitor)} has returned.
  365.      *
  366.      * @param nth
  367.      *            index of the object in the stream. Must be between 0 and
  368.      *            {@link #getObjectCount()}-1.
  369.      * @return the object information.
  370.      */
  371.     public PackedObjectInfo getObject(int nth) {
  372.         return entries[nth];
  373.     }

  374.     /**
  375.      * Get all of the objects, sorted by their name.
  376.      * <p>
  377.      * The object information is only available after
  378.      * {@link #parse(ProgressMonitor)} has returned.
  379.      * <p>
  380.      * To maintain lower memory usage and good runtime performance, this method
  381.      * sorts the objects in-place and therefore impacts the ordering presented
  382.      * by {@link #getObject(int)}.
  383.      *
  384.      * @param cmp
  385.      *            comparison function, if null objects are stored by ObjectId.
  386.      * @return sorted list of objects in this pack stream.
  387.      */
  388.     public List<PackedObjectInfo> getSortedObjectList(
  389.             Comparator<PackedObjectInfo> cmp) {
  390.         Arrays.sort(entries, 0, entryCount, cmp);
  391.         List<PackedObjectInfo> list = Arrays.asList(entries);
  392.         if (entryCount < entries.length)
  393.             list = list.subList(0, entryCount);
  394.         return list;
  395.     }

  396.     /**
  397.      * Get the size of the newly created pack.
  398.      * <p>
  399.      * This will also include the pack index size if an index was created. This
  400.      * method should only be called after pack parsing is finished.
  401.      *
  402.      * @return the pack size (including the index size) or -1 if the size cannot
  403.      *         be determined
  404.      * @since 3.3
  405.      */
  406.     public long getPackSize() {
  407.         return -1;
  408.     }

  409.     /**
  410.      * Returns the statistics of the parsed pack.
  411.      * <p>
  412.      * This should only be called after pack parsing is finished.
  413.      *
  414.      * @return {@link org.eclipse.jgit.transport.ReceivedPackStatistics}
  415.      * @since 4.6
  416.      */
  417.     public ReceivedPackStatistics getReceivedPackStatistics() {
  418.         return stats.build();
  419.     }

  420.     /**
  421.      * Parse the pack stream.
  422.      *
  423.      * @param progress
  424.      *            callback to provide progress feedback during parsing. If null,
  425.      *            {@link org.eclipse.jgit.lib.NullProgressMonitor} will be used.
  426.      * @return the pack lock, if one was requested by setting
  427.      *         {@link #setLockMessage(String)}.
  428.      * @throws java.io.IOException
  429.      *             the stream is malformed, or contains corrupt objects.
  430.      * @since 6.0
  431.      */
  432.     public final PackLock parse(ProgressMonitor progress) throws IOException {
  433.         return parse(progress, progress);
  434.     }

  435.     /**
  436.      * Parse the pack stream.
  437.      *
  438.      * @param receiving
  439.      *            receives progress feedback during the initial receiving
  440.      *            objects phase. If null,
  441.      *            {@link org.eclipse.jgit.lib.NullProgressMonitor} will be used.
  442.      * @param resolving
  443.      *            receives progress feedback during the resolving objects phase.
  444.      * @return the pack lock, if one was requested by setting
  445.      *         {@link #setLockMessage(String)}.
  446.      * @throws java.io.IOException
  447.      *             the stream is malformed, or contains corrupt objects.
  448.      * @since 6.0
  449.      */
  450.     public PackLock parse(ProgressMonitor receiving, ProgressMonitor resolving)
  451.             throws IOException {
  452.         if (receiving == null)
  453.             receiving = NullProgressMonitor.INSTANCE;
  454.         if (resolving == null)
  455.             resolving = NullProgressMonitor.INSTANCE;

  456.         if (receiving == resolving)
  457.             receiving.start(2 /* tasks */);
  458.         try {
  459.             readPackHeader();

  460.             entries = new PackedObjectInfo[(int) expectedObjectCount];
  461.             baseById = new ObjectIdOwnerMap<>();
  462.             baseByPos = new LongMap<>();
  463.             collisionCheckObjs = new BlockList<>();

  464.             receiving.beginTask(JGitText.get().receivingObjects,
  465.                     (int) expectedObjectCount);
  466.             try {
  467.                 for (int done = 0; done < expectedObjectCount; done++) {
  468.                     indexOneObject();
  469.                     receiving.update(1);
  470.                     if (receiving.isCancelled())
  471.                         throw new IOException(JGitText.get().downloadCancelled);
  472.                 }
  473.                 readPackFooter();
  474.                 endInput();
  475.             } finally {
  476.                 receiving.endTask();
  477.             }

  478.             if (!collisionCheckObjs.isEmpty()) {
  479.                 checkObjectCollision();
  480.             }

  481.             if (deltaCount > 0) {
  482.                 processDeltas(resolving);
  483.             }

  484.             packDigest = null;
  485.             baseById = null;
  486.             baseByPos = null;
  487.         } finally {
  488.             try {
  489.                 if (readCurs != null)
  490.                     readCurs.close();
  491.             } finally {
  492.                 readCurs = null;
  493.             }

  494.             try {
  495.                 inflater.release();
  496.             } finally {
  497.                 inflater = null;
  498.             }
  499.         }
  500.         return null; // By default there is no locking.
  501.     }

  502.     private void processDeltas(ProgressMonitor resolving) throws IOException {
  503.         if (resolving instanceof BatchingProgressMonitor) {
  504.             ((BatchingProgressMonitor) resolving).setDelayStart(1000,
  505.                     TimeUnit.MILLISECONDS);
  506.         }
  507.         resolving.beginTask(JGitText.get().resolvingDeltas, deltaCount);
  508.         resolveDeltas(resolving);
  509.         if (entryCount < expectedObjectCount) {
  510.             if (!isAllowThin()) {
  511.                 throw new IOException(MessageFormat.format(
  512.                         JGitText.get().packHasUnresolvedDeltas,
  513.                         Long.valueOf(expectedObjectCount - entryCount)));
  514.             }

  515.             resolveDeltasWithExternalBases(resolving);

  516.             if (entryCount < expectedObjectCount) {
  517.                 throw new IOException(MessageFormat.format(
  518.                         JGitText.get().packHasUnresolvedDeltas,
  519.                         Long.valueOf(expectedObjectCount - entryCount)));
  520.             }
  521.         }
  522.         resolving.endTask();
  523.     }

  524.     private void resolveDeltas(ProgressMonitor progress)
  525.             throws IOException {
  526.         final int last = entryCount;
  527.         for (int i = 0; i < last; i++) {
  528.             resolveDeltas(entries[i], progress);
  529.             if (progress.isCancelled())
  530.                 throw new IOException(
  531.                         JGitText.get().downloadCancelledDuringIndexing);
  532.         }
  533.     }

  534.     private void resolveDeltas(final PackedObjectInfo oe,
  535.             ProgressMonitor progress) throws IOException {
  536.         UnresolvedDelta children = firstChildOf(oe);
  537.         if (children == null)
  538.             return;

  539.         DeltaVisit visit = new DeltaVisit();
  540.         visit.nextChild = children;

  541.         ObjectTypeAndSize info = openDatabase(oe, new ObjectTypeAndSize());
  542.         switch (info.type) {
  543.         case Constants.OBJ_COMMIT:
  544.         case Constants.OBJ_TREE:
  545.         case Constants.OBJ_BLOB:
  546.         case Constants.OBJ_TAG:
  547.             visit.data = inflateAndReturn(Source.DATABASE, info.size);
  548.             visit.id = oe;
  549.             break;
  550.         default:
  551.             throw new IOException(MessageFormat.format(
  552.                     JGitText.get().unknownObjectType,
  553.                     Integer.valueOf(info.type)));
  554.         }

  555.         if (!checkCRC(oe.getCRC())) {
  556.             throw new IOException(MessageFormat.format(
  557.                     JGitText.get().corruptionDetectedReReadingAt,
  558.                     Long.valueOf(oe.getOffset())));
  559.         }

  560.         resolveDeltas(visit.next(), info.type, info, progress);
  561.     }

  562.     private void resolveDeltas(DeltaVisit visit, final int type,
  563.             ObjectTypeAndSize info, ProgressMonitor progress)
  564.             throws IOException {
  565.         stats.addDeltaObject(type);
  566.         do {
  567.             progress.update(1);
  568.             info = openDatabase(visit.delta, info);
  569.             switch (info.type) {
  570.             case Constants.OBJ_OFS_DELTA:
  571.             case Constants.OBJ_REF_DELTA:
  572.                 break;

  573.             default:
  574.                 throw new IOException(MessageFormat.format(
  575.                         JGitText.get().unknownObjectType,
  576.                         Integer.valueOf(info.type)));
  577.             }

  578.             byte[] delta = inflateAndReturn(Source.DATABASE, info.size);
  579.             long finalSz = BinaryDelta.getResultSize(delta);
  580.             checkIfTooLarge(type, finalSz);

  581.             visit.data = BinaryDelta.apply(visit.parent.data, delta);
  582.             delta = null;

  583.             if (!checkCRC(visit.delta.crc))
  584.                 throw new IOException(MessageFormat.format(
  585.                         JGitText.get().corruptionDetectedReReadingAt,
  586.                         Long.valueOf(visit.delta.position)));

  587.             SHA1 objectDigest = objectHasher.reset();
  588.             objectDigest.update(Constants.encodedTypeString(type));
  589.             objectDigest.update((byte) ' ');
  590.             objectDigest.update(Constants.encodeASCII(visit.data.length));
  591.             objectDigest.update((byte) 0);
  592.             objectDigest.update(visit.data);
  593.             objectDigest.digest(tempObjectId);

  594.             verifySafeObject(tempObjectId, type, visit.data);
  595.             if (isCheckObjectCollisions() && readCurs.has(tempObjectId)) {
  596.                 checkObjectCollision(tempObjectId, type, visit.data,
  597.                         visit.delta.sizeBeforeInflating);
  598.             }

  599.             PackedObjectInfo oe;
  600.             oe = newInfo(tempObjectId, visit.delta, visit.parent.id);
  601.             oe.setFullSize(finalSz);
  602.             oe.setOffset(visit.delta.position);
  603.             oe.setType(type);
  604.             onInflatedObjectData(oe, type, visit.data);
  605.             addObjectAndTrack(oe);
  606.             visit.id = oe;

  607.             visit.nextChild = firstChildOf(oe);
  608.             visit = visit.next();
  609.         } while (visit != null);
  610.     }

  611.     private final void checkIfTooLarge(int typeCode, long size)
  612.             throws IOException {
  613.         if (0 < maxObjectSizeLimit && maxObjectSizeLimit < size) {
  614.             switch (typeCode) {
  615.             case Constants.OBJ_COMMIT:
  616.             case Constants.OBJ_TREE:
  617.             case Constants.OBJ_BLOB:
  618.             case Constants.OBJ_TAG:
  619.                 throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);

  620.             case Constants.OBJ_OFS_DELTA:
  621.             case Constants.OBJ_REF_DELTA:
  622.                 throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);

  623.             default:
  624.                 throw new IOException(MessageFormat.format(
  625.                         JGitText.get().unknownObjectType,
  626.                         Integer.valueOf(typeCode)));
  627.             }
  628.         }
  629.         if (size > Integer.MAX_VALUE - 8) {
  630.             throw new TooLargeObjectInPackException(size, Integer.MAX_VALUE - 8);
  631.         }
  632.     }

  633.     /**
  634.      * Read the header of the current object.
  635.      * <p>
  636.      * After the header has been parsed, this method automatically invokes
  637.      * {@link #onObjectHeader(Source, byte[], int, int)} to allow the
  638.      * implementation to update its internal checksums for the bytes read.
  639.      * <p>
  640.      * When this method returns the database will be positioned on the first
  641.      * byte of the deflated data stream.
  642.      *
  643.      * @param info
  644.      *            the info object to populate.
  645.      * @return {@code info}, after populating.
  646.      * @throws java.io.IOException
  647.      *             the size cannot be read.
  648.      */
  649.     protected ObjectTypeAndSize readObjectHeader(ObjectTypeAndSize info)
  650.             throws IOException {
  651.         int hdrPtr = 0;
  652.         int c = readFrom(Source.DATABASE);
  653.         hdrBuf[hdrPtr++] = (byte) c;

  654.         info.type = (c >> 4) & 7;
  655.         long sz = c & 15;
  656.         int shift = 4;
  657.         while ((c & 0x80) != 0) {
  658.             c = readFrom(Source.DATABASE);
  659.             hdrBuf[hdrPtr++] = (byte) c;
  660.             sz += ((long) (c & 0x7f)) << shift;
  661.             shift += 7;
  662.         }
  663.         info.size = sz;

  664.         switch (info.type) {
  665.         case Constants.OBJ_COMMIT:
  666.         case Constants.OBJ_TREE:
  667.         case Constants.OBJ_BLOB:
  668.         case Constants.OBJ_TAG:
  669.             onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  670.             break;

  671.         case Constants.OBJ_OFS_DELTA:
  672.             c = readFrom(Source.DATABASE);
  673.             hdrBuf[hdrPtr++] = (byte) c;
  674.             while ((c & 128) != 0) {
  675.                 c = readFrom(Source.DATABASE);
  676.                 hdrBuf[hdrPtr++] = (byte) c;
  677.             }
  678.             onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  679.             break;

  680.         case Constants.OBJ_REF_DELTA:
  681.             System.arraycopy(buf, fill(Source.DATABASE, 20), hdrBuf, hdrPtr, 20);
  682.             hdrPtr += 20;
  683.             use(20);
  684.             onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  685.             break;

  686.         default:
  687.             throw new IOException(MessageFormat.format(
  688.                     JGitText.get().unknownObjectType,
  689.                     Integer.valueOf(info.type)));
  690.         }
  691.         return info;
  692.     }

  693.     private UnresolvedDelta removeBaseById(AnyObjectId id) {
  694.         final DeltaChain d = baseById.get(id);
  695.         return d != null ? d.remove() : null;
  696.     }

  697.     private static UnresolvedDelta reverse(UnresolvedDelta c) {
  698.         UnresolvedDelta tail = null;
  699.         while (c != null) {
  700.             final UnresolvedDelta n = c.next;
  701.             c.next = tail;
  702.             tail = c;
  703.             c = n;
  704.         }
  705.         return tail;
  706.     }

  707.     private UnresolvedDelta firstChildOf(PackedObjectInfo oe) {
  708.         UnresolvedDelta a = reverse(removeBaseById(oe));
  709.         UnresolvedDelta b = reverse(baseByPos.remove(oe.getOffset()));

  710.         if (a == null)
  711.             return b;
  712.         if (b == null)
  713.             return a;

  714.         UnresolvedDelta first = null;
  715.         UnresolvedDelta last = null;
  716.         while (a != null || b != null) {
  717.             UnresolvedDelta curr;
  718.             if (b == null || (a != null && a.position < b.position)) {
  719.                 curr = a;
  720.                 a = a.next;
  721.             } else {
  722.                 curr = b;
  723.                 b = b.next;
  724.             }
  725.             if (last != null)
  726.                 last.next = curr;
  727.             else
  728.                 first = curr;
  729.             last = curr;
  730.             curr.next = null;
  731.         }
  732.         return first;
  733.     }

  734.     private void resolveDeltasWithExternalBases(ProgressMonitor progress)
  735.             throws IOException {
  736.         growEntries(baseById.size());

  737.         if (needBaseObjectIds)
  738.             baseObjectIds = new ObjectIdSubclassMap<>();

  739.         final List<DeltaChain> missing = new ArrayList<>(64);
  740.         for (DeltaChain baseId : baseById) {
  741.             if (baseId.head == null)
  742.                 continue;

  743.             if (needBaseObjectIds)
  744.                 baseObjectIds.add(baseId);

  745.             final ObjectLoader ldr;
  746.             try {
  747.                 ldr = readCurs.open(baseId);
  748.             } catch (MissingObjectException notFound) {
  749.                 missing.add(baseId);
  750.                 continue;
  751.             }

  752.             final DeltaVisit visit = new DeltaVisit();
  753.             visit.data = ldr.getCachedBytes(Integer.MAX_VALUE);
  754.             visit.id = baseId;
  755.             final int typeCode = ldr.getType();
  756.             final PackedObjectInfo oe = newInfo(baseId, null, null);
  757.             oe.setType(typeCode);
  758.             oe.setFullSize(ldr.getSize());
  759.             if (onAppendBase(typeCode, visit.data, oe))
  760.                 entries[entryCount++] = oe;
  761.             visit.nextChild = firstChildOf(oe);
  762.             resolveDeltas(visit.next(), typeCode,
  763.                     new ObjectTypeAndSize(), progress);

  764.             if (progress.isCancelled())
  765.                 throw new IOException(
  766.                         JGitText.get().downloadCancelledDuringIndexing);
  767.         }

  768.         for (DeltaChain base : missing) {
  769.             if (base.head != null)
  770.                 throw new MissingObjectException(base, "delta base"); //$NON-NLS-1$
  771.         }

  772.         onEndThinPack();
  773.     }

  774.     private void growEntries(int extraObjects) {
  775.         final PackedObjectInfo[] ne;

  776.         ne = new PackedObjectInfo[(int) expectedObjectCount + extraObjects];
  777.         System.arraycopy(entries, 0, ne, 0, entryCount);
  778.         entries = ne;
  779.     }

  780.     private void readPackHeader() throws IOException {
  781.         if (expectDataAfterPackFooter) {
  782.             if (!in.markSupported())
  783.                 throw new IOException(
  784.                         JGitText.get().inputStreamMustSupportMark);
  785.             in.mark(buf.length);
  786.         }

  787.         final int hdrln = Constants.PACK_SIGNATURE.length + 4 + 4;
  788.         final int p = fill(Source.INPUT, hdrln);
  789.         for (int k = 0; k < Constants.PACK_SIGNATURE.length; k++)
  790.             if (buf[p + k] != Constants.PACK_SIGNATURE[k])
  791.                 throw new IOException(JGitText.get().notAPACKFile);

  792.         final long vers = NB.decodeUInt32(buf, p + 4);
  793.         if (vers != 2 && vers != 3)
  794.             throw new IOException(MessageFormat.format(
  795.                     JGitText.get().unsupportedPackVersion, Long.valueOf(vers)));
  796.         final long objectCount = NB.decodeUInt32(buf, p + 8);
  797.         use(hdrln);
  798.         setExpectedObjectCount(objectCount);
  799.         onPackHeader(objectCount);
  800.     }

  801.     private void readPackFooter() throws IOException {
  802.         sync();
  803.         final byte[] actHash = packDigest.digest();

  804.         final int c = fill(Source.INPUT, 20);
  805.         final byte[] srcHash = new byte[20];
  806.         System.arraycopy(buf, c, srcHash, 0, 20);
  807.         use(20);

  808.         if (bAvail != 0 && !expectDataAfterPackFooter)
  809.             throw new CorruptObjectException(MessageFormat.format(
  810.                     JGitText.get().expectedEOFReceived,
  811.                     "\\x" + Integer.toHexString(buf[bOffset] & 0xff))); //$NON-NLS-1$
  812.         if (isCheckEofAfterPackFooter()) {
  813.             int eof = in.read();
  814.             if (0 <= eof)
  815.                 throw new CorruptObjectException(MessageFormat.format(
  816.                         JGitText.get().expectedEOFReceived,
  817.                         "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  818.         } else if (bAvail > 0 && expectDataAfterPackFooter) {
  819.             in.reset();
  820.             IO.skipFully(in, bOffset);
  821.         }

  822.         if (!Arrays.equals(actHash, srcHash))
  823.             throw new CorruptObjectException(
  824.                     JGitText.get().corruptObjectPackfileChecksumIncorrect);

  825.         onPackFooter(srcHash);
  826.     }

  827.     // Cleanup all resources associated with our input parsing.
  828.     private void endInput() {
  829.         stats.setNumBytesRead(streamPosition());
  830.         in = null;
  831.     }

  832.     // Read one entire object or delta from the input.
  833.     private void indexOneObject() throws IOException {
  834.         final long streamPosition = streamPosition();

  835.         int hdrPtr = 0;
  836.         int c = readFrom(Source.INPUT);
  837.         hdrBuf[hdrPtr++] = (byte) c;

  838.         final int typeCode = (c >> 4) & 7;
  839.         long sz = c & 15;
  840.         int shift = 4;
  841.         while ((c & 0x80) != 0) {
  842.             c = readFrom(Source.INPUT);
  843.             hdrBuf[hdrPtr++] = (byte) c;
  844.             sz += ((long) (c & 0x7f)) << shift;
  845.             shift += 7;
  846.         }

  847.         checkIfTooLarge(typeCode, sz);

  848.         switch (typeCode) {
  849.         case Constants.OBJ_COMMIT:
  850.         case Constants.OBJ_TREE:
  851.         case Constants.OBJ_BLOB:
  852.         case Constants.OBJ_TAG:
  853.             stats.addWholeObject(typeCode);
  854.             onBeginWholeObject(streamPosition, typeCode, sz);
  855.             onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  856.             whole(streamPosition, typeCode, sz);
  857.             break;

  858.         case Constants.OBJ_OFS_DELTA: {
  859.             stats.addOffsetDelta();
  860.             c = readFrom(Source.INPUT);
  861.             hdrBuf[hdrPtr++] = (byte) c;
  862.             long ofs = c & 127;
  863.             while ((c & 128) != 0) {
  864.                 ofs += 1;
  865.                 c = readFrom(Source.INPUT);
  866.                 hdrBuf[hdrPtr++] = (byte) c;
  867.                 ofs <<= 7;
  868.                 ofs += (c & 127);
  869.             }
  870.             final long base = streamPosition - ofs;
  871.             onBeginOfsDelta(streamPosition, base, sz);
  872.             onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  873.             inflateAndSkip(Source.INPUT, sz);
  874.             UnresolvedDelta n = onEndDelta();
  875.             n.position = streamPosition;
  876.             n.next = baseByPos.put(base, n);
  877.             n.sizeBeforeInflating = streamPosition() - streamPosition;
  878.             deltaCount++;
  879.             break;
  880.         }

  881.         case Constants.OBJ_REF_DELTA: {
  882.             stats.addRefDelta();
  883.             c = fill(Source.INPUT, 20);
  884.             final ObjectId base = ObjectId.fromRaw(buf, c);
  885.             System.arraycopy(buf, c, hdrBuf, hdrPtr, 20);
  886.             hdrPtr += 20;
  887.             use(20);
  888.             DeltaChain r = baseById.get(base);
  889.             if (r == null) {
  890.                 r = new DeltaChain(base);
  891.                 baseById.add(r);
  892.             }
  893.             onBeginRefDelta(streamPosition, base, sz);
  894.             onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  895.             inflateAndSkip(Source.INPUT, sz);
  896.             UnresolvedDelta n = onEndDelta();
  897.             n.position = streamPosition;
  898.             n.sizeBeforeInflating = streamPosition() - streamPosition;
  899.             r.add(n);
  900.             deltaCount++;
  901.             break;
  902.         }

  903.         default:
  904.             throw new IOException(
  905.                     MessageFormat.format(JGitText.get().unknownObjectType,
  906.                             Integer.valueOf(typeCode)));
  907.         }
  908.     }

  909.     private void whole(long pos, int type, long sz)
  910.             throws IOException {
  911.         SHA1 objectDigest = objectHasher.reset();
  912.         objectDigest.update(Constants.encodedTypeString(type));
  913.         objectDigest.update((byte) ' ');
  914.         objectDigest.update(Constants.encodeASCII(sz));
  915.         objectDigest.update((byte) 0);

  916.         final byte[] data;
  917.         if (type == Constants.OBJ_BLOB) {
  918.             byte[] readBuffer = buffer();
  919.             BlobObjectChecker checker = null;
  920.             if (objCheck != null) {
  921.                 checker = objCheck.newBlobObjectChecker();
  922.             }
  923.             if (checker == null) {
  924.                 checker = BlobObjectChecker.NULL_CHECKER;
  925.             }
  926.             long cnt = 0;
  927.             try (InputStream inf = inflate(Source.INPUT, sz)) {
  928.                 while (cnt < sz) {
  929.                     int r = inf.read(readBuffer);
  930.                     if (r <= 0)
  931.                         break;
  932.                     objectDigest.update(readBuffer, 0, r);
  933.                     checker.update(readBuffer, 0, r);
  934.                     cnt += r;
  935.                 }
  936.             }
  937.             objectDigest.digest(tempObjectId);
  938.             checker.endBlob(tempObjectId);
  939.             data = null;
  940.         } else {
  941.             data = inflateAndReturn(Source.INPUT, sz);
  942.             objectDigest.update(data);
  943.             objectDigest.digest(tempObjectId);
  944.             verifySafeObject(tempObjectId, type, data);
  945.         }

  946.         long sizeBeforeInflating = streamPosition() - pos;
  947.         PackedObjectInfo obj = newInfo(tempObjectId, null, null);
  948.         obj.setOffset(pos);
  949.         obj.setType(type);
  950.         obj.setSize(sizeBeforeInflating);
  951.         obj.setFullSize(sz);
  952.         onEndWholeObject(obj);
  953.         if (data != null)
  954.             onInflatedObjectData(obj, type, data);
  955.         addObjectAndTrack(obj);

  956.         if (isCheckObjectCollisions()) {
  957.             collisionCheckObjs.add(obj);
  958.         }
  959.     }

  960.     /**
  961.      * Verify the integrity of the object.
  962.      *
  963.      * @param id
  964.      *            identity of the object to be checked.
  965.      * @param type
  966.      *            the type of the object.
  967.      * @param data
  968.      *            raw content of the object.
  969.      * @throws org.eclipse.jgit.errors.CorruptObjectException
  970.      * @since 4.9
  971.      */
  972.     protected void verifySafeObject(final AnyObjectId id, final int type,
  973.             final byte[] data) throws CorruptObjectException {
  974.         if (objCheck != null) {
  975.             try {
  976.                 objCheck.check(id, type, data);
  977.             } catch (CorruptObjectException e) {
  978.                 if (e.getErrorType() != null) {
  979.                     throw e;
  980.                 }
  981.                 throw new CorruptObjectException(
  982.                         MessageFormat.format(JGitText.get().invalidObject,
  983.                                 Constants.typeString(type), id.name(),
  984.                                 e.getMessage()),
  985.                         e);
  986.             }
  987.         }
  988.     }

  989.     private void checkObjectCollision() throws IOException {
  990.         for (PackedObjectInfo obj : collisionCheckObjs) {
  991.             if (!readCurs.has(obj)) {
  992.                 continue;
  993.             }
  994.             checkObjectCollision(obj);
  995.         }
  996.     }

  997.     private void checkObjectCollision(PackedObjectInfo obj)
  998.             throws IOException {
  999.         ObjectTypeAndSize info = openDatabase(obj, new ObjectTypeAndSize());
  1000.         final byte[] readBuffer = buffer();
  1001.         final byte[] curBuffer = new byte[readBuffer.length];
  1002.         long sz = info.size;
  1003.         try (ObjectStream cur = readCurs.open(obj, info.type).openStream()) {
  1004.             if (cur.getSize() != sz) {
  1005.                 throw new IOException(MessageFormat.format(
  1006.                         JGitText.get().collisionOn, obj.name()));
  1007.             }
  1008.             try (InputStream pck = inflate(Source.DATABASE, sz)) {
  1009.                 while (0 < sz) {
  1010.                     int n = (int) Math.min(readBuffer.length, sz);
  1011.                     IO.readFully(cur, curBuffer, 0, n);
  1012.                     IO.readFully(pck, readBuffer, 0, n);
  1013.                     for (int i = 0; i < n; i++) {
  1014.                         if (curBuffer[i] != readBuffer[i]) {
  1015.                             throw new IOException(MessageFormat.format(
  1016.                                     JGitText.get().collisionOn, obj.name()));
  1017.                         }
  1018.                     }
  1019.                     sz -= n;
  1020.                 }
  1021.             }
  1022.             stats.incrementObjectsDuplicated();
  1023.             stats.incrementNumBytesDuplicated(obj.getSize());
  1024.         } catch (MissingObjectException notLocal) {
  1025.             // This is OK, we don't have a copy of the object locally
  1026.             // but the API throws when we try to read it as usually it's
  1027.             // an error to read something that doesn't exist.
  1028.         }
  1029.     }

  1030.     private void checkObjectCollision(AnyObjectId obj, int type, byte[] data,
  1031.             long sizeBeforeInflating) throws IOException {
  1032.         try {
  1033.             final ObjectLoader ldr = readCurs.open(obj, type);
  1034.             final byte[] existingData = ldr.getCachedBytes(data.length);
  1035.             if (!Arrays.equals(data, existingData)) {
  1036.                 throw new IOException(MessageFormat
  1037.                         .format(JGitText.get().collisionOn, obj.name()));
  1038.             }
  1039.             stats.incrementObjectsDuplicated();
  1040.             stats.incrementNumBytesDuplicated(sizeBeforeInflating);
  1041.         } catch (MissingObjectException notLocal) {
  1042.             // This is OK, we don't have a copy of the object locally
  1043.             // but the API throws when we try to read it as usually its
  1044.             // an error to read something that doesn't exist.
  1045.         }
  1046.     }

  1047.     /** @return current position of the input stream being parsed. */
  1048.     private long streamPosition() {
  1049.         return bBase + bOffset;
  1050.     }

  1051.     private ObjectTypeAndSize openDatabase(PackedObjectInfo obj,
  1052.             ObjectTypeAndSize info) throws IOException {
  1053.         bOffset = 0;
  1054.         bAvail = 0;
  1055.         return seekDatabase(obj, info);
  1056.     }

  1057.     private ObjectTypeAndSize openDatabase(UnresolvedDelta delta,
  1058.             ObjectTypeAndSize info) throws IOException {
  1059.         bOffset = 0;
  1060.         bAvail = 0;
  1061.         return seekDatabase(delta, info);
  1062.     }

  1063.     // Consume exactly one byte from the buffer and return it.
  1064.     private int readFrom(Source src) throws IOException {
  1065.         if (bAvail == 0)
  1066.             fill(src, 1);
  1067.         bAvail--;
  1068.         return buf[bOffset++] & 0xff;
  1069.     }

  1070.     // Consume cnt bytes from the buffer.
  1071.     void use(int cnt) {
  1072.         bOffset += cnt;
  1073.         bAvail -= cnt;
  1074.     }

  1075.     // Ensure at least need bytes are available in {@link #buf}.
  1076.     int fill(Source src, int need) throws IOException {
  1077.         while (bAvail < need) {
  1078.             int next = bOffset + bAvail;
  1079.             int free = buf.length - next;
  1080.             if (free + bAvail < need) {
  1081.                 switch (src) {
  1082.                 case INPUT:
  1083.                     sync();
  1084.                     break;
  1085.                 case DATABASE:
  1086.                     if (bAvail > 0)
  1087.                         System.arraycopy(buf, bOffset, buf, 0, bAvail);
  1088.                     bOffset = 0;
  1089.                     break;
  1090.                 }
  1091.                 next = bAvail;
  1092.                 free = buf.length - next;
  1093.             }
  1094.             switch (src) {
  1095.             case INPUT:
  1096.                 next = in.read(buf, next, free);
  1097.                 break;
  1098.             case DATABASE:
  1099.                 next = readDatabase(buf, next, free);
  1100.                 break;
  1101.             }
  1102.             if (next <= 0)
  1103.                 throw new EOFException(
  1104.                         JGitText.get().packfileIsTruncatedNoParam);
  1105.             bAvail += next;
  1106.         }
  1107.         return bOffset;
  1108.     }

  1109.     // Store consumed bytes in {@link #buf} up to {@link #bOffset}.
  1110.     private void sync() throws IOException {
  1111.         packDigest.update(buf, 0, bOffset);
  1112.         onStoreStream(buf, 0, bOffset);
  1113.         if (expectDataAfterPackFooter) {
  1114.             if (bAvail > 0) {
  1115.                 in.reset();
  1116.                 IO.skipFully(in, bOffset);
  1117.                 bAvail = 0;
  1118.             }
  1119.             in.mark(buf.length);
  1120.         } else if (bAvail > 0)
  1121.             System.arraycopy(buf, bOffset, buf, 0, bAvail);
  1122.         bBase += bOffset;
  1123.         bOffset = 0;
  1124.     }

  1125.     /**
  1126.      * Get a temporary byte array for use by the caller.
  1127.      *
  1128.      * @return a temporary byte array for use by the caller.
  1129.      */
  1130.     protected byte[] buffer() {
  1131.         return tempBuffer;
  1132.     }

  1133.     /**
  1134.      * Construct a PackedObjectInfo instance for this parser.
  1135.      *
  1136.      * @param id
  1137.      *            identity of the object to be tracked.
  1138.      * @param delta
  1139.      *            if the object was previously an unresolved delta, this is the
  1140.      *            delta object that was tracking it. Otherwise null.
  1141.      * @param deltaBase
  1142.      *            if the object was previously an unresolved delta, this is the
  1143.      *            ObjectId of the base of the delta. The base may be outside of
  1144.      *            the pack stream if the stream was a thin-pack.
  1145.      * @return info object containing this object's data.
  1146.      */
  1147.     protected PackedObjectInfo newInfo(AnyObjectId id, UnresolvedDelta delta,
  1148.             ObjectId deltaBase) {
  1149.         PackedObjectInfo oe = new PackedObjectInfo(id);
  1150.         if (delta != null)
  1151.             oe.setCRC(delta.crc);
  1152.         return oe;
  1153.     }

  1154.     /**
  1155.      * Set the expected number of objects in the pack stream.
  1156.      * <p>
  1157.      * The object count in the pack header is not always correct for some Dfs
  1158.      * pack files. e.g. INSERT pack always assume 1 object in the header since
  1159.      * the actual object count is unknown when the pack is written.
  1160.      * <p>
  1161.      * If external implementation wants to overwrite the expectedObjectCount,
  1162.      * they should call this method during {@link #onPackHeader(long)}.
  1163.      *
  1164.      * @param expectedObjectCount a long.
  1165.      * @since 4.9
  1166.      */
  1167.     protected void setExpectedObjectCount(long expectedObjectCount) {
  1168.         this.expectedObjectCount = expectedObjectCount;
  1169.     }

  1170.     /**
  1171.      * Store bytes received from the raw stream.
  1172.      * <p>
  1173.      * This method is invoked during {@link #parse(ProgressMonitor)} as data is
  1174.      * consumed from the incoming stream. Implementors may use this event to
  1175.      * archive the raw incoming stream to the destination repository in large
  1176.      * chunks, without paying attention to object boundaries.
  1177.      * <p>
  1178.      * The only component of the pack not supplied to this method is the last 20
  1179.      * bytes of the pack that comprise the trailing SHA-1 checksum. Those are
  1180.      * passed to {@link #onPackFooter(byte[])}.
  1181.      *
  1182.      * @param raw
  1183.      *            buffer to copy data out of.
  1184.      * @param pos
  1185.      *            first offset within the buffer that is valid.
  1186.      * @param len
  1187.      *            number of bytes in the buffer that are valid.
  1188.      * @throws java.io.IOException
  1189.      *             the stream cannot be archived.
  1190.      */
  1191.     protected abstract void onStoreStream(byte[] raw, int pos, int len)
  1192.             throws IOException;

  1193.     /**
  1194.      * Store (and/or checksum) an object header.
  1195.      * <p>
  1196.      * Invoked after any of the {@code onBegin()} events. The entire header is
  1197.      * supplied in a single invocation, before any object data is supplied.
  1198.      *
  1199.      * @param src
  1200.      *            where the data came from
  1201.      * @param raw
  1202.      *            buffer to read data from.
  1203.      * @param pos
  1204.      *            first offset within buffer that is valid.
  1205.      * @param len
  1206.      *            number of bytes in buffer that are valid.
  1207.      * @throws java.io.IOException
  1208.      *             the stream cannot be archived.
  1209.      */
  1210.     protected abstract void onObjectHeader(Source src, byte[] raw, int pos,
  1211.             int len) throws IOException;

  1212.     /**
  1213.      * Store (and/or checksum) a portion of an object's data.
  1214.      * <p>
  1215.      * This method may be invoked multiple times per object, depending on the
  1216.      * size of the object, the size of the parser's internal read buffer, and
  1217.      * the alignment of the object relative to the read buffer.
  1218.      * <p>
  1219.      * Invoked after {@link #onObjectHeader(Source, byte[], int, int)}.
  1220.      *
  1221.      * @param src
  1222.      *            where the data came from
  1223.      * @param raw
  1224.      *            buffer to read data from.
  1225.      * @param pos
  1226.      *            first offset within buffer that is valid.
  1227.      * @param len
  1228.      *            number of bytes in buffer that are valid.
  1229.      * @throws java.io.IOException
  1230.      *             the stream cannot be archived.
  1231.      */
  1232.     protected abstract void onObjectData(Source src, byte[] raw, int pos,
  1233.             int len) throws IOException;

  1234.     /**
  1235.      * Invoked for commits, trees, tags, and small blobs.
  1236.      *
  1237.      * @param obj
  1238.      *            the object info, populated.
  1239.      * @param typeCode
  1240.      *            the type of the object.
  1241.      * @param data
  1242.      *            inflated data for the object.
  1243.      * @throws java.io.IOException
  1244.      *             the object cannot be archived.
  1245.      */
  1246.     protected abstract void onInflatedObjectData(PackedObjectInfo obj,
  1247.             int typeCode, byte[] data) throws IOException;

  1248.     /**
  1249.      * Provide the implementation with the original stream's pack header.
  1250.      *
  1251.      * @param objCnt
  1252.      *            number of objects expected in the stream.
  1253.      * @throws java.io.IOException
  1254.      *             the implementation refuses to work with this many objects.
  1255.      */
  1256.     protected abstract void onPackHeader(long objCnt) throws IOException;

  1257.     /**
  1258.      * Provide the implementation with the original stream's pack footer.
  1259.      *
  1260.      * @param hash
  1261.      *            the trailing 20 bytes of the pack, this is a SHA-1 checksum of
  1262.      *            all of the pack data.
  1263.      * @throws java.io.IOException
  1264.      *             the stream cannot be archived.
  1265.      */
  1266.     protected abstract void onPackFooter(byte[] hash) throws IOException;

  1267.     /**
  1268.      * Provide the implementation with a base that was outside of the pack.
  1269.      * <p>
  1270.      * This event only occurs on a thin pack for base objects that were outside
  1271.      * of the pack and came from the local repository. Usually an implementation
  1272.      * uses this event to compress the base and append it onto the end of the
  1273.      * pack, so the pack stays self-contained.
  1274.      *
  1275.      * @param typeCode
  1276.      *            type of the base object.
  1277.      * @param data
  1278.      *            complete content of the base object.
  1279.      * @param info
  1280.      *            packed object information for this base. Implementors must
  1281.      *            populate the CRC and offset members if returning true.
  1282.      * @return true if the {@code info} should be included in the object list
  1283.      *         returned by {@link #getSortedObjectList(Comparator)}, false if it
  1284.      *         should not be included.
  1285.      * @throws java.io.IOException
  1286.      *             the base could not be included into the pack.
  1287.      */
  1288.     protected abstract boolean onAppendBase(int typeCode, byte[] data,
  1289.             PackedObjectInfo info) throws IOException;

  1290.     /**
  1291.      * Event indicating a thin pack has been completely processed.
  1292.      * <p>
  1293.      * This event is invoked only if a thin pack has delta references to objects
  1294.      * external from the pack. The event is called after all of those deltas
  1295.      * have been resolved.
  1296.      *
  1297.      * @throws java.io.IOException
  1298.      *             the pack cannot be archived.
  1299.      */
  1300.     protected abstract void onEndThinPack() throws IOException;

  1301.     /**
  1302.      * Reposition the database to re-read a previously stored object.
  1303.      * <p>
  1304.      * If the database is computing CRC-32 checksums for object data, it should
  1305.      * reset its internal CRC instance during this method call.
  1306.      *
  1307.      * @param obj
  1308.      *            the object position to begin reading from. This is from
  1309.      *            {@link #newInfo(AnyObjectId, UnresolvedDelta, ObjectId)}.
  1310.      * @param info
  1311.      *            object to populate with type and size.
  1312.      * @return the {@code info} object.
  1313.      * @throws java.io.IOException
  1314.      *             the database cannot reposition to this location.
  1315.      */
  1316.     protected abstract ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
  1317.             ObjectTypeAndSize info) throws IOException;

  1318.     /**
  1319.      * Reposition the database to re-read a previously stored object.
  1320.      * <p>
  1321.      * If the database is computing CRC-32 checksums for object data, it should
  1322.      * reset its internal CRC instance during this method call.
  1323.      *
  1324.      * @param delta
  1325.      *            the object position to begin reading from. This is an instance
  1326.      *            previously returned by {@link #onEndDelta()}.
  1327.      * @param info
  1328.      *            object to populate with type and size.
  1329.      * @return the {@code info} object.
  1330.      * @throws java.io.IOException
  1331.      *             the database cannot reposition to this location.
  1332.      */
  1333.     protected abstract ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
  1334.             ObjectTypeAndSize info) throws IOException;

  1335.     /**
  1336.      * Read from the database's current position into the buffer.
  1337.      *
  1338.      * @param dst
  1339.      *            the buffer to copy read data into.
  1340.      * @param pos
  1341.      *            position within {@code dst} to start copying data into.
  1342.      * @param cnt
  1343.      *            ideal target number of bytes to read. Actual read length may
  1344.      *            be shorter.
  1345.      * @return number of bytes stored.
  1346.      * @throws java.io.IOException
  1347.      *             the database cannot be accessed.
  1348.      */
  1349.     protected abstract int readDatabase(byte[] dst, int pos, int cnt)
  1350.             throws IOException;

  1351.     /**
  1352.      * Check the current CRC matches the expected value.
  1353.      * <p>
  1354.      * This method is invoked when an object is read back in from the database
  1355.      * and its data is used during delta resolution. The CRC is validated after
  1356.      * the object has been fully read, allowing the parser to verify there was
  1357.      * no silent data corruption.
  1358.      * <p>
  1359.      * Implementations are free to ignore this check by always returning true if
  1360.      * they are performing other data integrity validations at a lower level.
  1361.      *
  1362.      * @param oldCRC
  1363.      *            the prior CRC that was recorded during the first scan of the
  1364.      *            object from the pack stream.
  1365.      * @return true if the CRC matches; false if it does not.
  1366.      */
  1367.     protected abstract boolean checkCRC(int oldCRC);

  1368.     /**
  1369.      * Event notifying the start of an object stored whole (not as a delta).
  1370.      *
  1371.      * @param streamPosition
  1372.      *            position of this object in the incoming stream.
  1373.      * @param type
  1374.      *            type of the object; one of
  1375.      *            {@link org.eclipse.jgit.lib.Constants#OBJ_COMMIT},
  1376.      *            {@link org.eclipse.jgit.lib.Constants#OBJ_TREE},
  1377.      *            {@link org.eclipse.jgit.lib.Constants#OBJ_BLOB}, or
  1378.      *            {@link org.eclipse.jgit.lib.Constants#OBJ_TAG}.
  1379.      * @param inflatedSize
  1380.      *            size of the object when fully inflated. The size stored within
  1381.      *            the pack may be larger or smaller, and is not yet known.
  1382.      * @throws java.io.IOException
  1383.      *             the object cannot be recorded.
  1384.      */
  1385.     protected abstract void onBeginWholeObject(long streamPosition, int type,
  1386.             long inflatedSize) throws IOException;

  1387.     /**
  1388.      * Event notifying the current object.
  1389.      *
  1390.      *@param info
  1391.      *            object information.
  1392.      * @throws java.io.IOException
  1393.      *             the object cannot be recorded.
  1394.      */
  1395.     protected abstract void onEndWholeObject(PackedObjectInfo info)
  1396.             throws IOException;

  1397.     /**
  1398.      * Event notifying start of a delta referencing its base by offset.
  1399.      *
  1400.      * @param deltaStreamPosition
  1401.      *            position of this object in the incoming stream.
  1402.      * @param baseStreamPosition
  1403.      *            position of the base object in the incoming stream. The base
  1404.      *            must be before the delta, therefore {@code baseStreamPosition
  1405.      *            &lt; deltaStreamPosition}. This is <b>not</b> the position
  1406.      *            returned by a prior end object event.
  1407.      * @param inflatedSize
  1408.      *            size of the delta when fully inflated. The size stored within
  1409.      *            the pack may be larger or smaller, and is not yet known.
  1410.      * @throws java.io.IOException
  1411.      *             the object cannot be recorded.
  1412.      */
  1413.     protected abstract void onBeginOfsDelta(long deltaStreamPosition,
  1414.             long baseStreamPosition, long inflatedSize) throws IOException;

  1415.     /**
  1416.      * Event notifying start of a delta referencing its base by ObjectId.
  1417.      *
  1418.      * @param deltaStreamPosition
  1419.      *            position of this object in the incoming stream.
  1420.      * @param baseId
  1421.      *            name of the base object. This object may be later in the
  1422.      *            stream, or might not appear at all in the stream (in the case
  1423.      *            of a thin-pack).
  1424.      * @param inflatedSize
  1425.      *            size of the delta when fully inflated. The size stored within
  1426.      *            the pack may be larger or smaller, and is not yet known.
  1427.      * @throws java.io.IOException
  1428.      *             the object cannot be recorded.
  1429.      */
  1430.     protected abstract void onBeginRefDelta(long deltaStreamPosition,
  1431.             AnyObjectId baseId, long inflatedSize) throws IOException;

  1432.     /**
  1433.      * Event notifying the current object.
  1434.      *
  1435.      *@return object information that must be populated with at least the
  1436.      *         offset.
  1437.      * @throws java.io.IOException
  1438.      *             the object cannot be recorded.
  1439.      */
  1440.     protected UnresolvedDelta onEndDelta() throws IOException {
  1441.         return new UnresolvedDelta();
  1442.     }

  1443.     /** Type and size information about an object in the database buffer. */
  1444.     public static class ObjectTypeAndSize {
  1445.         /** The type of the object. */
  1446.         public int type;

  1447.         /** The inflated size of the object. */
  1448.         public long size;
  1449.     }

  1450.     private void inflateAndSkip(Source src, long inflatedSize)
  1451.             throws IOException {
  1452.         try (InputStream inf = inflate(src, inflatedSize)) {
  1453.             IO.skipFully(inf, inflatedSize);
  1454.         }
  1455.     }

  1456.     private byte[] inflateAndReturn(Source src, long inflatedSize)
  1457.             throws IOException {
  1458.         final byte[] dst = new byte[(int) inflatedSize];
  1459.         try (InputStream inf = inflate(src, inflatedSize)) {
  1460.             IO.readFully(inf, dst, 0, dst.length);
  1461.         }
  1462.         return dst;
  1463.     }

  1464.     private InputStream inflate(Source src, long inflatedSize)
  1465.             throws IOException {
  1466.         inflater.open(src, inflatedSize);
  1467.         return inflater;
  1468.     }

  1469.     private static class DeltaChain extends ObjectIdOwnerMap.Entry {
  1470.         UnresolvedDelta head;

  1471.         DeltaChain(AnyObjectId id) {
  1472.             super(id);
  1473.         }

  1474.         UnresolvedDelta remove() {
  1475.             final UnresolvedDelta r = head;
  1476.             if (r != null)
  1477.                 head = null;
  1478.             return r;
  1479.         }

  1480.         void add(UnresolvedDelta d) {
  1481.             d.next = head;
  1482.             head = d;
  1483.         }
  1484.     }

  1485.     /** Information about an unresolved delta in this pack stream. */
  1486.     public static class UnresolvedDelta {
  1487.         long position;

  1488.         int crc;

  1489.         UnresolvedDelta next;

  1490.         long sizeBeforeInflating;

  1491.         /** @return offset within the input stream. */
  1492.         public long getOffset() {
  1493.             return position;
  1494.         }

  1495.         /** @return the CRC-32 checksum of the stored delta data. */
  1496.         public int getCRC() {
  1497.             return crc;
  1498.         }

  1499.         /**
  1500.          * @param crc32
  1501.          *            the CRC-32 checksum of the stored delta data.
  1502.          */
  1503.         public void setCRC(int crc32) {
  1504.             crc = crc32;
  1505.         }
  1506.     }

  1507.     private static class DeltaVisit {
  1508.         final UnresolvedDelta delta;

  1509.         ObjectId id;

  1510.         byte[] data;

  1511.         DeltaVisit parent;

  1512.         UnresolvedDelta nextChild;

  1513.         DeltaVisit() {
  1514.             this.delta = null; // At the root of the stack we have a base.
  1515.         }

  1516.         DeltaVisit(DeltaVisit parent) {
  1517.             this.parent = parent;
  1518.             this.delta = parent.nextChild;
  1519.             parent.nextChild = delta.next;
  1520.         }

  1521.         DeltaVisit next() {
  1522.             // If our parent has no more children, discard it.
  1523.             if (parent != null && parent.nextChild == null) {
  1524.                 parent.data = null;
  1525.                 parent = parent.parent;
  1526.             }

  1527.             if (nextChild != null)
  1528.                 return new DeltaVisit(this);

  1529.             // If we have no child ourselves, our parent must (if it exists),
  1530.             // due to the discard rule above. With no parent, we are done.
  1531.             if (parent != null)
  1532.                 return new DeltaVisit(parent);
  1533.             return null;
  1534.         }
  1535.     }

  1536.     private void addObjectAndTrack(PackedObjectInfo oe) {
  1537.         entries[entryCount++] = oe;
  1538.         if (needNewObjectIds())
  1539.             newObjectIds.add(oe);
  1540.     }

  1541.     private class InflaterStream extends InputStream {
  1542.         private final Inflater inf;

  1543.         private final byte[] skipBuffer;

  1544.         private Source src;

  1545.         private long expectedSize;

  1546.         private long actualSize;

  1547.         private int p;

  1548.         InflaterStream() {
  1549.             inf = InflaterCache.get();
  1550.             skipBuffer = new byte[512];
  1551.         }

  1552.         void release() {
  1553.             inf.reset();
  1554.             InflaterCache.release(inf);
  1555.         }

  1556.         void open(Source source, long inflatedSize) throws IOException {
  1557.             src = source;
  1558.             expectedSize = inflatedSize;
  1559.             actualSize = 0;

  1560.             p = fill(src, 1);
  1561.             inf.setInput(buf, p, bAvail);
  1562.         }

  1563.         @Override
  1564.         public long skip(long toSkip) throws IOException {
  1565.             long n = 0;
  1566.             while (n < toSkip) {
  1567.                 final int cnt = (int) Math.min(skipBuffer.length, toSkip - n);
  1568.                 final int r = read(skipBuffer, 0, cnt);
  1569.                 if (r <= 0)
  1570.                     break;
  1571.                 n += r;
  1572.             }
  1573.             return n;
  1574.         }

  1575.         @Override
  1576.         public int read() throws IOException {
  1577.             int n = read(skipBuffer, 0, 1);
  1578.             return n == 1 ? skipBuffer[0] & 0xff : -1;
  1579.         }

  1580.         @Override
  1581.         public int read(byte[] dst, int pos, int cnt) throws IOException {
  1582.             try {
  1583.                 int n = 0;
  1584.                 while (n < cnt) {
  1585.                     int r = inf.inflate(dst, pos + n, cnt - n);
  1586.                     n += r;
  1587.                     if (inf.finished())
  1588.                         break;
  1589.                     if (inf.needsInput()) {
  1590.                         onObjectData(src, buf, p, bAvail);
  1591.                         use(bAvail);

  1592.                         p = fill(src, 1);
  1593.                         inf.setInput(buf, p, bAvail);
  1594.                     } else if (r == 0) {
  1595.                         throw new CorruptObjectException(MessageFormat.format(
  1596.                                 JGitText.get().packfileCorruptionDetected,
  1597.                                 JGitText.get().unknownZlibError));
  1598.                     }
  1599.                 }
  1600.                 actualSize += n;
  1601.                 return 0 < n ? n : -1;
  1602.             } catch (DataFormatException dfe) {
  1603.                 throw new CorruptObjectException(MessageFormat.format(JGitText
  1604.                         .get().packfileCorruptionDetected, dfe.getMessage()));
  1605.             }
  1606.         }

  1607.         @Override
  1608.         public void close() throws IOException {
  1609.             // We need to read here to enter the loop above and pump the
  1610.             // trailing checksum into the Inflater. It should return -1 as the
  1611.             // caller was supposed to consume all content.
  1612.             //
  1613.             if (read(skipBuffer) != -1 || actualSize != expectedSize) {
  1614.                 throw new CorruptObjectException(MessageFormat.format(JGitText
  1615.                         .get().packfileCorruptionDetected,
  1616.                         JGitText.get().wrongDecompressedLength));
  1617.             }

  1618.             int used = bAvail - inf.getRemaining();
  1619.             if (0 < used) {
  1620.                 onObjectData(src, buf, p, used);
  1621.                 use(used);
  1622.             }

  1623.             inf.reset();
  1624.         }
  1625.     }
  1626. }