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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  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 IOException(MessageFormat.format(
  886. JGitText.get().invalidObject, Constants
  887. .typeString(type), id.name(), e.getMessage()));
  888. }
  889. }
  890. try {
  891. final ObjectLoader ldr = readCurs.open(id, type);
  892. final byte[] existingData = ldr.getCachedBytes(data.length);
  893. if (!Arrays.equals(data, existingData)) {
  894. throw new IOException(MessageFormat.format(
  895. JGitText.get().collisionOn, id.name()));
  896. }
  897. } catch (MissingObjectException notLocal) {
  898. // This is OK, we don't have a copy of the object locally
  899. // but the API throws when we try to read it as usually its
  900. // an error to read something that doesn't exist.
  901. }
  902. }
  903. private void doDeferredCheckBlobs() throws IOException {
  904. final byte[] readBuffer = buffer();
  905. final byte[] curBuffer = new byte[readBuffer.length];
  906. ObjectTypeAndSize info = new ObjectTypeAndSize();
  907. for (PackedObjectInfo obj : deferredCheckBlobs) {
  908. info = openDatabase(obj, info);
  909. if (info.type != Constants.OBJ_BLOB)
  910. throw new IOException(MessageFormat.format(
  911. JGitText.get().unknownObjectType,
  912. Integer.valueOf(info.type)));
  913. ObjectStream cur = readCurs.open(obj, info.type).openStream();
  914. try {
  915. long sz = info.size;
  916. if (cur.getSize() != sz)
  917. throw new IOException(MessageFormat.format(
  918. JGitText.get().collisionOn, obj.name()));
  919. InputStream pck = inflate(Source.DATABASE, sz);
  920. while (0 < sz) {
  921. int n = (int) Math.min(readBuffer.length, sz);
  922. IO.readFully(cur, curBuffer, 0, n);
  923. IO.readFully(pck, readBuffer, 0, n);
  924. for (int i = 0; i < n; i++) {
  925. if (curBuffer[i] != readBuffer[i])
  926. throw new IOException(MessageFormat.format(JGitText
  927. .get().collisionOn, obj.name()));
  928. }
  929. sz -= n;
  930. }
  931. pck.close();
  932. } finally {
  933. cur.close();
  934. }
  935. }
  936. }
  937. /** @return current position of the input stream being parsed. */
  938. private long streamPosition() {
  939. return bBase + bOffset;
  940. }
  941. private ObjectTypeAndSize openDatabase(PackedObjectInfo obj,
  942. ObjectTypeAndSize info) throws IOException {
  943. bOffset = 0;
  944. bAvail = 0;
  945. return seekDatabase(obj, info);
  946. }
  947. private ObjectTypeAndSize openDatabase(UnresolvedDelta delta,
  948. ObjectTypeAndSize info) throws IOException {
  949. bOffset = 0;
  950. bAvail = 0;
  951. return seekDatabase(delta, info);
  952. }
  953. // Consume exactly one byte from the buffer and return it.
  954. private int readFrom(final Source src) throws IOException {
  955. if (bAvail == 0)
  956. fill(src, 1);
  957. bAvail--;
  958. return buf[bOffset++] & 0xff;
  959. }
  960. // Consume cnt bytes from the buffer.
  961. private void use(final int cnt) {
  962. bOffset += cnt;
  963. bAvail -= cnt;
  964. }
  965. // Ensure at least need bytes are available in in {@link #buf}.
  966. private int fill(final Source src, final int need) throws IOException {
  967. while (bAvail < need) {
  968. int next = bOffset + bAvail;
  969. int free = buf.length - next;
  970. if (free + bAvail < need) {
  971. switch (src) {
  972. case INPUT:
  973. sync();
  974. break;
  975. case DATABASE:
  976. if (bAvail > 0)
  977. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  978. bOffset = 0;
  979. break;
  980. }
  981. next = bAvail;
  982. free = buf.length - next;
  983. }
  984. switch (src) {
  985. case INPUT:
  986. next = in.read(buf, next, free);
  987. break;
  988. case DATABASE:
  989. next = readDatabase(buf, next, free);
  990. break;
  991. }
  992. if (next <= 0)
  993. throw new EOFException(JGitText.get().packfileIsTruncated);
  994. bAvail += next;
  995. }
  996. return bOffset;
  997. }
  998. // Store consumed bytes in {@link #buf} up to {@link #bOffset}.
  999. private void sync() throws IOException {
  1000. packDigest.update(buf, 0, bOffset);
  1001. onStoreStream(buf, 0, bOffset);
  1002. if (expectDataAfterPackFooter) {
  1003. if (bAvail > 0) {
  1004. in.reset();
  1005. IO.skipFully(in, bOffset);
  1006. bAvail = 0;
  1007. }
  1008. in.mark(buf.length);
  1009. } else if (bAvail > 0)
  1010. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  1011. bBase += bOffset;
  1012. bOffset = 0;
  1013. }
  1014. /** @return a temporary byte array for use by the caller. */
  1015. protected byte[] buffer() {
  1016. return tempBuffer;
  1017. }
  1018. /**
  1019. * Construct a PackedObjectInfo instance for this parser.
  1020. *
  1021. * @param id
  1022. * identity of the object to be tracked.
  1023. * @param delta
  1024. * if the object was previously an unresolved delta, this is the
  1025. * delta object that was tracking it. Otherwise null.
  1026. * @param deltaBase
  1027. * if the object was previously an unresolved delta, this is the
  1028. * ObjectId of the base of the delta. The base may be outside of
  1029. * the pack stream if the stream was a thin-pack.
  1030. * @return info object containing this object's data.
  1031. */
  1032. protected PackedObjectInfo newInfo(AnyObjectId id, UnresolvedDelta delta,
  1033. ObjectId deltaBase) {
  1034. PackedObjectInfo oe = new PackedObjectInfo(id);
  1035. if (delta != null)
  1036. oe.setCRC(delta.crc);
  1037. return oe;
  1038. }
  1039. /**
  1040. * Store bytes received from the raw stream.
  1041. * <p>
  1042. * This method is invoked during {@link #parse(ProgressMonitor)} as data is
  1043. * consumed from the incoming stream. Implementors may use this event to
  1044. * archive the raw incoming stream to the destination repository in large
  1045. * chunks, without paying attention to object boundaries.
  1046. * <p>
  1047. * The only component of the pack not supplied to this method is the last 20
  1048. * bytes of the pack that comprise the trailing SHA-1 checksum. Those are
  1049. * passed to {@link #onPackFooter(byte[])}.
  1050. *
  1051. * @param raw
  1052. * buffer to copy data out of.
  1053. * @param pos
  1054. * first offset within the buffer that is valid.
  1055. * @param len
  1056. * number of bytes in the buffer that are valid.
  1057. * @throws IOException
  1058. * the stream cannot be archived.
  1059. */
  1060. protected abstract void onStoreStream(byte[] raw, int pos, int len)
  1061. throws IOException;
  1062. /**
  1063. * Store (and/or checksum) an object header.
  1064. * <p>
  1065. * Invoked after any of the {@code onBegin()} events. The entire header is
  1066. * supplied in a single invocation, before any object data is supplied.
  1067. *
  1068. * @param src
  1069. * where the data came from
  1070. * @param raw
  1071. * buffer to read data from.
  1072. * @param pos
  1073. * first offset within buffer that is valid.
  1074. * @param len
  1075. * number of bytes in buffer that are valid.
  1076. * @throws IOException
  1077. * the stream cannot be archived.
  1078. */
  1079. protected abstract void onObjectHeader(Source src, byte[] raw, int pos,
  1080. int len) throws IOException;
  1081. /**
  1082. * Store (and/or checksum) a portion of an object's data.
  1083. * <p>
  1084. * This method may be invoked multiple times per object, depending on the
  1085. * size of the object, the size of the parser's internal read buffer, and
  1086. * the alignment of the object relative to the read buffer.
  1087. * <p>
  1088. * Invoked after {@link #onObjectHeader(Source, byte[], int, int)}.
  1089. *
  1090. * @param src
  1091. * where the data came from
  1092. * @param raw
  1093. * buffer to read data from.
  1094. * @param pos
  1095. * first offset within buffer that is valid.
  1096. * @param len
  1097. * number of bytes in buffer that are valid.
  1098. * @throws IOException
  1099. * the stream cannot be archived.
  1100. */
  1101. protected abstract void onObjectData(Source src, byte[] raw, int pos,
  1102. int len) throws IOException;
  1103. /**
  1104. * Invoked for commits, trees, tags, and small blobs.
  1105. *
  1106. * @param obj
  1107. * the object info, populated.
  1108. * @param typeCode
  1109. * the type of the object.
  1110. * @param data
  1111. * inflated data for the object.
  1112. * @throws IOException
  1113. * the object cannot be archived.
  1114. */
  1115. protected abstract void onInflatedObjectData(PackedObjectInfo obj,
  1116. int typeCode, byte[] data) throws IOException;
  1117. /**
  1118. * Provide the implementation with the original stream's pack header.
  1119. *
  1120. * @param objCnt
  1121. * number of objects expected in the stream.
  1122. * @throws IOException
  1123. * the implementation refuses to work with this many objects.
  1124. */
  1125. protected abstract void onPackHeader(long objCnt) throws IOException;
  1126. /**
  1127. * Provide the implementation with the original stream's pack footer.
  1128. *
  1129. * @param hash
  1130. * the trailing 20 bytes of the pack, this is a SHA-1 checksum of
  1131. * all of the pack data.
  1132. * @throws IOException
  1133. * the stream cannot be archived.
  1134. */
  1135. protected abstract void onPackFooter(byte[] hash) throws IOException;
  1136. /**
  1137. * Provide the implementation with a base that was outside of the pack.
  1138. * <p>
  1139. * This event only occurs on a thin pack for base objects that were outside
  1140. * of the pack and came from the local repository. Usually an implementation
  1141. * uses this event to compress the base and append it onto the end of the
  1142. * pack, so the pack stays self-contained.
  1143. *
  1144. * @param typeCode
  1145. * type of the base object.
  1146. * @param data
  1147. * complete content of the base object.
  1148. * @param info
  1149. * packed object information for this base. Implementors must
  1150. * populate the CRC and offset members if returning true.
  1151. * @return true if the {@code info} should be included in the object list
  1152. * returned by {@link #getSortedObjectList(Comparator)}, false if it
  1153. * should not be included.
  1154. * @throws IOException
  1155. * the base could not be included into the pack.
  1156. */
  1157. protected abstract boolean onAppendBase(int typeCode, byte[] data,
  1158. PackedObjectInfo info) throws IOException;
  1159. /**
  1160. * Event indicating a thin pack has been completely processed.
  1161. * <p>
  1162. * This event is invoked only if a thin pack has delta references to objects
  1163. * external from the pack. The event is called after all of those deltas
  1164. * have been resolved.
  1165. *
  1166. * @throws IOException
  1167. * the pack cannot be archived.
  1168. */
  1169. protected abstract void onEndThinPack() throws IOException;
  1170. /**
  1171. * Reposition the database to re-read a previously stored object.
  1172. * <p>
  1173. * If the database is computing CRC-32 checksums for object data, it should
  1174. * reset its internal CRC instance during this method call.
  1175. *
  1176. * @param obj
  1177. * the object position to begin reading from. This is from
  1178. * {@link #newInfo(AnyObjectId, UnresolvedDelta, ObjectId)}.
  1179. * @param info
  1180. * object to populate with type and size.
  1181. * @return the {@code info} object.
  1182. * @throws IOException
  1183. * the database cannot reposition to this location.
  1184. */
  1185. protected abstract ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
  1186. ObjectTypeAndSize info) throws IOException;
  1187. /**
  1188. * Reposition the database to re-read a previously stored object.
  1189. * <p>
  1190. * If the database is computing CRC-32 checksums for object data, it should
  1191. * reset its internal CRC instance during this method call.
  1192. *
  1193. * @param delta
  1194. * the object position to begin reading from. This is an instance
  1195. * previously returned by {@link #onEndDelta()}.
  1196. * @param info
  1197. * object to populate with type and size.
  1198. * @return the {@code info} object.
  1199. * @throws IOException
  1200. * the database cannot reposition to this location.
  1201. */
  1202. protected abstract ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
  1203. ObjectTypeAndSize info) throws IOException;
  1204. /**
  1205. * Read from the database's current position into the buffer.
  1206. *
  1207. * @param dst
  1208. * the buffer to copy read data into.
  1209. * @param pos
  1210. * position within {@code dst} to start copying data into.
  1211. * @param cnt
  1212. * ideal target number of bytes to read. Actual read length may
  1213. * be shorter.
  1214. * @return number of bytes stored.
  1215. * @throws IOException
  1216. * the database cannot be accessed.
  1217. */
  1218. protected abstract int readDatabase(byte[] dst, int pos, int cnt)
  1219. throws IOException;
  1220. /**
  1221. * Check the current CRC matches the expected value.
  1222. * <p>
  1223. * This method is invoked when an object is read back in from the database
  1224. * and its data is used during delta resolution. The CRC is validated after
  1225. * the object has been fully read, allowing the parser to verify there was
  1226. * no silent data corruption.
  1227. * <p>
  1228. * Implementations are free to ignore this check by always returning true if
  1229. * they are performing other data integrity validations at a lower level.
  1230. *
  1231. * @param oldCRC
  1232. * the prior CRC that was recorded during the first scan of the
  1233. * object from the pack stream.
  1234. * @return true if the CRC matches; false if it does not.
  1235. */
  1236. protected abstract boolean checkCRC(int oldCRC);
  1237. /**
  1238. * Event notifying the start of an object stored whole (not as a delta).
  1239. *
  1240. * @param streamPosition
  1241. * position of this object in the incoming stream.
  1242. * @param type
  1243. * type of the object; one of {@link Constants#OBJ_COMMIT},
  1244. * {@link Constants#OBJ_TREE}, {@link Constants#OBJ_BLOB}, or
  1245. * {@link Constants#OBJ_TAG}.
  1246. * @param inflatedSize
  1247. * size of the object when fully inflated. The size stored within
  1248. * the pack may be larger or smaller, and is not yet known.
  1249. * @throws IOException
  1250. * the object cannot be recorded.
  1251. */
  1252. protected abstract void onBeginWholeObject(long streamPosition, int type,
  1253. long inflatedSize) throws IOException;
  1254. /**
  1255. * Event notifying the the current object.
  1256. *
  1257. *@param info
  1258. * object information.
  1259. * @throws IOException
  1260. * the object cannot be recorded.
  1261. */
  1262. protected abstract void onEndWholeObject(PackedObjectInfo info)
  1263. throws IOException;
  1264. /**
  1265. * Event notifying start of a delta referencing its base by offset.
  1266. *
  1267. * @param deltaStreamPosition
  1268. * position of this object in the incoming stream.
  1269. * @param baseStreamPosition
  1270. * position of the base object in the incoming stream. The base
  1271. * must be before the delta, therefore {@code baseStreamPosition
  1272. * &lt; deltaStreamPosition}. This is <b>not</b> the position
  1273. * returned by a prior end object event.
  1274. * @param inflatedSize
  1275. * size of the delta when fully inflated. The size stored within
  1276. * the pack may be larger or smaller, and is not yet known.
  1277. * @throws IOException
  1278. * the object cannot be recorded.
  1279. */
  1280. protected abstract void onBeginOfsDelta(long deltaStreamPosition,
  1281. long baseStreamPosition, long inflatedSize) throws IOException;
  1282. /**
  1283. * Event notifying start of a delta referencing its base by ObjectId.
  1284. *
  1285. * @param deltaStreamPosition
  1286. * position of this object in the incoming stream.
  1287. * @param baseId
  1288. * name of the base object. This object may be later in the
  1289. * stream, or might not appear at all in the stream (in the case
  1290. * of a thin-pack).
  1291. * @param inflatedSize
  1292. * size of the delta when fully inflated. The size stored within
  1293. * the pack may be larger or smaller, and is not yet known.
  1294. * @throws IOException
  1295. * the object cannot be recorded.
  1296. */
  1297. protected abstract void onBeginRefDelta(long deltaStreamPosition,
  1298. AnyObjectId baseId, long inflatedSize) throws IOException;
  1299. /**
  1300. * Event notifying the the current object.
  1301. *
  1302. *@return object information that must be populated with at least the
  1303. * offset.
  1304. * @throws IOException
  1305. * the object cannot be recorded.
  1306. */
  1307. protected UnresolvedDelta onEndDelta() throws IOException {
  1308. return new UnresolvedDelta();
  1309. }
  1310. /** Type and size information about an object in the database buffer. */
  1311. public static class ObjectTypeAndSize {
  1312. /** The type of the object. */
  1313. public int type;
  1314. /** The inflated size of the object. */
  1315. public long size;
  1316. }
  1317. private void inflateAndSkip(final Source src, final long inflatedSize)
  1318. throws IOException {
  1319. final InputStream inf = inflate(src, inflatedSize);
  1320. IO.skipFully(inf, inflatedSize);
  1321. inf.close();
  1322. }
  1323. private byte[] inflateAndReturn(final Source src, final long inflatedSize)
  1324. throws IOException {
  1325. final byte[] dst = new byte[(int) inflatedSize];
  1326. final InputStream inf = inflate(src, inflatedSize);
  1327. IO.readFully(inf, dst, 0, dst.length);
  1328. inf.close();
  1329. return dst;
  1330. }
  1331. private InputStream inflate(final Source src, final long inflatedSize)
  1332. throws IOException {
  1333. inflater.open(src, inflatedSize);
  1334. return inflater;
  1335. }
  1336. private static class DeltaChain extends ObjectIdOwnerMap.Entry {
  1337. UnresolvedDelta head;
  1338. DeltaChain(final AnyObjectId id) {
  1339. super(id);
  1340. }
  1341. UnresolvedDelta remove() {
  1342. final UnresolvedDelta r = head;
  1343. if (r != null)
  1344. head = null;
  1345. return r;
  1346. }
  1347. void add(final UnresolvedDelta d) {
  1348. d.next = head;
  1349. head = d;
  1350. }
  1351. }
  1352. /** Information about an unresolved delta in this pack stream. */
  1353. public static class UnresolvedDelta {
  1354. long position;
  1355. int crc;
  1356. UnresolvedDelta next;
  1357. /** @return offset within the input stream. */
  1358. public long getOffset() {
  1359. return position;
  1360. }
  1361. /** @return the CRC-32 checksum of the stored delta data. */
  1362. public int getCRC() {
  1363. return crc;
  1364. }
  1365. /**
  1366. * @param crc32
  1367. * the CRC-32 checksum of the stored delta data.
  1368. */
  1369. public void setCRC(int crc32) {
  1370. crc = crc32;
  1371. }
  1372. }
  1373. private static class DeltaVisit {
  1374. final UnresolvedDelta delta;
  1375. ObjectId id;
  1376. byte[] data;
  1377. DeltaVisit parent;
  1378. UnresolvedDelta nextChild;
  1379. DeltaVisit() {
  1380. this.delta = null; // At the root of the stack we have a base.
  1381. }
  1382. DeltaVisit(DeltaVisit parent) {
  1383. this.parent = parent;
  1384. this.delta = parent.nextChild;
  1385. parent.nextChild = delta.next;
  1386. }
  1387. DeltaVisit next() {
  1388. // If our parent has no more children, discard it.
  1389. if (parent != null && parent.nextChild == null) {
  1390. parent.data = null;
  1391. parent = parent.parent;
  1392. }
  1393. if (nextChild != null)
  1394. return new DeltaVisit(this);
  1395. // If we have no child ourselves, our parent must (if it exists),
  1396. // due to the discard rule above. With no parent, we are done.
  1397. if (parent != null)
  1398. return new DeltaVisit(parent);
  1399. return null;
  1400. }
  1401. }
  1402. private void addObjectAndTrack(PackedObjectInfo oe) {
  1403. entries[entryCount++] = oe;
  1404. if (needNewObjectIds())
  1405. newObjectIds.add(oe);
  1406. }
  1407. private class InflaterStream extends InputStream {
  1408. private final Inflater inf;
  1409. private final byte[] skipBuffer;
  1410. private Source src;
  1411. private long expectedSize;
  1412. private long actualSize;
  1413. private int p;
  1414. InflaterStream() {
  1415. inf = InflaterCache.get();
  1416. skipBuffer = new byte[512];
  1417. }
  1418. void release() {
  1419. inf.reset();
  1420. InflaterCache.release(inf);
  1421. }
  1422. void open(Source source, long inflatedSize) throws IOException {
  1423. src = source;
  1424. expectedSize = inflatedSize;
  1425. actualSize = 0;
  1426. p = fill(src, 1);
  1427. inf.setInput(buf, p, bAvail);
  1428. }
  1429. @Override
  1430. public long skip(long toSkip) throws IOException {
  1431. long n = 0;
  1432. while (n < toSkip) {
  1433. final int cnt = (int) Math.min(skipBuffer.length, toSkip - n);
  1434. final int r = read(skipBuffer, 0, cnt);
  1435. if (r <= 0)
  1436. break;
  1437. n += r;
  1438. }
  1439. return n;
  1440. }
  1441. @Override
  1442. public int read() throws IOException {
  1443. int n = read(skipBuffer, 0, 1);
  1444. return n == 1 ? skipBuffer[0] & 0xff : -1;
  1445. }
  1446. @Override
  1447. public int read(byte[] dst, int pos, int cnt) throws IOException {
  1448. try {
  1449. int n = 0;
  1450. while (n < cnt) {
  1451. int r = inf.inflate(dst, pos + n, cnt - n);
  1452. if (r == 0) {
  1453. if (inf.finished())
  1454. break;
  1455. if (inf.needsInput()) {
  1456. onObjectData(src, buf, p, bAvail);
  1457. use(bAvail);
  1458. p = fill(src, 1);
  1459. inf.setInput(buf, p, bAvail);
  1460. } else {
  1461. throw new CorruptObjectException(
  1462. MessageFormat
  1463. .format(
  1464. JGitText.get().packfileCorruptionDetected,
  1465. JGitText.get().unknownZlibError));
  1466. }
  1467. } else {
  1468. n += r;
  1469. }
  1470. }
  1471. actualSize += n;
  1472. return 0 < n ? n : -1;
  1473. } catch (DataFormatException dfe) {
  1474. throw new CorruptObjectException(MessageFormat.format(JGitText
  1475. .get().packfileCorruptionDetected, dfe.getMessage()));
  1476. }
  1477. }
  1478. @Override
  1479. public void close() throws IOException {
  1480. // We need to read here to enter the loop above and pump the
  1481. // trailing checksum into the Inflater. It should return -1 as the
  1482. // caller was supposed to consume all content.
  1483. //
  1484. if (read(skipBuffer) != -1 || actualSize != expectedSize) {
  1485. throw new CorruptObjectException(MessageFormat.format(JGitText
  1486. .get().packfileCorruptionDetected,
  1487. JGitText.get().wrongDecompressedLength));
  1488. }
  1489. int used = bAvail - inf.getRemaining();
  1490. if (0 < used) {
  1491. onObjectData(src, buf, p, used);
  1492. use(used);
  1493. }
  1494. inf.reset();
  1495. }
  1496. }
  1497. }