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

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