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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  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(JGitText
  448. .get().packHasUnresolvedDeltas,
  449. (objectCount - entryCount)));
  450. }
  451. resolveDeltasWithExternalBases(resolving);
  452. if (entryCount < objectCount) {
  453. throw new IOException(MessageFormat.format(JGitText
  454. .get().packHasUnresolvedDeltas,
  455. (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, info.type));
  507. }
  508. if (!checkCRC(oe.getCRC())) {
  509. throw new IOException(MessageFormat.format(
  510. JGitText.get().corruptionDetectedReReadingAt, oe
  511. .getOffset()));
  512. }
  513. resolveDeltas(visit.next(), info.type, info, progress);
  514. }
  515. private void resolveDeltas(DeltaVisit visit, final int type,
  516. ObjectTypeAndSize info, ProgressMonitor progress)
  517. throws IOException {
  518. do {
  519. progress.update(1);
  520. info = openDatabase(visit.delta, info);
  521. switch (info.type) {
  522. case Constants.OBJ_OFS_DELTA:
  523. case Constants.OBJ_REF_DELTA:
  524. break;
  525. default:
  526. throw new IOException(MessageFormat.format(
  527. JGitText.get().unknownObjectType, info.type));
  528. }
  529. byte[] delta = inflateAndReturn(Source.DATABASE, info.size);
  530. checkIfTooLarge(type, BinaryDelta.getResultSize(delta));
  531. visit.data = BinaryDelta.apply(visit.parent.data, delta);
  532. delta = null;
  533. if (!checkCRC(visit.delta.crc))
  534. throw new IOException(MessageFormat.format(
  535. JGitText.get().corruptionDetectedReReadingAt,
  536. visit.delta.position));
  537. objectDigest.update(Constants.encodedTypeString(type));
  538. objectDigest.update((byte) ' ');
  539. objectDigest.update(Constants.encodeASCII(visit.data.length));
  540. objectDigest.update((byte) 0);
  541. objectDigest.update(visit.data);
  542. tempObjectId.fromRaw(objectDigest.digest(), 0);
  543. verifySafeObject(tempObjectId, type, visit.data);
  544. PackedObjectInfo oe;
  545. oe = newInfo(tempObjectId, visit.delta, visit.parent.id);
  546. oe.setOffset(visit.delta.position);
  547. onInflatedObjectData(oe, type, visit.data);
  548. addObjectAndTrack(oe);
  549. visit.id = oe;
  550. visit.nextChild = firstChildOf(oe);
  551. visit = visit.next();
  552. } while (visit != null);
  553. }
  554. private final void checkIfTooLarge(int typeCode, long size)
  555. throws IOException {
  556. if (0 < maxObjectSizeLimit && maxObjectSizeLimit < size)
  557. switch (typeCode) {
  558. case Constants.OBJ_COMMIT:
  559. case Constants.OBJ_TREE:
  560. case Constants.OBJ_BLOB:
  561. case Constants.OBJ_TAG:
  562. throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);
  563. case Constants.OBJ_OFS_DELTA:
  564. case Constants.OBJ_REF_DELTA:
  565. throw new TooLargeObjectInPackException(maxObjectSizeLimit);
  566. default:
  567. throw new IOException(MessageFormat.format(
  568. JGitText.get().unknownObjectType, typeCode));
  569. }
  570. }
  571. /**
  572. * Read the header of the current object.
  573. * <p>
  574. * After the header has been parsed, this method automatically invokes
  575. * {@link #onObjectHeader(Source, byte[], int, int)} to allow the
  576. * implementation to update its internal checksums for the bytes read.
  577. * <p>
  578. * When this method returns the database will be positioned on the first
  579. * byte of the deflated data stream.
  580. *
  581. * @param info
  582. * the info object to populate.
  583. * @return {@code info}, after populating.
  584. * @throws IOException
  585. * the size cannot be read.
  586. */
  587. protected ObjectTypeAndSize readObjectHeader(ObjectTypeAndSize info)
  588. throws IOException {
  589. int hdrPtr = 0;
  590. int c = readFrom(Source.DATABASE);
  591. hdrBuf[hdrPtr++] = (byte) c;
  592. info.type = (c >> 4) & 7;
  593. long sz = c & 15;
  594. int shift = 4;
  595. while ((c & 0x80) != 0) {
  596. c = readFrom(Source.DATABASE);
  597. hdrBuf[hdrPtr++] = (byte) c;
  598. sz += ((long) (c & 0x7f)) << shift;
  599. shift += 7;
  600. }
  601. info.size = sz;
  602. switch (info.type) {
  603. case Constants.OBJ_COMMIT:
  604. case Constants.OBJ_TREE:
  605. case Constants.OBJ_BLOB:
  606. case Constants.OBJ_TAG:
  607. onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  608. break;
  609. case Constants.OBJ_OFS_DELTA:
  610. c = readFrom(Source.DATABASE);
  611. hdrBuf[hdrPtr++] = (byte) c;
  612. while ((c & 128) != 0) {
  613. c = readFrom(Source.DATABASE);
  614. hdrBuf[hdrPtr++] = (byte) c;
  615. }
  616. onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  617. break;
  618. case Constants.OBJ_REF_DELTA:
  619. System.arraycopy(buf, fill(Source.DATABASE, 20), hdrBuf, hdrPtr, 20);
  620. hdrPtr += 20;
  621. use(20);
  622. onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  623. break;
  624. default:
  625. throw new IOException(MessageFormat.format(
  626. JGitText.get().unknownObjectType, info.type));
  627. }
  628. return info;
  629. }
  630. private UnresolvedDelta removeBaseById(final AnyObjectId id) {
  631. final DeltaChain d = baseById.get(id);
  632. return d != null ? d.remove() : null;
  633. }
  634. private static UnresolvedDelta reverse(UnresolvedDelta c) {
  635. UnresolvedDelta tail = null;
  636. while (c != null) {
  637. final UnresolvedDelta n = c.next;
  638. c.next = tail;
  639. tail = c;
  640. c = n;
  641. }
  642. return tail;
  643. }
  644. private UnresolvedDelta firstChildOf(PackedObjectInfo oe) {
  645. UnresolvedDelta a = reverse(removeBaseById(oe));
  646. UnresolvedDelta b = reverse(baseByPos.remove(oe.getOffset()));
  647. if (a == null)
  648. return b;
  649. if (b == null)
  650. return a;
  651. UnresolvedDelta first = null;
  652. UnresolvedDelta last = null;
  653. while (a != null || b != null) {
  654. UnresolvedDelta curr;
  655. if (b == null || (a != null && a.position < b.position)) {
  656. curr = a;
  657. a = a.next;
  658. } else {
  659. curr = b;
  660. b = b.next;
  661. }
  662. if (last != null)
  663. last.next = curr;
  664. else
  665. first = curr;
  666. last = curr;
  667. curr.next = null;
  668. }
  669. return first;
  670. }
  671. private void resolveDeltasWithExternalBases(final ProgressMonitor progress)
  672. throws IOException {
  673. growEntries(baseById.size());
  674. if (needBaseObjectIds)
  675. baseObjectIds = new ObjectIdSubclassMap<ObjectId>();
  676. final List<DeltaChain> missing = new ArrayList<DeltaChain>(64);
  677. for (final DeltaChain baseId : baseById) {
  678. if (baseId.head == null)
  679. continue;
  680. if (needBaseObjectIds)
  681. baseObjectIds.add(baseId);
  682. final ObjectLoader ldr;
  683. try {
  684. ldr = readCurs.open(baseId);
  685. } catch (MissingObjectException notFound) {
  686. missing.add(baseId);
  687. continue;
  688. }
  689. final DeltaVisit visit = new DeltaVisit();
  690. visit.data = ldr.getCachedBytes(Integer.MAX_VALUE);
  691. visit.id = baseId;
  692. final int typeCode = ldr.getType();
  693. final PackedObjectInfo oe = newInfo(baseId, null, null);
  694. if (onAppendBase(typeCode, visit.data, oe))
  695. entries[entryCount++] = oe;
  696. visit.nextChild = firstChildOf(oe);
  697. resolveDeltas(visit.next(), typeCode,
  698. new ObjectTypeAndSize(), progress);
  699. if (progress.isCancelled())
  700. throw new IOException(
  701. JGitText.get().downloadCancelledDuringIndexing);
  702. }
  703. for (final DeltaChain base : missing) {
  704. if (base.head != null)
  705. throw new MissingObjectException(base, "delta base");
  706. }
  707. onEndThinPack();
  708. }
  709. private void growEntries(int extraObjects) {
  710. final PackedObjectInfo[] ne;
  711. ne = new PackedObjectInfo[(int) objectCount + extraObjects];
  712. System.arraycopy(entries, 0, ne, 0, entryCount);
  713. entries = ne;
  714. }
  715. private void readPackHeader() throws IOException {
  716. final int hdrln = Constants.PACK_SIGNATURE.length + 4 + 4;
  717. final int p = fill(Source.INPUT, hdrln);
  718. for (int k = 0; k < Constants.PACK_SIGNATURE.length; k++)
  719. if (buf[p + k] != Constants.PACK_SIGNATURE[k])
  720. throw new IOException(JGitText.get().notAPACKFile);
  721. final long vers = NB.decodeUInt32(buf, p + 4);
  722. if (vers != 2 && vers != 3)
  723. throw new IOException(MessageFormat.format(
  724. JGitText.get().unsupportedPackVersion, vers));
  725. objectCount = NB.decodeUInt32(buf, p + 8);
  726. use(hdrln);
  727. onPackHeader(objectCount);
  728. }
  729. private void readPackFooter() throws IOException {
  730. sync();
  731. final byte[] actHash = packDigest.digest();
  732. final int c = fill(Source.INPUT, 20);
  733. final byte[] srcHash = new byte[20];
  734. System.arraycopy(buf, c, srcHash, 0, 20);
  735. use(20);
  736. // The input stream should be at EOF at this point. We do not support
  737. // yielding back any remaining buffered data after the pack footer, so
  738. // protocols that embed a pack stream are required to either end their
  739. // stream with the pack, or embed the pack with a framing system like
  740. // the SideBandInputStream does.
  741. if (bAvail != 0)
  742. throw new CorruptObjectException(MessageFormat.format(
  743. JGitText.get().expectedEOFReceived,
  744. "\\x" + Integer.toHexString(buf[bOffset] & 0xff)));
  745. if (isCheckEofAfterPackFooter()) {
  746. int eof = in.read();
  747. if (0 <= eof)
  748. throw new CorruptObjectException(MessageFormat.format(
  749. JGitText.get().expectedEOFReceived,
  750. "\\x" + Integer.toHexString(eof)));
  751. }
  752. if (!Arrays.equals(actHash, srcHash))
  753. throw new CorruptObjectException(
  754. JGitText.get().corruptObjectPackfileChecksumIncorrect);
  755. onPackFooter(srcHash);
  756. }
  757. // Cleanup all resources associated with our input parsing.
  758. private void endInput() {
  759. in = null;
  760. }
  761. // Read one entire object or delta from the input.
  762. private void indexOneObject() throws IOException {
  763. final long streamPosition = streamPosition();
  764. int hdrPtr = 0;
  765. int c = readFrom(Source.INPUT);
  766. hdrBuf[hdrPtr++] = (byte) c;
  767. final int typeCode = (c >> 4) & 7;
  768. long sz = c & 15;
  769. int shift = 4;
  770. while ((c & 0x80) != 0) {
  771. c = readFrom(Source.INPUT);
  772. hdrBuf[hdrPtr++] = (byte) c;
  773. sz += ((long) (c & 0x7f)) << shift;
  774. shift += 7;
  775. }
  776. checkIfTooLarge(typeCode, sz);
  777. switch (typeCode) {
  778. case Constants.OBJ_COMMIT:
  779. case Constants.OBJ_TREE:
  780. case Constants.OBJ_BLOB:
  781. case Constants.OBJ_TAG:
  782. onBeginWholeObject(streamPosition, typeCode, sz);
  783. onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  784. whole(streamPosition, typeCode, sz);
  785. break;
  786. case Constants.OBJ_OFS_DELTA: {
  787. c = readFrom(Source.INPUT);
  788. hdrBuf[hdrPtr++] = (byte) c;
  789. long ofs = c & 127;
  790. while ((c & 128) != 0) {
  791. ofs += 1;
  792. c = readFrom(Source.INPUT);
  793. hdrBuf[hdrPtr++] = (byte) c;
  794. ofs <<= 7;
  795. ofs += (c & 127);
  796. }
  797. final long base = streamPosition - ofs;
  798. onBeginOfsDelta(streamPosition, base, sz);
  799. onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  800. inflateAndSkip(Source.INPUT, sz);
  801. UnresolvedDelta n = onEndDelta();
  802. n.position = streamPosition;
  803. n.next = baseByPos.put(base, n);
  804. deltaCount++;
  805. break;
  806. }
  807. case Constants.OBJ_REF_DELTA: {
  808. c = fill(Source.INPUT, 20);
  809. final ObjectId base = ObjectId.fromRaw(buf, c);
  810. System.arraycopy(buf, c, hdrBuf, hdrPtr, 20);
  811. hdrPtr += 20;
  812. use(20);
  813. DeltaChain r = baseById.get(base);
  814. if (r == null) {
  815. r = new DeltaChain(base);
  816. baseById.add(r);
  817. }
  818. onBeginRefDelta(streamPosition, base, sz);
  819. onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  820. inflateAndSkip(Source.INPUT, sz);
  821. UnresolvedDelta n = onEndDelta();
  822. n.position = streamPosition;
  823. r.add(n);
  824. deltaCount++;
  825. break;
  826. }
  827. default:
  828. throw new IOException(MessageFormat.format(
  829. JGitText.get().unknownObjectType, typeCode));
  830. }
  831. }
  832. private void whole(final long pos, final int type, final long sz)
  833. throws IOException {
  834. objectDigest.update(Constants.encodedTypeString(type));
  835. objectDigest.update((byte) ' ');
  836. objectDigest.update(Constants.encodeASCII(sz));
  837. objectDigest.update((byte) 0);
  838. final byte[] data;
  839. boolean checkContentLater = false;
  840. if (type == Constants.OBJ_BLOB) {
  841. byte[] readBuffer = buffer();
  842. InputStream inf = inflate(Source.INPUT, sz);
  843. long cnt = 0;
  844. while (cnt < sz) {
  845. int r = inf.read(readBuffer);
  846. if (r <= 0)
  847. break;
  848. objectDigest.update(readBuffer, 0, r);
  849. cnt += r;
  850. }
  851. inf.close();
  852. tempObjectId.fromRaw(objectDigest.digest(), 0);
  853. checkContentLater = isCheckObjectCollisions()
  854. && readCurs.has(tempObjectId);
  855. data = null;
  856. } else {
  857. data = inflateAndReturn(Source.INPUT, sz);
  858. objectDigest.update(data);
  859. tempObjectId.fromRaw(objectDigest.digest(), 0);
  860. verifySafeObject(tempObjectId, type, data);
  861. }
  862. PackedObjectInfo obj = newInfo(tempObjectId, null, null);
  863. obj.setOffset(pos);
  864. onEndWholeObject(obj);
  865. if (data != null)
  866. onInflatedObjectData(obj, type, data);
  867. addObjectAndTrack(obj);
  868. if (checkContentLater)
  869. deferredCheckBlobs.add(obj);
  870. }
  871. private void verifySafeObject(final AnyObjectId id, final int type,
  872. final byte[] data) throws IOException {
  873. if (objCheck != null) {
  874. try {
  875. objCheck.check(type, data);
  876. } catch (CorruptObjectException e) {
  877. throw new IOException(MessageFormat.format(
  878. JGitText.get().invalidObject, Constants
  879. .typeString(type), id.name(), e.getMessage()));
  880. }
  881. }
  882. if (isCheckObjectCollisions()) {
  883. try {
  884. final ObjectLoader ldr = readCurs.open(id, type);
  885. final byte[] existingData = ldr.getCachedBytes(data.length);
  886. if (!Arrays.equals(data, existingData)) {
  887. throw new IOException(MessageFormat.format(
  888. JGitText.get().collisionOn, id.name()));
  889. }
  890. } catch (MissingObjectException notLocal) {
  891. // This is OK, we don't have a copy of the object locally
  892. // but the API throws when we try to read it as usually its
  893. // an error to read something that doesn't exist.
  894. }
  895. }
  896. }
  897. private void doDeferredCheckBlobs() throws IOException {
  898. final byte[] readBuffer = buffer();
  899. final byte[] curBuffer = new byte[readBuffer.length];
  900. ObjectTypeAndSize info = new ObjectTypeAndSize();
  901. for (PackedObjectInfo obj : deferredCheckBlobs) {
  902. info = openDatabase(obj, info);
  903. if (info.type != Constants.OBJ_BLOB)
  904. throw new IOException(MessageFormat.format(
  905. JGitText.get().unknownObjectType, info.type));
  906. ObjectStream cur = readCurs.open(obj, info.type).openStream();
  907. try {
  908. long sz = info.size;
  909. if (cur.getSize() != sz)
  910. throw new IOException(MessageFormat.format(
  911. JGitText.get().collisionOn, obj.name()));
  912. InputStream pck = inflate(Source.DATABASE, sz);
  913. while (0 < sz) {
  914. int n = (int) Math.min(readBuffer.length, sz);
  915. IO.readFully(cur, curBuffer, 0, n);
  916. IO.readFully(pck, readBuffer, 0, n);
  917. for (int i = 0; i < n; i++) {
  918. if (curBuffer[i] != readBuffer[i])
  919. throw new IOException(MessageFormat.format(JGitText
  920. .get().collisionOn, obj.name()));
  921. }
  922. sz -= n;
  923. }
  924. pck.close();
  925. } finally {
  926. cur.close();
  927. }
  928. }
  929. }
  930. /** @return current position of the input stream being parsed. */
  931. private long streamPosition() {
  932. return bBase + bOffset;
  933. }
  934. private ObjectTypeAndSize openDatabase(PackedObjectInfo obj,
  935. ObjectTypeAndSize info) throws IOException {
  936. bOffset = 0;
  937. bAvail = 0;
  938. return seekDatabase(obj, info);
  939. }
  940. private ObjectTypeAndSize openDatabase(UnresolvedDelta delta,
  941. ObjectTypeAndSize info) throws IOException {
  942. bOffset = 0;
  943. bAvail = 0;
  944. return seekDatabase(delta, info);
  945. }
  946. // Consume exactly one byte from the buffer and return it.
  947. private int readFrom(final Source src) throws IOException {
  948. if (bAvail == 0)
  949. fill(src, 1);
  950. bAvail--;
  951. return buf[bOffset++] & 0xff;
  952. }
  953. // Consume cnt bytes from the buffer.
  954. private void use(final int cnt) {
  955. bOffset += cnt;
  956. bAvail -= cnt;
  957. }
  958. // Ensure at least need bytes are available in in {@link #buf}.
  959. private int fill(final Source src, final int need) throws IOException {
  960. while (bAvail < need) {
  961. int next = bOffset + bAvail;
  962. int free = buf.length - next;
  963. if (free + bAvail < need) {
  964. switch (src) {
  965. case INPUT:
  966. sync();
  967. break;
  968. case DATABASE:
  969. if (bAvail > 0)
  970. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  971. bOffset = 0;
  972. break;
  973. }
  974. next = bAvail;
  975. free = buf.length - next;
  976. }
  977. switch (src) {
  978. case INPUT:
  979. next = in.read(buf, next, free);
  980. break;
  981. case DATABASE:
  982. next = readDatabase(buf, next, free);
  983. break;
  984. }
  985. if (next <= 0)
  986. throw new EOFException(JGitText.get().packfileIsTruncated);
  987. bAvail += next;
  988. }
  989. return bOffset;
  990. }
  991. // Store consumed bytes in {@link #buf} up to {@link #bOffset}.
  992. private void sync() throws IOException {
  993. packDigest.update(buf, 0, bOffset);
  994. onStoreStream(buf, 0, bOffset);
  995. if (bAvail > 0)
  996. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  997. bBase += bOffset;
  998. bOffset = 0;
  999. }
  1000. /** @return a temporary byte array for use by the caller. */
  1001. protected byte[] buffer() {
  1002. return tempBuffer;
  1003. }
  1004. /**
  1005. * Construct a PackedObjectInfo instance for this parser.
  1006. *
  1007. * @param id
  1008. * identity of the object to be tracked.
  1009. * @param delta
  1010. * if the object was previously an unresolved delta, this is the
  1011. * delta object that was tracking it. Otherwise null.
  1012. * @param deltaBase
  1013. * if the object was previously an unresolved delta, this is the
  1014. * ObjectId of the base of the delta. The base may be outside of
  1015. * the pack stream if the stream was a thin-pack.
  1016. * @return info object containing this object's data.
  1017. */
  1018. protected PackedObjectInfo newInfo(AnyObjectId id, UnresolvedDelta delta,
  1019. ObjectId deltaBase) {
  1020. PackedObjectInfo oe = new PackedObjectInfo(id);
  1021. if (delta != null)
  1022. oe.setCRC(delta.crc);
  1023. return oe;
  1024. }
  1025. /**
  1026. * Store bytes received from the raw stream.
  1027. * <p>
  1028. * This method is invoked during {@link #parse(ProgressMonitor)} as data is
  1029. * consumed from the incoming stream. Implementors may use this event to
  1030. * archive the raw incoming stream to the destination repository in large
  1031. * chunks, without paying attention to object boundaries.
  1032. * <p>
  1033. * The only component of the pack not supplied to this method is the last 20
  1034. * bytes of the pack that comprise the trailing SHA-1 checksum. Those are
  1035. * passed to {@link #onPackFooter(byte[])}.
  1036. *
  1037. * @param raw
  1038. * buffer to copy data out of.
  1039. * @param pos
  1040. * first offset within the buffer that is valid.
  1041. * @param len
  1042. * number of bytes in the buffer that are valid.
  1043. * @throws IOException
  1044. * the stream cannot be archived.
  1045. */
  1046. protected abstract void onStoreStream(byte[] raw, int pos, int len)
  1047. throws IOException;
  1048. /**
  1049. * Store (and/or checksum) an object header.
  1050. * <p>
  1051. * Invoked after any of the {@code onBegin()} events. The entire header is
  1052. * supplied in a single invocation, before any object data is supplied.
  1053. *
  1054. * @param src
  1055. * where the data came from
  1056. * @param raw
  1057. * buffer to read data from.
  1058. * @param pos
  1059. * first offset within buffer that is valid.
  1060. * @param len
  1061. * number of bytes in buffer that are valid.
  1062. * @throws IOException
  1063. * the stream cannot be archived.
  1064. */
  1065. protected abstract void onObjectHeader(Source src, byte[] raw, int pos,
  1066. int len) throws IOException;
  1067. /**
  1068. * Store (and/or checksum) a portion of an object's data.
  1069. * <p>
  1070. * This method may be invoked multiple times per object, depending on the
  1071. * size of the object, the size of the parser's internal read buffer, and
  1072. * the alignment of the object relative to the read buffer.
  1073. * <p>
  1074. * Invoked after {@link #onObjectHeader(Source, byte[], int, int)}.
  1075. *
  1076. * @param src
  1077. * where the data came from
  1078. * @param raw
  1079. * buffer to read data from.
  1080. * @param pos
  1081. * first offset within buffer that is valid.
  1082. * @param len
  1083. * number of bytes in buffer that are valid.
  1084. * @throws IOException
  1085. * the stream cannot be archived.
  1086. */
  1087. protected abstract void onObjectData(Source src, byte[] raw, int pos,
  1088. int len) throws IOException;
  1089. /**
  1090. * Invoked for commits, trees, tags, and small blobs.
  1091. *
  1092. * @param obj
  1093. * the object info, populated.
  1094. * @param typeCode
  1095. * the type of the object.
  1096. * @param data
  1097. * inflated data for the object.
  1098. * @throws IOException
  1099. * the object cannot be archived.
  1100. */
  1101. protected abstract void onInflatedObjectData(PackedObjectInfo obj,
  1102. int typeCode, byte[] data) throws IOException;
  1103. /**
  1104. * Provide the implementation with the original stream's pack header.
  1105. *
  1106. * @param objCnt
  1107. * number of objects expected in the stream.
  1108. * @throws IOException
  1109. * the implementation refuses to work with this many objects.
  1110. */
  1111. protected abstract void onPackHeader(long objCnt) throws IOException;
  1112. /**
  1113. * Provide the implementation with the original stream's pack footer.
  1114. *
  1115. * @param hash
  1116. * the trailing 20 bytes of the pack, this is a SHA-1 checksum of
  1117. * all of the pack data.
  1118. * @throws IOException
  1119. * the stream cannot be archived.
  1120. */
  1121. protected abstract void onPackFooter(byte[] hash) throws IOException;
  1122. /**
  1123. * Provide the implementation with a base that was outside of the pack.
  1124. * <p>
  1125. * This event only occurs on a thin pack for base objects that were outside
  1126. * of the pack and came from the local repository. Usually an implementation
  1127. * uses this event to compress the base and append it onto the end of the
  1128. * pack, so the pack stays self-contained.
  1129. *
  1130. * @param typeCode
  1131. * type of the base object.
  1132. * @param data
  1133. * complete content of the base object.
  1134. * @param info
  1135. * packed object information for this base. Implementors must
  1136. * populate the CRC and offset members if returning true.
  1137. * @return true if the {@code info} should be included in the object list
  1138. * returned by {@link #getSortedObjectList(Comparator)}, false if it
  1139. * should not be included.
  1140. * @throws IOException
  1141. * the base could not be included into the pack.
  1142. */
  1143. protected abstract boolean onAppendBase(int typeCode, byte[] data,
  1144. PackedObjectInfo info) throws IOException;
  1145. /**
  1146. * Event indicating a thin pack has been completely processed.
  1147. * <p>
  1148. * This event is invoked only if a thin pack has delta references to objects
  1149. * external from the pack. The event is called after all of those deltas
  1150. * have been resolved.
  1151. *
  1152. * @throws IOException
  1153. * the pack cannot be archived.
  1154. */
  1155. protected abstract void onEndThinPack() throws IOException;
  1156. /**
  1157. * Reposition the database to re-read a previously stored object.
  1158. * <p>
  1159. * If the database is computing CRC-32 checksums for object data, it should
  1160. * reset its internal CRC instance during this method call.
  1161. *
  1162. * @param obj
  1163. * the object position to begin reading from. This is from
  1164. * {@link #newInfo(AnyObjectId, UnresolvedDelta, ObjectId)}.
  1165. * @param info
  1166. * object to populate with type and size.
  1167. * @return the {@code info} object.
  1168. * @throws IOException
  1169. * the database cannot reposition to this location.
  1170. */
  1171. protected abstract ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
  1172. ObjectTypeAndSize info) throws IOException;
  1173. /**
  1174. * Reposition the database to re-read a previously stored object.
  1175. * <p>
  1176. * If the database is computing CRC-32 checksums for object data, it should
  1177. * reset its internal CRC instance during this method call.
  1178. *
  1179. * @param delta
  1180. * the object position to begin reading from. This is an instance
  1181. * previously returned by {@link #onEndDelta()}.
  1182. * @param info
  1183. * object to populate with type and size.
  1184. * @return the {@code info} object.
  1185. * @throws IOException
  1186. * the database cannot reposition to this location.
  1187. */
  1188. protected abstract ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
  1189. ObjectTypeAndSize info) throws IOException;
  1190. /**
  1191. * Read from the database's current position into the buffer.
  1192. *
  1193. * @param dst
  1194. * the buffer to copy read data into.
  1195. * @param pos
  1196. * position within {@code dst} to start copying data into.
  1197. * @param cnt
  1198. * ideal target number of bytes to read. Actual read length may
  1199. * be shorter.
  1200. * @return number of bytes stored.
  1201. * @throws IOException
  1202. * the database cannot be accessed.
  1203. */
  1204. protected abstract int readDatabase(byte[] dst, int pos, int cnt)
  1205. throws IOException;
  1206. /**
  1207. * Check the current CRC matches the expected value.
  1208. * <p>
  1209. * This method is invoked when an object is read back in from the database
  1210. * and its data is used during delta resolution. The CRC is validated after
  1211. * the object has been fully read, allowing the parser to verify there was
  1212. * no silent data corruption.
  1213. * <p>
  1214. * Implementations are free to ignore this check by always returning true if
  1215. * they are performing other data integrity validations at a lower level.
  1216. *
  1217. * @param oldCRC
  1218. * the prior CRC that was recorded during the first scan of the
  1219. * object from the pack stream.
  1220. * @return true if the CRC matches; false if it does not.
  1221. */
  1222. protected abstract boolean checkCRC(int oldCRC);
  1223. /**
  1224. * Event notifying the start of an object stored whole (not as a delta).
  1225. *
  1226. * @param streamPosition
  1227. * position of this object in the incoming stream.
  1228. * @param type
  1229. * type of the object; one of {@link Constants#OBJ_COMMIT},
  1230. * {@link Constants#OBJ_TREE}, {@link Constants#OBJ_BLOB}, or
  1231. * {@link Constants#OBJ_TAG}.
  1232. * @param inflatedSize
  1233. * size of the object when fully inflated. The size stored within
  1234. * the pack may be larger or smaller, and is not yet known.
  1235. * @throws IOException
  1236. * the object cannot be recorded.
  1237. */
  1238. protected abstract void onBeginWholeObject(long streamPosition, int type,
  1239. long inflatedSize) throws IOException;
  1240. /**
  1241. * Event notifying the the current object.
  1242. *
  1243. *@param info
  1244. * object information.
  1245. * @throws IOException
  1246. * the object cannot be recorded.
  1247. */
  1248. protected abstract void onEndWholeObject(PackedObjectInfo info)
  1249. throws IOException;
  1250. /**
  1251. * Event notifying start of a delta referencing its base by offset.
  1252. *
  1253. * @param deltaStreamPosition
  1254. * position of this object in the incoming stream.
  1255. * @param baseStreamPosition
  1256. * position of the base object in the incoming stream. The base
  1257. * must be before the delta, therefore {@code baseStreamPosition
  1258. * &lt; deltaStreamPosition}. This is <b>not</b> the position
  1259. * returned by a prior end object event.
  1260. * @param inflatedSize
  1261. * size of the delta when fully inflated. The size stored within
  1262. * the pack may be larger or smaller, and is not yet known.
  1263. * @throws IOException
  1264. * the object cannot be recorded.
  1265. */
  1266. protected abstract void onBeginOfsDelta(long deltaStreamPosition,
  1267. long baseStreamPosition, long inflatedSize) throws IOException;
  1268. /**
  1269. * Event notifying start of a delta referencing its base by ObjectId.
  1270. *
  1271. * @param deltaStreamPosition
  1272. * position of this object in the incoming stream.
  1273. * @param baseId
  1274. * name of the base object. This object may be later in the
  1275. * stream, or might not appear at all in the stream (in the case
  1276. * of a thin-pack).
  1277. * @param inflatedSize
  1278. * size of the delta when fully inflated. The size stored within
  1279. * the pack may be larger or smaller, and is not yet known.
  1280. * @throws IOException
  1281. * the object cannot be recorded.
  1282. */
  1283. protected abstract void onBeginRefDelta(long deltaStreamPosition,
  1284. AnyObjectId baseId, long inflatedSize) throws IOException;
  1285. /**
  1286. * Event notifying the the current object.
  1287. *
  1288. *@return object information that must be populated with at least the
  1289. * offset.
  1290. * @throws IOException
  1291. * the object cannot be recorded.
  1292. */
  1293. protected UnresolvedDelta onEndDelta() throws IOException {
  1294. return new UnresolvedDelta();
  1295. }
  1296. /** Type and size information about an object in the database buffer. */
  1297. public static class ObjectTypeAndSize {
  1298. /** The type of the object. */
  1299. public int type;
  1300. /** The inflated size of the object. */
  1301. public long size;
  1302. }
  1303. private void inflateAndSkip(final Source src, final long inflatedSize)
  1304. throws IOException {
  1305. final InputStream inf = inflate(src, inflatedSize);
  1306. IO.skipFully(inf, inflatedSize);
  1307. inf.close();
  1308. }
  1309. private byte[] inflateAndReturn(final Source src, final long inflatedSize)
  1310. throws IOException {
  1311. final byte[] dst = new byte[(int) inflatedSize];
  1312. final InputStream inf = inflate(src, inflatedSize);
  1313. IO.readFully(inf, dst, 0, dst.length);
  1314. inf.close();
  1315. return dst;
  1316. }
  1317. private InputStream inflate(final Source src, final long inflatedSize)
  1318. throws IOException {
  1319. inflater.open(src, inflatedSize);
  1320. return inflater;
  1321. }
  1322. private static class DeltaChain extends ObjectIdOwnerMap.Entry {
  1323. UnresolvedDelta head;
  1324. DeltaChain(final AnyObjectId id) {
  1325. super(id);
  1326. }
  1327. UnresolvedDelta remove() {
  1328. final UnresolvedDelta r = head;
  1329. if (r != null)
  1330. head = null;
  1331. return r;
  1332. }
  1333. void add(final UnresolvedDelta d) {
  1334. d.next = head;
  1335. head = d;
  1336. }
  1337. }
  1338. /** Information about an unresolved delta in this pack stream. */
  1339. public static class UnresolvedDelta {
  1340. long position;
  1341. int crc;
  1342. UnresolvedDelta next;
  1343. /** @return offset within the input stream. */
  1344. public long getOffset() {
  1345. return position;
  1346. }
  1347. /** @return the CRC-32 checksum of the stored delta data. */
  1348. public int getCRC() {
  1349. return crc;
  1350. }
  1351. /**
  1352. * @param crc32
  1353. * the CRC-32 checksum of the stored delta data.
  1354. */
  1355. public void setCRC(int crc32) {
  1356. crc = crc32;
  1357. }
  1358. }
  1359. private static class DeltaVisit {
  1360. final UnresolvedDelta delta;
  1361. ObjectId id;
  1362. byte[] data;
  1363. DeltaVisit parent;
  1364. UnresolvedDelta nextChild;
  1365. DeltaVisit() {
  1366. this.delta = null; // At the root of the stack we have a base.
  1367. }
  1368. DeltaVisit(DeltaVisit parent) {
  1369. this.parent = parent;
  1370. this.delta = parent.nextChild;
  1371. parent.nextChild = delta.next;
  1372. }
  1373. DeltaVisit next() {
  1374. // If our parent has no more children, discard it.
  1375. if (parent != null && parent.nextChild == null) {
  1376. parent.data = null;
  1377. parent = parent.parent;
  1378. }
  1379. if (nextChild != null)
  1380. return new DeltaVisit(this);
  1381. // If we have no child ourselves, our parent must (if it exists),
  1382. // due to the discard rule above. With no parent, we are done.
  1383. if (parent != null)
  1384. return new DeltaVisit(parent);
  1385. return null;
  1386. }
  1387. }
  1388. private void addObjectAndTrack(PackedObjectInfo oe) {
  1389. entries[entryCount++] = oe;
  1390. if (needNewObjectIds())
  1391. newObjectIds.add(oe);
  1392. }
  1393. private class InflaterStream extends InputStream {
  1394. private final Inflater inf;
  1395. private final byte[] skipBuffer;
  1396. private Source src;
  1397. private long expectedSize;
  1398. private long actualSize;
  1399. private int p;
  1400. InflaterStream() {
  1401. inf = InflaterCache.get();
  1402. skipBuffer = new byte[512];
  1403. }
  1404. void release() {
  1405. inf.reset();
  1406. InflaterCache.release(inf);
  1407. }
  1408. void open(Source source, long inflatedSize) throws IOException {
  1409. src = source;
  1410. expectedSize = inflatedSize;
  1411. actualSize = 0;
  1412. p = fill(src, 1);
  1413. inf.setInput(buf, p, bAvail);
  1414. }
  1415. @Override
  1416. public long skip(long toSkip) throws IOException {
  1417. long n = 0;
  1418. while (n < toSkip) {
  1419. final int cnt = (int) Math.min(skipBuffer.length, toSkip - n);
  1420. final int r = read(skipBuffer, 0, cnt);
  1421. if (r <= 0)
  1422. break;
  1423. n += r;
  1424. }
  1425. return n;
  1426. }
  1427. @Override
  1428. public int read() throws IOException {
  1429. int n = read(skipBuffer, 0, 1);
  1430. return n == 1 ? skipBuffer[0] & 0xff : -1;
  1431. }
  1432. @Override
  1433. public int read(byte[] dst, int pos, int cnt) throws IOException {
  1434. try {
  1435. int n = 0;
  1436. while (n < cnt) {
  1437. int r = inf.inflate(dst, pos + n, cnt - n);
  1438. if (r == 0) {
  1439. if (inf.finished())
  1440. break;
  1441. if (inf.needsInput()) {
  1442. onObjectData(src, buf, p, bAvail);
  1443. use(bAvail);
  1444. p = fill(src, 1);
  1445. inf.setInput(buf, p, bAvail);
  1446. } else {
  1447. throw new CorruptObjectException(
  1448. MessageFormat
  1449. .format(
  1450. JGitText.get().packfileCorruptionDetected,
  1451. JGitText.get().unknownZlibError));
  1452. }
  1453. } else {
  1454. n += r;
  1455. }
  1456. }
  1457. actualSize += n;
  1458. return 0 < n ? n : -1;
  1459. } catch (DataFormatException dfe) {
  1460. throw new CorruptObjectException(MessageFormat.format(JGitText
  1461. .get().packfileCorruptionDetected, dfe.getMessage()));
  1462. }
  1463. }
  1464. @Override
  1465. public void close() throws IOException {
  1466. // We need to read here to enter the loop above and pump the
  1467. // trailing checksum into the Inflater. It should return -1 as the
  1468. // caller was supposed to consume all content.
  1469. //
  1470. if (read(skipBuffer) != -1 || actualSize != expectedSize) {
  1471. throw new CorruptObjectException(MessageFormat.format(JGitText
  1472. .get().packfileCorruptionDetected,
  1473. JGitText.get().wrongDecompressedLength));
  1474. }
  1475. int used = bAvail - inf.getRemaining();
  1476. if (0 < used) {
  1477. onObjectData(src, buf, p, used);
  1478. use(used);
  1479. }
  1480. inf.reset();
  1481. }
  1482. }
  1483. }