Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

PackParser.java 45KB

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