BasePackConnection.java

  1. /*
  2.  * Copyright (C) 2008-2010, Google Inc.
  3.  * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
  4.  * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  5.  * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  6.  * and other copyright owners as documented in the project's IP log.
  7.  *
  8.  * This program and the accompanying materials are made available
  9.  * under the terms of the Eclipse Distribution License v1.0 which
  10.  * accompanies this distribution, is reproduced below, and is
  11.  * available at http://www.eclipse.org/org/documents/edl-v10.php
  12.  *
  13.  * All rights reserved.
  14.  *
  15.  * Redistribution and use in source and binary forms, with or
  16.  * without modification, are permitted provided that the following
  17.  * conditions are met:
  18.  *
  19.  * - Redistributions of source code must retain the above copyright
  20.  *   notice, this list of conditions and the following disclaimer.
  21.  *
  22.  * - Redistributions in binary form must reproduce the above
  23.  *   copyright notice, this list of conditions and the following
  24.  *   disclaimer in the documentation and/or other materials provided
  25.  *   with the distribution.
  26.  *
  27.  * - Neither the name of the Eclipse Foundation, Inc. nor the
  28.  *   names of its contributors may be used to endorse or promote
  29.  *   products derived from this software without specific prior
  30.  *   written permission.
  31.  *
  32.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33.  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34.  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35.  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36.  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41.  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42.  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44.  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45.  */

  46. package org.eclipse.jgit.transport;

  47. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;

  48. import java.io.EOFException;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.OutputStream;
  52. import java.text.MessageFormat;
  53. import java.util.HashSet;
  54. import java.util.LinkedHashMap;
  55. import java.util.Set;

  56. import org.eclipse.jgit.errors.InvalidObjectIdException;
  57. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  58. import org.eclipse.jgit.errors.PackProtocolException;
  59. import org.eclipse.jgit.errors.RemoteRepositoryException;
  60. import org.eclipse.jgit.errors.TransportException;
  61. import org.eclipse.jgit.internal.JGitText;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.ObjectIdRef;
  64. import org.eclipse.jgit.lib.Ref;
  65. import org.eclipse.jgit.lib.Repository;
  66. import org.eclipse.jgit.util.io.InterruptTimer;
  67. import org.eclipse.jgit.util.io.TimeoutInputStream;
  68. import org.eclipse.jgit.util.io.TimeoutOutputStream;

  69. /**
  70.  * Base helper class for pack-based operations implementations. Provides partial
  71.  * implementation of pack-protocol - refs advertising and capabilities support,
  72.  * and some other helper methods.
  73.  *
  74.  * @see BasePackFetchConnection
  75.  * @see BasePackPushConnection
  76.  */
  77. abstract class BasePackConnection extends BaseConnection {

  78.     /** The repository this transport fetches into, or pushes out of. */
  79.     protected final Repository local;

  80.     /** Remote repository location. */
  81.     protected final URIish uri;

  82.     /** A transport connected to {@link #uri}. */
  83.     protected final Transport transport;

  84.     /** Low-level input stream, if a timeout was configured. */
  85.     protected TimeoutInputStream timeoutIn;

  86.     /** Low-level output stream, if a timeout was configured. */
  87.     protected TimeoutOutputStream timeoutOut;

  88.     /** Timer to manage {@link #timeoutIn} and {@link #timeoutOut}. */
  89.     private InterruptTimer myTimer;

  90.     /** Input stream reading from the remote. */
  91.     protected InputStream in;

  92.     /** Output stream sending to the remote. */
  93.     protected OutputStream out;

  94.     /** Packet line decoder around {@link #in}. */
  95.     protected PacketLineIn pckIn;

  96.     /** Packet line encoder around {@link #out}. */
  97.     protected PacketLineOut pckOut;

  98.     /** Send {@link PacketLineOut#end()} before closing {@link #out}? */
  99.     protected boolean outNeedsEnd;

  100.     /** True if this is a stateless RPC connection. */
  101.     protected boolean statelessRPC;

  102.     /** Capability tokens advertised by the remote side. */
  103.     private final Set<String> remoteCapablities = new HashSet<>();

  104.     /** Extra objects the remote has, but which aren't offered as refs. */
  105.     protected final Set<ObjectId> additionalHaves = new HashSet<>();

  106.     BasePackConnection(PackTransport packTransport) {
  107.         transport = (Transport) packTransport;
  108.         local = transport.local;
  109.         uri = transport.uri;
  110.     }

  111.     /**
  112.      * Configure this connection with the directional pipes.
  113.      *
  114.      * @param myIn
  115.      *            input stream to receive data from the peer. Caller must ensure
  116.      *            the input is buffered, otherwise read performance may suffer.
  117.      * @param myOut
  118.      *            output stream to transmit data to the peer. Caller must ensure
  119.      *            the output is buffered, otherwise write performance may
  120.      *            suffer.
  121.      */
  122.     protected final void init(InputStream myIn, OutputStream myOut) {
  123.         final int timeout = transport.getTimeout();
  124.         if (timeout > 0) {
  125.             final Thread caller = Thread.currentThread();
  126.             if (myTimer == null) {
  127.                 myTimer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  128.             }
  129.             timeoutIn = new TimeoutInputStream(myIn, myTimer);
  130.             timeoutOut = new TimeoutOutputStream(myOut, myTimer);
  131.             timeoutIn.setTimeout(timeout * 1000);
  132.             timeoutOut.setTimeout(timeout * 1000);
  133.             myIn = timeoutIn;
  134.             myOut = timeoutOut;
  135.         }

  136.         in = myIn;
  137.         out = myOut;

  138.         pckIn = new PacketLineIn(in);
  139.         pckOut = new PacketLineOut(out);
  140.         outNeedsEnd = true;
  141.     }

  142.     /**
  143.      * Reads the advertised references through the initialized stream.
  144.      * <p>
  145.      * Subclass implementations may call this method only after setting up the
  146.      * input and output streams with {@link #init(InputStream, OutputStream)}.
  147.      * <p>
  148.      * If any errors occur, this connection is automatically closed by invoking
  149.      * {@link #close()} and the exception is wrapped (if necessary) and thrown
  150.      * as a {@link org.eclipse.jgit.errors.TransportException}.
  151.      *
  152.      * @throws org.eclipse.jgit.errors.TransportException
  153.      *             the reference list could not be scanned.
  154.      */
  155.     protected void readAdvertisedRefs() throws TransportException {
  156.         try {
  157.             readAdvertisedRefsImpl();
  158.         } catch (TransportException err) {
  159.             close();
  160.             throw err;
  161.         } catch (IOException err) {
  162.             close();
  163.             throw new TransportException(err.getMessage(), err);
  164.         } catch (RuntimeException err) {
  165.             close();
  166.             throw new TransportException(err.getMessage(), err);
  167.         }
  168.     }

  169.     private void readAdvertisedRefsImpl() throws IOException {
  170.         final LinkedHashMap<String, Ref> avail = new LinkedHashMap<>();
  171.         for (;;) {
  172.             String line;

  173.             try {
  174.                 line = pckIn.readString();
  175.             } catch (EOFException eof) {
  176.                 if (avail.isEmpty())
  177.                     throw noRepository();
  178.                 throw eof;
  179.             }
  180.             if (line == PacketLineIn.END)
  181.                 break;

  182.             if (line.startsWith("ERR ")) { //$NON-NLS-1$
  183.                 // This is a customized remote service error.
  184.                 // Users should be informed about it.
  185.                 throw new RemoteRepositoryException(uri, line.substring(4));
  186.             }

  187.             if (avail.isEmpty()) {
  188.                 final int nul = line.indexOf('\0');
  189.                 if (nul >= 0) {
  190.                     // The first line (if any) may contain "hidden"
  191.                     // capability values after a NUL byte.
  192.                     for (String c : line.substring(nul + 1).split(" ")) //$NON-NLS-1$
  193.                         remoteCapablities.add(c);
  194.                     line = line.substring(0, nul);
  195.                 }
  196.             }

  197.             // Expecting to get a line in the form "sha1 refname"
  198.             if (line.length() < 41 || line.charAt(40) != ' ') {
  199.                 throw invalidRefAdvertisementLine(line);
  200.             }
  201.             String name = line.substring(41, line.length());
  202.             if (avail.isEmpty() && name.equals("capabilities^{}")) { //$NON-NLS-1$
  203.                 // special line from git-receive-pack to show
  204.                 // capabilities when there are no refs to advertise
  205.                 continue;
  206.             }

  207.             final ObjectId id;
  208.             try {
  209.                 id  = ObjectId.fromString(line.substring(0, 40));
  210.             } catch (InvalidObjectIdException e) {
  211.                 throw invalidRefAdvertisementLine(line);
  212.             }
  213.             if (name.equals(".have")) { //$NON-NLS-1$
  214.                 additionalHaves.add(id);
  215.             } else if (name.endsWith("^{}")) { //$NON-NLS-1$
  216.                 name = name.substring(0, name.length() - 3);
  217.                 final Ref prior = avail.get(name);
  218.                 if (prior == null)
  219.                     throw new PackProtocolException(uri, MessageFormat.format(
  220.                             JGitText.get().advertisementCameBefore, name, name));

  221.                 if (prior.getPeeledObjectId() != null)
  222.                     throw duplicateAdvertisement(name + "^{}"); //$NON-NLS-1$

  223.                 avail.put(name, new ObjectIdRef.PeeledTag(
  224.                         Ref.Storage.NETWORK, name, prior.getObjectId(), id));
  225.             } else {
  226.                 final Ref prior = avail.put(name, new ObjectIdRef.PeeledNonTag(
  227.                         Ref.Storage.NETWORK, name, id));
  228.                 if (prior != null)
  229.                     throw duplicateAdvertisement(name);
  230.             }
  231.         }
  232.         available(avail);
  233.     }

  234.     /**
  235.      * Create an exception to indicate problems finding a remote repository. The
  236.      * caller is expected to throw the returned exception.
  237.      *
  238.      * Subclasses may override this method to provide better diagnostics.
  239.      *
  240.      * @return a TransportException saying a repository cannot be found and
  241.      *         possibly why.
  242.      */
  243.     protected TransportException noRepository() {
  244.         return new NoRemoteRepositoryException(uri, JGitText.get().notFound);
  245.     }

  246.     /**
  247.      * Whether this option is supported
  248.      *
  249.      * @param option
  250.      *            option string
  251.      * @return whether this option is supported
  252.      */
  253.     protected boolean isCapableOf(String option) {
  254.         return remoteCapablities.contains(option);
  255.     }

  256.     /**
  257.      * Request capability
  258.      *
  259.      * @param b
  260.      *            buffer
  261.      * @param option
  262.      *            option we want
  263.      * @return {@code true} if the requested option is supported
  264.      */
  265.     protected boolean wantCapability(StringBuilder b, String option) {
  266.         if (!isCapableOf(option))
  267.             return false;
  268.         b.append(' ');
  269.         b.append(option);
  270.         return true;
  271.     }

  272.     /**
  273.      * Add user agent capability
  274.      *
  275.      * @param b
  276.      *            a {@link java.lang.StringBuilder} object.
  277.      */
  278.     protected void addUserAgentCapability(StringBuilder b) {
  279.         String a = UserAgent.get();
  280.         if (a != null && UserAgent.hasAgent(remoteCapablities)) {
  281.             b.append(' ').append(OPTION_AGENT).append('=').append(a);
  282.         }
  283.     }

  284.     /** {@inheritDoc} */
  285.     @Override
  286.     public String getPeerUserAgent() {
  287.         return UserAgent.getAgent(remoteCapablities, super.getPeerUserAgent());
  288.     }

  289.     private PackProtocolException duplicateAdvertisement(String name) {
  290.         return new PackProtocolException(uri, MessageFormat.format(JGitText.get().duplicateAdvertisementsOf, name));
  291.     }

  292.     private PackProtocolException invalidRefAdvertisementLine(String line) {
  293.         return new PackProtocolException(uri, MessageFormat.format(JGitText.get().invalidRefAdvertisementLine, line));
  294.     }

  295.     /** {@inheritDoc} */
  296.     @Override
  297.     public void close() {
  298.         if (out != null) {
  299.             try {
  300.                 if (outNeedsEnd) {
  301.                     outNeedsEnd = false;
  302.                     pckOut.end();
  303.                 }
  304.                 out.close();
  305.             } catch (IOException err) {
  306.                 // Ignore any close errors.
  307.             } finally {
  308.                 out = null;
  309.                 pckOut = null;
  310.             }
  311.         }

  312.         if (in != null) {
  313.             try {
  314.                 in.close();
  315.             } catch (IOException err) {
  316.                 // Ignore any close errors.
  317.             } finally {
  318.                 in = null;
  319.                 pckIn = null;
  320.             }
  321.         }

  322.         if (myTimer != null) {
  323.             try {
  324.                 myTimer.terminate();
  325.             } finally {
  326.                 myTimer = null;
  327.                 timeoutIn = null;
  328.                 timeoutOut = null;
  329.             }
  330.         }
  331.     }

  332.     /**
  333.      * Tell the peer we are disconnecting, if it cares to know.
  334.      */
  335.     protected void endOut() {
  336.         if (outNeedsEnd && out != null) {
  337.             try {
  338.                 outNeedsEnd = false;
  339.                 pckOut.end();
  340.             } catch (IOException e) {
  341.                 try {
  342.                     out.close();
  343.                 } catch (IOException err) {
  344.                     // Ignore any close errors.
  345.                 } finally {
  346.                     out = null;
  347.                     pckOut = null;
  348.                 }
  349.             }
  350.         }
  351.     }
  352. }