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

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