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

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