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

IndexPack.java 33KB

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