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

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