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>
  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.IOException;
  48. import java.io.InputStream;
  49. import java.security.MessageDigest;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.Arrays;
  53. import java.util.Comparator;
  54. import java.util.List;
  55. import java.util.concurrent.TimeUnit;
  56. import java.util.zip.DataFormatException;
  57. import java.util.zip.Inflater;

  58. import org.eclipse.jgit.errors.CorruptObjectException;
  59. import org.eclipse.jgit.errors.MissingObjectException;
  60. import org.eclipse.jgit.errors.TooLargeObjectInPackException;
  61. import org.eclipse.jgit.internal.JGitText;
  62. import org.eclipse.jgit.internal.storage.file.PackLock;
  63. import org.eclipse.jgit.internal.storage.pack.BinaryDelta;
  64. import org.eclipse.jgit.lib.AnyObjectId;
  65. import org.eclipse.jgit.lib.BatchingProgressMonitor;
  66. import org.eclipse.jgit.lib.BlobObjectChecker;
  67. import org.eclipse.jgit.lib.Constants;
  68. import org.eclipse.jgit.lib.InflaterCache;
  69. import org.eclipse.jgit.lib.MutableObjectId;
  70. import org.eclipse.jgit.lib.NullProgressMonitor;
  71. import org.eclipse.jgit.lib.ObjectChecker;
  72. import org.eclipse.jgit.lib.ObjectDatabase;
  73. import org.eclipse.jgit.lib.ObjectId;
  74. import org.eclipse.jgit.lib.ObjectIdOwnerMap;
  75. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  76. import org.eclipse.jgit.lib.ObjectLoader;
  77. import org.eclipse.jgit.lib.ObjectReader;
  78. import org.eclipse.jgit.lib.ObjectStream;
  79. import org.eclipse.jgit.lib.ProgressMonitor;
  80. import org.eclipse.jgit.util.BlockList;
  81. import org.eclipse.jgit.util.IO;
  82. import org.eclipse.jgit.util.LongMap;
  83. import org.eclipse.jgit.util.NB;
  84. import org.eclipse.jgit.util.sha1.SHA1;

  85. /**
  86.  * Parses a pack stream and imports it for an
  87.  * {@link org.eclipse.jgit.lib.ObjectInserter}.
  88.  * <p>
  89.  * Applications can acquire an instance of a parser from ObjectInserter's
  90.  * {@link org.eclipse.jgit.lib.ObjectInserter#newPackParser(InputStream)}
  91.  * method.
  92.  * <p>
  93.  * Implementations of {@link org.eclipse.jgit.lib.ObjectInserter} should
  94.  * subclass this type and provide their own logic for the various {@code on*()}
  95.  * event methods declared to be abstract.
  96.  */
  97. public abstract class PackParser {
  98.     /** Size of the internal stream buffer. */
  99.     private static final int BUFFER_SIZE = 8192;

  100.     /** Location data is being obtained from. */
  101.     public static enum Source {
  102.         /** Data is read from the incoming stream. */
  103.         INPUT,

  104.         /** Data is read back from the database's buffers. */
  105.         DATABASE;
  106.     }

  107.     /** Object database used for loading existing objects. */
  108.     private final ObjectDatabase objectDatabase;

  109.     private InflaterStream inflater;

  110.     private byte[] tempBuffer;

  111.     private byte[] hdrBuf;

  112.     private final SHA1 objectHasher = SHA1.newInstance();
  113.     private final MutableObjectId tempObjectId;

  114.     private InputStream in;

  115.     byte[] buf;

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

  118.     private int bOffset;

  119.     int bAvail;

  120.     private ObjectChecker objCheck;

  121.     private boolean allowThin;

  122.     private boolean checkObjectCollisions;

  123.     private boolean needBaseObjectIds;

  124.     private boolean checkEofAfterPackFooter;

  125.     private boolean expectDataAfterPackFooter;

  126.     private long expectedObjectCount;

  127.     private PackedObjectInfo[] entries;

  128.     /**
  129.      * Every object contained within the incoming pack.
  130.      * <p>
  131.      * This is a subset of {@link #entries}, as thin packs can add additional
  132.      * objects to {@code entries} by copying already existing objects from the
  133.      * repository onto the end of the thin pack to make it self-contained.
  134.      */
  135.     private ObjectIdSubclassMap<ObjectId> newObjectIds;

  136.     private int deltaCount;

  137.     private int entryCount;

  138.     private ObjectIdOwnerMap<DeltaChain> baseById;

  139.     /**
  140.      * Objects referenced by their name from deltas, that aren't in this pack.
  141.      * <p>
  142.      * This is the set of objects that were copied onto the end of this pack to
  143.      * make it complete. These objects were not transmitted by the remote peer,
  144.      * but instead were assumed to already exist in the local repository.
  145.      */
  146.     private ObjectIdSubclassMap<ObjectId> baseObjectIds;

  147.     private LongMap<UnresolvedDelta> baseByPos;

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

  150.     private MessageDigest packDigest;

  151.     private ObjectReader readCurs;

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

  154.     /** Git object size limit */
  155.     private long maxObjectSizeLimit;

  156.     private final ReceivedPackStatistics.Builder stats =
  157.             new ReceivedPackStatistics.Builder();

  158.     /**
  159.      * Initialize a pack parser.
  160.      *
  161.      * @param odb
  162.      *            database the parser will write its objects into.
  163.      * @param src
  164.      *            the stream the parser will read.
  165.      */
  166.     protected PackParser(ObjectDatabase odb, InputStream src) {
  167.         objectDatabase = odb.newCachedDatabase();
  168.         in = src;

  169.         inflater = new InflaterStream();
  170.         readCurs = objectDatabase.newReader();
  171.         buf = new byte[BUFFER_SIZE];
  172.         tempBuffer = new byte[BUFFER_SIZE];
  173.         hdrBuf = new byte[64];
  174.         tempObjectId = new MutableObjectId();
  175.         packDigest = Constants.newMessageDigest();
  176.         checkObjectCollisions = true;
  177.     }

  178.     /**
  179.      * Whether a thin pack (missing base objects) is permitted.
  180.      *
  181.      * @return {@code true} if a thin pack (missing base objects) is permitted.
  182.      */
  183.     public boolean isAllowThin() {
  184.         return allowThin;
  185.     }

  186.     /**
  187.      * Configure this index pack instance to allow a thin pack.
  188.      * <p>
  189.      * Thin packs are sometimes used during network transfers to allow a delta
  190.      * to be sent without a base object. Such packs are not permitted on disk.
  191.      *
  192.      * @param allow
  193.      *            true to enable a thin pack.
  194.      */
  195.     public void setAllowThin(boolean allow) {
  196.         allowThin = allow;
  197.     }

  198.     /**
  199.      * Whether received objects are verified to prevent collisions.
  200.      *
  201.      * @return if true received objects are verified to prevent collisions.
  202.      * @since 4.1
  203.      */
  204.     protected boolean isCheckObjectCollisions() {
  205.         return checkObjectCollisions;
  206.     }

  207.     /**
  208.      * Enable checking for collisions with existing objects.
  209.      * <p>
  210.      * By default PackParser looks for each received object in the repository.
  211.      * If the object already exists, the existing object is compared
  212.      * byte-for-byte with the newly received copy to ensure they are identical.
  213.      * The receive is aborted with an exception if any byte differs. This check
  214.      * is necessary to prevent an evil attacker from supplying a replacement
  215.      * object into this repository in the event that a discovery enabling SHA-1
  216.      * collisions is made.
  217.      * <p>
  218.      * This check may be very costly to perform, and some repositories may have
  219.      * other ways to segregate newly received object data. The check is enabled
  220.      * by default, but can be explicitly disabled if the implementation can
  221.      * provide the same guarantee, or is willing to accept the risks associated
  222.      * with bypassing the check.
  223.      *
  224.      * @param check
  225.      *            true to enable collision checking (strongly encouraged).
  226.      * @since 4.1
  227.      */
  228.     protected void setCheckObjectCollisions(boolean check) {
  229.         checkObjectCollisions = check;
  230.     }

  231.     /**
  232.      * Configure this index pack instance to keep track of new objects.
  233.      * <p>
  234.      * By default an index pack doesn't save the new objects that were created
  235.      * when it was instantiated. Setting this flag to {@code true} allows the
  236.      * caller to use {@link #getNewObjectIds()} to retrieve that list.
  237.      *
  238.      * @param b
  239.      *            {@code true} to enable keeping track of new objects.
  240.      */
  241.     public void setNeedNewObjectIds(boolean b) {
  242.         if (b)
  243.             newObjectIds = new ObjectIdSubclassMap<>();
  244.         else
  245.             newObjectIds = null;
  246.     }

  247.     private boolean needNewObjectIds() {
  248.         return newObjectIds != null;
  249.     }

  250.     /**
  251.      * Configure this index pack instance to keep track of the objects assumed
  252.      * for delta bases.
  253.      * <p>
  254.      * By default an index pack doesn't save the objects that were used as delta
  255.      * bases. Setting this flag to {@code true} will allow the caller to use
  256.      * {@link #getBaseObjectIds()} to retrieve that list.
  257.      *
  258.      * @param b
  259.      *            {@code true} to enable keeping track of delta bases.
  260.      */
  261.     public void setNeedBaseObjectIds(boolean b) {
  262.         this.needBaseObjectIds = b;
  263.     }

  264.     /**
  265.      * Whether the EOF should be read from the input after the footer.
  266.      *
  267.      * @return true if the EOF should be read from the input after the footer.
  268.      */
  269.     public boolean isCheckEofAfterPackFooter() {
  270.         return checkEofAfterPackFooter;
  271.     }

  272.     /**
  273.      * Ensure EOF is read from the input stream after the footer.
  274.      *
  275.      * @param b
  276.      *            true if the EOF should be read; false if it is not checked.
  277.      */
  278.     public void setCheckEofAfterPackFooter(boolean b) {
  279.         checkEofAfterPackFooter = b;
  280.     }

  281.     /**
  282.      * Whether there is data expected after the pack footer.
  283.      *
  284.      * @return true if there is data expected after the pack footer.
  285.      */
  286.     public boolean isExpectDataAfterPackFooter() {
  287.         return expectDataAfterPackFooter;
  288.     }

  289.     /**
  290.      * Set if there is additional data in InputStream after pack.
  291.      *
  292.      * @param e
  293.      *            true if there is additional data in InputStream after pack.
  294.      *            This requires the InputStream to support the mark and reset
  295.      *            functions.
  296.      */
  297.     public void setExpectDataAfterPackFooter(boolean e) {
  298.         expectDataAfterPackFooter = e;
  299.     }

  300.     /**
  301.      * Get the new objects that were sent by the user
  302.      *
  303.      * @return the new objects that were sent by the user
  304.      */
  305.     public ObjectIdSubclassMap<ObjectId> getNewObjectIds() {
  306.         if (newObjectIds != null)
  307.             return newObjectIds;
  308.         return new ObjectIdSubclassMap<>();
  309.     }

  310.     /**
  311.      * Get set of objects the incoming pack assumed for delta purposes
  312.      *
  313.      * @return set of objects the incoming pack assumed for delta purposes
  314.      */
  315.     public ObjectIdSubclassMap<ObjectId> getBaseObjectIds() {
  316.         if (baseObjectIds != null)
  317.             return baseObjectIds;
  318.         return new ObjectIdSubclassMap<>();
  319.     }

  320.     /**
  321.      * Configure the checker used to validate received objects.
  322.      * <p>
  323.      * Usually object checking isn't necessary, as Git implementations only
  324.      * create valid objects in pack files. However, additional checking may be
  325.      * useful if processing data from an untrusted source.
  326.      *
  327.      * @param oc
  328.      *            the checker instance; null to disable object checking.
  329.      */
  330.     public void setObjectChecker(ObjectChecker oc) {
  331.         objCheck = oc;
  332.     }

  333.     /**
  334.      * Configure the checker used to validate received objects.
  335.      * <p>
  336.      * Usually object checking isn't necessary, as Git implementations only
  337.      * create valid objects in pack files. However, additional checking may be
  338.      * useful if processing data from an untrusted source.
  339.      * <p>
  340.      * This is shorthand for:
  341.      *
  342.      * <pre>
  343.      * setObjectChecker(on ? new ObjectChecker() : null);
  344.      * </pre>
  345.      *
  346.      * @param on
  347.      *            true to enable the default checker; false to disable it.
  348.      */
  349.     public void setObjectChecking(boolean on) {
  350.         setObjectChecker(on ? new ObjectChecker() : null);
  351.     }

  352.     /**
  353.      * Get the message to record with the pack lock.
  354.      *
  355.      * @return the message to record with the pack lock.
  356.      */
  357.     public String getLockMessage() {
  358.         return lockMessage;
  359.     }

  360.     /**
  361.      * Set the lock message for the incoming pack data.
  362.      *
  363.      * @param msg
  364.      *            if not null, the message to associate with the incoming data
  365.      *            while it is locked to prevent garbage collection.
  366.      */
  367.     public void setLockMessage(String msg) {
  368.         lockMessage = msg;
  369.     }

  370.     /**
  371.      * Set the maximum allowed Git object size.
  372.      * <p>
  373.      * If an object is larger than the given size the pack-parsing will throw an
  374.      * exception aborting the parsing.
  375.      *
  376.      * @param limit
  377.      *            the Git object size limit. If zero then there is not limit.
  378.      */
  379.     public void setMaxObjectSizeLimit(long limit) {
  380.         maxObjectSizeLimit = limit;
  381.     }

  382.     /**
  383.      * Get the number of objects in the stream.
  384.      * <p>
  385.      * The object count is only available after {@link #parse(ProgressMonitor)}
  386.      * has returned. The count may have been increased if the stream was a thin
  387.      * pack, and missing bases objects were appending onto it by the subclass.
  388.      *
  389.      * @return number of objects parsed out of the stream.
  390.      */
  391.     public int getObjectCount() {
  392.         return entryCount;
  393.     }

  394.     /**
  395.      * Get the information about the requested object.
  396.      * <p>
  397.      * The object information is only available after
  398.      * {@link #parse(ProgressMonitor)} has returned.
  399.      *
  400.      * @param nth
  401.      *            index of the object in the stream. Must be between 0 and
  402.      *            {@link #getObjectCount()}-1.
  403.      * @return the object information.
  404.      */
  405.     public PackedObjectInfo getObject(int nth) {
  406.         return entries[nth];
  407.     }

  408.     /**
  409.      * Get all of the objects, sorted by their name.
  410.      * <p>
  411.      * The object information is only available after
  412.      * {@link #parse(ProgressMonitor)} has returned.
  413.      * <p>
  414.      * To maintain lower memory usage and good runtime performance, this method
  415.      * sorts the objects in-place and therefore impacts the ordering presented
  416.      * by {@link #getObject(int)}.
  417.      *
  418.      * @param cmp
  419.      *            comparison function, if null objects are stored by ObjectId.
  420.      * @return sorted list of objects in this pack stream.
  421.      */
  422.     public List<PackedObjectInfo> getSortedObjectList(
  423.             Comparator<PackedObjectInfo> cmp) {
  424.         Arrays.sort(entries, 0, entryCount, cmp);
  425.         List<PackedObjectInfo> list = Arrays.asList(entries);
  426.         if (entryCount < entries.length)
  427.             list = list.subList(0, entryCount);
  428.         return list;
  429.     }

  430.     /**
  431.      * Get the size of the newly created pack.
  432.      * <p>
  433.      * This will also include the pack index size if an index was created. This
  434.      * method should only be called after pack parsing is finished.
  435.      *
  436.      * @return the pack size (including the index size) or -1 if the size cannot
  437.      *         be determined
  438.      * @since 3.3
  439.      */
  440.     public long getPackSize() {
  441.         return -1;
  442.     }

  443.     /**
  444.      * Returns the statistics of the parsed pack.
  445.      * <p>
  446.      * This should only be called after pack parsing is finished.
  447.      *
  448.      * @return {@link org.eclipse.jgit.transport.ReceivedPackStatistics}
  449.      * @since 4.6
  450.      */
  451.     public ReceivedPackStatistics getReceivedPackStatistics() {
  452.         return stats.build();
  453.     }

  454.     /**
  455.      * Parse the pack stream.
  456.      *
  457.      * @param progress
  458.      *            callback to provide progress feedback during parsing. If null,
  459.      *            {@link org.eclipse.jgit.lib.NullProgressMonitor} will be used.
  460.      * @return the pack lock, if one was requested by setting
  461.      *         {@link #setLockMessage(String)}.
  462.      * @throws java.io.IOException
  463.      *             the stream is malformed, or contains corrupt objects.
  464.      * @since 3.0
  465.      */
  466.     public final PackLock parse(ProgressMonitor progress) throws IOException {
  467.         return parse(progress, progress);
  468.     }

  469.     /**
  470.      * Parse the pack stream.
  471.      *
  472.      * @param receiving
  473.      *            receives progress feedback during the initial receiving
  474.      *            objects phase. If null,
  475.      *            {@link org.eclipse.jgit.lib.NullProgressMonitor} will be used.
  476.      * @param resolving
  477.      *            receives progress feedback during the resolving objects phase.
  478.      * @return the pack lock, if one was requested by setting
  479.      *         {@link #setLockMessage(String)}.
  480.      * @throws java.io.IOException
  481.      *             the stream is malformed, or contains corrupt objects.
  482.      * @since 3.0
  483.      */
  484.     public PackLock parse(ProgressMonitor receiving, ProgressMonitor resolving)
  485.             throws IOException {
  486.         if (receiving == null)
  487.             receiving = NullProgressMonitor.INSTANCE;
  488.         if (resolving == null)
  489.             resolving = NullProgressMonitor.INSTANCE;

  490.         if (receiving == resolving)
  491.             receiving.start(2 /* tasks */);
  492.         try {
  493.             readPackHeader();

  494.             entries = new PackedObjectInfo[(int) expectedObjectCount];
  495.             baseById = new ObjectIdOwnerMap<>();
  496.             baseByPos = new LongMap<>();
  497.             collisionCheckObjs = new BlockList<>();

  498.             receiving.beginTask(JGitText.get().receivingObjects,
  499.                     (int) expectedObjectCount);
  500.             try {
  501.                 for (int done = 0; done < expectedObjectCount; done++) {
  502.                     indexOneObject();
  503.                     receiving.update(1);
  504.                     if (receiving.isCancelled())
  505.                         throw new IOException(JGitText.get().downloadCancelled);
  506.                 }
  507.                 readPackFooter();
  508.                 endInput();
  509.             } finally {
  510.                 receiving.endTask();
  511.             }

  512.             if (!collisionCheckObjs.isEmpty()) {
  513.                 checkObjectCollision();
  514.             }

  515.             if (deltaCount > 0) {
  516.                 processDeltas(resolving);
  517.             }

  518.             packDigest = null;
  519.             baseById = null;
  520.             baseByPos = null;
  521.         } finally {
  522.             try {
  523.                 if (readCurs != null)
  524.                     readCurs.close();
  525.             } finally {
  526.                 readCurs = null;
  527.             }

  528.             try {
  529.                 inflater.release();
  530.             } finally {
  531.                 inflater = null;
  532.             }
  533.         }
  534.         return null; // By default there is no locking.
  535.     }

  536.     private void processDeltas(ProgressMonitor resolving) throws IOException {
  537.         if (resolving instanceof BatchingProgressMonitor) {
  538.             ((BatchingProgressMonitor) resolving).setDelayStart(1000,
  539.                     TimeUnit.MILLISECONDS);
  540.         }
  541.         resolving.beginTask(JGitText.get().resolvingDeltas, deltaCount);
  542.         resolveDeltas(resolving);
  543.         if (entryCount < expectedObjectCount) {
  544.             if (!isAllowThin()) {
  545.                 throw new IOException(MessageFormat.format(
  546.                         JGitText.get().packHasUnresolvedDeltas,
  547.                         Long.valueOf(expectedObjectCount - entryCount)));
  548.             }

  549.             resolveDeltasWithExternalBases(resolving);

  550.             if (entryCount < expectedObjectCount) {
  551.                 throw new IOException(MessageFormat.format(
  552.                         JGitText.get().packHasUnresolvedDeltas,
  553.                         Long.valueOf(expectedObjectCount - entryCount)));
  554.             }
  555.         }
  556.         resolving.endTask();
  557.     }

  558.     private void resolveDeltas(ProgressMonitor progress)
  559.             throws IOException {
  560.         final int last = entryCount;
  561.         for (int i = 0; i < last; i++) {
  562.             resolveDeltas(entries[i], progress);
  563.             if (progress.isCancelled())
  564.                 throw new IOException(
  565.                         JGitText.get().downloadCancelledDuringIndexing);
  566.         }
  567.     }

  568.     private void resolveDeltas(final PackedObjectInfo oe,
  569.             ProgressMonitor progress) throws IOException {
  570.         UnresolvedDelta children = firstChildOf(oe);
  571.         if (children == null)
  572.             return;

  573.         DeltaVisit visit = new DeltaVisit();
  574.         visit.nextChild = children;

  575.         ObjectTypeAndSize info = openDatabase(oe, new ObjectTypeAndSize());
  576.         switch (info.type) {
  577.         case Constants.OBJ_COMMIT:
  578.         case Constants.OBJ_TREE:
  579.         case Constants.OBJ_BLOB:
  580.         case Constants.OBJ_TAG:
  581.             visit.data = inflateAndReturn(Source.DATABASE, info.size);
  582.             visit.id = oe;
  583.             break;
  584.         default:
  585.             throw new IOException(MessageFormat.format(
  586.                     JGitText.get().unknownObjectType,
  587.                     Integer.valueOf(info.type)));
  588.         }

  589.         if (!checkCRC(oe.getCRC())) {
  590.             throw new IOException(MessageFormat.format(
  591.                     JGitText.get().corruptionDetectedReReadingAt,
  592.                     Long.valueOf(oe.getOffset())));
  593.         }

  594.         resolveDeltas(visit.next(), info.type, info, progress);
  595.     }

  596.     private void resolveDeltas(DeltaVisit visit, final int type,
  597.             ObjectTypeAndSize info, ProgressMonitor progress)
  598.             throws IOException {
  599.         stats.addDeltaObject(type);
  600.         do {
  601.             progress.update(1);
  602.             info = openDatabase(visit.delta, info);
  603.             switch (info.type) {
  604.             case Constants.OBJ_OFS_DELTA:
  605.             case Constants.OBJ_REF_DELTA:
  606.                 break;

  607.             default:
  608.                 throw new IOException(MessageFormat.format(
  609.                         JGitText.get().unknownObjectType,
  610.                         Integer.valueOf(info.type)));
  611.             }

  612.             byte[] delta = inflateAndReturn(Source.DATABASE, info.size);
  613.             checkIfTooLarge(type, BinaryDelta.getResultSize(delta));

  614.             visit.data = BinaryDelta.apply(visit.parent.data, delta);
  615.             delta = null;

  616.             if (!checkCRC(visit.delta.crc))
  617.                 throw new IOException(MessageFormat.format(
  618.                         JGitText.get().corruptionDetectedReReadingAt,
  619.                         Long.valueOf(visit.delta.position)));

  620.             SHA1 objectDigest = objectHasher.reset();
  621.             objectDigest.update(Constants.encodedTypeString(type));
  622.             objectDigest.update((byte) ' ');
  623.             objectDigest.update(Constants.encodeASCII(visit.data.length));
  624.             objectDigest.update((byte) 0);
  625.             objectDigest.update(visit.data);
  626.             objectDigest.digest(tempObjectId);

  627.             verifySafeObject(tempObjectId, type, visit.data);
  628.             if (isCheckObjectCollisions() && readCurs.has(tempObjectId)) {
  629.                 checkObjectCollision(tempObjectId, type, visit.data);
  630.             }

  631.             PackedObjectInfo oe;
  632.             oe = newInfo(tempObjectId, visit.delta, visit.parent.id);
  633.             oe.setOffset(visit.delta.position);
  634.             oe.setType(type);
  635.             onInflatedObjectData(oe, type, visit.data);
  636.             addObjectAndTrack(oe);
  637.             visit.id = oe;

  638.             visit.nextChild = firstChildOf(oe);
  639.             visit = visit.next();
  640.         } while (visit != null);
  641.     }

  642.     private final void checkIfTooLarge(int typeCode, long size)
  643.             throws IOException {
  644.         if (0 < maxObjectSizeLimit && maxObjectSizeLimit < size) {
  645.             switch (typeCode) {
  646.             case Constants.OBJ_COMMIT:
  647.             case Constants.OBJ_TREE:
  648.             case Constants.OBJ_BLOB:
  649.             case Constants.OBJ_TAG:
  650.                 throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);

  651.             case Constants.OBJ_OFS_DELTA:
  652.             case Constants.OBJ_REF_DELTA:
  653.                 throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);

  654.             default:
  655.                 throw new IOException(MessageFormat.format(
  656.                         JGitText.get().unknownObjectType,
  657.                         Integer.valueOf(typeCode)));
  658.             }
  659.         }
  660.         if (size > Integer.MAX_VALUE - 8) {
  661.             throw new TooLargeObjectInPackException(size, Integer.MAX_VALUE - 8);
  662.         }
  663.     }

  664.     /**
  665.      * Read the header of the current object.
  666.      * <p>
  667.      * After the header has been parsed, this method automatically invokes
  668.      * {@link #onObjectHeader(Source, byte[], int, int)} to allow the
  669.      * implementation to update its internal checksums for the bytes read.
  670.      * <p>
  671.      * When this method returns the database will be positioned on the first
  672.      * byte of the deflated data stream.
  673.      *
  674.      * @param info
  675.      *            the info object to populate.
  676.      * @return {@code info}, after populating.
  677.      * @throws java.io.IOException
  678.      *             the size cannot be read.
  679.      */
  680.     protected ObjectTypeAndSize readObjectHeader(ObjectTypeAndSize info)
  681.             throws IOException {
  682.         int hdrPtr = 0;
  683.         int c = readFrom(Source.DATABASE);
  684.         hdrBuf[hdrPtr++] = (byte) c;

  685.         info.type = (c >> 4) & 7;
  686.         long sz = c & 15;
  687.         int shift = 4;
  688.         while ((c & 0x80) != 0) {
  689.             c = readFrom(Source.DATABASE);
  690.             hdrBuf[hdrPtr++] = (byte) c;
  691.             sz += ((long) (c & 0x7f)) << shift;
  692.             shift += 7;
  693.         }
  694.         info.size = sz;

  695.         switch (info.type) {
  696.         case Constants.OBJ_COMMIT:
  697.         case Constants.OBJ_TREE:
  698.         case Constants.OBJ_BLOB:
  699.         case Constants.OBJ_TAG:
  700.             onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  701.             break;

  702.         case Constants.OBJ_OFS_DELTA:
  703.             c = readFrom(Source.DATABASE);
  704.             hdrBuf[hdrPtr++] = (byte) c;
  705.             while ((c & 128) != 0) {
  706.                 c = readFrom(Source.DATABASE);
  707.                 hdrBuf[hdrPtr++] = (byte) c;
  708.             }
  709.             onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  710.             break;

  711.         case Constants.OBJ_REF_DELTA:
  712.             System.arraycopy(buf, fill(Source.DATABASE, 20), hdrBuf, hdrPtr, 20);
  713.             hdrPtr += 20;
  714.             use(20);
  715.             onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  716.             break;

  717.         default:
  718.             throw new IOException(MessageFormat.format(
  719.                     JGitText.get().unknownObjectType,
  720.                     Integer.valueOf(info.type)));
  721.         }
  722.         return info;
  723.     }

  724.     private UnresolvedDelta removeBaseById(AnyObjectId id) {
  725.         final DeltaChain d = baseById.get(id);
  726.         return d != null ? d.remove() : null;
  727.     }

  728.     private static UnresolvedDelta reverse(UnresolvedDelta c) {
  729.         UnresolvedDelta tail = null;
  730.         while (c != null) {
  731.             final UnresolvedDelta n = c.next;
  732.             c.next = tail;
  733.             tail = c;
  734.             c = n;
  735.         }
  736.         return tail;
  737.     }

  738.     private UnresolvedDelta firstChildOf(PackedObjectInfo oe) {
  739.         UnresolvedDelta a = reverse(removeBaseById(oe));
  740.         UnresolvedDelta b = reverse(baseByPos.remove(oe.getOffset()));

  741.         if (a == null)
  742.             return b;
  743.         if (b == null)
  744.             return a;

  745.         UnresolvedDelta first = null;
  746.         UnresolvedDelta last = null;
  747.         while (a != null || b != null) {
  748.             UnresolvedDelta curr;
  749.             if (b == null || (a != null && a.position < b.position)) {
  750.                 curr = a;
  751.                 a = a.next;
  752.             } else {
  753.                 curr = b;
  754.                 b = b.next;
  755.             }
  756.             if (last != null)
  757.                 last.next = curr;
  758.             else
  759.                 first = curr;
  760.             last = curr;
  761.             curr.next = null;
  762.         }
  763.         return first;
  764.     }

  765.     private void resolveDeltasWithExternalBases(ProgressMonitor progress)
  766.             throws IOException {
  767.         growEntries(baseById.size());

  768.         if (needBaseObjectIds)
  769.             baseObjectIds = new ObjectIdSubclassMap<>();

  770.         final List<DeltaChain> missing = new ArrayList<>(64);
  771.         for (DeltaChain baseId : baseById) {
  772.             if (baseId.head == null)
  773.                 continue;

  774.             if (needBaseObjectIds)
  775.                 baseObjectIds.add(baseId);

  776.             final ObjectLoader ldr;
  777.             try {
  778.                 ldr = readCurs.open(baseId);
  779.             } catch (MissingObjectException notFound) {
  780.                 missing.add(baseId);
  781.                 continue;
  782.             }

  783.             final DeltaVisit visit = new DeltaVisit();
  784.             visit.data = ldr.getCachedBytes(Integer.MAX_VALUE);
  785.             visit.id = baseId;
  786.             final int typeCode = ldr.getType();
  787.             final PackedObjectInfo oe = newInfo(baseId, null, null);
  788.             oe.setType(typeCode);
  789.             if (onAppendBase(typeCode, visit.data, oe))
  790.                 entries[entryCount++] = oe;
  791.             visit.nextChild = firstChildOf(oe);
  792.             resolveDeltas(visit.next(), typeCode,
  793.                     new ObjectTypeAndSize(), progress);

  794.             if (progress.isCancelled())
  795.                 throw new IOException(
  796.                         JGitText.get().downloadCancelledDuringIndexing);
  797.         }

  798.         for (DeltaChain base : missing) {
  799.             if (base.head != null)
  800.                 throw new MissingObjectException(base, "delta base"); //$NON-NLS-1$
  801.         }

  802.         onEndThinPack();
  803.     }

  804.     private void growEntries(int extraObjects) {
  805.         final PackedObjectInfo[] ne;

  806.         ne = new PackedObjectInfo[(int) expectedObjectCount + extraObjects];
  807.         System.arraycopy(entries, 0, ne, 0, entryCount);
  808.         entries = ne;
  809.     }

  810.     private void readPackHeader() throws IOException {
  811.         if (expectDataAfterPackFooter) {
  812.             if (!in.markSupported())
  813.                 throw new IOException(
  814.                         JGitText.get().inputStreamMustSupportMark);
  815.             in.mark(buf.length);
  816.         }

  817.         final int hdrln = Constants.PACK_SIGNATURE.length + 4 + 4;
  818.         final int p = fill(Source.INPUT, hdrln);
  819.         for (int k = 0; k < Constants.PACK_SIGNATURE.length; k++)
  820.             if (buf[p + k] != Constants.PACK_SIGNATURE[k])
  821.                 throw new IOException(JGitText.get().notAPACKFile);

  822.         final long vers = NB.decodeUInt32(buf, p + 4);
  823.         if (vers != 2 && vers != 3)
  824.             throw new IOException(MessageFormat.format(
  825.                     JGitText.get().unsupportedPackVersion, Long.valueOf(vers)));
  826.         final long objectCount = NB.decodeUInt32(buf, p + 8);
  827.         use(hdrln);
  828.         setExpectedObjectCount(objectCount);
  829.         onPackHeader(objectCount);
  830.     }

  831.     private void readPackFooter() throws IOException {
  832.         sync();
  833.         final byte[] actHash = packDigest.digest();

  834.         final int c = fill(Source.INPUT, 20);
  835.         final byte[] srcHash = new byte[20];
  836.         System.arraycopy(buf, c, srcHash, 0, 20);
  837.         use(20);

  838.         if (bAvail != 0 && !expectDataAfterPackFooter)
  839.             throw new CorruptObjectException(MessageFormat.format(
  840.                     JGitText.get().expectedEOFReceived,
  841.                     "\\x" + Integer.toHexString(buf[bOffset] & 0xff))); //$NON-NLS-1$
  842.         if (isCheckEofAfterPackFooter()) {
  843.             int eof = in.read();
  844.             if (0 <= eof)
  845.                 throw new CorruptObjectException(MessageFormat.format(
  846.                         JGitText.get().expectedEOFReceived,
  847.                         "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  848.         } else if (bAvail > 0 && expectDataAfterPackFooter) {
  849.             in.reset();
  850.             IO.skipFully(in, bOffset);
  851.         }

  852.         if (!Arrays.equals(actHash, srcHash))
  853.             throw new CorruptObjectException(
  854.                     JGitText.get().corruptObjectPackfileChecksumIncorrect);

  855.         onPackFooter(srcHash);
  856.     }

  857.     // Cleanup all resources associated with our input parsing.
  858.     private void endInput() {
  859.         stats.setNumBytesRead(streamPosition());
  860.         in = null;
  861.     }

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

  865.         int hdrPtr = 0;
  866.         int c = readFrom(Source.INPUT);
  867.         hdrBuf[hdrPtr++] = (byte) c;

  868.         final int typeCode = (c >> 4) & 7;
  869.         long sz = c & 15;
  870.         int shift = 4;
  871.         while ((c & 0x80) != 0) {
  872.             c = readFrom(Source.INPUT);
  873.             hdrBuf[hdrPtr++] = (byte) c;
  874.             sz += ((long) (c & 0x7f)) << shift;
  875.             shift += 7;
  876.         }

  877.         checkIfTooLarge(typeCode, sz);

  878.         switch (typeCode) {
  879.         case Constants.OBJ_COMMIT:
  880.         case Constants.OBJ_TREE:
  881.         case Constants.OBJ_BLOB:
  882.         case Constants.OBJ_TAG:
  883.             stats.addWholeObject(typeCode);
  884.             onBeginWholeObject(streamPosition, typeCode, sz);
  885.             onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  886.             whole(streamPosition, typeCode, sz);
  887.             break;

  888.         case Constants.OBJ_OFS_DELTA: {
  889.             stats.addOffsetDelta();
  890.             c = readFrom(Source.INPUT);
  891.             hdrBuf[hdrPtr++] = (byte) c;
  892.             long ofs = c & 127;
  893.             while ((c & 128) != 0) {
  894.                 ofs += 1;
  895.                 c = readFrom(Source.INPUT);
  896.                 hdrBuf[hdrPtr++] = (byte) c;
  897.                 ofs <<= 7;
  898.                 ofs += (c & 127);
  899.             }
  900.             final long base = streamPosition - ofs;
  901.             onBeginOfsDelta(streamPosition, base, sz);
  902.             onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  903.             inflateAndSkip(Source.INPUT, sz);
  904.             UnresolvedDelta n = onEndDelta();
  905.             n.position = streamPosition;
  906.             n.next = baseByPos.put(base, n);
  907.             deltaCount++;
  908.             break;
  909.         }

  910.         case Constants.OBJ_REF_DELTA: {
  911.             stats.addRefDelta();
  912.             c = fill(Source.INPUT, 20);
  913.             final ObjectId base = ObjectId.fromRaw(buf, c);
  914.             System.arraycopy(buf, c, hdrBuf, hdrPtr, 20);
  915.             hdrPtr += 20;
  916.             use(20);
  917.             DeltaChain r = baseById.get(base);
  918.             if (r == null) {
  919.                 r = new DeltaChain(base);
  920.                 baseById.add(r);
  921.             }
  922.             onBeginRefDelta(streamPosition, base, sz);
  923.             onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  924.             inflateAndSkip(Source.INPUT, sz);
  925.             UnresolvedDelta n = onEndDelta();
  926.             n.position = streamPosition;
  927.             r.add(n);
  928.             deltaCount++;
  929.             break;
  930.         }

  931.         default:
  932.             throw new IOException(
  933.                     MessageFormat.format(JGitText.get().unknownObjectType,
  934.                             Integer.valueOf(typeCode)));
  935.         }
  936.     }

  937.     private void whole(long pos, int type, long sz)
  938.             throws IOException {
  939.         SHA1 objectDigest = objectHasher.reset();
  940.         objectDigest.update(Constants.encodedTypeString(type));
  941.         objectDigest.update((byte) ' ');
  942.         objectDigest.update(Constants.encodeASCII(sz));
  943.         objectDigest.update((byte) 0);

  944.         final byte[] data;
  945.         if (type == Constants.OBJ_BLOB) {
  946.             byte[] readBuffer = buffer();
  947.             BlobObjectChecker checker = null;
  948.             if (objCheck != null) {
  949.                 checker = objCheck.newBlobObjectChecker();
  950.             }
  951.             if (checker == null) {
  952.                 checker = BlobObjectChecker.NULL_CHECKER;
  953.             }
  954.             long cnt = 0;
  955.             try (InputStream inf = inflate(Source.INPUT, sz)) {
  956.                 while (cnt < sz) {
  957.                     int r = inf.read(readBuffer);
  958.                     if (r <= 0)
  959.                         break;
  960.                     objectDigest.update(readBuffer, 0, r);
  961.                     checker.update(readBuffer, 0, r);
  962.                     cnt += r;
  963.                 }
  964.             }
  965.             objectDigest.digest(tempObjectId);
  966.             checker.endBlob(tempObjectId);
  967.             data = null;
  968.         } else {
  969.             data = inflateAndReturn(Source.INPUT, sz);
  970.             objectDigest.update(data);
  971.             objectDigest.digest(tempObjectId);
  972.             verifySafeObject(tempObjectId, type, data);
  973.         }

  974.         PackedObjectInfo obj = newInfo(tempObjectId, null, null);
  975.         obj.setOffset(pos);
  976.         obj.setType(type);
  977.         onEndWholeObject(obj);
  978.         if (data != null)
  979.             onInflatedObjectData(obj, type, data);
  980.         addObjectAndTrack(obj);

  981.         if (isCheckObjectCollisions()) {
  982.             collisionCheckObjs.add(obj);
  983.         }
  984.     }

  985.     /**
  986.      * Verify the integrity of the object.
  987.      *
  988.      * @param id
  989.      *            identity of the object to be checked.
  990.      * @param type
  991.      *            the type of the object.
  992.      * @param data
  993.      *            raw content of the object.
  994.      * @throws org.eclipse.jgit.errors.CorruptObjectException
  995.      * @since 4.9
  996.      */
  997.     protected void verifySafeObject(final AnyObjectId id, final int type,
  998.             final byte[] data) throws CorruptObjectException {
  999.         if (objCheck != null) {
  1000.             try {
  1001.                 objCheck.check(id, type, data);
  1002.             } catch (CorruptObjectException e) {
  1003.                 if (e.getErrorType() != null) {
  1004.                     throw e;
  1005.                 }
  1006.                 throw new CorruptObjectException(
  1007.                         MessageFormat.format(JGitText.get().invalidObject,
  1008.                                 Constants.typeString(type), id.name(),
  1009.                                 e.getMessage()),
  1010.                         e);
  1011.             }
  1012.         }
  1013.     }

  1014.     private void checkObjectCollision() throws IOException {
  1015.         for (PackedObjectInfo obj : collisionCheckObjs) {
  1016.             if (!readCurs.has(obj)) {
  1017.                 continue;
  1018.             }
  1019.             checkObjectCollision(obj);
  1020.         }
  1021.     }

  1022.     private void checkObjectCollision(PackedObjectInfo obj)
  1023.             throws IOException {
  1024.         ObjectTypeAndSize info = openDatabase(obj, new ObjectTypeAndSize());
  1025.         final byte[] readBuffer = buffer();
  1026.         final byte[] curBuffer = new byte[readBuffer.length];
  1027.         long sz = info.size;
  1028.         try (ObjectStream cur = readCurs.open(obj, info.type).openStream()) {
  1029.             if (cur.getSize() != sz) {
  1030.                 throw new IOException(MessageFormat.format(
  1031.                         JGitText.get().collisionOn, obj.name()));
  1032.             }
  1033.             try (InputStream pck = inflate(Source.DATABASE, sz)) {
  1034.                 while (0 < sz) {
  1035.                     int n = (int) Math.min(readBuffer.length, sz);
  1036.                     IO.readFully(cur, curBuffer, 0, n);
  1037.                     IO.readFully(pck, readBuffer, 0, n);
  1038.                     for (int i = 0; i < n; i++) {
  1039.                         if (curBuffer[i] != readBuffer[i]) {
  1040.                             throw new IOException(MessageFormat.format(
  1041.                                     JGitText.get().collisionOn, obj.name()));
  1042.                         }
  1043.                     }
  1044.                     sz -= n;
  1045.                 }
  1046.             }
  1047.         } catch (MissingObjectException notLocal) {
  1048.             // This is OK, we don't have a copy of the object locally
  1049.             // but the API throws when we try to read it as usually it's
  1050.             // an error to read something that doesn't exist.
  1051.         }
  1052.     }

  1053.     private void checkObjectCollision(AnyObjectId obj, int type, byte[] data)
  1054.             throws IOException {
  1055.         try {
  1056.             final ObjectLoader ldr = readCurs.open(obj, type);
  1057.             final byte[] existingData = ldr.getCachedBytes(data.length);
  1058.             if (!Arrays.equals(data, existingData)) {
  1059.                 throw new IOException(MessageFormat.format(
  1060.                         JGitText.get().collisionOn, obj.name()));
  1061.             }
  1062.         } catch (MissingObjectException notLocal) {
  1063.             // This is OK, we don't have a copy of the object locally
  1064.             // but the API throws when we try to read it as usually its
  1065.             // an error to read something that doesn't exist.
  1066.         }
  1067.     }

  1068.     /** @return current position of the input stream being parsed. */
  1069.     private long streamPosition() {
  1070.         return bBase + bOffset;
  1071.     }

  1072.     private ObjectTypeAndSize openDatabase(PackedObjectInfo obj,
  1073.             ObjectTypeAndSize info) throws IOException {
  1074.         bOffset = 0;
  1075.         bAvail = 0;
  1076.         return seekDatabase(obj, info);
  1077.     }

  1078.     private ObjectTypeAndSize openDatabase(UnresolvedDelta delta,
  1079.             ObjectTypeAndSize info) throws IOException {
  1080.         bOffset = 0;
  1081.         bAvail = 0;
  1082.         return seekDatabase(delta, info);
  1083.     }

  1084.     // Consume exactly one byte from the buffer and return it.
  1085.     private int readFrom(Source src) throws IOException {
  1086.         if (bAvail == 0)
  1087.             fill(src, 1);
  1088.         bAvail--;
  1089.         return buf[bOffset++] & 0xff;
  1090.     }

  1091.     // Consume cnt bytes from the buffer.
  1092.     void use(int cnt) {
  1093.         bOffset += cnt;
  1094.         bAvail -= cnt;
  1095.     }

  1096.     // Ensure at least need bytes are available in {@link #buf}.
  1097.     int fill(Source src, int need) throws IOException {
  1098.         while (bAvail < need) {
  1099.             int next = bOffset + bAvail;
  1100.             int free = buf.length - next;
  1101.             if (free + bAvail < need) {
  1102.                 switch (src) {
  1103.                 case INPUT:
  1104.                     sync();
  1105.                     break;
  1106.                 case DATABASE:
  1107.                     if (bAvail > 0)
  1108.                         System.arraycopy(buf, bOffset, buf, 0, bAvail);
  1109.                     bOffset = 0;
  1110.                     break;
  1111.                 }
  1112.                 next = bAvail;
  1113.                 free = buf.length - next;
  1114.             }
  1115.             switch (src) {
  1116.             case INPUT:
  1117.                 next = in.read(buf, next, free);
  1118.                 break;
  1119.             case DATABASE:
  1120.                 next = readDatabase(buf, next, free);
  1121.                 break;
  1122.             }
  1123.             if (next <= 0)
  1124.                 throw new EOFException(
  1125.                         JGitText.get().packfileIsTruncatedNoParam);
  1126.             bAvail += next;
  1127.         }
  1128.         return bOffset;
  1129.     }

  1130.     // Store consumed bytes in {@link #buf} up to {@link #bOffset}.
  1131.     private void sync() throws IOException {
  1132.         packDigest.update(buf, 0, bOffset);
  1133.         onStoreStream(buf, 0, bOffset);
  1134.         if (expectDataAfterPackFooter) {
  1135.             if (bAvail > 0) {
  1136.                 in.reset();
  1137.                 IO.skipFully(in, bOffset);
  1138.                 bAvail = 0;
  1139.             }
  1140.             in.mark(buf.length);
  1141.         } else if (bAvail > 0)
  1142.             System.arraycopy(buf, bOffset, buf, 0, bAvail);
  1143.         bBase += bOffset;
  1144.         bOffset = 0;
  1145.     }

  1146.     /**
  1147.      * Get a temporary byte array for use by the caller.
  1148.      *
  1149.      * @return a temporary byte array for use by the caller.
  1150.      */
  1151.     protected byte[] buffer() {
  1152.         return tempBuffer;
  1153.     }

  1154.     /**
  1155.      * Construct a PackedObjectInfo instance for this parser.
  1156.      *
  1157.      * @param id
  1158.      *            identity of the object to be tracked.
  1159.      * @param delta
  1160.      *            if the object was previously an unresolved delta, this is the
  1161.      *            delta object that was tracking it. Otherwise null.
  1162.      * @param deltaBase
  1163.      *            if the object was previously an unresolved delta, this is the
  1164.      *            ObjectId of the base of the delta. The base may be outside of
  1165.      *            the pack stream if the stream was a thin-pack.
  1166.      * @return info object containing this object's data.
  1167.      */
  1168.     protected PackedObjectInfo newInfo(AnyObjectId id, UnresolvedDelta delta,
  1169.             ObjectId deltaBase) {
  1170.         PackedObjectInfo oe = new PackedObjectInfo(id);
  1171.         if (delta != null)
  1172.             oe.setCRC(delta.crc);
  1173.         return oe;
  1174.     }

  1175.     /**
  1176.      * Set the expected number of objects in the pack stream.
  1177.      * <p>
  1178.      * The object count in the pack header is not always correct for some Dfs
  1179.      * pack files. e.g. INSERT pack always assume 1 object in the header since
  1180.      * the actual object count is unknown when the pack is written.
  1181.      * <p>
  1182.      * If external implementation wants to overwrite the expectedObjectCount,
  1183.      * they should call this method during {@link #onPackHeader(long)}.
  1184.      *
  1185.      * @param expectedObjectCount a long.
  1186.      * @since 4.9
  1187.      */
  1188.     protected void setExpectedObjectCount(long expectedObjectCount) {
  1189.         this.expectedObjectCount = expectedObjectCount;
  1190.     }

  1191.     /**
  1192.      * Store bytes received from the raw stream.
  1193.      * <p>
  1194.      * This method is invoked during {@link #parse(ProgressMonitor)} as data is
  1195.      * consumed from the incoming stream. Implementors may use this event to
  1196.      * archive the raw incoming stream to the destination repository in large
  1197.      * chunks, without paying attention to object boundaries.
  1198.      * <p>
  1199.      * The only component of the pack not supplied to this method is the last 20
  1200.      * bytes of the pack that comprise the trailing SHA-1 checksum. Those are
  1201.      * passed to {@link #onPackFooter(byte[])}.
  1202.      *
  1203.      * @param raw
  1204.      *            buffer to copy data out of.
  1205.      * @param pos
  1206.      *            first offset within the buffer that is valid.
  1207.      * @param len
  1208.      *            number of bytes in the buffer that are valid.
  1209.      * @throws java.io.IOException
  1210.      *             the stream cannot be archived.
  1211.      */
  1212.     protected abstract void onStoreStream(byte[] raw, int pos, int len)
  1213.             throws IOException;

  1214.     /**
  1215.      * Store (and/or checksum) an object header.
  1216.      * <p>
  1217.      * Invoked after any of the {@code onBegin()} events. The entire header is
  1218.      * supplied in a single invocation, before any object data is supplied.
  1219.      *
  1220.      * @param src
  1221.      *            where the data came from
  1222.      * @param raw
  1223.      *            buffer to read data from.
  1224.      * @param pos
  1225.      *            first offset within buffer that is valid.
  1226.      * @param len
  1227.      *            number of bytes in buffer that are valid.
  1228.      * @throws java.io.IOException
  1229.      *             the stream cannot be archived.
  1230.      */
  1231.     protected abstract void onObjectHeader(Source src, byte[] raw, int pos,
  1232.             int len) throws IOException;

  1233.     /**
  1234.      * Store (and/or checksum) a portion of an object's data.
  1235.      * <p>
  1236.      * This method may be invoked multiple times per object, depending on the
  1237.      * size of the object, the size of the parser's internal read buffer, and
  1238.      * the alignment of the object relative to the read buffer.
  1239.      * <p>
  1240.      * Invoked after {@link #onObjectHeader(Source, byte[], int, int)}.
  1241.      *
  1242.      * @param src
  1243.      *            where the data came from
  1244.      * @param raw
  1245.      *            buffer to read data from.
  1246.      * @param pos
  1247.      *            first offset within buffer that is valid.
  1248.      * @param len
  1249.      *            number of bytes in buffer that are valid.
  1250.      * @throws java.io.IOException
  1251.      *             the stream cannot be archived.
  1252.      */
  1253.     protected abstract void onObjectData(Source src, byte[] raw, int pos,
  1254.             int len) throws IOException;

  1255.     /**
  1256.      * Invoked for commits, trees, tags, and small blobs.
  1257.      *
  1258.      * @param obj
  1259.      *            the object info, populated.
  1260.      * @param typeCode
  1261.      *            the type of the object.
  1262.      * @param data
  1263.      *            inflated data for the object.
  1264.      * @throws java.io.IOException
  1265.      *             the object cannot be archived.
  1266.      */
  1267.     protected abstract void onInflatedObjectData(PackedObjectInfo obj,
  1268.             int typeCode, byte[] data) throws IOException;

  1269.     /**
  1270.      * Provide the implementation with the original stream's pack header.
  1271.      *
  1272.      * @param objCnt
  1273.      *            number of objects expected in the stream.
  1274.      * @throws java.io.IOException
  1275.      *             the implementation refuses to work with this many objects.
  1276.      */
  1277.     protected abstract void onPackHeader(long objCnt) throws IOException;

  1278.     /**
  1279.      * Provide the implementation with the original stream's pack footer.
  1280.      *
  1281.      * @param hash
  1282.      *            the trailing 20 bytes of the pack, this is a SHA-1 checksum of
  1283.      *            all of the pack data.
  1284.      * @throws java.io.IOException
  1285.      *             the stream cannot be archived.
  1286.      */
  1287.     protected abstract void onPackFooter(byte[] hash) throws IOException;

  1288.     /**
  1289.      * Provide the implementation with a base that was outside of the pack.
  1290.      * <p>
  1291.      * This event only occurs on a thin pack for base objects that were outside
  1292.      * of the pack and came from the local repository. Usually an implementation
  1293.      * uses this event to compress the base and append it onto the end of the
  1294.      * pack, so the pack stays self-contained.
  1295.      *
  1296.      * @param typeCode
  1297.      *            type of the base object.
  1298.      * @param data
  1299.      *            complete content of the base object.
  1300.      * @param info
  1301.      *            packed object information for this base. Implementors must
  1302.      *            populate the CRC and offset members if returning true.
  1303.      * @return true if the {@code info} should be included in the object list
  1304.      *         returned by {@link #getSortedObjectList(Comparator)}, false if it
  1305.      *         should not be included.
  1306.      * @throws java.io.IOException
  1307.      *             the base could not be included into the pack.
  1308.      */
  1309.     protected abstract boolean onAppendBase(int typeCode, byte[] data,
  1310.             PackedObjectInfo info) throws IOException;

  1311.     /**
  1312.      * Event indicating a thin pack has been completely processed.
  1313.      * <p>
  1314.      * This event is invoked only if a thin pack has delta references to objects
  1315.      * external from the pack. The event is called after all of those deltas
  1316.      * have been resolved.
  1317.      *
  1318.      * @throws java.io.IOException
  1319.      *             the pack cannot be archived.
  1320.      */
  1321.     protected abstract void onEndThinPack() throws IOException;

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

  1339.     /**
  1340.      * Reposition the database to re-read a previously stored object.
  1341.      * <p>
  1342.      * If the database is computing CRC-32 checksums for object data, it should
  1343.      * reset its internal CRC instance during this method call.
  1344.      *
  1345.      * @param delta
  1346.      *            the object position to begin reading from. This is an instance
  1347.      *            previously returned by {@link #onEndDelta()}.
  1348.      * @param info
  1349.      *            object to populate with type and size.
  1350.      * @return the {@code info} object.
  1351.      * @throws java.io.IOException
  1352.      *             the database cannot reposition to this location.
  1353.      */
  1354.     protected abstract ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
  1355.             ObjectTypeAndSize info) throws IOException;

  1356.     /**
  1357.      * Read from the database's current position into the buffer.
  1358.      *
  1359.      * @param dst
  1360.      *            the buffer to copy read data into.
  1361.      * @param pos
  1362.      *            position within {@code dst} to start copying data into.
  1363.      * @param cnt
  1364.      *            ideal target number of bytes to read. Actual read length may
  1365.      *            be shorter.
  1366.      * @return number of bytes stored.
  1367.      * @throws java.io.IOException
  1368.      *             the database cannot be accessed.
  1369.      */
  1370.     protected abstract int readDatabase(byte[] dst, int pos, int cnt)
  1371.             throws IOException;

  1372.     /**
  1373.      * Check the current CRC matches the expected value.
  1374.      * <p>
  1375.      * This method is invoked when an object is read back in from the database
  1376.      * and its data is used during delta resolution. The CRC is validated after
  1377.      * the object has been fully read, allowing the parser to verify there was
  1378.      * no silent data corruption.
  1379.      * <p>
  1380.      * Implementations are free to ignore this check by always returning true if
  1381.      * they are performing other data integrity validations at a lower level.
  1382.      *
  1383.      * @param oldCRC
  1384.      *            the prior CRC that was recorded during the first scan of the
  1385.      *            object from the pack stream.
  1386.      * @return true if the CRC matches; false if it does not.
  1387.      */
  1388.     protected abstract boolean checkCRC(int oldCRC);

  1389.     /**
  1390.      * Event notifying the start of an object stored whole (not as a delta).
  1391.      *
  1392.      * @param streamPosition
  1393.      *            position of this object in the incoming stream.
  1394.      * @param type
  1395.      *            type of the object; one of
  1396.      *            {@link org.eclipse.jgit.lib.Constants#OBJ_COMMIT},
  1397.      *            {@link org.eclipse.jgit.lib.Constants#OBJ_TREE},
  1398.      *            {@link org.eclipse.jgit.lib.Constants#OBJ_BLOB}, or
  1399.      *            {@link org.eclipse.jgit.lib.Constants#OBJ_TAG}.
  1400.      * @param inflatedSize
  1401.      *            size of the object when fully inflated. The size stored within
  1402.      *            the pack may be larger or smaller, and is not yet known.
  1403.      * @throws java.io.IOException
  1404.      *             the object cannot be recorded.
  1405.      */
  1406.     protected abstract void onBeginWholeObject(long streamPosition, int type,
  1407.             long inflatedSize) throws IOException;

  1408.     /**
  1409.      * Event notifying the current object.
  1410.      *
  1411.      *@param info
  1412.      *            object information.
  1413.      * @throws java.io.IOException
  1414.      *             the object cannot be recorded.
  1415.      */
  1416.     protected abstract void onEndWholeObject(PackedObjectInfo info)
  1417.             throws IOException;

  1418.     /**
  1419.      * Event notifying start of a delta referencing its base by offset.
  1420.      *
  1421.      * @param deltaStreamPosition
  1422.      *            position of this object in the incoming stream.
  1423.      * @param baseStreamPosition
  1424.      *            position of the base object in the incoming stream. The base
  1425.      *            must be before the delta, therefore {@code baseStreamPosition
  1426.      *            &lt; deltaStreamPosition}. This is <b>not</b> the position
  1427.      *            returned by a prior end object event.
  1428.      * @param inflatedSize
  1429.      *            size of the delta when fully inflated. The size stored within
  1430.      *            the pack may be larger or smaller, and is not yet known.
  1431.      * @throws java.io.IOException
  1432.      *             the object cannot be recorded.
  1433.      */
  1434.     protected abstract void onBeginOfsDelta(long deltaStreamPosition,
  1435.             long baseStreamPosition, long inflatedSize) throws IOException;

  1436.     /**
  1437.      * Event notifying start of a delta referencing its base by ObjectId.
  1438.      *
  1439.      * @param deltaStreamPosition
  1440.      *            position of this object in the incoming stream.
  1441.      * @param baseId
  1442.      *            name of the base object. This object may be later in the
  1443.      *            stream, or might not appear at all in the stream (in the case
  1444.      *            of a thin-pack).
  1445.      * @param inflatedSize
  1446.      *            size of the delta when fully inflated. The size stored within
  1447.      *            the pack may be larger or smaller, and is not yet known.
  1448.      * @throws java.io.IOException
  1449.      *             the object cannot be recorded.
  1450.      */
  1451.     protected abstract void onBeginRefDelta(long deltaStreamPosition,
  1452.             AnyObjectId baseId, long inflatedSize) throws IOException;

  1453.     /**
  1454.      * Event notifying the current object.
  1455.      *
  1456.      *@return object information that must be populated with at least the
  1457.      *         offset.
  1458.      * @throws java.io.IOException
  1459.      *             the object cannot be recorded.
  1460.      */
  1461.     protected UnresolvedDelta onEndDelta() throws IOException {
  1462.         return new UnresolvedDelta();
  1463.     }

  1464.     /** Type and size information about an object in the database buffer. */
  1465.     public static class ObjectTypeAndSize {
  1466.         /** The type of the object. */
  1467.         public int type;

  1468.         /** The inflated size of the object. */
  1469.         public long size;
  1470.     }

  1471.     private void inflateAndSkip(Source src, long inflatedSize)
  1472.             throws IOException {
  1473.         try (InputStream inf = inflate(src, inflatedSize)) {
  1474.             IO.skipFully(inf, inflatedSize);
  1475.         }
  1476.     }

  1477.     private byte[] inflateAndReturn(Source src, long inflatedSize)
  1478.             throws IOException {
  1479.         final byte[] dst = new byte[(int) inflatedSize];
  1480.         try (InputStream inf = inflate(src, inflatedSize)) {
  1481.             IO.readFully(inf, dst, 0, dst.length);
  1482.         }
  1483.         return dst;
  1484.     }

  1485.     private InputStream inflate(Source src, long inflatedSize)
  1486.             throws IOException {
  1487.         inflater.open(src, inflatedSize);
  1488.         return inflater;
  1489.     }

  1490.     private static class DeltaChain extends ObjectIdOwnerMap.Entry {
  1491.         UnresolvedDelta head;

  1492.         DeltaChain(AnyObjectId id) {
  1493.             super(id);
  1494.         }

  1495.         UnresolvedDelta remove() {
  1496.             final UnresolvedDelta r = head;
  1497.             if (r != null)
  1498.                 head = null;
  1499.             return r;
  1500.         }

  1501.         void add(UnresolvedDelta d) {
  1502.             d.next = head;
  1503.             head = d;
  1504.         }
  1505.     }

  1506.     /** Information about an unresolved delta in this pack stream. */
  1507.     public static class UnresolvedDelta {
  1508.         long position;

  1509.         int crc;

  1510.         UnresolvedDelta next;

  1511.         /** @return offset within the input stream. */
  1512.         public long getOffset() {
  1513.             return position;
  1514.         }

  1515.         /** @return the CRC-32 checksum of the stored delta data. */
  1516.         public int getCRC() {
  1517.             return crc;
  1518.         }

  1519.         /**
  1520.          * @param crc32
  1521.          *            the CRC-32 checksum of the stored delta data.
  1522.          */
  1523.         public void setCRC(int crc32) {
  1524.             crc = crc32;
  1525.         }
  1526.     }

  1527.     private static class DeltaVisit {
  1528.         final UnresolvedDelta delta;

  1529.         ObjectId id;

  1530.         byte[] data;

  1531.         DeltaVisit parent;

  1532.         UnresolvedDelta nextChild;

  1533.         DeltaVisit() {
  1534.             this.delta = null; // At the root of the stack we have a base.
  1535.         }

  1536.         DeltaVisit(DeltaVisit parent) {
  1537.             this.parent = parent;
  1538.             this.delta = parent.nextChild;
  1539.             parent.nextChild = delta.next;
  1540.         }

  1541.         DeltaVisit next() {
  1542.             // If our parent has no more children, discard it.
  1543.             if (parent != null && parent.nextChild == null) {
  1544.                 parent.data = null;
  1545.                 parent = parent.parent;
  1546.             }

  1547.             if (nextChild != null)
  1548.                 return new DeltaVisit(this);

  1549.             // If we have no child ourselves, our parent must (if it exists),
  1550.             // due to the discard rule above. With no parent, we are done.
  1551.             if (parent != null)
  1552.                 return new DeltaVisit(parent);
  1553.             return null;
  1554.         }
  1555.     }

  1556.     private void addObjectAndTrack(PackedObjectInfo oe) {
  1557.         entries[entryCount++] = oe;
  1558.         if (needNewObjectIds())
  1559.             newObjectIds.add(oe);
  1560.     }

  1561.     private class InflaterStream extends InputStream {
  1562.         private final Inflater inf;

  1563.         private final byte[] skipBuffer;

  1564.         private Source src;

  1565.         private long expectedSize;

  1566.         private long actualSize;

  1567.         private int p;

  1568.         InflaterStream() {
  1569.             inf = InflaterCache.get();
  1570.             skipBuffer = new byte[512];
  1571.         }

  1572.         void release() {
  1573.             inf.reset();
  1574.             InflaterCache.release(inf);
  1575.         }

  1576.         void open(Source source, long inflatedSize) throws IOException {
  1577.             src = source;
  1578.             expectedSize = inflatedSize;
  1579.             actualSize = 0;

  1580.             p = fill(src, 1);
  1581.             inf.setInput(buf, p, bAvail);
  1582.         }

  1583.         @Override
  1584.         public long skip(long toSkip) throws IOException {
  1585.             long n = 0;
  1586.             while (n < toSkip) {
  1587.                 final int cnt = (int) Math.min(skipBuffer.length, toSkip - n);
  1588.                 final int r = read(skipBuffer, 0, cnt);
  1589.                 if (r <= 0)
  1590.                     break;
  1591.                 n += r;
  1592.             }
  1593.             return n;
  1594.         }

  1595.         @Override
  1596.         public int read() throws IOException {
  1597.             int n = read(skipBuffer, 0, 1);
  1598.             return n == 1 ? skipBuffer[0] & 0xff : -1;
  1599.         }

  1600.         @Override
  1601.         public int read(byte[] dst, int pos, int cnt) throws IOException {
  1602.             try {
  1603.                 int n = 0;
  1604.                 while (n < cnt) {
  1605.                     int r = inf.inflate(dst, pos + n, cnt - n);
  1606.                     n += r;
  1607.                     if (inf.finished())
  1608.                         break;
  1609.                     if (inf.needsInput()) {
  1610.                         onObjectData(src, buf, p, bAvail);
  1611.                         use(bAvail);

  1612.                         p = fill(src, 1);
  1613.                         inf.setInput(buf, p, bAvail);
  1614.                     } else if (r == 0) {
  1615.                         throw new CorruptObjectException(MessageFormat.format(
  1616.                                 JGitText.get().packfileCorruptionDetected,
  1617.                                 JGitText.get().unknownZlibError));
  1618.                     }
  1619.                 }
  1620.                 actualSize += n;
  1621.                 return 0 < n ? n : -1;
  1622.             } catch (DataFormatException dfe) {
  1623.                 throw new CorruptObjectException(MessageFormat.format(JGitText
  1624.                         .get().packfileCorruptionDetected, dfe.getMessage()));
  1625.             }
  1626.         }

  1627.         @Override
  1628.         public void close() throws IOException {
  1629.             // We need to read here to enter the loop above and pump the
  1630.             // trailing checksum into the Inflater. It should return -1 as the
  1631.             // caller was supposed to consume all content.
  1632.             //
  1633.             if (read(skipBuffer) != -1 || actualSize != expectedSize) {
  1634.                 throw new CorruptObjectException(MessageFormat.format(JGitText
  1635.                         .get().packfileCorruptionDetected,
  1636.                         JGitText.get().wrongDecompressedLength));
  1637.             }

  1638.             int used = bAvail - inf.getRemaining();
  1639.             if (0 < used) {
  1640.                 onObjectData(src, buf, p, used);
  1641.                 use(used);
  1642.             }

  1643.             inf.reset();
  1644.         }
  1645.     }
  1646. }