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 51KB

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