WalkFetchConnection.java

  1. /*
  2.  * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  3.  * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
  4.  *
  5.  * This program and the accompanying materials are made available under the
  6.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  7.  * https://www.eclipse.org/org/documents/edl-v10.php.
  8.  *
  9.  * SPDX-License-Identifier: BSD-3-Clause
  10.  */

  11. package org.eclipse.jgit.transport;

  12. import java.io.File;
  13. import java.io.FileNotFoundException;
  14. import java.io.FileOutputStream;
  15. import java.io.IOException;
  16. import java.text.MessageFormat;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.HashMap;
  20. import java.util.HashSet;
  21. import java.util.Iterator;
  22. import java.util.LinkedList;
  23. import java.util.List;
  24. import java.util.Set;

  25. import org.eclipse.jgit.errors.CompoundException;
  26. import org.eclipse.jgit.errors.CorruptObjectException;
  27. import org.eclipse.jgit.errors.MissingObjectException;
  28. import org.eclipse.jgit.errors.TransportException;
  29. import org.eclipse.jgit.internal.JGitText;
  30. import org.eclipse.jgit.internal.storage.file.ObjectDirectory;
  31. import org.eclipse.jgit.internal.storage.file.PackIndex;
  32. import org.eclipse.jgit.internal.storage.file.UnpackedObject;
  33. import org.eclipse.jgit.lib.AnyObjectId;
  34. import org.eclipse.jgit.lib.Constants;
  35. import org.eclipse.jgit.lib.FileMode;
  36. import org.eclipse.jgit.lib.MutableObjectId;
  37. import org.eclipse.jgit.lib.ObjectChecker;
  38. import org.eclipse.jgit.lib.ObjectId;
  39. import org.eclipse.jgit.lib.ObjectInserter;
  40. import org.eclipse.jgit.lib.ObjectLoader;
  41. import org.eclipse.jgit.lib.ObjectReader;
  42. import org.eclipse.jgit.lib.ProgressMonitor;
  43. import org.eclipse.jgit.lib.Ref;
  44. import org.eclipse.jgit.lib.Repository;
  45. import org.eclipse.jgit.revwalk.DateRevQueue;
  46. import org.eclipse.jgit.revwalk.RevCommit;
  47. import org.eclipse.jgit.revwalk.RevFlag;
  48. import org.eclipse.jgit.revwalk.RevObject;
  49. import org.eclipse.jgit.revwalk.RevTag;
  50. import org.eclipse.jgit.revwalk.RevTree;
  51. import org.eclipse.jgit.revwalk.RevWalk;
  52. import org.eclipse.jgit.treewalk.TreeWalk;
  53. import org.eclipse.jgit.util.FileUtils;

  54. /**
  55.  * Generic fetch support for dumb transport protocols.
  56.  * <p>
  57.  * Since there are no Git-specific smarts on the remote side of the connection
  58.  * the client side must determine which objects it needs to copy in order to
  59.  * completely fetch the requested refs and their history. The generic walk
  60.  * support in this class parses each individual object (once it has been copied
  61.  * to the local repository) and examines the list of objects that must also be
  62.  * copied to create a complete history. Objects which are already available
  63.  * locally are retained (and not copied), saving bandwidth for incremental
  64.  * fetches. Pack files are copied from the remote repository only as a last
  65.  * resort, as the entire pack must be copied locally in order to access any
  66.  * single object.
  67.  * <p>
  68.  * This fetch connection does not actually perform the object data transfer.
  69.  * Instead it delegates the transfer to a {@link WalkRemoteObjectDatabase},
  70.  * which knows how to read individual files from the remote repository and
  71.  * supply the data as a standard Java InputStream.
  72.  *
  73.  * @see WalkRemoteObjectDatabase
  74.  */
  75. class WalkFetchConnection extends BaseFetchConnection {
  76.     /** The repository this transport fetches into, or pushes out of. */
  77.     final Repository local;

  78.     /** If not null the validator for received objects. */
  79.     final ObjectChecker objCheck;

  80.     /**
  81.      * List of all remote repositories we may need to get objects out of.
  82.      * <p>
  83.      * The first repository in the list is the one we were asked to fetch from;
  84.      * the remaining repositories point to the alternate locations we can fetch
  85.      * objects through.
  86.      */
  87.     private final List<WalkRemoteObjectDatabase> remotes;

  88.     /** Most recently used item in {@link #remotes}. */
  89.     private int lastRemoteIdx;

  90.     private final RevWalk revWalk;

  91.     private final TreeWalk treeWalk;

  92.     /** Objects whose direct dependents we know we have (or will have). */
  93.     private final RevFlag COMPLETE;

  94.     /** Objects that have already entered {@link #workQueue}. */
  95.     private final RevFlag IN_WORK_QUEUE;

  96.     /** Commits that have already entered {@link #localCommitQueue}. */
  97.     private final RevFlag LOCALLY_SEEN;

  98.     /** Commits already reachable from all local refs. */
  99.     private final DateRevQueue localCommitQueue;

  100.     /** Objects we need to copy from the remote repository. */
  101.     private LinkedList<ObjectId> workQueue;

  102.     /** Databases we have not yet obtained the list of packs from. */
  103.     private final LinkedList<WalkRemoteObjectDatabase> noPacksYet;

  104.     /** Databases we have not yet obtained the alternates from. */
  105.     private final LinkedList<WalkRemoteObjectDatabase> noAlternatesYet;

  106.     /** Packs we have discovered, but have not yet fetched locally. */
  107.     private final LinkedList<RemotePack> unfetchedPacks;

  108.     /**
  109.      * Packs whose indexes we have looked at in {@link #unfetchedPacks}.
  110.      * <p>
  111.      * We try to avoid getting duplicate copies of the same pack through
  112.      * multiple alternates by only looking at packs whose names are not yet in
  113.      * this collection.
  114.      */
  115.     private final Set<String> packsConsidered;

  116.     private final MutableObjectId idBuffer = new MutableObjectId();

  117.     /**
  118.      * Errors received while trying to obtain an object.
  119.      * <p>
  120.      * If the fetch winds up failing because we cannot locate a specific object
  121.      * then we need to report all errors related to that object back to the
  122.      * caller as there may be cascading failures.
  123.      */
  124.     private final HashMap<ObjectId, List<Throwable>> fetchErrors;

  125.     String lockMessage;

  126.     final List<PackLock> packLocks;

  127.     /** Inserter to write objects onto {@link #local}. */
  128.     final ObjectInserter inserter;

  129.     /** Inserter to read objects from {@link #local}. */
  130.     private final ObjectReader reader;

  131.     WalkFetchConnection(WalkTransport t, WalkRemoteObjectDatabase w) {
  132.         Transport wt = (Transport)t;
  133.         local = wt.local;
  134.         objCheck = wt.getObjectChecker();
  135.         inserter = local.newObjectInserter();
  136.         reader = inserter.newReader();

  137.         remotes = new ArrayList<>();
  138.         remotes.add(w);

  139.         unfetchedPacks = new LinkedList<>();
  140.         packsConsidered = new HashSet<>();

  141.         noPacksYet = new LinkedList<>();
  142.         noPacksYet.add(w);

  143.         noAlternatesYet = new LinkedList<>();
  144.         noAlternatesYet.add(w);

  145.         fetchErrors = new HashMap<>();
  146.         packLocks = new ArrayList<>(4);

  147.         revWalk = new RevWalk(reader);
  148.         revWalk.setRetainBody(false);
  149.         treeWalk = new TreeWalk(reader);
  150.         COMPLETE = revWalk.newFlag("COMPLETE"); //$NON-NLS-1$
  151.         IN_WORK_QUEUE = revWalk.newFlag("IN_WORK_QUEUE"); //$NON-NLS-1$
  152.         LOCALLY_SEEN = revWalk.newFlag("LOCALLY_SEEN"); //$NON-NLS-1$

  153.         localCommitQueue = new DateRevQueue();
  154.         workQueue = new LinkedList<>();
  155.     }

  156.     /** {@inheritDoc} */
  157.     @Override
  158.     public boolean didFetchTestConnectivity() {
  159.         return true;
  160.     }

  161.     /** {@inheritDoc} */
  162.     @Override
  163.     protected void doFetch(final ProgressMonitor monitor,
  164.             final Collection<Ref> want, final Set<ObjectId> have)
  165.             throws TransportException {
  166.         markLocalRefsComplete(have);
  167.         queueWants(want);

  168.         while (!monitor.isCancelled() && !workQueue.isEmpty()) {
  169.             final ObjectId id = workQueue.removeFirst();
  170.             if (!(id instanceof RevObject) || !((RevObject) id).has(COMPLETE))
  171.                 downloadObject(monitor, id);
  172.             process(id);
  173.         }

  174.         try {
  175.             inserter.flush();
  176.         } catch (IOException e) {
  177.             throw new TransportException(e.getMessage(), e);
  178.         }
  179.     }

  180.     /** {@inheritDoc} */
  181.     @Override
  182.     public Collection<PackLock> getPackLocks() {
  183.         return packLocks;
  184.     }

  185.     /** {@inheritDoc} */
  186.     @Override
  187.     public void setPackLockMessage(String message) {
  188.         lockMessage = message;
  189.     }

  190.     /** {@inheritDoc} */
  191.     @Override
  192.     public void close() {
  193.         inserter.close();
  194.         reader.close();
  195.         for (RemotePack p : unfetchedPacks) {
  196.             if (p.tmpIdx != null)
  197.                 p.tmpIdx.delete();
  198.         }
  199.         for (WalkRemoteObjectDatabase r : remotes)
  200.             r.close();
  201.     }

  202.     private void queueWants(Collection<Ref> want)
  203.             throws TransportException {
  204.         final HashSet<ObjectId> inWorkQueue = new HashSet<>();
  205.         for (Ref r : want) {
  206.             final ObjectId id = r.getObjectId();
  207.             if (id == null) {
  208.                 throw new NullPointerException(MessageFormat.format(
  209.                         JGitText.get().transportProvidedRefWithNoObjectId, r.getName()));
  210.             }
  211.             try {
  212.                 final RevObject obj = revWalk.parseAny(id);
  213.                 if (obj.has(COMPLETE))
  214.                     continue;
  215.                 if (inWorkQueue.add(id)) {
  216.                     obj.add(IN_WORK_QUEUE);
  217.                     workQueue.add(obj);
  218.                 }
  219.             } catch (MissingObjectException e) {
  220.                 if (inWorkQueue.add(id))
  221.                     workQueue.add(id);
  222.             } catch (IOException e) {
  223.                 throw new TransportException(MessageFormat.format(JGitText.get().cannotRead, id.name()), e);
  224.             }
  225.         }
  226.     }

  227.     private void process(ObjectId id) throws TransportException {
  228.         final RevObject obj;
  229.         try {
  230.             if (id instanceof RevObject) {
  231.                 obj = (RevObject) id;
  232.                 if (obj.has(COMPLETE))
  233.                     return;
  234.                 revWalk.parseHeaders(obj);
  235.             } else {
  236.                 obj = revWalk.parseAny(id);
  237.                 if (obj.has(COMPLETE))
  238.                     return;
  239.             }
  240.         } catch (IOException e) {
  241.             throw new TransportException(MessageFormat.format(JGitText.get().cannotRead, id.name()), e);
  242.         }

  243.         switch (obj.getType()) {
  244.         case Constants.OBJ_BLOB:
  245.             processBlob(obj);
  246.             break;
  247.         case Constants.OBJ_TREE:
  248.             processTree(obj);
  249.             break;
  250.         case Constants.OBJ_COMMIT:
  251.             processCommit(obj);
  252.             break;
  253.         case Constants.OBJ_TAG:
  254.             processTag(obj);
  255.             break;
  256.         default:
  257.             throw new TransportException(MessageFormat.format(JGitText.get().unknownObjectType, id.name()));
  258.         }

  259.         // If we had any prior errors fetching this object they are
  260.         // now resolved, as the object was parsed successfully.
  261.         //
  262.         fetchErrors.remove(id);
  263.     }

  264.     private void processBlob(RevObject obj) throws TransportException {
  265.         try {
  266.             if (reader.has(obj, Constants.OBJ_BLOB))
  267.                 obj.add(COMPLETE);
  268.             else
  269.                 throw new TransportException(MessageFormat.format(JGitText
  270.                         .get().cannotReadBlob, obj.name()),
  271.                         new MissingObjectException(obj, Constants.TYPE_BLOB));
  272.         } catch (IOException error) {
  273.             throw new TransportException(MessageFormat.format(
  274.                     JGitText.get().cannotReadBlob, obj.name()), error);
  275.         }
  276.     }

  277.     private void processTree(RevObject obj) throws TransportException {
  278.         try {
  279.             treeWalk.reset(obj);
  280.             while (treeWalk.next()) {
  281.                 final FileMode mode = treeWalk.getFileMode(0);
  282.                 final int sType = mode.getObjectType();

  283.                 switch (sType) {
  284.                 case Constants.OBJ_BLOB:
  285.                 case Constants.OBJ_TREE:
  286.                     treeWalk.getObjectId(idBuffer, 0);
  287.                     needs(revWalk.lookupAny(idBuffer, sType));
  288.                     continue;

  289.                 default:
  290.                     if (FileMode.GITLINK.equals(mode))
  291.                         continue;
  292.                     treeWalk.getObjectId(idBuffer, 0);
  293.                     throw new CorruptObjectException(MessageFormat.format(JGitText.get().invalidModeFor
  294.                             , mode, idBuffer.name(), treeWalk.getPathString(), obj.getId().name()));
  295.                 }
  296.             }
  297.         } catch (IOException ioe) {
  298.             throw new TransportException(MessageFormat.format(JGitText.get().cannotReadTree, obj.name()), ioe);
  299.         }
  300.         obj.add(COMPLETE);
  301.     }

  302.     private void processCommit(RevObject obj) throws TransportException {
  303.         final RevCommit commit = (RevCommit) obj;
  304.         markLocalCommitsComplete(commit.getCommitTime());
  305.         needs(commit.getTree());
  306.         for (RevCommit p : commit.getParents())
  307.             needs(p);
  308.         obj.add(COMPLETE);
  309.     }

  310.     private void processTag(RevObject obj) {
  311.         final RevTag tag = (RevTag) obj;
  312.         needs(tag.getObject());
  313.         obj.add(COMPLETE);
  314.     }

  315.     private void needs(RevObject obj) {
  316.         if (obj.has(COMPLETE))
  317.             return;
  318.         if (!obj.has(IN_WORK_QUEUE)) {
  319.             obj.add(IN_WORK_QUEUE);
  320.             workQueue.add(obj);
  321.         }
  322.     }

  323.     private void downloadObject(ProgressMonitor pm, AnyObjectId id)
  324.             throws TransportException {
  325.         if (alreadyHave(id))
  326.             return;

  327.         for (;;) {
  328.             // Try a pack file we know about, but don't have yet. Odds are
  329.             // that if it has this object, it has others related to it so
  330.             // getting the pack is a good bet.
  331.             //
  332.             if (downloadPackedObject(pm, id))
  333.                 return;

  334.             // Search for a loose object over all alternates, starting
  335.             // from the one we last successfully located an object through.
  336.             //
  337.             final String idStr = id.name();
  338.             final String subdir = idStr.substring(0, 2);
  339.             final String file = idStr.substring(2);
  340.             final String looseName = subdir + "/" + file; //$NON-NLS-1$

  341.             for (int i = lastRemoteIdx; i < remotes.size(); i++) {
  342.                 if (downloadLooseObject(id, looseName, remotes.get(i))) {
  343.                     lastRemoteIdx = i;
  344.                     return;
  345.                 }
  346.             }
  347.             for (int i = 0; i < lastRemoteIdx; i++) {
  348.                 if (downloadLooseObject(id, looseName, remotes.get(i))) {
  349.                     lastRemoteIdx = i;
  350.                     return;
  351.                 }
  352.             }

  353.             // Try to obtain more pack information and search those.
  354.             //
  355.             while (!noPacksYet.isEmpty()) {
  356.                 final WalkRemoteObjectDatabase wrr = noPacksYet.removeFirst();
  357.                 final Collection<String> packNameList;
  358.                 try {
  359.                     pm.beginTask(JGitText.get().listingPacks,
  360.                             ProgressMonitor.UNKNOWN);
  361.                     packNameList = wrr.getPackNames();
  362.                 } catch (IOException e) {
  363.                     // Try another repository.
  364.                     //
  365.                     recordError(id, e);
  366.                     continue;
  367.                 } finally {
  368.                     pm.endTask();
  369.                 }

  370.                 if (packNameList == null || packNameList.isEmpty())
  371.                     continue;
  372.                 for (String packName : packNameList) {
  373.                     if (packsConsidered.add(packName))
  374.                         unfetchedPacks.add(new RemotePack(wrr, packName));
  375.                 }
  376.                 if (downloadPackedObject(pm, id))
  377.                     return;
  378.             }

  379.             // Try to expand the first alternate we haven't expanded yet.
  380.             //
  381.             Collection<WalkRemoteObjectDatabase> al = expandOneAlternate(id, pm);
  382.             if (al != null && !al.isEmpty()) {
  383.                 for (WalkRemoteObjectDatabase alt : al) {
  384.                     remotes.add(alt);
  385.                     noPacksYet.add(alt);
  386.                     noAlternatesYet.add(alt);
  387.                 }
  388.                 continue;
  389.             }

  390.             // We could not obtain the object. There may be reasons why.
  391.             //
  392.             List<Throwable> failures = fetchErrors.get(id);
  393.             final TransportException te;

  394.             te = new TransportException(MessageFormat.format(JGitText.get().cannotGet, id.name()));
  395.             if (failures != null && !failures.isEmpty()) {
  396.                 if (failures.size() == 1)
  397.                     te.initCause(failures.get(0));
  398.                 else
  399.                     te.initCause(new CompoundException(failures));
  400.             }
  401.             throw te;
  402.         }
  403.     }

  404.     private boolean alreadyHave(AnyObjectId id) throws TransportException {
  405.         try {
  406.             return reader.has(id);
  407.         } catch (IOException error) {
  408.             throw new TransportException(MessageFormat.format(
  409.                     JGitText.get().cannotReadObject, id.name()), error);
  410.         }
  411.     }

  412.     private boolean downloadPackedObject(final ProgressMonitor monitor,
  413.             final AnyObjectId id) throws TransportException {
  414.         // Search for the object in a remote pack whose index we have,
  415.         // but whose pack we do not yet have.
  416.         //
  417.         final Iterator<RemotePack> packItr = unfetchedPacks.iterator();
  418.         while (packItr.hasNext() && !monitor.isCancelled()) {
  419.             final RemotePack pack = packItr.next();
  420.             try {
  421.                 pack.openIndex(monitor);
  422.             } catch (IOException err) {
  423.                 // If the index won't open its either not found or
  424.                 // its a format we don't recognize. In either case
  425.                 // we may still be able to obtain the object from
  426.                 // another source, so don't consider it a failure.
  427.                 //
  428.                 recordError(id, err);
  429.                 packItr.remove();
  430.                 continue;
  431.             }

  432.             if (monitor.isCancelled()) {
  433.                 // If we were cancelled while the index was opening
  434.                 // the open may have aborted. We can't search an
  435.                 // unopen index.
  436.                 //
  437.                 return false;
  438.             }

  439.             if (!pack.index.hasObject(id)) {
  440.                 // Not in this pack? Try another.
  441.                 //
  442.                 continue;
  443.             }

  444.             // It should be in the associated pack. Download that
  445.             // and attach it to the local repository so we can use
  446.             // all of the contained objects.
  447.             //
  448.             Throwable e1 = null;
  449.             try {
  450.                 pack.downloadPack(monitor);
  451.             } catch (IOException err) {
  452.                 // If the pack failed to download, index correctly,
  453.                 // or open in the local repository we may still be
  454.                 // able to obtain this object from another pack or
  455.                 // an alternate.
  456.                 //
  457.                 recordError(id, err);
  458.                 e1 = err;
  459.                 continue;
  460.             } finally {
  461.                 // If the pack was good its in the local repository
  462.                 // and Repository.getObjectDatabase().has(id) will
  463.                 // succeed in the future, so we do not need this
  464.                 // data any more. If it failed the index and pack
  465.                 // are unusable and we shouldn't consult them again.
  466.                 //
  467.                 try {
  468.                     if (pack.tmpIdx != null)
  469.                         FileUtils.delete(pack.tmpIdx);
  470.                 } catch (IOException e) {
  471.                     if (e1 != null) {
  472.                         e.addSuppressed(e1);
  473.                     }
  474.                     throw new TransportException(e.getMessage(), e);
  475.                 }
  476.                 packItr.remove();
  477.             }

  478.             if (!alreadyHave(id)) {
  479.                 // What the hell? This pack claimed to have
  480.                 // the object, but after indexing we didn't
  481.                 // actually find it in the pack.
  482.                 //
  483.                 recordError(id, new FileNotFoundException(MessageFormat.format(
  484.                         JGitText.get().objectNotFoundIn, id.name(), pack.packName)));
  485.                 continue;
  486.             }

  487.             // Complete any other objects that we can.
  488.             //
  489.             final Iterator<ObjectId> pending = swapFetchQueue();
  490.             while (pending.hasNext()) {
  491.                 final ObjectId p = pending.next();
  492.                 if (pack.index.hasObject(p)) {
  493.                     pending.remove();
  494.                     process(p);
  495.                 } else {
  496.                     workQueue.add(p);
  497.                 }
  498.             }
  499.             return true;

  500.         }
  501.         return false;
  502.     }

  503.     private Iterator<ObjectId> swapFetchQueue() {
  504.         final Iterator<ObjectId> r = workQueue.iterator();
  505.         workQueue = new LinkedList<>();
  506.         return r;
  507.     }

  508.     private boolean downloadLooseObject(final AnyObjectId id,
  509.             final String looseName, final WalkRemoteObjectDatabase remote)
  510.             throws TransportException {
  511.         try {
  512.             final byte[] compressed = remote.open(looseName).toArray();
  513.             verifyAndInsertLooseObject(id, compressed);
  514.             return true;
  515.         } catch (FileNotFoundException e) {
  516.             // Not available in a loose format from this alternate?
  517.             // Try another strategy to get the object.
  518.             //
  519.             recordError(id, e);
  520.             return false;
  521.         } catch (IOException e) {
  522.             throw new TransportException(MessageFormat.format(JGitText.get().cannotDownload, id.name()), e);
  523.         }
  524.     }

  525.     private void verifyAndInsertLooseObject(final AnyObjectId id,
  526.             final byte[] compressed) throws IOException {
  527.         final ObjectLoader uol;
  528.         try {
  529.             uol = UnpackedObject.parse(compressed, id);
  530.         } catch (CorruptObjectException parsingError) {
  531.             // Some HTTP servers send back a "200 OK" status with an HTML
  532.             // page that explains the requested file could not be found.
  533.             // These servers are most certainly misconfigured, but many
  534.             // of them exist in the world, and many of those are hosting
  535.             // Git repositories.
  536.             //
  537.             // Since an HTML page is unlikely to hash to one of our loose
  538.             // objects we treat this condition as a FileNotFoundException
  539.             // and attempt to recover by getting the object from another
  540.             // source.
  541.             //
  542.             final FileNotFoundException e;
  543.             e = new FileNotFoundException(id.name());
  544.             e.initCause(parsingError);
  545.             throw e;
  546.         }

  547.         final int type = uol.getType();
  548.         final byte[] raw = uol.getCachedBytes();
  549.         if (objCheck != null) {
  550.             try {
  551.                 objCheck.check(id, type, raw);
  552.             } catch (CorruptObjectException e) {
  553.                 throw new TransportException(MessageFormat.format(
  554.                         JGitText.get().transportExceptionInvalid,
  555.                         Constants.typeString(type), id.name(), e.getMessage()));
  556.             }
  557.         }

  558.         ObjectId act = inserter.insert(type, raw);
  559.         if (!AnyObjectId.isEqual(id, act)) {
  560.             throw new TransportException(MessageFormat.format(
  561.                     JGitText.get().incorrectHashFor, id.name(), act.name(),
  562.                     Constants.typeString(type),
  563.                     Integer.valueOf(compressed.length)));
  564.         }
  565.     }

  566.     private Collection<WalkRemoteObjectDatabase> expandOneAlternate(
  567.             final AnyObjectId id, final ProgressMonitor pm) {
  568.         while (!noAlternatesYet.isEmpty()) {
  569.             final WalkRemoteObjectDatabase wrr = noAlternatesYet.removeFirst();
  570.             try {
  571.                 pm.beginTask(JGitText.get().listingAlternates, ProgressMonitor.UNKNOWN);
  572.                 Collection<WalkRemoteObjectDatabase> altList = wrr
  573.                         .getAlternates();
  574.                 if (altList != null && !altList.isEmpty())
  575.                     return altList;
  576.             } catch (IOException e) {
  577.                 // Try another repository.
  578.                 //
  579.                 recordError(id, e);
  580.             } finally {
  581.                 pm.endTask();
  582.             }
  583.         }
  584.         return null;
  585.     }

  586.     private void markLocalRefsComplete(Set<ObjectId> have) throws TransportException {
  587.         List<Ref> refs;
  588.         try {
  589.             refs = local.getRefDatabase().getRefs();
  590.         } catch (IOException e) {
  591.             throw new TransportException(e.getMessage(), e);
  592.         }
  593.         for (Ref r : refs) {
  594.             try {
  595.                 markLocalObjComplete(revWalk.parseAny(r.getObjectId()));
  596.             } catch (IOException readError) {
  597.                 throw new TransportException(MessageFormat.format(JGitText.get().localRefIsMissingObjects, r.getName()), readError);
  598.             }
  599.         }
  600.         for (ObjectId id : have) {
  601.             try {
  602.                 markLocalObjComplete(revWalk.parseAny(id));
  603.             } catch (IOException readError) {
  604.                 throw new TransportException(MessageFormat.format(JGitText.get().transportExceptionMissingAssumed, id.name()), readError);
  605.             }
  606.         }
  607.     }

  608.     private void markLocalObjComplete(RevObject obj) throws IOException {
  609.         while (obj.getType() == Constants.OBJ_TAG) {
  610.             obj.add(COMPLETE);
  611.             obj = ((RevTag) obj).getObject();
  612.             revWalk.parseHeaders(obj);
  613.         }

  614.         switch (obj.getType()) {
  615.         case Constants.OBJ_BLOB:
  616.             obj.add(COMPLETE);
  617.             break;
  618.         case Constants.OBJ_COMMIT:
  619.             pushLocalCommit((RevCommit) obj);
  620.             break;
  621.         case Constants.OBJ_TREE:
  622.             markTreeComplete((RevTree) obj);
  623.             break;
  624.         }
  625.     }

  626.     private void markLocalCommitsComplete(int until)
  627.             throws TransportException {
  628.         try {
  629.             for (;;) {
  630.                 final RevCommit c = localCommitQueue.peek();
  631.                 if (c == null || c.getCommitTime() < until)
  632.                     return;
  633.                 localCommitQueue.next();

  634.                 markTreeComplete(c.getTree());
  635.                 for (RevCommit p : c.getParents())
  636.                     pushLocalCommit(p);
  637.             }
  638.         } catch (IOException err) {
  639.             throw new TransportException(JGitText.get().localObjectsIncomplete, err);
  640.         }
  641.     }

  642.     private void pushLocalCommit(RevCommit p)
  643.             throws MissingObjectException, IOException {
  644.         if (p.has(LOCALLY_SEEN))
  645.             return;
  646.         revWalk.parseHeaders(p);
  647.         p.add(LOCALLY_SEEN);
  648.         p.add(COMPLETE);
  649.         p.carry(COMPLETE);
  650.         localCommitQueue.add(p);
  651.     }

  652.     private void markTreeComplete(RevTree tree) throws IOException {
  653.         if (tree.has(COMPLETE))
  654.             return;
  655.         tree.add(COMPLETE);
  656.         treeWalk.reset(tree);
  657.         while (treeWalk.next()) {
  658.             final FileMode mode = treeWalk.getFileMode(0);
  659.             final int sType = mode.getObjectType();

  660.             switch (sType) {
  661.             case Constants.OBJ_BLOB:
  662.                 treeWalk.getObjectId(idBuffer, 0);
  663.                 revWalk.lookupAny(idBuffer, sType).add(COMPLETE);
  664.                 continue;

  665.             case Constants.OBJ_TREE: {
  666.                 treeWalk.getObjectId(idBuffer, 0);
  667.                 final RevObject o = revWalk.lookupAny(idBuffer, sType);
  668.                 if (!o.has(COMPLETE)) {
  669.                     o.add(COMPLETE);
  670.                     treeWalk.enterSubtree();
  671.                 }
  672.                 continue;
  673.             }
  674.             default:
  675.                 if (FileMode.GITLINK.equals(mode))
  676.                     continue;
  677.                 treeWalk.getObjectId(idBuffer, 0);
  678.                 throw new CorruptObjectException(MessageFormat.format(JGitText.get().corruptObjectInvalidMode3
  679.                         , mode, idBuffer.name(), treeWalk.getPathString(), tree.name()));
  680.             }
  681.         }
  682.     }

  683.     private void recordError(AnyObjectId id, Throwable what) {
  684.         final ObjectId objId = id.copy();
  685.         List<Throwable> errors = fetchErrors.get(objId);
  686.         if (errors == null) {
  687.             errors = new ArrayList<>(2);
  688.             fetchErrors.put(objId, errors);
  689.         }
  690.         errors.add(what);
  691.     }

  692.     private class RemotePack {
  693.         final WalkRemoteObjectDatabase connection;

  694.         final String packName;

  695.         final String idxName;

  696.         File tmpIdx;

  697.         PackIndex index;

  698.         RemotePack(WalkRemoteObjectDatabase c, String pn) {
  699.             connection = c;
  700.             packName = pn;
  701.             idxName = packName.substring(0, packName.length() - 5) + ".idx"; //$NON-NLS-1$

  702.             String tn = idxName;
  703.             if (tn.startsWith("pack-")) //$NON-NLS-1$
  704.                 tn = tn.substring(5);
  705.             if (tn.endsWith(".idx")) //$NON-NLS-1$
  706.                 tn = tn.substring(0, tn.length() - 4);

  707.             if (local.getObjectDatabase() instanceof ObjectDirectory) {
  708.                 tmpIdx = new File(((ObjectDirectory) local.getObjectDatabase())
  709.                                 .getDirectory(),
  710.                         "walk-" + tn + ".walkidx"); //$NON-NLS-1$ //$NON-NLS-2$
  711.             }
  712.         }

  713.         void openIndex(ProgressMonitor pm) throws IOException {
  714.             if (index != null)
  715.                 return;
  716.             if (tmpIdx == null)
  717.                 tmpIdx = File.createTempFile("jgit-walk-", ".idx"); //$NON-NLS-1$ //$NON-NLS-2$
  718.             else if (tmpIdx.isFile()) {
  719.                 try {
  720.                     index = PackIndex.open(tmpIdx);
  721.                     return;
  722.                 } catch (FileNotFoundException err) {
  723.                     // Fall through and get the file.
  724.                 }
  725.             }

  726.             final WalkRemoteObjectDatabase.FileStream s;
  727.             s = connection.open("pack/" + idxName); //$NON-NLS-1$
  728.             pm.beginTask("Get " + idxName.substring(0, 12) + "..idx", //$NON-NLS-1$ //$NON-NLS-2$
  729.                     s.length < 0 ? ProgressMonitor.UNKNOWN
  730.                             : (int) (s.length / 1024));
  731.             try (FileOutputStream fos = new FileOutputStream(tmpIdx)) {
  732.                 final byte[] buf = new byte[2048];
  733.                 int cnt;
  734.                 while (!pm.isCancelled() && (cnt = s.in.read(buf)) >= 0) {
  735.                     fos.write(buf, 0, cnt);
  736.                     pm.update(cnt / 1024);
  737.                 }
  738.             } catch (IOException err) {
  739.                 FileUtils.delete(tmpIdx);
  740.                 throw err;
  741.             } finally {
  742.                 s.in.close();
  743.             }
  744.             pm.endTask();

  745.             if (pm.isCancelled()) {
  746.                 FileUtils.delete(tmpIdx);
  747.                 return;
  748.             }

  749.             try {
  750.                 index = PackIndex.open(tmpIdx);
  751.             } catch (IOException e) {
  752.                 FileUtils.delete(tmpIdx);
  753.                 throw e;
  754.             }
  755.         }

  756.         void downloadPack(ProgressMonitor monitor) throws IOException {
  757.             String name = "pack/" + packName; //$NON-NLS-1$
  758.             WalkRemoteObjectDatabase.FileStream s = connection.open(name);
  759.             try {
  760.                 PackParser parser = inserter.newPackParser(s.in);
  761.                 parser.setAllowThin(false);
  762.                 parser.setObjectChecker(objCheck);
  763.                 parser.setLockMessage(lockMessage);
  764.                 PackLock lock = parser.parse(monitor);
  765.                 if (lock != null)
  766.                     packLocks.add(lock);
  767.             } finally {
  768.                 s.in.close();
  769.             }
  770.         }
  771.     }
  772. }