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

PackParser.java 53KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824
  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.ObjectInserter;
  77. import org.eclipse.jgit.lib.ObjectLoader;
  78. import org.eclipse.jgit.lib.ObjectReader;
  79. import org.eclipse.jgit.lib.ObjectStream;
  80. import org.eclipse.jgit.lib.ProgressMonitor;
  81. import org.eclipse.jgit.util.BlockList;
  82. import org.eclipse.jgit.util.IO;
  83. import org.eclipse.jgit.util.LongMap;
  84. import org.eclipse.jgit.util.NB;
  85. import org.eclipse.jgit.util.sha1.SHA1;
  86. /**
  87. * Parses a pack stream and imports it for an {@link ObjectInserter}.
  88. * <p>
  89. * Applications can acquire an instance of a parser from ObjectInserter's
  90. * {@link ObjectInserter#newPackParser(InputStream)} method.
  91. * <p>
  92. * Implementations of {@link ObjectInserter} should subclass this type and
  93. * provide their own logic for the various {@code on*()} event methods declared
  94. * to be abstract.
  95. */
  96. public abstract class PackParser {
  97. /** Size of the internal stream buffer. */
  98. private static final int BUFFER_SIZE = 8192;
  99. /** Location data is being obtained from. */
  100. public static enum Source {
  101. /** Data is read from the incoming stream. */
  102. INPUT,
  103. /** Data is read back from the database's buffers. */
  104. DATABASE;
  105. }
  106. /** Object database used for loading existing objects. */
  107. private final ObjectDatabase objectDatabase;
  108. private InflaterStream inflater;
  109. private byte[] tempBuffer;
  110. private byte[] hdrBuf;
  111. private final SHA1 objectHasher = SHA1.newInstance();
  112. private final MutableObjectId tempObjectId;
  113. private InputStream in;
  114. byte[] buf;
  115. /** Position in the input stream of {@code buf[0]}. */
  116. private long bBase;
  117. private int bOffset;
  118. int bAvail;
  119. private ObjectChecker objCheck;
  120. private boolean allowThin;
  121. private boolean checkObjectCollisions;
  122. private boolean needBaseObjectIds;
  123. private boolean checkEofAfterPackFooter;
  124. private boolean expectDataAfterPackFooter;
  125. private long expectedObjectCount;
  126. private PackedObjectInfo[] entries;
  127. /**
  128. * Every object contained within the incoming pack.
  129. * <p>
  130. * This is a subset of {@link #entries}, as thin packs can add additional
  131. * objects to {@code entries} by copying already existing objects from the
  132. * repository onto the end of the thin pack to make it self-contained.
  133. */
  134. private ObjectIdSubclassMap<ObjectId> newObjectIds;
  135. private int deltaCount;
  136. private int entryCount;
  137. private ObjectIdOwnerMap<DeltaChain> baseById;
  138. /**
  139. * Objects referenced by their name from deltas, that aren't in this pack.
  140. * <p>
  141. * This is the set of objects that were copied onto the end of this pack to
  142. * make it complete. These objects were not transmitted by the remote peer,
  143. * but instead were assumed to already exist in the local repository.
  144. */
  145. private ObjectIdSubclassMap<ObjectId> baseObjectIds;
  146. private LongMap<UnresolvedDelta> baseByPos;
  147. /** Objects need to be double-checked for collision after indexing. */
  148. private BlockList<PackedObjectInfo> collisionCheckObjs;
  149. private MessageDigest packDigest;
  150. private ObjectReader readCurs;
  151. /** Message to protect the pack data from garbage collection. */
  152. private String lockMessage;
  153. /** Git object size limit */
  154. private long maxObjectSizeLimit;
  155. private final ReceivedPackStatistics.Builder stats =
  156. new ReceivedPackStatistics.Builder();
  157. /**
  158. * Initialize a pack parser.
  159. *
  160. * @param odb
  161. * database the parser will write its objects into.
  162. * @param src
  163. * the stream the parser will read.
  164. */
  165. protected PackParser(final ObjectDatabase odb, final InputStream src) {
  166. objectDatabase = odb.newCachedDatabase();
  167. in = src;
  168. inflater = new InflaterStream();
  169. readCurs = objectDatabase.newReader();
  170. buf = new byte[BUFFER_SIZE];
  171. tempBuffer = new byte[BUFFER_SIZE];
  172. hdrBuf = new byte[64];
  173. tempObjectId = new MutableObjectId();
  174. packDigest = Constants.newMessageDigest();
  175. checkObjectCollisions = true;
  176. }
  177. /** @return true if a thin pack (missing base objects) is permitted. */
  178. public boolean isAllowThin() {
  179. return allowThin;
  180. }
  181. /**
  182. * Configure this index pack instance to allow a thin pack.
  183. * <p>
  184. * Thin packs are sometimes used during network transfers to allow a delta
  185. * to be sent without a base object. Such packs are not permitted on disk.
  186. *
  187. * @param allow
  188. * true to enable a thin pack.
  189. */
  190. public void setAllowThin(final boolean allow) {
  191. allowThin = allow;
  192. }
  193. /**
  194. * @return if true received objects are verified to prevent collisions.
  195. * @since 4.1
  196. */
  197. protected boolean isCheckObjectCollisions() {
  198. return checkObjectCollisions;
  199. }
  200. /**
  201. * Enable checking for collisions with existing objects.
  202. * <p>
  203. * By default PackParser looks for each received object in the repository.
  204. * If the object already exists, the existing object is compared
  205. * byte-for-byte with the newly received copy to ensure they are identical.
  206. * The receive is aborted with an exception if any byte differs. This check
  207. * is necessary to prevent an evil attacker from supplying a replacement
  208. * object into this repository in the event that a discovery enabling SHA-1
  209. * collisions is made.
  210. * <p>
  211. * This check may be very costly to perform, and some repositories may have
  212. * other ways to segregate newly received object data. The check is enabled
  213. * by default, but can be explicitly disabled if the implementation can
  214. * provide the same guarantee, or is willing to accept the risks associated
  215. * with bypassing the check.
  216. *
  217. * @param check
  218. * true to enable collision checking (strongly encouraged).
  219. * @since 4.1
  220. */
  221. protected void setCheckObjectCollisions(boolean check) {
  222. checkObjectCollisions = check;
  223. }
  224. /**
  225. * Configure this index pack instance to keep track of new objects.
  226. * <p>
  227. * By default an index pack doesn't save the new objects that were created
  228. * when it was instantiated. Setting this flag to {@code true} allows the
  229. * caller to use {@link #getNewObjectIds()} to retrieve that list.
  230. *
  231. * @param b
  232. * {@code true} to enable keeping track of new objects.
  233. */
  234. public void setNeedNewObjectIds(boolean b) {
  235. if (b)
  236. newObjectIds = new ObjectIdSubclassMap<>();
  237. else
  238. newObjectIds = null;
  239. }
  240. private boolean needNewObjectIds() {
  241. return newObjectIds != null;
  242. }
  243. /**
  244. * Configure this index pack instance to keep track of the objects assumed
  245. * for delta bases.
  246. * <p>
  247. * By default an index pack doesn't save the objects that were used as delta
  248. * bases. Setting this flag to {@code true} will allow the caller to use
  249. * {@link #getBaseObjectIds()} to retrieve that list.
  250. *
  251. * @param b
  252. * {@code true} to enable keeping track of delta bases.
  253. */
  254. public void setNeedBaseObjectIds(boolean b) {
  255. this.needBaseObjectIds = b;
  256. }
  257. /** @return true if the EOF should be read from the input after the footer. */
  258. public boolean isCheckEofAfterPackFooter() {
  259. return checkEofAfterPackFooter;
  260. }
  261. /**
  262. * Ensure EOF is read from the input stream after the footer.
  263. *
  264. * @param b
  265. * true if the EOF should be read; false if it is not checked.
  266. */
  267. public void setCheckEofAfterPackFooter(boolean b) {
  268. checkEofAfterPackFooter = b;
  269. }
  270. /** @return true if there is data expected after the pack footer. */
  271. public boolean isExpectDataAfterPackFooter() {
  272. return expectDataAfterPackFooter;
  273. }
  274. /**
  275. * @param e
  276. * true if there is additional data in InputStream after pack.
  277. * This requires the InputStream to support the mark and reset
  278. * functions.
  279. */
  280. public void setExpectDataAfterPackFooter(boolean e) {
  281. expectDataAfterPackFooter = e;
  282. }
  283. /** @return the new objects that were sent by the user */
  284. public ObjectIdSubclassMap<ObjectId> getNewObjectIds() {
  285. if (newObjectIds != null)
  286. return newObjectIds;
  287. return new ObjectIdSubclassMap<>();
  288. }
  289. /** @return set of objects the incoming pack assumed for delta purposes */
  290. public ObjectIdSubclassMap<ObjectId> getBaseObjectIds() {
  291. if (baseObjectIds != null)
  292. return baseObjectIds;
  293. return new ObjectIdSubclassMap<>();
  294. }
  295. /**
  296. * Configure the checker used to validate received objects.
  297. * <p>
  298. * Usually object checking isn't necessary, as Git implementations only
  299. * create valid objects in pack files. However, additional checking may be
  300. * useful if processing data from an untrusted source.
  301. *
  302. * @param oc
  303. * the checker instance; null to disable object checking.
  304. */
  305. public void setObjectChecker(final ObjectChecker oc) {
  306. objCheck = oc;
  307. }
  308. /**
  309. * Configure the checker used to validate received objects.
  310. * <p>
  311. * Usually object checking isn't necessary, as Git implementations only
  312. * create valid objects in pack files. However, additional checking may be
  313. * useful if processing data from an untrusted source.
  314. * <p>
  315. * This is shorthand for:
  316. *
  317. * <pre>
  318. * setObjectChecker(on ? new ObjectChecker() : null);
  319. * </pre>
  320. *
  321. * @param on
  322. * true to enable the default checker; false to disable it.
  323. */
  324. public void setObjectChecking(final boolean on) {
  325. setObjectChecker(on ? new ObjectChecker() : null);
  326. }
  327. /** @return the message to record with the pack lock. */
  328. public String getLockMessage() {
  329. return lockMessage;
  330. }
  331. /**
  332. * Set the lock message for the incoming pack data.
  333. *
  334. * @param msg
  335. * if not null, the message to associate with the incoming data
  336. * while it is locked to prevent garbage collection.
  337. */
  338. public void setLockMessage(String msg) {
  339. lockMessage = msg;
  340. }
  341. /**
  342. * Set the maximum allowed Git object size.
  343. * <p>
  344. * If an object is larger than the given size the pack-parsing will throw an
  345. * exception aborting the parsing.
  346. *
  347. * @param limit
  348. * the Git object size limit. If zero then there is not limit.
  349. */
  350. public void setMaxObjectSizeLimit(long limit) {
  351. maxObjectSizeLimit = limit;
  352. }
  353. /**
  354. * Get the number of objects in the stream.
  355. * <p>
  356. * The object count is only available after {@link #parse(ProgressMonitor)}
  357. * has returned. The count may have been increased if the stream was a thin
  358. * pack, and missing bases objects were appending onto it by the subclass.
  359. *
  360. * @return number of objects parsed out of the stream.
  361. */
  362. public int getObjectCount() {
  363. return entryCount;
  364. }
  365. /***
  366. * Get the information about the requested object.
  367. * <p>
  368. * The object information is only available after
  369. * {@link #parse(ProgressMonitor)} has returned.
  370. *
  371. * @param nth
  372. * index of the object in the stream. Must be between 0 and
  373. * {@link #getObjectCount()}-1.
  374. * @return the object information.
  375. */
  376. public PackedObjectInfo getObject(int nth) {
  377. return entries[nth];
  378. }
  379. /**
  380. * Get all of the objects, sorted by their name.
  381. * <p>
  382. * The object information is only available after
  383. * {@link #parse(ProgressMonitor)} has returned.
  384. * <p>
  385. * To maintain lower memory usage and good runtime performance, this method
  386. * sorts the objects in-place and therefore impacts the ordering presented
  387. * by {@link #getObject(int)}.
  388. *
  389. * @param cmp
  390. * comparison function, if null objects are stored by ObjectId.
  391. * @return sorted list of objects in this pack stream.
  392. */
  393. public List<PackedObjectInfo> getSortedObjectList(
  394. Comparator<PackedObjectInfo> cmp) {
  395. Arrays.sort(entries, 0, entryCount, cmp);
  396. List<PackedObjectInfo> list = Arrays.asList(entries);
  397. if (entryCount < entries.length)
  398. list = list.subList(0, entryCount);
  399. return list;
  400. }
  401. /**
  402. * Get the size of the newly created pack.
  403. * <p>
  404. * This will also include the pack index size if an index was created. This
  405. * method should only be called after pack parsing is finished.
  406. *
  407. * @return the pack size (including the index size) or -1 if the size cannot
  408. * be determined
  409. * @since 3.3
  410. */
  411. public long getPackSize() {
  412. return -1;
  413. }
  414. /**
  415. * Returns the statistics of the parsed pack.
  416. * <p>
  417. * This should only be called after pack parsing is finished.
  418. *
  419. * @return {@link ReceivedPackStatistics}
  420. * @since 4.6
  421. */
  422. public ReceivedPackStatistics getReceivedPackStatistics() {
  423. return stats.build();
  424. }
  425. /**
  426. * Parse the pack stream.
  427. *
  428. * @param progress
  429. * callback to provide progress feedback during parsing. If null,
  430. * {@link NullProgressMonitor} will be used.
  431. * @return the pack lock, if one was requested by setting
  432. * {@link #setLockMessage(String)}.
  433. * @throws IOException
  434. * the stream is malformed, or contains corrupt objects.
  435. * @since 3.0
  436. */
  437. public final PackLock parse(ProgressMonitor progress) throws IOException {
  438. return parse(progress, progress);
  439. }
  440. /**
  441. * Parse the pack stream.
  442. *
  443. * @param receiving
  444. * receives progress feedback during the initial receiving
  445. * objects phase. If null, {@link NullProgressMonitor} will be
  446. * used.
  447. * @param resolving
  448. * receives progress feedback during the resolving objects phase.
  449. * @return the pack lock, if one was requested by setting
  450. * {@link #setLockMessage(String)}.
  451. * @throws IOException
  452. * the stream is malformed, or contains corrupt objects.
  453. * @since 3.0
  454. */
  455. public PackLock parse(ProgressMonitor receiving, ProgressMonitor resolving)
  456. throws IOException {
  457. if (receiving == null)
  458. receiving = NullProgressMonitor.INSTANCE;
  459. if (resolving == null)
  460. resolving = NullProgressMonitor.INSTANCE;
  461. if (receiving == resolving)
  462. receiving.start(2 /* tasks */);
  463. try {
  464. readPackHeader();
  465. entries = new PackedObjectInfo[(int) expectedObjectCount];
  466. baseById = new ObjectIdOwnerMap<>();
  467. baseByPos = new LongMap<>();
  468. collisionCheckObjs = new BlockList<>();
  469. receiving.beginTask(JGitText.get().receivingObjects,
  470. (int) expectedObjectCount);
  471. try {
  472. for (int done = 0; done < expectedObjectCount; done++) {
  473. indexOneObject();
  474. receiving.update(1);
  475. if (receiving.isCancelled())
  476. throw new IOException(JGitText.get().downloadCancelled);
  477. }
  478. readPackFooter();
  479. endInput();
  480. } finally {
  481. receiving.endTask();
  482. }
  483. if (!collisionCheckObjs.isEmpty()) {
  484. checkObjectCollision();
  485. }
  486. if (deltaCount > 0) {
  487. processDeltas(resolving);
  488. }
  489. packDigest = null;
  490. baseById = null;
  491. baseByPos = null;
  492. } finally {
  493. try {
  494. if (readCurs != null)
  495. readCurs.close();
  496. } finally {
  497. readCurs = null;
  498. }
  499. try {
  500. inflater.release();
  501. } finally {
  502. inflater = null;
  503. }
  504. }
  505. return null; // By default there is no locking.
  506. }
  507. private void processDeltas(ProgressMonitor resolving) throws IOException {
  508. if (resolving instanceof BatchingProgressMonitor) {
  509. ((BatchingProgressMonitor) resolving).setDelayStart(1000,
  510. TimeUnit.MILLISECONDS);
  511. }
  512. resolving.beginTask(JGitText.get().resolvingDeltas, deltaCount);
  513. resolveDeltas(resolving);
  514. if (entryCount < expectedObjectCount) {
  515. if (!isAllowThin()) {
  516. throw new IOException(MessageFormat.format(
  517. JGitText.get().packHasUnresolvedDeltas,
  518. Long.valueOf(expectedObjectCount - entryCount)));
  519. }
  520. resolveDeltasWithExternalBases(resolving);
  521. if (entryCount < expectedObjectCount) {
  522. throw new IOException(MessageFormat.format(
  523. JGitText.get().packHasUnresolvedDeltas,
  524. Long.valueOf(expectedObjectCount - entryCount)));
  525. }
  526. }
  527. resolving.endTask();
  528. }
  529. private void resolveDeltas(final ProgressMonitor progress)
  530. throws IOException {
  531. final int last = entryCount;
  532. for (int i = 0; i < last; i++) {
  533. resolveDeltas(entries[i], progress);
  534. if (progress.isCancelled())
  535. throw new IOException(
  536. JGitText.get().downloadCancelledDuringIndexing);
  537. }
  538. }
  539. private void resolveDeltas(final PackedObjectInfo oe,
  540. ProgressMonitor progress) throws IOException {
  541. UnresolvedDelta children = firstChildOf(oe);
  542. if (children == null)
  543. return;
  544. DeltaVisit visit = new DeltaVisit();
  545. visit.nextChild = children;
  546. ObjectTypeAndSize info = openDatabase(oe, new ObjectTypeAndSize());
  547. switch (info.type) {
  548. case Constants.OBJ_COMMIT:
  549. case Constants.OBJ_TREE:
  550. case Constants.OBJ_BLOB:
  551. case Constants.OBJ_TAG:
  552. visit.data = inflateAndReturn(Source.DATABASE, info.size);
  553. visit.id = oe;
  554. break;
  555. default:
  556. throw new IOException(MessageFormat.format(
  557. JGitText.get().unknownObjectType,
  558. Integer.valueOf(info.type)));
  559. }
  560. if (!checkCRC(oe.getCRC())) {
  561. throw new IOException(MessageFormat.format(
  562. JGitText.get().corruptionDetectedReReadingAt,
  563. Long.valueOf(oe.getOffset())));
  564. }
  565. resolveDeltas(visit.next(), info.type, info, progress);
  566. }
  567. private void resolveDeltas(DeltaVisit visit, final int type,
  568. ObjectTypeAndSize info, ProgressMonitor progress)
  569. throws IOException {
  570. stats.addDeltaObject(type);
  571. do {
  572. progress.update(1);
  573. info = openDatabase(visit.delta, info);
  574. switch (info.type) {
  575. case Constants.OBJ_OFS_DELTA:
  576. case Constants.OBJ_REF_DELTA:
  577. break;
  578. default:
  579. throw new IOException(MessageFormat.format(
  580. JGitText.get().unknownObjectType,
  581. Integer.valueOf(info.type)));
  582. }
  583. byte[] delta = inflateAndReturn(Source.DATABASE, info.size);
  584. checkIfTooLarge(type, BinaryDelta.getResultSize(delta));
  585. visit.data = BinaryDelta.apply(visit.parent.data, delta);
  586. delta = null;
  587. if (!checkCRC(visit.delta.crc))
  588. throw new IOException(MessageFormat.format(
  589. JGitText.get().corruptionDetectedReReadingAt,
  590. Long.valueOf(visit.delta.position)));
  591. SHA1 objectDigest = objectHasher.reset();
  592. objectDigest.update(Constants.encodedTypeString(type));
  593. objectDigest.update((byte) ' ');
  594. objectDigest.update(Constants.encodeASCII(visit.data.length));
  595. objectDigest.update((byte) 0);
  596. objectDigest.update(visit.data);
  597. objectDigest.digest(tempObjectId);
  598. verifySafeObject(tempObjectId, type, visit.data);
  599. if (isCheckObjectCollisions() && readCurs.has(tempObjectId)) {
  600. checkObjectCollision(tempObjectId, type, visit.data);
  601. }
  602. PackedObjectInfo oe;
  603. oe = newInfo(tempObjectId, visit.delta, visit.parent.id);
  604. oe.setOffset(visit.delta.position);
  605. oe.setType(type);
  606. onInflatedObjectData(oe, type, visit.data);
  607. addObjectAndTrack(oe);
  608. visit.id = oe;
  609. visit.nextChild = firstChildOf(oe);
  610. visit = visit.next();
  611. } while (visit != null);
  612. }
  613. private final void checkIfTooLarge(int typeCode, long size)
  614. throws IOException {
  615. if (0 < maxObjectSizeLimit && maxObjectSizeLimit < size) {
  616. switch (typeCode) {
  617. case Constants.OBJ_COMMIT:
  618. case Constants.OBJ_TREE:
  619. case Constants.OBJ_BLOB:
  620. case Constants.OBJ_TAG:
  621. throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);
  622. case Constants.OBJ_OFS_DELTA:
  623. case Constants.OBJ_REF_DELTA:
  624. throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);
  625. default:
  626. throw new IOException(MessageFormat.format(
  627. JGitText.get().unknownObjectType,
  628. Integer.valueOf(typeCode)));
  629. }
  630. }
  631. if (size > Integer.MAX_VALUE - 8) {
  632. throw new TooLargeObjectInPackException(size, Integer.MAX_VALUE - 8);
  633. }
  634. }
  635. /**
  636. * Read the header of the current object.
  637. * <p>
  638. * After the header has been parsed, this method automatically invokes
  639. * {@link #onObjectHeader(Source, byte[], int, int)} to allow the
  640. * implementation to update its internal checksums for the bytes read.
  641. * <p>
  642. * When this method returns the database will be positioned on the first
  643. * byte of the deflated data stream.
  644. *
  645. * @param info
  646. * the info object to populate.
  647. * @return {@code info}, after populating.
  648. * @throws IOException
  649. * the size cannot be read.
  650. */
  651. protected ObjectTypeAndSize readObjectHeader(ObjectTypeAndSize info)
  652. throws IOException {
  653. int hdrPtr = 0;
  654. int c = readFrom(Source.DATABASE);
  655. hdrBuf[hdrPtr++] = (byte) c;
  656. info.type = (c >> 4) & 7;
  657. long sz = c & 15;
  658. int shift = 4;
  659. while ((c & 0x80) != 0) {
  660. c = readFrom(Source.DATABASE);
  661. hdrBuf[hdrPtr++] = (byte) c;
  662. sz += ((long) (c & 0x7f)) << shift;
  663. shift += 7;
  664. }
  665. info.size = sz;
  666. switch (info.type) {
  667. case Constants.OBJ_COMMIT:
  668. case Constants.OBJ_TREE:
  669. case Constants.OBJ_BLOB:
  670. case Constants.OBJ_TAG:
  671. onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  672. break;
  673. case Constants.OBJ_OFS_DELTA:
  674. c = readFrom(Source.DATABASE);
  675. hdrBuf[hdrPtr++] = (byte) c;
  676. while ((c & 128) != 0) {
  677. c = readFrom(Source.DATABASE);
  678. hdrBuf[hdrPtr++] = (byte) c;
  679. }
  680. onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  681. break;
  682. case Constants.OBJ_REF_DELTA:
  683. System.arraycopy(buf, fill(Source.DATABASE, 20), hdrBuf, hdrPtr, 20);
  684. hdrPtr += 20;
  685. use(20);
  686. onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  687. break;
  688. default:
  689. throw new IOException(MessageFormat.format(
  690. JGitText.get().unknownObjectType,
  691. Integer.valueOf(info.type)));
  692. }
  693. return info;
  694. }
  695. private UnresolvedDelta removeBaseById(final AnyObjectId id) {
  696. final DeltaChain d = baseById.get(id);
  697. return d != null ? d.remove() : null;
  698. }
  699. private static UnresolvedDelta reverse(UnresolvedDelta c) {
  700. UnresolvedDelta tail = null;
  701. while (c != null) {
  702. final UnresolvedDelta n = c.next;
  703. c.next = tail;
  704. tail = c;
  705. c = n;
  706. }
  707. return tail;
  708. }
  709. private UnresolvedDelta firstChildOf(PackedObjectInfo oe) {
  710. UnresolvedDelta a = reverse(removeBaseById(oe));
  711. UnresolvedDelta b = reverse(baseByPos.remove(oe.getOffset()));
  712. if (a == null)
  713. return b;
  714. if (b == null)
  715. return a;
  716. UnresolvedDelta first = null;
  717. UnresolvedDelta last = null;
  718. while (a != null || b != null) {
  719. UnresolvedDelta curr;
  720. if (b == null || (a != null && a.position < b.position)) {
  721. curr = a;
  722. a = a.next;
  723. } else {
  724. curr = b;
  725. b = b.next;
  726. }
  727. if (last != null)
  728. last.next = curr;
  729. else
  730. first = curr;
  731. last = curr;
  732. curr.next = null;
  733. }
  734. return first;
  735. }
  736. private void resolveDeltasWithExternalBases(final ProgressMonitor progress)
  737. throws IOException {
  738. growEntries(baseById.size());
  739. if (needBaseObjectIds)
  740. baseObjectIds = new ObjectIdSubclassMap<>();
  741. final List<DeltaChain> missing = new ArrayList<>(64);
  742. for (final DeltaChain baseId : baseById) {
  743. if (baseId.head == null)
  744. continue;
  745. if (needBaseObjectIds)
  746. baseObjectIds.add(baseId);
  747. final ObjectLoader ldr;
  748. try {
  749. ldr = readCurs.open(baseId);
  750. } catch (MissingObjectException notFound) {
  751. missing.add(baseId);
  752. continue;
  753. }
  754. final DeltaVisit visit = new DeltaVisit();
  755. visit.data = ldr.getCachedBytes(Integer.MAX_VALUE);
  756. visit.id = baseId;
  757. final int typeCode = ldr.getType();
  758. final PackedObjectInfo oe = newInfo(baseId, null, null);
  759. oe.setType(typeCode);
  760. if (onAppendBase(typeCode, visit.data, oe))
  761. entries[entryCount++] = oe;
  762. visit.nextChild = firstChildOf(oe);
  763. resolveDeltas(visit.next(), typeCode,
  764. new ObjectTypeAndSize(), progress);
  765. if (progress.isCancelled())
  766. throw new IOException(
  767. JGitText.get().downloadCancelledDuringIndexing);
  768. }
  769. for (final DeltaChain base : missing) {
  770. if (base.head != null)
  771. throw new MissingObjectException(base, "delta base"); //$NON-NLS-1$
  772. }
  773. onEndThinPack();
  774. }
  775. private void growEntries(int extraObjects) {
  776. final PackedObjectInfo[] ne;
  777. ne = new PackedObjectInfo[(int) expectedObjectCount + extraObjects];
  778. System.arraycopy(entries, 0, ne, 0, entryCount);
  779. entries = ne;
  780. }
  781. private void readPackHeader() throws IOException {
  782. if (expectDataAfterPackFooter) {
  783. if (!in.markSupported())
  784. throw new IOException(
  785. JGitText.get().inputStreamMustSupportMark);
  786. in.mark(buf.length);
  787. }
  788. final int hdrln = Constants.PACK_SIGNATURE.length + 4 + 4;
  789. final int p = fill(Source.INPUT, hdrln);
  790. for (int k = 0; k < Constants.PACK_SIGNATURE.length; k++)
  791. if (buf[p + k] != Constants.PACK_SIGNATURE[k])
  792. throw new IOException(JGitText.get().notAPACKFile);
  793. final long vers = NB.decodeUInt32(buf, p + 4);
  794. if (vers != 2 && vers != 3)
  795. throw new IOException(MessageFormat.format(
  796. JGitText.get().unsupportedPackVersion, Long.valueOf(vers)));
  797. final long objectCount = NB.decodeUInt32(buf, p + 8);
  798. use(hdrln);
  799. setExpectedObjectCount(objectCount);
  800. onPackHeader(objectCount);
  801. }
  802. private void readPackFooter() throws IOException {
  803. sync();
  804. final byte[] actHash = packDigest.digest();
  805. final int c = fill(Source.INPUT, 20);
  806. final byte[] srcHash = new byte[20];
  807. System.arraycopy(buf, c, srcHash, 0, 20);
  808. use(20);
  809. if (bAvail != 0 && !expectDataAfterPackFooter)
  810. throw new CorruptObjectException(MessageFormat.format(
  811. JGitText.get().expectedEOFReceived,
  812. "\\x" + Integer.toHexString(buf[bOffset] & 0xff))); //$NON-NLS-1$
  813. if (isCheckEofAfterPackFooter()) {
  814. int eof = in.read();
  815. if (0 <= eof)
  816. throw new CorruptObjectException(MessageFormat.format(
  817. JGitText.get().expectedEOFReceived,
  818. "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  819. } else if (bAvail > 0 && expectDataAfterPackFooter) {
  820. in.reset();
  821. IO.skipFully(in, bOffset);
  822. }
  823. if (!Arrays.equals(actHash, srcHash))
  824. throw new CorruptObjectException(
  825. JGitText.get().corruptObjectPackfileChecksumIncorrect);
  826. onPackFooter(srcHash);
  827. }
  828. // Cleanup all resources associated with our input parsing.
  829. private void endInput() {
  830. stats.setNumBytesRead(streamPosition());
  831. in = null;
  832. }
  833. // Read one entire object or delta from the input.
  834. private void indexOneObject() throws IOException {
  835. final long streamPosition = streamPosition();
  836. int hdrPtr = 0;
  837. int c = readFrom(Source.INPUT);
  838. hdrBuf[hdrPtr++] = (byte) c;
  839. final int typeCode = (c >> 4) & 7;
  840. long sz = c & 15;
  841. int shift = 4;
  842. while ((c & 0x80) != 0) {
  843. c = readFrom(Source.INPUT);
  844. hdrBuf[hdrPtr++] = (byte) c;
  845. sz += ((long) (c & 0x7f)) << shift;
  846. shift += 7;
  847. }
  848. checkIfTooLarge(typeCode, sz);
  849. switch (typeCode) {
  850. case Constants.OBJ_COMMIT:
  851. case Constants.OBJ_TREE:
  852. case Constants.OBJ_BLOB:
  853. case Constants.OBJ_TAG:
  854. stats.addWholeObject(typeCode);
  855. onBeginWholeObject(streamPosition, typeCode, sz);
  856. onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  857. whole(streamPosition, typeCode, sz);
  858. break;
  859. case Constants.OBJ_OFS_DELTA: {
  860. stats.addOffsetDelta();
  861. c = readFrom(Source.INPUT);
  862. hdrBuf[hdrPtr++] = (byte) c;
  863. long ofs = c & 127;
  864. while ((c & 128) != 0) {
  865. ofs += 1;
  866. c = readFrom(Source.INPUT);
  867. hdrBuf[hdrPtr++] = (byte) c;
  868. ofs <<= 7;
  869. ofs += (c & 127);
  870. }
  871. final long base = streamPosition - ofs;
  872. onBeginOfsDelta(streamPosition, base, sz);
  873. onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  874. inflateAndSkip(Source.INPUT, sz);
  875. UnresolvedDelta n = onEndDelta();
  876. n.position = streamPosition;
  877. n.next = baseByPos.put(base, n);
  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. r.add(n);
  899. deltaCount++;
  900. break;
  901. }
  902. default:
  903. throw new IOException(
  904. MessageFormat.format(JGitText.get().unknownObjectType,
  905. Integer.valueOf(typeCode)));
  906. }
  907. }
  908. private void whole(final long pos, final int type, final long sz)
  909. throws IOException {
  910. SHA1 objectDigest = objectHasher.reset();
  911. objectDigest.update(Constants.encodedTypeString(type));
  912. objectDigest.update((byte) ' ');
  913. objectDigest.update(Constants.encodeASCII(sz));
  914. objectDigest.update((byte) 0);
  915. final byte[] data;
  916. if (type == Constants.OBJ_BLOB) {
  917. byte[] readBuffer = buffer();
  918. InputStream inf = inflate(Source.INPUT, sz);
  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. while (cnt < sz) {
  928. int r = inf.read(readBuffer);
  929. if (r <= 0)
  930. break;
  931. objectDigest.update(readBuffer, 0, r);
  932. checker.update(readBuffer, 0, r);
  933. cnt += r;
  934. }
  935. inf.close();
  936. objectDigest.digest(tempObjectId);
  937. checker.endBlob(tempObjectId);
  938. data = null;
  939. } else {
  940. data = inflateAndReturn(Source.INPUT, sz);
  941. objectDigest.update(data);
  942. objectDigest.digest(tempObjectId);
  943. verifySafeObject(tempObjectId, type, data);
  944. }
  945. PackedObjectInfo obj = newInfo(tempObjectId, null, null);
  946. obj.setOffset(pos);
  947. obj.setType(type);
  948. onEndWholeObject(obj);
  949. if (data != null)
  950. onInflatedObjectData(obj, type, data);
  951. addObjectAndTrack(obj);
  952. if (isCheckObjectCollisions()) {
  953. collisionCheckObjs.add(obj);
  954. }
  955. }
  956. /**
  957. * Verify the integrity of the object.
  958. *
  959. * @param id
  960. * identity of the object to be checked.
  961. * @param type
  962. * the type of the object.
  963. * @param data
  964. * raw content of the object.
  965. * @throws CorruptObjectException
  966. * @since 4.9
  967. *
  968. */
  969. protected void verifySafeObject(final AnyObjectId id, final int type,
  970. final byte[] data) throws CorruptObjectException {
  971. if (objCheck != null) {
  972. try {
  973. objCheck.check(id, type, data);
  974. } catch (CorruptObjectException e) {
  975. if (e.getErrorType() != null) {
  976. throw e;
  977. }
  978. throw new CorruptObjectException(
  979. MessageFormat.format(JGitText.get().invalidObject,
  980. Constants.typeString(type), id.name(),
  981. e.getMessage()),
  982. e);
  983. }
  984. }
  985. }
  986. private void checkObjectCollision() throws IOException {
  987. for (PackedObjectInfo obj : collisionCheckObjs) {
  988. if (!readCurs.has(obj)) {
  989. continue;
  990. }
  991. checkObjectCollision(obj);
  992. }
  993. }
  994. private void checkObjectCollision(PackedObjectInfo obj)
  995. throws IOException {
  996. ObjectTypeAndSize info = openDatabase(obj, new ObjectTypeAndSize());
  997. final byte[] readBuffer = buffer();
  998. final byte[] curBuffer = new byte[readBuffer.length];
  999. long sz = info.size;
  1000. InputStream pck = null;
  1001. try (ObjectStream cur = readCurs.open(obj, info.type).openStream()) {
  1002. if (cur.getSize() != sz) {
  1003. throw new IOException(MessageFormat.format(
  1004. JGitText.get().collisionOn, obj.name()));
  1005. }
  1006. pck = inflate(Source.DATABASE, sz);
  1007. while (0 < sz) {
  1008. int n = (int) Math.min(readBuffer.length, sz);
  1009. IO.readFully(cur, curBuffer, 0, n);
  1010. IO.readFully(pck, readBuffer, 0, n);
  1011. for (int i = 0; i < n; i++) {
  1012. if (curBuffer[i] != readBuffer[i]) {
  1013. throw new IOException(MessageFormat.format(JGitText
  1014. .get().collisionOn, obj.name()));
  1015. }
  1016. }
  1017. sz -= n;
  1018. }
  1019. } catch (MissingObjectException notLocal) {
  1020. // This is OK, we don't have a copy of the object locally
  1021. // but the API throws when we try to read it as usually its
  1022. // an error to read something that doesn't exist.
  1023. } finally {
  1024. if (pck != null) {
  1025. pck.close();
  1026. }
  1027. }
  1028. }
  1029. private void checkObjectCollision(AnyObjectId obj, int type, byte[] data)
  1030. throws IOException {
  1031. try {
  1032. final ObjectLoader ldr = readCurs.open(obj, type);
  1033. final byte[] existingData = ldr.getCachedBytes(data.length);
  1034. if (!Arrays.equals(data, existingData)) {
  1035. throw new IOException(MessageFormat.format(
  1036. JGitText.get().collisionOn, obj.name()));
  1037. }
  1038. } catch (MissingObjectException notLocal) {
  1039. // This is OK, we don't have a copy of the object locally
  1040. // but the API throws when we try to read it as usually its
  1041. // an error to read something that doesn't exist.
  1042. }
  1043. }
  1044. /** @return current position of the input stream being parsed. */
  1045. private long streamPosition() {
  1046. return bBase + bOffset;
  1047. }
  1048. private ObjectTypeAndSize openDatabase(PackedObjectInfo obj,
  1049. ObjectTypeAndSize info) throws IOException {
  1050. bOffset = 0;
  1051. bAvail = 0;
  1052. return seekDatabase(obj, info);
  1053. }
  1054. private ObjectTypeAndSize openDatabase(UnresolvedDelta delta,
  1055. ObjectTypeAndSize info) throws IOException {
  1056. bOffset = 0;
  1057. bAvail = 0;
  1058. return seekDatabase(delta, info);
  1059. }
  1060. // Consume exactly one byte from the buffer and return it.
  1061. private int readFrom(final Source src) throws IOException {
  1062. if (bAvail == 0)
  1063. fill(src, 1);
  1064. bAvail--;
  1065. return buf[bOffset++] & 0xff;
  1066. }
  1067. // Consume cnt bytes from the buffer.
  1068. void use(final int cnt) {
  1069. bOffset += cnt;
  1070. bAvail -= cnt;
  1071. }
  1072. // Ensure at least need bytes are available in in {@link #buf}.
  1073. int fill(final Source src, final int need) throws IOException {
  1074. while (bAvail < need) {
  1075. int next = bOffset + bAvail;
  1076. int free = buf.length - next;
  1077. if (free + bAvail < need) {
  1078. switch (src) {
  1079. case INPUT:
  1080. sync();
  1081. break;
  1082. case DATABASE:
  1083. if (bAvail > 0)
  1084. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  1085. bOffset = 0;
  1086. break;
  1087. }
  1088. next = bAvail;
  1089. free = buf.length - next;
  1090. }
  1091. switch (src) {
  1092. case INPUT:
  1093. next = in.read(buf, next, free);
  1094. break;
  1095. case DATABASE:
  1096. next = readDatabase(buf, next, free);
  1097. break;
  1098. }
  1099. if (next <= 0)
  1100. throw new EOFException(
  1101. JGitText.get().packfileIsTruncatedNoParam);
  1102. bAvail += next;
  1103. }
  1104. return bOffset;
  1105. }
  1106. // Store consumed bytes in {@link #buf} up to {@link #bOffset}.
  1107. private void sync() throws IOException {
  1108. packDigest.update(buf, 0, bOffset);
  1109. onStoreStream(buf, 0, bOffset);
  1110. if (expectDataAfterPackFooter) {
  1111. if (bAvail > 0) {
  1112. in.reset();
  1113. IO.skipFully(in, bOffset);
  1114. bAvail = 0;
  1115. }
  1116. in.mark(buf.length);
  1117. } else if (bAvail > 0)
  1118. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  1119. bBase += bOffset;
  1120. bOffset = 0;
  1121. }
  1122. /** @return a temporary byte array for use by the caller. */
  1123. protected byte[] buffer() {
  1124. return tempBuffer;
  1125. }
  1126. /**
  1127. * Construct a PackedObjectInfo instance for this parser.
  1128. *
  1129. * @param id
  1130. * identity of the object to be tracked.
  1131. * @param delta
  1132. * if the object was previously an unresolved delta, this is the
  1133. * delta object that was tracking it. Otherwise null.
  1134. * @param deltaBase
  1135. * if the object was previously an unresolved delta, this is the
  1136. * ObjectId of the base of the delta. The base may be outside of
  1137. * the pack stream if the stream was a thin-pack.
  1138. * @return info object containing this object's data.
  1139. */
  1140. protected PackedObjectInfo newInfo(AnyObjectId id, UnresolvedDelta delta,
  1141. ObjectId deltaBase) {
  1142. PackedObjectInfo oe = new PackedObjectInfo(id);
  1143. if (delta != null)
  1144. oe.setCRC(delta.crc);
  1145. return oe;
  1146. }
  1147. /**
  1148. * Set the expected number of objects in the pack stream.
  1149. * <p>
  1150. * The object count in the pack header is not always correct for some Dfs
  1151. * pack files. e.g. INSERT pack always assume 1 object in the header since
  1152. * the actual object count is unknown when the pack is written.
  1153. * <p>
  1154. * If external implementation wants to overwrite the expectedObjectCount,
  1155. * they should call this method during {@link #onPackHeader(long)}.
  1156. *
  1157. * @param expectedObjectCount
  1158. * @since 4.9
  1159. */
  1160. protected void setExpectedObjectCount(long expectedObjectCount) {
  1161. this.expectedObjectCount = expectedObjectCount;
  1162. }
  1163. /**
  1164. * Store bytes received from the raw stream.
  1165. * <p>
  1166. * This method is invoked during {@link #parse(ProgressMonitor)} as data is
  1167. * consumed from the incoming stream. Implementors may use this event to
  1168. * archive the raw incoming stream to the destination repository in large
  1169. * chunks, without paying attention to object boundaries.
  1170. * <p>
  1171. * The only component of the pack not supplied to this method is the last 20
  1172. * bytes of the pack that comprise the trailing SHA-1 checksum. Those are
  1173. * passed to {@link #onPackFooter(byte[])}.
  1174. *
  1175. * @param raw
  1176. * buffer to copy data out of.
  1177. * @param pos
  1178. * first offset within the buffer that is valid.
  1179. * @param len
  1180. * number of bytes in the buffer that are valid.
  1181. * @throws IOException
  1182. * the stream cannot be archived.
  1183. */
  1184. protected abstract void onStoreStream(byte[] raw, int pos, int len)
  1185. throws IOException;
  1186. /**
  1187. * Store (and/or checksum) an object header.
  1188. * <p>
  1189. * Invoked after any of the {@code onBegin()} events. The entire header is
  1190. * supplied in a single invocation, before any object data is supplied.
  1191. *
  1192. * @param src
  1193. * where the data came from
  1194. * @param raw
  1195. * buffer to read data from.
  1196. * @param pos
  1197. * first offset within buffer that is valid.
  1198. * @param len
  1199. * number of bytes in buffer that are valid.
  1200. * @throws IOException
  1201. * the stream cannot be archived.
  1202. */
  1203. protected abstract void onObjectHeader(Source src, byte[] raw, int pos,
  1204. int len) throws IOException;
  1205. /**
  1206. * Store (and/or checksum) a portion of an object's data.
  1207. * <p>
  1208. * This method may be invoked multiple times per object, depending on the
  1209. * size of the object, the size of the parser's internal read buffer, and
  1210. * the alignment of the object relative to the read buffer.
  1211. * <p>
  1212. * Invoked after {@link #onObjectHeader(Source, byte[], int, int)}.
  1213. *
  1214. * @param src
  1215. * where the data came from
  1216. * @param raw
  1217. * buffer to read data from.
  1218. * @param pos
  1219. * first offset within buffer that is valid.
  1220. * @param len
  1221. * number of bytes in buffer that are valid.
  1222. * @throws IOException
  1223. * the stream cannot be archived.
  1224. */
  1225. protected abstract void onObjectData(Source src, byte[] raw, int pos,
  1226. int len) throws IOException;
  1227. /**
  1228. * Invoked for commits, trees, tags, and small blobs.
  1229. *
  1230. * @param obj
  1231. * the object info, populated.
  1232. * @param typeCode
  1233. * the type of the object.
  1234. * @param data
  1235. * inflated data for the object.
  1236. * @throws IOException
  1237. * the object cannot be archived.
  1238. */
  1239. protected abstract void onInflatedObjectData(PackedObjectInfo obj,
  1240. int typeCode, byte[] data) throws IOException;
  1241. /**
  1242. * Provide the implementation with the original stream's pack header.
  1243. *
  1244. * @param objCnt
  1245. * number of objects expected in the stream.
  1246. * @throws IOException
  1247. * the implementation refuses to work with this many objects.
  1248. */
  1249. protected abstract void onPackHeader(long objCnt) throws IOException;
  1250. /**
  1251. * Provide the implementation with the original stream's pack footer.
  1252. *
  1253. * @param hash
  1254. * the trailing 20 bytes of the pack, this is a SHA-1 checksum of
  1255. * all of the pack data.
  1256. * @throws IOException
  1257. * the stream cannot be archived.
  1258. */
  1259. protected abstract void onPackFooter(byte[] hash) throws IOException;
  1260. /**
  1261. * Provide the implementation with a base that was outside of the pack.
  1262. * <p>
  1263. * This event only occurs on a thin pack for base objects that were outside
  1264. * of the pack and came from the local repository. Usually an implementation
  1265. * uses this event to compress the base and append it onto the end of the
  1266. * pack, so the pack stays self-contained.
  1267. *
  1268. * @param typeCode
  1269. * type of the base object.
  1270. * @param data
  1271. * complete content of the base object.
  1272. * @param info
  1273. * packed object information for this base. Implementors must
  1274. * populate the CRC and offset members if returning true.
  1275. * @return true if the {@code info} should be included in the object list
  1276. * returned by {@link #getSortedObjectList(Comparator)}, false if it
  1277. * should not be included.
  1278. * @throws IOException
  1279. * the base could not be included into the pack.
  1280. */
  1281. protected abstract boolean onAppendBase(int typeCode, byte[] data,
  1282. PackedObjectInfo info) throws IOException;
  1283. /**
  1284. * Event indicating a thin pack has been completely processed.
  1285. * <p>
  1286. * This event is invoked only if a thin pack has delta references to objects
  1287. * external from the pack. The event is called after all of those deltas
  1288. * have been resolved.
  1289. *
  1290. * @throws IOException
  1291. * the pack cannot be archived.
  1292. */
  1293. protected abstract void onEndThinPack() throws IOException;
  1294. /**
  1295. * Reposition the database to re-read a previously stored object.
  1296. * <p>
  1297. * If the database is computing CRC-32 checksums for object data, it should
  1298. * reset its internal CRC instance during this method call.
  1299. *
  1300. * @param obj
  1301. * the object position to begin reading from. This is from
  1302. * {@link #newInfo(AnyObjectId, UnresolvedDelta, ObjectId)}.
  1303. * @param info
  1304. * object to populate with type and size.
  1305. * @return the {@code info} object.
  1306. * @throws IOException
  1307. * the database cannot reposition to this location.
  1308. */
  1309. protected abstract ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
  1310. ObjectTypeAndSize info) throws IOException;
  1311. /**
  1312. * Reposition the database to re-read a previously stored object.
  1313. * <p>
  1314. * If the database is computing CRC-32 checksums for object data, it should
  1315. * reset its internal CRC instance during this method call.
  1316. *
  1317. * @param delta
  1318. * the object position to begin reading from. This is an instance
  1319. * previously returned by {@link #onEndDelta()}.
  1320. * @param info
  1321. * object to populate with type and size.
  1322. * @return the {@code info} object.
  1323. * @throws IOException
  1324. * the database cannot reposition to this location.
  1325. */
  1326. protected abstract ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
  1327. ObjectTypeAndSize info) throws IOException;
  1328. /**
  1329. * Read from the database's current position into the buffer.
  1330. *
  1331. * @param dst
  1332. * the buffer to copy read data into.
  1333. * @param pos
  1334. * position within {@code dst} to start copying data into.
  1335. * @param cnt
  1336. * ideal target number of bytes to read. Actual read length may
  1337. * be shorter.
  1338. * @return number of bytes stored.
  1339. * @throws IOException
  1340. * the database cannot be accessed.
  1341. */
  1342. protected abstract int readDatabase(byte[] dst, int pos, int cnt)
  1343. throws IOException;
  1344. /**
  1345. * Check the current CRC matches the expected value.
  1346. * <p>
  1347. * This method is invoked when an object is read back in from the database
  1348. * and its data is used during delta resolution. The CRC is validated after
  1349. * the object has been fully read, allowing the parser to verify there was
  1350. * no silent data corruption.
  1351. * <p>
  1352. * Implementations are free to ignore this check by always returning true if
  1353. * they are performing other data integrity validations at a lower level.
  1354. *
  1355. * @param oldCRC
  1356. * the prior CRC that was recorded during the first scan of the
  1357. * object from the pack stream.
  1358. * @return true if the CRC matches; false if it does not.
  1359. */
  1360. protected abstract boolean checkCRC(int oldCRC);
  1361. /**
  1362. * Event notifying the start of an object stored whole (not as a delta).
  1363. *
  1364. * @param streamPosition
  1365. * position of this object in the incoming stream.
  1366. * @param type
  1367. * type of the object; one of {@link Constants#OBJ_COMMIT},
  1368. * {@link Constants#OBJ_TREE}, {@link Constants#OBJ_BLOB}, or
  1369. * {@link Constants#OBJ_TAG}.
  1370. * @param inflatedSize
  1371. * size of the object when fully inflated. The size stored within
  1372. * the pack may be larger or smaller, and is not yet known.
  1373. * @throws IOException
  1374. * the object cannot be recorded.
  1375. */
  1376. protected abstract void onBeginWholeObject(long streamPosition, int type,
  1377. long inflatedSize) throws IOException;
  1378. /**
  1379. * Event notifying the the current object.
  1380. *
  1381. *@param info
  1382. * object information.
  1383. * @throws IOException
  1384. * the object cannot be recorded.
  1385. */
  1386. protected abstract void onEndWholeObject(PackedObjectInfo info)
  1387. throws IOException;
  1388. /**
  1389. * Event notifying start of a delta referencing its base by offset.
  1390. *
  1391. * @param deltaStreamPosition
  1392. * position of this object in the incoming stream.
  1393. * @param baseStreamPosition
  1394. * position of the base object in the incoming stream. The base
  1395. * must be before the delta, therefore {@code baseStreamPosition
  1396. * &lt; deltaStreamPosition}. This is <b>not</b> the position
  1397. * returned by a prior end object event.
  1398. * @param inflatedSize
  1399. * size of the delta when fully inflated. The size stored within
  1400. * the pack may be larger or smaller, and is not yet known.
  1401. * @throws IOException
  1402. * the object cannot be recorded.
  1403. */
  1404. protected abstract void onBeginOfsDelta(long deltaStreamPosition,
  1405. long baseStreamPosition, long inflatedSize) throws IOException;
  1406. /**
  1407. * Event notifying start of a delta referencing its base by ObjectId.
  1408. *
  1409. * @param deltaStreamPosition
  1410. * position of this object in the incoming stream.
  1411. * @param baseId
  1412. * name of the base object. This object may be later in the
  1413. * stream, or might not appear at all in the stream (in the case
  1414. * of a thin-pack).
  1415. * @param inflatedSize
  1416. * size of the delta when fully inflated. The size stored within
  1417. * the pack may be larger or smaller, and is not yet known.
  1418. * @throws IOException
  1419. * the object cannot be recorded.
  1420. */
  1421. protected abstract void onBeginRefDelta(long deltaStreamPosition,
  1422. AnyObjectId baseId, long inflatedSize) throws IOException;
  1423. /**
  1424. * Event notifying the the current object.
  1425. *
  1426. *@return object information that must be populated with at least the
  1427. * offset.
  1428. * @throws IOException
  1429. * the object cannot be recorded.
  1430. */
  1431. protected UnresolvedDelta onEndDelta() throws IOException {
  1432. return new UnresolvedDelta();
  1433. }
  1434. /** Type and size information about an object in the database buffer. */
  1435. public static class ObjectTypeAndSize {
  1436. /** The type of the object. */
  1437. public int type;
  1438. /** The inflated size of the object. */
  1439. public long size;
  1440. }
  1441. private void inflateAndSkip(final Source src, final long inflatedSize)
  1442. throws IOException {
  1443. final InputStream inf = inflate(src, inflatedSize);
  1444. IO.skipFully(inf, inflatedSize);
  1445. inf.close();
  1446. }
  1447. private byte[] inflateAndReturn(final Source src, final long inflatedSize)
  1448. throws IOException {
  1449. final byte[] dst = new byte[(int) inflatedSize];
  1450. final InputStream inf = inflate(src, inflatedSize);
  1451. IO.readFully(inf, dst, 0, dst.length);
  1452. inf.close();
  1453. return dst;
  1454. }
  1455. private InputStream inflate(final Source src, final long inflatedSize)
  1456. throws IOException {
  1457. inflater.open(src, inflatedSize);
  1458. return inflater;
  1459. }
  1460. private static class DeltaChain extends ObjectIdOwnerMap.Entry {
  1461. UnresolvedDelta head;
  1462. DeltaChain(final AnyObjectId id) {
  1463. super(id);
  1464. }
  1465. UnresolvedDelta remove() {
  1466. final UnresolvedDelta r = head;
  1467. if (r != null)
  1468. head = null;
  1469. return r;
  1470. }
  1471. void add(final UnresolvedDelta d) {
  1472. d.next = head;
  1473. head = d;
  1474. }
  1475. }
  1476. /** Information about an unresolved delta in this pack stream. */
  1477. public static class UnresolvedDelta {
  1478. long position;
  1479. int crc;
  1480. UnresolvedDelta next;
  1481. /** @return offset within the input stream. */
  1482. public long getOffset() {
  1483. return position;
  1484. }
  1485. /** @return the CRC-32 checksum of the stored delta data. */
  1486. public int getCRC() {
  1487. return crc;
  1488. }
  1489. /**
  1490. * @param crc32
  1491. * the CRC-32 checksum of the stored delta data.
  1492. */
  1493. public void setCRC(int crc32) {
  1494. crc = crc32;
  1495. }
  1496. }
  1497. private static class DeltaVisit {
  1498. final UnresolvedDelta delta;
  1499. ObjectId id;
  1500. byte[] data;
  1501. DeltaVisit parent;
  1502. UnresolvedDelta nextChild;
  1503. DeltaVisit() {
  1504. this.delta = null; // At the root of the stack we have a base.
  1505. }
  1506. DeltaVisit(DeltaVisit parent) {
  1507. this.parent = parent;
  1508. this.delta = parent.nextChild;
  1509. parent.nextChild = delta.next;
  1510. }
  1511. DeltaVisit next() {
  1512. // If our parent has no more children, discard it.
  1513. if (parent != null && parent.nextChild == null) {
  1514. parent.data = null;
  1515. parent = parent.parent;
  1516. }
  1517. if (nextChild != null)
  1518. return new DeltaVisit(this);
  1519. // If we have no child ourselves, our parent must (if it exists),
  1520. // due to the discard rule above. With no parent, we are done.
  1521. if (parent != null)
  1522. return new DeltaVisit(parent);
  1523. return null;
  1524. }
  1525. }
  1526. private void addObjectAndTrack(PackedObjectInfo oe) {
  1527. entries[entryCount++] = oe;
  1528. if (needNewObjectIds())
  1529. newObjectIds.add(oe);
  1530. }
  1531. private class InflaterStream extends InputStream {
  1532. private final Inflater inf;
  1533. private final byte[] skipBuffer;
  1534. private Source src;
  1535. private long expectedSize;
  1536. private long actualSize;
  1537. private int p;
  1538. InflaterStream() {
  1539. inf = InflaterCache.get();
  1540. skipBuffer = new byte[512];
  1541. }
  1542. void release() {
  1543. inf.reset();
  1544. InflaterCache.release(inf);
  1545. }
  1546. void open(Source source, long inflatedSize) throws IOException {
  1547. src = source;
  1548. expectedSize = inflatedSize;
  1549. actualSize = 0;
  1550. p = fill(src, 1);
  1551. inf.setInput(buf, p, bAvail);
  1552. }
  1553. @Override
  1554. public long skip(long toSkip) throws IOException {
  1555. long n = 0;
  1556. while (n < toSkip) {
  1557. final int cnt = (int) Math.min(skipBuffer.length, toSkip - n);
  1558. final int r = read(skipBuffer, 0, cnt);
  1559. if (r <= 0)
  1560. break;
  1561. n += r;
  1562. }
  1563. return n;
  1564. }
  1565. @Override
  1566. public int read() throws IOException {
  1567. int n = read(skipBuffer, 0, 1);
  1568. return n == 1 ? skipBuffer[0] & 0xff : -1;
  1569. }
  1570. @Override
  1571. public int read(byte[] dst, int pos, int cnt) throws IOException {
  1572. try {
  1573. int n = 0;
  1574. while (n < cnt) {
  1575. int r = inf.inflate(dst, pos + n, cnt - n);
  1576. n += r;
  1577. if (inf.finished())
  1578. break;
  1579. if (inf.needsInput()) {
  1580. onObjectData(src, buf, p, bAvail);
  1581. use(bAvail);
  1582. p = fill(src, 1);
  1583. inf.setInput(buf, p, bAvail);
  1584. } else if (r == 0) {
  1585. throw new CorruptObjectException(MessageFormat.format(
  1586. JGitText.get().packfileCorruptionDetected,
  1587. JGitText.get().unknownZlibError));
  1588. }
  1589. }
  1590. actualSize += n;
  1591. return 0 < n ? n : -1;
  1592. } catch (DataFormatException dfe) {
  1593. throw new CorruptObjectException(MessageFormat.format(JGitText
  1594. .get().packfileCorruptionDetected, dfe.getMessage()));
  1595. }
  1596. }
  1597. @Override
  1598. public void close() throws IOException {
  1599. // We need to read here to enter the loop above and pump the
  1600. // trailing checksum into the Inflater. It should return -1 as the
  1601. // caller was supposed to consume all content.
  1602. //
  1603. if (read(skipBuffer) != -1 || actualSize != expectedSize) {
  1604. throw new CorruptObjectException(MessageFormat.format(JGitText
  1605. .get().packfileCorruptionDetected,
  1606. JGitText.get().wrongDecompressedLength));
  1607. }
  1608. int used = bAvail - inf.getRemaining();
  1609. if (0 < used) {
  1610. onObjectData(src, buf, p, used);
  1611. use(used);
  1612. }
  1613. inf.reset();
  1614. }
  1615. }
  1616. }