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 53KB

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