You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PackParser.java 51KB

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