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.

IndexPack.java 34KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. /*
  2. * Copyright (C) 2008-2010, 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.File;
  48. import java.io.FileOutputStream;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.RandomAccessFile;
  52. import java.security.MessageDigest;
  53. import java.text.MessageFormat;
  54. import java.util.ArrayList;
  55. import java.util.Arrays;
  56. import java.util.List;
  57. import java.util.zip.CRC32;
  58. import java.util.zip.DataFormatException;
  59. import java.util.zip.Deflater;
  60. import java.util.zip.Inflater;
  61. import org.eclipse.jgit.JGitText;
  62. import org.eclipse.jgit.errors.CorruptObjectException;
  63. import org.eclipse.jgit.errors.MissingObjectException;
  64. import org.eclipse.jgit.lib.AnyObjectId;
  65. import org.eclipse.jgit.lib.Constants;
  66. import org.eclipse.jgit.lib.CoreConfig;
  67. import org.eclipse.jgit.lib.InflaterCache;
  68. import org.eclipse.jgit.lib.MutableObjectId;
  69. import org.eclipse.jgit.lib.ObjectChecker;
  70. import org.eclipse.jgit.lib.ObjectDatabase;
  71. import org.eclipse.jgit.lib.ObjectId;
  72. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  73. import org.eclipse.jgit.lib.ObjectLoader;
  74. import org.eclipse.jgit.lib.ProgressMonitor;
  75. import org.eclipse.jgit.lib.Repository;
  76. import org.eclipse.jgit.lib.ObjectReader;
  77. import org.eclipse.jgit.storage.file.PackIndexWriter;
  78. import org.eclipse.jgit.storage.file.PackLock;
  79. import org.eclipse.jgit.storage.pack.BinaryDelta;
  80. import org.eclipse.jgit.util.NB;
  81. /** Indexes Git pack files for local use. */
  82. public class IndexPack {
  83. /** Progress message when reading raw data from the pack. */
  84. public static final String PROGRESS_DOWNLOAD = JGitText.get().receivingObjects;
  85. /** Progress message when computing names of delta compressed objects. */
  86. public static final String PROGRESS_RESOLVE_DELTA = JGitText.get().resolvingDeltas;
  87. /**
  88. * Size of the internal stream buffer.
  89. * <p>
  90. * If callers are going to be supplying IndexPack a BufferedInputStream they
  91. * should use this buffer size as the size of the buffer for that
  92. * BufferedInputStream, and any other its may be wrapping. This way the
  93. * buffers will cascade efficiently and only the IndexPack buffer will be
  94. * receiving the bulk of the data stream.
  95. */
  96. public static final int BUFFER_SIZE = 8192;
  97. /**
  98. * Create an index pack instance to load a new pack into a repository.
  99. * <p>
  100. * The received pack data and generated index will be saved to temporary
  101. * files within the repository's <code>objects</code> directory. To use the
  102. * data contained within them call {@link #renameAndOpenPack()} once the
  103. * indexing is complete.
  104. *
  105. * @param db
  106. * the repository that will receive the new pack.
  107. * @param is
  108. * stream to read the pack data from. If the stream is buffered
  109. * use {@link #BUFFER_SIZE} as the buffer size for the stream.
  110. * @return a new index pack instance.
  111. * @throws IOException
  112. * a temporary file could not be created.
  113. */
  114. public static IndexPack create(final Repository db, final InputStream is)
  115. throws IOException {
  116. final String suffix = ".pack";
  117. final File objdir = db.getObjectsDirectory();
  118. final File tmp = File.createTempFile("incoming_", suffix, objdir);
  119. final String n = tmp.getName();
  120. final File base;
  121. base = new File(objdir, n.substring(0, n.length() - suffix.length()));
  122. final IndexPack ip = new IndexPack(db, is, base);
  123. ip.setIndexVersion(db.getConfig().get(CoreConfig.KEY)
  124. .getPackIndexVersion());
  125. return ip;
  126. }
  127. private final Repository repo;
  128. /**
  129. * Object database used for loading existing objects
  130. */
  131. private final ObjectDatabase objectDatabase;
  132. private Inflater inflater;
  133. private final MessageDigest objectDigest;
  134. private final MutableObjectId tempObjectId;
  135. private InputStream in;
  136. private byte[] buf;
  137. private long bBase;
  138. private int bOffset;
  139. private int bAvail;
  140. private ObjectChecker objCheck;
  141. private boolean fixThin;
  142. private boolean keepEmpty;
  143. private boolean needBaseObjectIds;
  144. private int outputVersion;
  145. private final File dstPack;
  146. private final File dstIdx;
  147. private long objectCount;
  148. private PackedObjectInfo[] entries;
  149. /**
  150. * Every object contained within the incoming pack.
  151. * <p>
  152. * This is a subset of {@link #entries}, as thin packs can add additional
  153. * objects to {@code entries} by copying already existing objects from the
  154. * repository onto the end of the thin pack to make it self-contained.
  155. */
  156. private ObjectIdSubclassMap<ObjectId> newObjectIds;
  157. private int deltaCount;
  158. private int entryCount;
  159. private final CRC32 crc = new CRC32();
  160. private ObjectIdSubclassMap<DeltaChain> baseById;
  161. /**
  162. * Objects referenced by their name from deltas, that aren't in this pack.
  163. * <p>
  164. * This is the set of objects that were copied onto the end of this pack to
  165. * make it complete. These objects were not transmitted by the remote peer,
  166. * but instead were assumed to already exist in the local repository.
  167. */
  168. private ObjectIdSubclassMap<ObjectId> baseObjectIds;
  169. private LongMap<UnresolvedDelta> baseByPos;
  170. private byte[] objectData;
  171. private MessageDigest packDigest;
  172. private RandomAccessFile packOut;
  173. private byte[] packcsum;
  174. /** If {@link #fixThin} this is the last byte of the original checksum. */
  175. private long originalEOF;
  176. private ObjectReader readCurs;
  177. /**
  178. * Create a new pack indexer utility.
  179. *
  180. * @param db
  181. * @param src
  182. * stream to read the pack data from. If the stream is buffered
  183. * use {@link #BUFFER_SIZE} as the buffer size for the stream.
  184. * @param dstBase
  185. * @throws IOException
  186. * the output packfile could not be created.
  187. */
  188. public IndexPack(final Repository db, final InputStream src,
  189. final File dstBase) throws IOException {
  190. repo = db;
  191. objectDatabase = db.getObjectDatabase().newCachedDatabase();
  192. in = src;
  193. inflater = InflaterCache.get();
  194. readCurs = objectDatabase.newReader();
  195. buf = new byte[BUFFER_SIZE];
  196. objectData = new byte[BUFFER_SIZE];
  197. objectDigest = Constants.newMessageDigest();
  198. tempObjectId = new MutableObjectId();
  199. packDigest = Constants.newMessageDigest();
  200. if (dstBase != null) {
  201. final File dir = dstBase.getParentFile();
  202. final String nam = dstBase.getName();
  203. dstPack = new File(dir, nam + ".pack");
  204. dstIdx = new File(dir, nam + ".idx");
  205. packOut = new RandomAccessFile(dstPack, "rw");
  206. packOut.setLength(0);
  207. } else {
  208. dstPack = null;
  209. dstIdx = null;
  210. }
  211. }
  212. /**
  213. * Set the pack index file format version this instance will create.
  214. *
  215. * @param version
  216. * the version to write. The special version 0 designates the
  217. * oldest (most compatible) format available for the objects.
  218. * @see PackIndexWriter
  219. */
  220. public void setIndexVersion(final int version) {
  221. outputVersion = version;
  222. }
  223. /**
  224. * Configure this index pack instance to make a thin pack complete.
  225. * <p>
  226. * Thin packs are sometimes used during network transfers to allow a delta
  227. * to be sent without a base object. Such packs are not permitted on disk.
  228. * They can be fixed by copying the base object onto the end of the pack.
  229. *
  230. * @param fix
  231. * true to enable fixing a thin pack.
  232. */
  233. public void setFixThin(final boolean fix) {
  234. fixThin = fix;
  235. }
  236. /**
  237. * Configure this index pack instance to keep an empty pack.
  238. * <p>
  239. * By default an empty pack (a pack with no objects) is not kept, as doing
  240. * so is completely pointless. With no objects in the pack there is no data
  241. * stored by it, so the pack is unnecessary.
  242. *
  243. * @param empty true to enable keeping an empty pack.
  244. */
  245. public void setKeepEmpty(final boolean empty) {
  246. keepEmpty = empty;
  247. }
  248. /**
  249. * Configure this index pack instance to keep track of new objects.
  250. * <p>
  251. * By default an index pack doesn't save the new objects that were created
  252. * when it was instantiated. Setting this flag to {@code true} allows the
  253. * caller to use {@link #getNewObjectIds()} to retrieve that list.
  254. *
  255. * @param b {@code true} to enable keeping track of new objects.
  256. */
  257. public void setNeedNewObjectIds(boolean b) {
  258. if (b)
  259. newObjectIds = new ObjectIdSubclassMap<ObjectId>();
  260. else
  261. newObjectIds = null;
  262. }
  263. private boolean needNewObjectIds() {
  264. return newObjectIds != null;
  265. }
  266. /**
  267. * Configure this index pack instance to keep track of the objects assumed
  268. * for delta bases.
  269. * <p>
  270. * By default an index pack doesn't save the objects that were used as delta
  271. * bases. Setting this flag to {@code true} will allow the caller to
  272. * use {@link #getBaseObjectIds()} to retrieve that list.
  273. *
  274. * @param b {@code true} to enable keeping track of delta bases.
  275. */
  276. public void setNeedBaseObjectIds(boolean b) {
  277. this.needBaseObjectIds = b;
  278. }
  279. /** @return the new objects that were sent by the user */
  280. public ObjectIdSubclassMap<ObjectId> getNewObjectIds() {
  281. if (newObjectIds != null)
  282. return newObjectIds;
  283. return new ObjectIdSubclassMap<ObjectId>();
  284. }
  285. /** @return set of objects the incoming pack assumed for delta purposes */
  286. public ObjectIdSubclassMap<ObjectId> getBaseObjectIds() {
  287. if (baseObjectIds != null)
  288. return baseObjectIds;
  289. return new ObjectIdSubclassMap<ObjectId>();
  290. }
  291. /**
  292. * Configure the checker used to validate received objects.
  293. * <p>
  294. * Usually object checking isn't necessary, as Git implementations only
  295. * create valid objects in pack files. However, additional checking may be
  296. * useful if processing data from an untrusted source.
  297. *
  298. * @param oc
  299. * the checker instance; null to disable object checking.
  300. */
  301. public void setObjectChecker(final ObjectChecker oc) {
  302. objCheck = oc;
  303. }
  304. /**
  305. * Configure the checker used to validate received objects.
  306. * <p>
  307. * Usually object checking isn't necessary, as Git implementations only
  308. * create valid objects in pack files. However, additional checking may be
  309. * useful if processing data from an untrusted source.
  310. * <p>
  311. * This is shorthand for:
  312. *
  313. * <pre>
  314. * setObjectChecker(on ? new ObjectChecker() : null);
  315. * </pre>
  316. *
  317. * @param on
  318. * true to enable the default checker; false to disable it.
  319. */
  320. public void setObjectChecking(final boolean on) {
  321. setObjectChecker(on ? new ObjectChecker() : null);
  322. }
  323. /**
  324. * Consume data from the input stream until the packfile is indexed.
  325. *
  326. * @param progress
  327. * progress feedback
  328. *
  329. * @throws IOException
  330. */
  331. public void index(final ProgressMonitor progress) throws IOException {
  332. progress.start(2 /* tasks */);
  333. try {
  334. try {
  335. readPackHeader();
  336. entries = new PackedObjectInfo[(int) objectCount];
  337. baseById = new ObjectIdSubclassMap<DeltaChain>();
  338. baseByPos = new LongMap<UnresolvedDelta>();
  339. progress.beginTask(PROGRESS_DOWNLOAD, (int) objectCount);
  340. for (int done = 0; done < objectCount; done++) {
  341. indexOneObject();
  342. progress.update(1);
  343. if (progress.isCancelled())
  344. throw new IOException(JGitText.get().downloadCancelled);
  345. }
  346. readPackFooter();
  347. endInput();
  348. progress.endTask();
  349. if (deltaCount > 0) {
  350. if (packOut == null)
  351. throw new IOException(JGitText.get().needPackOut);
  352. resolveDeltas(progress);
  353. if (entryCount < objectCount) {
  354. if (!fixThin) {
  355. throw new IOException(MessageFormat.format(
  356. JGitText.get().packHasUnresolvedDeltas, (objectCount - entryCount)));
  357. }
  358. fixThinPack(progress);
  359. }
  360. }
  361. if (packOut != null && (keepEmpty || entryCount > 0))
  362. packOut.getChannel().force(true);
  363. packDigest = null;
  364. baseById = null;
  365. baseByPos = null;
  366. if (dstIdx != null && (keepEmpty || entryCount > 0))
  367. writeIdx();
  368. } finally {
  369. try {
  370. InflaterCache.release(inflater);
  371. } finally {
  372. inflater = null;
  373. objectDatabase.close();
  374. }
  375. try {
  376. if (readCurs != null)
  377. readCurs.release();
  378. } finally {
  379. readCurs = null;
  380. }
  381. progress.endTask();
  382. if (packOut != null)
  383. packOut.close();
  384. }
  385. if (keepEmpty || entryCount > 0) {
  386. if (dstPack != null)
  387. dstPack.setReadOnly();
  388. if (dstIdx != null)
  389. dstIdx.setReadOnly();
  390. }
  391. } catch (IOException err) {
  392. if (dstPack != null)
  393. dstPack.delete();
  394. if (dstIdx != null)
  395. dstIdx.delete();
  396. throw err;
  397. }
  398. }
  399. private void resolveDeltas(final ProgressMonitor progress)
  400. throws IOException {
  401. progress.beginTask(PROGRESS_RESOLVE_DELTA, deltaCount);
  402. final int last = entryCount;
  403. for (int i = 0; i < last; i++) {
  404. final int before = entryCount;
  405. resolveDeltas(entries[i]);
  406. progress.update(entryCount - before);
  407. if (progress.isCancelled())
  408. throw new IOException(JGitText.get().downloadCancelledDuringIndexing);
  409. }
  410. progress.endTask();
  411. }
  412. private void resolveDeltas(final PackedObjectInfo oe) throws IOException {
  413. final int oldCRC = oe.getCRC();
  414. if (baseById.get(oe) != null || baseByPos.containsKey(oe.getOffset()))
  415. resolveDeltas(oe.getOffset(), oldCRC, Constants.OBJ_BAD, null, oe);
  416. }
  417. private void resolveDeltas(final long pos, final int oldCRC, int type,
  418. byte[] data, PackedObjectInfo oe) throws IOException {
  419. crc.reset();
  420. position(pos);
  421. int c = readFromFile();
  422. final int typeCode = (c >> 4) & 7;
  423. long sz = c & 15;
  424. int shift = 4;
  425. while ((c & 0x80) != 0) {
  426. c = readFromFile();
  427. sz += (c & 0x7f) << shift;
  428. shift += 7;
  429. }
  430. switch (typeCode) {
  431. case Constants.OBJ_COMMIT:
  432. case Constants.OBJ_TREE:
  433. case Constants.OBJ_BLOB:
  434. case Constants.OBJ_TAG:
  435. type = typeCode;
  436. data = inflateFromFile((int) sz);
  437. break;
  438. case Constants.OBJ_OFS_DELTA: {
  439. c = readFromFile() & 0xff;
  440. while ((c & 128) != 0)
  441. c = readFromFile() & 0xff;
  442. data = BinaryDelta.apply(data, inflateFromFile((int) sz));
  443. break;
  444. }
  445. case Constants.OBJ_REF_DELTA: {
  446. crc.update(buf, fillFromFile(20), 20);
  447. use(20);
  448. data = BinaryDelta.apply(data, inflateFromFile((int) sz));
  449. break;
  450. }
  451. default:
  452. throw new IOException(MessageFormat.format(JGitText.get().unknownObjectType, typeCode));
  453. }
  454. final int crc32 = (int) crc.getValue();
  455. if (oldCRC != crc32)
  456. throw new IOException(MessageFormat.format(JGitText.get().corruptionDetectedReReadingAt, pos));
  457. if (oe == null) {
  458. objectDigest.update(Constants.encodedTypeString(type));
  459. objectDigest.update((byte) ' ');
  460. objectDigest.update(Constants.encodeASCII(data.length));
  461. objectDigest.update((byte) 0);
  462. objectDigest.update(data);
  463. tempObjectId.fromRaw(objectDigest.digest(), 0);
  464. verifySafeObject(tempObjectId, type, data);
  465. oe = new PackedObjectInfo(pos, crc32, tempObjectId);
  466. addObjectAndTrack(oe);
  467. }
  468. resolveChildDeltas(pos, type, data, oe);
  469. }
  470. private UnresolvedDelta removeBaseById(final AnyObjectId id){
  471. final DeltaChain d = baseById.get(id);
  472. return d != null ? d.remove() : null;
  473. }
  474. private static UnresolvedDelta reverse(UnresolvedDelta c) {
  475. UnresolvedDelta tail = null;
  476. while (c != null) {
  477. final UnresolvedDelta n = c.next;
  478. c.next = tail;
  479. tail = c;
  480. c = n;
  481. }
  482. return tail;
  483. }
  484. private void resolveChildDeltas(final long pos, int type, byte[] data,
  485. PackedObjectInfo oe) throws IOException {
  486. UnresolvedDelta a = reverse(removeBaseById(oe));
  487. UnresolvedDelta b = reverse(baseByPos.remove(pos));
  488. while (a != null && b != null) {
  489. if (a.position < b.position) {
  490. resolveDeltas(a.position, a.crc, type, data, null);
  491. a = a.next;
  492. } else {
  493. resolveDeltas(b.position, b.crc, type, data, null);
  494. b = b.next;
  495. }
  496. }
  497. resolveChildDeltaChain(type, data, a);
  498. resolveChildDeltaChain(type, data, b);
  499. }
  500. private void resolveChildDeltaChain(final int type, final byte[] data,
  501. UnresolvedDelta a) throws IOException {
  502. while (a != null) {
  503. resolveDeltas(a.position, a.crc, type, data, null);
  504. a = a.next;
  505. }
  506. }
  507. private void fixThinPack(final ProgressMonitor progress) throws IOException {
  508. growEntries();
  509. if (needBaseObjectIds)
  510. baseObjectIds = new ObjectIdSubclassMap<ObjectId>();
  511. packDigest.reset();
  512. originalEOF = packOut.length() - 20;
  513. final Deflater def = new Deflater(Deflater.DEFAULT_COMPRESSION, false);
  514. final List<DeltaChain> missing = new ArrayList<DeltaChain>(64);
  515. long end = originalEOF;
  516. for (final DeltaChain baseId : baseById) {
  517. if (baseId.head == null)
  518. continue;
  519. if (needBaseObjectIds)
  520. baseObjectIds.add(baseId);
  521. final ObjectLoader ldr = repo.openObject(readCurs, baseId);
  522. if (ldr == null) {
  523. missing.add(baseId);
  524. continue;
  525. }
  526. final byte[] data = ldr.getCachedBytes();
  527. final int typeCode = ldr.getType();
  528. final PackedObjectInfo oe;
  529. crc.reset();
  530. packOut.seek(end);
  531. writeWhole(def, typeCode, data);
  532. oe = new PackedObjectInfo(end, (int) crc.getValue(), baseId);
  533. entries[entryCount++] = oe;
  534. end = packOut.getFilePointer();
  535. resolveChildDeltas(oe.getOffset(), typeCode, data, oe);
  536. if (progress.isCancelled())
  537. throw new IOException(JGitText.get().downloadCancelledDuringIndexing);
  538. }
  539. def.end();
  540. for (final DeltaChain base : missing) {
  541. if (base.head != null)
  542. throw new MissingObjectException(base, "delta base");
  543. }
  544. if (end - originalEOF < 20) {
  545. // Ugly corner case; if what we appended on to complete deltas
  546. // doesn't completely cover the SHA-1 we have to truncate off
  547. // we need to shorten the file, otherwise we will include part
  548. // of the old footer as object content.
  549. packOut.setLength(end);
  550. }
  551. fixHeaderFooter(packcsum, packDigest.digest());
  552. }
  553. private void writeWhole(final Deflater def, final int typeCode,
  554. final byte[] data) throws IOException {
  555. int sz = data.length;
  556. int hdrlen = 0;
  557. buf[hdrlen++] = (byte) ((typeCode << 4) | sz & 15);
  558. sz >>>= 4;
  559. while (sz > 0) {
  560. buf[hdrlen - 1] |= 0x80;
  561. buf[hdrlen++] = (byte) (sz & 0x7f);
  562. sz >>>= 7;
  563. }
  564. packDigest.update(buf, 0, hdrlen);
  565. crc.update(buf, 0, hdrlen);
  566. packOut.write(buf, 0, hdrlen);
  567. def.reset();
  568. def.setInput(data);
  569. def.finish();
  570. while (!def.finished()) {
  571. final int datlen = def.deflate(buf);
  572. packDigest.update(buf, 0, datlen);
  573. crc.update(buf, 0, datlen);
  574. packOut.write(buf, 0, datlen);
  575. }
  576. }
  577. private void fixHeaderFooter(final byte[] origcsum, final byte[] tailcsum)
  578. throws IOException {
  579. final MessageDigest origDigest = Constants.newMessageDigest();
  580. final MessageDigest tailDigest = Constants.newMessageDigest();
  581. long origRemaining = originalEOF;
  582. packOut.seek(0);
  583. bAvail = 0;
  584. bOffset = 0;
  585. fillFromFile(12);
  586. {
  587. final int origCnt = (int) Math.min(bAvail, origRemaining);
  588. origDigest.update(buf, 0, origCnt);
  589. origRemaining -= origCnt;
  590. if (origRemaining == 0)
  591. tailDigest.update(buf, origCnt, bAvail - origCnt);
  592. }
  593. NB.encodeInt32(buf, 8, entryCount);
  594. packOut.seek(0);
  595. packOut.write(buf, 0, 12);
  596. packOut.seek(bAvail);
  597. packDigest.reset();
  598. packDigest.update(buf, 0, bAvail);
  599. for (;;) {
  600. final int n = packOut.read(buf);
  601. if (n < 0)
  602. break;
  603. if (origRemaining != 0) {
  604. final int origCnt = (int) Math.min(n, origRemaining);
  605. origDigest.update(buf, 0, origCnt);
  606. origRemaining -= origCnt;
  607. if (origRemaining == 0)
  608. tailDigest.update(buf, origCnt, n - origCnt);
  609. } else
  610. tailDigest.update(buf, 0, n);
  611. packDigest.update(buf, 0, n);
  612. }
  613. if (!Arrays.equals(origDigest.digest(), origcsum)
  614. || !Arrays.equals(tailDigest.digest(), tailcsum))
  615. throw new IOException(JGitText.get().packCorruptedWhileWritingToFilesystem);
  616. packcsum = packDigest.digest();
  617. packOut.write(packcsum);
  618. }
  619. private void growEntries() {
  620. final PackedObjectInfo[] ne;
  621. ne = new PackedObjectInfo[(int) objectCount + baseById.size()];
  622. System.arraycopy(entries, 0, ne, 0, entryCount);
  623. entries = ne;
  624. }
  625. private void writeIdx() throws IOException {
  626. Arrays.sort(entries, 0, entryCount);
  627. List<PackedObjectInfo> list = Arrays.asList(entries);
  628. if (entryCount < entries.length)
  629. list = list.subList(0, entryCount);
  630. final FileOutputStream os = new FileOutputStream(dstIdx);
  631. try {
  632. final PackIndexWriter iw;
  633. if (outputVersion <= 0)
  634. iw = PackIndexWriter.createOldestPossible(os, list);
  635. else
  636. iw = PackIndexWriter.createVersion(os, outputVersion);
  637. iw.write(list, packcsum);
  638. os.getChannel().force(true);
  639. } finally {
  640. os.close();
  641. }
  642. }
  643. private void readPackHeader() throws IOException {
  644. final int hdrln = Constants.PACK_SIGNATURE.length + 4 + 4;
  645. final int p = fillFromInput(hdrln);
  646. for (int k = 0; k < Constants.PACK_SIGNATURE.length; k++)
  647. if (buf[p + k] != Constants.PACK_SIGNATURE[k])
  648. throw new IOException(JGitText.get().notAPACKFile);
  649. final long vers = NB.decodeUInt32(buf, p + 4);
  650. if (vers != 2 && vers != 3)
  651. throw new IOException(MessageFormat.format(JGitText.get().unsupportedPackVersion, vers));
  652. objectCount = NB.decodeUInt32(buf, p + 8);
  653. use(hdrln);
  654. }
  655. private void readPackFooter() throws IOException {
  656. sync();
  657. final byte[] cmpcsum = packDigest.digest();
  658. final int c = fillFromInput(20);
  659. packcsum = new byte[20];
  660. System.arraycopy(buf, c, packcsum, 0, 20);
  661. use(20);
  662. if (packOut != null)
  663. packOut.write(packcsum);
  664. if (!Arrays.equals(cmpcsum, packcsum))
  665. throw new CorruptObjectException(JGitText.get().corruptObjectPackfileChecksumIncorrect);
  666. }
  667. // Cleanup all resources associated with our input parsing.
  668. private void endInput() {
  669. in = null;
  670. objectData = null;
  671. }
  672. // Read one entire object or delta from the input.
  673. private void indexOneObject() throws IOException {
  674. final long pos = position();
  675. crc.reset();
  676. int c = readFromInput();
  677. final int typeCode = (c >> 4) & 7;
  678. long sz = c & 15;
  679. int shift = 4;
  680. while ((c & 0x80) != 0) {
  681. c = readFromInput();
  682. sz += (c & 0x7f) << shift;
  683. shift += 7;
  684. }
  685. switch (typeCode) {
  686. case Constants.OBJ_COMMIT:
  687. case Constants.OBJ_TREE:
  688. case Constants.OBJ_BLOB:
  689. case Constants.OBJ_TAG:
  690. whole(typeCode, pos, sz);
  691. break;
  692. case Constants.OBJ_OFS_DELTA: {
  693. c = readFromInput();
  694. long ofs = c & 127;
  695. while ((c & 128) != 0) {
  696. ofs += 1;
  697. c = readFromInput();
  698. ofs <<= 7;
  699. ofs += (c & 127);
  700. }
  701. final long base = pos - ofs;
  702. final UnresolvedDelta n;
  703. skipInflateFromInput(sz);
  704. n = new UnresolvedDelta(pos, (int) crc.getValue());
  705. n.next = baseByPos.put(base, n);
  706. deltaCount++;
  707. break;
  708. }
  709. case Constants.OBJ_REF_DELTA: {
  710. c = fillFromInput(20);
  711. crc.update(buf, c, 20);
  712. final ObjectId base = ObjectId.fromRaw(buf, c);
  713. use(20);
  714. DeltaChain r = baseById.get(base);
  715. if (r == null) {
  716. r = new DeltaChain(base);
  717. baseById.add(r);
  718. }
  719. skipInflateFromInput(sz);
  720. r.add(new UnresolvedDelta(pos, (int) crc.getValue()));
  721. deltaCount++;
  722. break;
  723. }
  724. default:
  725. throw new IOException(MessageFormat.format(JGitText.get().unknownObjectType, typeCode));
  726. }
  727. }
  728. private void whole(final int type, final long pos, final long sz)
  729. throws IOException {
  730. final byte[] data = inflateFromInput(sz);
  731. objectDigest.update(Constants.encodedTypeString(type));
  732. objectDigest.update((byte) ' ');
  733. objectDigest.update(Constants.encodeASCII(sz));
  734. objectDigest.update((byte) 0);
  735. objectDigest.update(data);
  736. tempObjectId.fromRaw(objectDigest.digest(), 0);
  737. verifySafeObject(tempObjectId, type, data);
  738. final int crc32 = (int) crc.getValue();
  739. addObjectAndTrack(new PackedObjectInfo(pos, crc32, tempObjectId));
  740. }
  741. private void verifySafeObject(final AnyObjectId id, final int type,
  742. final byte[] data) throws IOException {
  743. if (objCheck != null) {
  744. try {
  745. objCheck.check(type, data);
  746. } catch (CorruptObjectException e) {
  747. throw new IOException(MessageFormat.format(JGitText.get().invalidObject
  748. , Constants.typeString(type) , id.name() , e.getMessage()));
  749. }
  750. }
  751. try {
  752. final ObjectLoader ldr = readCurs.openObject(id, type);
  753. final byte[] existingData = ldr.getCachedBytes();
  754. if (ldr.getType() != type || !Arrays.equals(data, existingData)) {
  755. throw new IOException(MessageFormat.format(JGitText.get().collisionOn, id.name()));
  756. }
  757. } catch (MissingObjectException notLocal) {
  758. // This is OK, we don't have a copy of the object locally
  759. // but the API throws when we try to read it as usually its
  760. // an error to read something that doesn't exist.
  761. }
  762. }
  763. // Current position of {@link #bOffset} within the entire file.
  764. private long position() {
  765. return bBase + bOffset;
  766. }
  767. private void position(final long pos) throws IOException {
  768. packOut.seek(pos);
  769. bBase = pos;
  770. bOffset = 0;
  771. bAvail = 0;
  772. }
  773. // Consume exactly one byte from the buffer and return it.
  774. private int readFromInput() throws IOException {
  775. if (bAvail == 0)
  776. fillFromInput(1);
  777. bAvail--;
  778. final int b = buf[bOffset++] & 0xff;
  779. crc.update(b);
  780. return b;
  781. }
  782. // Consume exactly one byte from the buffer and return it.
  783. private int readFromFile() throws IOException {
  784. if (bAvail == 0)
  785. fillFromFile(1);
  786. bAvail--;
  787. final int b = buf[bOffset++] & 0xff;
  788. crc.update(b);
  789. return b;
  790. }
  791. // Consume cnt bytes from the buffer.
  792. private void use(final int cnt) {
  793. bOffset += cnt;
  794. bAvail -= cnt;
  795. }
  796. // Ensure at least need bytes are available in in {@link #buf}.
  797. private int fillFromInput(final int need) throws IOException {
  798. while (bAvail < need) {
  799. int next = bOffset + bAvail;
  800. int free = buf.length - next;
  801. if (free + bAvail < need) {
  802. sync();
  803. next = bAvail;
  804. free = buf.length - next;
  805. }
  806. next = in.read(buf, next, free);
  807. if (next <= 0)
  808. throw new EOFException(JGitText.get().packfileIsTruncated);
  809. bAvail += next;
  810. }
  811. return bOffset;
  812. }
  813. // Ensure at least need bytes are available in in {@link #buf}.
  814. private int fillFromFile(final int need) throws IOException {
  815. if (bAvail < need) {
  816. int next = bOffset + bAvail;
  817. int free = buf.length - next;
  818. if (free + bAvail < need) {
  819. if (bAvail > 0)
  820. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  821. bOffset = 0;
  822. next = bAvail;
  823. free = buf.length - next;
  824. }
  825. next = packOut.read(buf, next, free);
  826. if (next <= 0)
  827. throw new EOFException(JGitText.get().packfileIsTruncated);
  828. bAvail += next;
  829. }
  830. return bOffset;
  831. }
  832. // Store consumed bytes in {@link #buf} up to {@link #bOffset}.
  833. private void sync() throws IOException {
  834. packDigest.update(buf, 0, bOffset);
  835. if (packOut != null)
  836. packOut.write(buf, 0, bOffset);
  837. if (bAvail > 0)
  838. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  839. bBase += bOffset;
  840. bOffset = 0;
  841. }
  842. private void skipInflateFromInput(long sz) throws IOException {
  843. final Inflater inf = inflater;
  844. try {
  845. final byte[] dst = objectData;
  846. int n = 0;
  847. int p = -1;
  848. while (!inf.finished()) {
  849. if (inf.needsInput()) {
  850. if (p >= 0) {
  851. crc.update(buf, p, bAvail);
  852. use(bAvail);
  853. }
  854. p = fillFromInput(1);
  855. inf.setInput(buf, p, bAvail);
  856. }
  857. int free = dst.length - n;
  858. if (free < 8) {
  859. sz -= n;
  860. n = 0;
  861. free = dst.length;
  862. }
  863. n += inf.inflate(dst, n, free);
  864. }
  865. if (n != sz)
  866. throw new DataFormatException(JGitText.get().wrongDecompressedLength);
  867. n = bAvail - inf.getRemaining();
  868. if (n > 0) {
  869. crc.update(buf, p, n);
  870. use(n);
  871. }
  872. } catch (DataFormatException dfe) {
  873. throw corrupt(dfe);
  874. } finally {
  875. inf.reset();
  876. }
  877. }
  878. private byte[] inflateFromInput(final long sz) throws IOException {
  879. final byte[] dst = new byte[(int) sz];
  880. final Inflater inf = inflater;
  881. try {
  882. int n = 0;
  883. int p = -1;
  884. while (!inf.finished()) {
  885. if (inf.needsInput()) {
  886. if (p >= 0) {
  887. crc.update(buf, p, bAvail);
  888. use(bAvail);
  889. }
  890. p = fillFromInput(1);
  891. inf.setInput(buf, p, bAvail);
  892. }
  893. n += inf.inflate(dst, n, dst.length - n);
  894. }
  895. if (n != sz)
  896. throw new DataFormatException(JGitText.get().wrongDecompressedLength);
  897. n = bAvail - inf.getRemaining();
  898. if (n > 0) {
  899. crc.update(buf, p, n);
  900. use(n);
  901. }
  902. return dst;
  903. } catch (DataFormatException dfe) {
  904. throw corrupt(dfe);
  905. } finally {
  906. inf.reset();
  907. }
  908. }
  909. private byte[] inflateFromFile(final int sz) throws IOException {
  910. final Inflater inf = inflater;
  911. try {
  912. final byte[] dst = new byte[sz];
  913. int n = 0;
  914. int p = -1;
  915. while (!inf.finished()) {
  916. if (inf.needsInput()) {
  917. if (p >= 0) {
  918. crc.update(buf, p, bAvail);
  919. use(bAvail);
  920. }
  921. p = fillFromFile(1);
  922. inf.setInput(buf, p, bAvail);
  923. }
  924. n += inf.inflate(dst, n, sz - n);
  925. }
  926. n = bAvail - inf.getRemaining();
  927. if (n > 0) {
  928. crc.update(buf, p, n);
  929. use(n);
  930. }
  931. return dst;
  932. } catch (DataFormatException dfe) {
  933. throw corrupt(dfe);
  934. } finally {
  935. inf.reset();
  936. }
  937. }
  938. private static CorruptObjectException corrupt(final DataFormatException dfe) {
  939. return new CorruptObjectException(MessageFormat.format(
  940. JGitText.get().packfileCorruptionDetected, dfe.getMessage()));
  941. }
  942. private static class DeltaChain extends ObjectId {
  943. UnresolvedDelta head;
  944. DeltaChain(final AnyObjectId id) {
  945. super(id);
  946. }
  947. UnresolvedDelta remove() {
  948. final UnresolvedDelta r = head;
  949. if (r != null)
  950. head = null;
  951. return r;
  952. }
  953. void add(final UnresolvedDelta d) {
  954. d.next = head;
  955. head = d;
  956. }
  957. }
  958. private static class UnresolvedDelta {
  959. final long position;
  960. final int crc;
  961. UnresolvedDelta next;
  962. UnresolvedDelta(final long headerOffset, final int crc32) {
  963. position = headerOffset;
  964. crc = crc32;
  965. }
  966. }
  967. /**
  968. * Rename the pack to it's final name and location and open it.
  969. * <p>
  970. * If the call completes successfully the repository this IndexPack instance
  971. * was created with will have the objects in the pack available for reading
  972. * and use, without needing to scan for packs.
  973. *
  974. * @throws IOException
  975. * The pack could not be inserted into the repository's objects
  976. * directory. The pack no longer exists on disk, as it was
  977. * removed prior to throwing the exception to the caller.
  978. */
  979. public void renameAndOpenPack() throws IOException {
  980. renameAndOpenPack(null);
  981. }
  982. /**
  983. * Rename the pack to it's final name and location and open it.
  984. * <p>
  985. * If the call completes successfully the repository this IndexPack instance
  986. * was created with will have the objects in the pack available for reading
  987. * and use, without needing to scan for packs.
  988. *
  989. * @param lockMessage
  990. * message to place in the pack-*.keep file. If null, no lock
  991. * will be created, and this method returns null.
  992. * @return the pack lock object, if lockMessage is not null.
  993. * @throws IOException
  994. * The pack could not be inserted into the repository's objects
  995. * directory. The pack no longer exists on disk, as it was
  996. * removed prior to throwing the exception to the caller.
  997. */
  998. public PackLock renameAndOpenPack(final String lockMessage)
  999. throws IOException {
  1000. if (!keepEmpty && entryCount == 0) {
  1001. cleanupTemporaryFiles();
  1002. return null;
  1003. }
  1004. final MessageDigest d = Constants.newMessageDigest();
  1005. final byte[] oeBytes = new byte[Constants.OBJECT_ID_LENGTH];
  1006. for (int i = 0; i < entryCount; i++) {
  1007. final PackedObjectInfo oe = entries[i];
  1008. oe.copyRawTo(oeBytes, 0);
  1009. d.update(oeBytes);
  1010. }
  1011. final String name = ObjectId.fromRaw(d.digest()).name();
  1012. final File packDir = new File(repo.getObjectsDirectory(), "pack");
  1013. final File finalPack = new File(packDir, "pack-" + name + ".pack");
  1014. final File finalIdx = new File(packDir, "pack-" + name + ".idx");
  1015. final PackLock keep = new PackLock(finalPack);
  1016. if (!packDir.exists() && !packDir.mkdir() && !packDir.exists()) {
  1017. // The objects/pack directory isn't present, and we are unable
  1018. // to create it. There is no way to move this pack in.
  1019. //
  1020. cleanupTemporaryFiles();
  1021. throw new IOException(MessageFormat.format(JGitText.get().cannotCreateDirectory, packDir.getAbsolutePath()));
  1022. }
  1023. if (finalPack.exists()) {
  1024. // If the pack is already present we should never replace it.
  1025. //
  1026. cleanupTemporaryFiles();
  1027. return null;
  1028. }
  1029. if (lockMessage != null) {
  1030. // If we have a reason to create a keep file for this pack, do
  1031. // so, or fail fast and don't put the pack in place.
  1032. //
  1033. try {
  1034. if (!keep.lock(lockMessage))
  1035. throw new IOException(MessageFormat.format(JGitText.get().cannotLockPackIn, finalPack));
  1036. } catch (IOException e) {
  1037. cleanupTemporaryFiles();
  1038. throw e;
  1039. }
  1040. }
  1041. if (!dstPack.renameTo(finalPack)) {
  1042. cleanupTemporaryFiles();
  1043. keep.unlock();
  1044. throw new IOException(MessageFormat.format(JGitText.get().cannotMovePackTo, finalPack));
  1045. }
  1046. if (!dstIdx.renameTo(finalIdx)) {
  1047. cleanupTemporaryFiles();
  1048. keep.unlock();
  1049. if (!finalPack.delete())
  1050. finalPack.deleteOnExit();
  1051. throw new IOException(MessageFormat.format(JGitText.get().cannotMoveIndexTo, finalIdx));
  1052. }
  1053. try {
  1054. repo.openPack(finalPack, finalIdx);
  1055. } catch (IOException err) {
  1056. keep.unlock();
  1057. finalPack.delete();
  1058. finalIdx.delete();
  1059. throw err;
  1060. }
  1061. return lockMessage != null ? keep : null;
  1062. }
  1063. private void cleanupTemporaryFiles() {
  1064. if (!dstIdx.delete())
  1065. dstIdx.deleteOnExit();
  1066. if (!dstPack.delete())
  1067. dstPack.deleteOnExit();
  1068. }
  1069. private void addObjectAndTrack(PackedObjectInfo oe) {
  1070. entries[entryCount++] = oe;
  1071. if (needNewObjectIds())
  1072. newObjectIds.add(oe);
  1073. }
  1074. }