Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

IndexPack.java 33KB

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