/* * Copyright (C) 2008-2010, Google Inc. * and other copyright owners as documented in the project's IP log. * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Eclipse Foundation, Inc. nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.eclipse.jgit.transport; import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_DELETE_REFS; import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_OFS_DELTA; import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_REPORT_STATUS; import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_SIDE_BAND_64K; import static org.eclipse.jgit.transport.SideBandOutputStream.CH_DATA; import static org.eclipse.jgit.transport.SideBandOutputStream.CH_PROGRESS; import static org.eclipse.jgit.transport.SideBandOutputStream.MAX_BUF; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.errors.PackProtocolException; import org.eclipse.jgit.errors.TooLargePackException; import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.internal.storage.file.PackLock; import org.eclipse.jgit.lib.BatchRefUpdate; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.Config.SectionParser; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.NullProgressMonitor; import org.eclipse.jgit.lib.ObjectChecker; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectIdSubclassMap; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.ProgressMonitor; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.ObjectWalk; import org.eclipse.jgit.revwalk.RevBlob; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevFlag; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.ReceiveCommand.Result; import org.eclipse.jgit.util.io.InterruptTimer; import org.eclipse.jgit.util.io.LimitedInputStream; import org.eclipse.jgit.util.io.TimeoutInputStream; import org.eclipse.jgit.util.io.TimeoutOutputStream; /** * Base implementation of the side of a push connection that receives objects. *
* Contains high-level operations for initializing and closing streams,
* advertising refs, reading commands, and receiving and applying a pack.
* Subclasses compose these operations into full service implementations.
*/
public abstract class BaseReceivePack {
/** Data in the first line of a request, the line itself plus capabilities. */
public static class FirstLine {
private final String line;
private final Set
* If true, this class assumes it can perform multiple read and write cycles
* with the client over the input and output streams. This matches the
* functionality available with a standard TCP/IP connection, or a local
* operating system or in-memory pipe.
*
* If false, this class runs in a read everything then output results mode,
* making it suitable for single round-trip systems RPCs such as HTTP.
*/
private boolean biDirectionalPipe = true;
/** Expecting data after the pack footer */
private boolean expectDataAfterPackFooter;
/** Should an incoming transfer validate objects? */
private ObjectChecker objectChecker;
/** Should an incoming transfer permit create requests? */
private boolean allowCreates;
/** Should an incoming transfer permit delete requests? */
private boolean allowDeletes;
/** Should an incoming transfer permit non-fast-forward requests? */
private boolean allowNonFastForwards;
private boolean allowOfsDelta;
/** Identity to record action as within the reflog. */
private PersonIdent refLogIdent;
/** Hook used while advertising the refs to the client. */
private AdvertiseRefsHook advertiseRefsHook;
/** Filter used while advertising the refs to the client. */
private RefFilter refFilter;
/** Timeout in seconds to wait for client interaction. */
private int timeout;
/** Timer to manage {@link #timeout}. */
private InterruptTimer timer;
private TimeoutInputStream timeoutIn;
// Original stream passed to init(), since rawOut may be wrapped in a
// sideband.
private OutputStream origOut;
/** Raw input stream. */
protected InputStream rawIn;
/** Raw output stream. */
protected OutputStream rawOut;
/** Optional message output stream. */
protected OutputStream msgOut;
/** Packet line input stream around {@link #rawIn}. */
protected PacketLineIn pckIn;
/** Packet line output stream around {@link #rawOut}. */
protected PacketLineOut pckOut;
private final MessageOutputWrapper msgOutWrapper = new MessageOutputWrapper();
private PackParser parser;
/** The refs we advertised as existing at the start of the connection. */
private Map
* We don't want to expose {@link #msgOut} directly because it can change
* several times over the course of a session.
*/
class MessageOutputWrapper extends OutputStream {
@Override
public void write(int ch) {
if (msgOut != null) {
try {
msgOut.write(ch);
} catch (IOException e) {
// Ignore write failures.
}
}
}
@Override
public void write(byte[] b, int off, int len) {
if (msgOut != null) {
try {
msgOut.write(b, off, len);
} catch (IOException e) {
// Ignore write failures.
}
}
}
@Override
public void write(byte[] b) {
write(b, 0, b.length);
}
@Override
public void flush() {
if (msgOut != null) {
try {
msgOut.flush();
} catch (IOException e) {
// Ignore write failures.
}
}
}
}
/** @return the process name used for pack lock messages. */
protected abstract String getLockMessageProcessName();
/** @return the repository this receive completes into. */
public final Repository getRepository() {
return db;
}
/** @return the RevWalk instance used by this connection. */
public final RevWalk getRevWalk() {
return walk;
}
/**
* Get refs which were advertised to the client.
*
* @return all refs which were advertised to the client, or null if
* {@link #setAdvertisedRefs(Map, Set)} has not been called yet.
*/
public final Map
* Intended to be called from a {@link PreReceiveHook}.
*
* @param allRefs
* explicit set of references to claim as advertised by this
* ReceivePack instance. This overrides any references that
* may exist in the source repository. The map is passed
* to the configured {@link #getRefFilter()}. If null, assumes
* all refs were advertised.
* @param additionalHaves
* explicit set of additional haves to claim as advertised. If
* null, assumes the default set of additional haves from the
* repository.
*/
public void setAdvertisedRefs(Map
* If enabled, this instance will verify that references to objects not
* contained within the received pack are already reachable through at least
* one other reference displayed as part of {@link #getAdvertisedRefs()}.
*
* This feature is useful when the application doesn't trust the client to
* not provide a forged SHA-1 reference to an object, in an attempt to
* access parts of the DAG that they aren't allowed to see and which have
* been hidden from them via the configured {@link AdvertiseRefsHook} or
* {@link RefFilter}.
*
* Enabling this feature may imply at least some, if not all, of the same
* functionality performed by {@link #setCheckReceivedObjects(boolean)}.
* Applications are encouraged to enable both features, if desired.
*
* @param b
* {@code true} to enable the additional check.
*/
public void setCheckReferencedObjectsAreReachable(boolean b) {
this.checkReferencedIsReachable = b;
}
/**
* @return true if this class expects a bi-directional pipe opened between
* the client and itself. The default is true.
*/
public boolean isBiDirectionalPipe() {
return biDirectionalPipe;
}
/**
* @param twoWay
* if true, this class will assume the socket is a fully
* bidirectional pipe between the two peers and takes advantage
* of that by first transmitting the known refs, then waiting to
* read commands. If false, this class assumes it must read the
* commands before writing output and does not perform the
* initial advertising.
*/
public void setBiDirectionalPipe(final boolean twoWay) {
biDirectionalPipe = twoWay;
}
/** @return true if there is data expected after the pack footer. */
public boolean isExpectDataAfterPackFooter() {
return expectDataAfterPackFooter;
}
/**
* @param e
* true if there is additional data in InputStream after pack.
*/
public void setExpectDataAfterPackFooter(boolean e) {
expectDataAfterPackFooter = e;
}
/**
* @return true if this instance will verify received objects are formatted
* correctly. Validating objects requires more CPU time on this side
* of the connection.
*/
public boolean isCheckReceivedObjects() {
return objectChecker != null;
}
/**
* @param check
* true to enable checking received objects; false to assume all
* received objects are valid.
* @see #setObjectChecker(ObjectChecker)
*/
public void setCheckReceivedObjects(final boolean check) {
if (check && objectChecker == null)
setObjectChecker(new ObjectChecker());
else if (!check && objectChecker != null)
setObjectChecker(null);
}
/**
* @param impl if non-null the object checking instance to verify each
* received object with; null to disable object checking.
* @since 3.4
*/
public void setObjectChecker(ObjectChecker impl) {
objectChecker = impl;
}
/** @return true if the client can request refs to be created. */
public boolean isAllowCreates() {
return allowCreates;
}
/**
* @param canCreate
* true to permit create ref commands to be processed.
*/
public void setAllowCreates(final boolean canCreate) {
allowCreates = canCreate;
}
/** @return true if the client can request refs to be deleted. */
public boolean isAllowDeletes() {
return allowDeletes;
}
/**
* @param canDelete
* true to permit delete ref commands to be processed.
*/
public void setAllowDeletes(final boolean canDelete) {
allowDeletes = canDelete;
}
/**
* @return true if the client can request non-fast-forward updates of a ref,
* possibly making objects unreachable.
*/
public boolean isAllowNonFastForwards() {
return allowNonFastForwards;
}
/**
* @param canRewind
* true to permit the client to ask for non-fast-forward updates
* of an existing ref.
*/
public void setAllowNonFastForwards(final boolean canRewind) {
allowNonFastForwards = canRewind;
}
/** @return identity of the user making the changes in the reflog. */
public PersonIdent getRefLogIdent() {
return refLogIdent;
}
/**
* Set the identity of the user appearing in the affected reflogs.
*
* The timestamp portion of the identity is ignored. A new identity with the
* current timestamp will be created automatically when the updates occur
* and the log records are written.
*
* @param pi
* identity of the user. If null the identity will be
* automatically determined based on the repository
* configuration.
*/
public void setRefLogIdent(final PersonIdent pi) {
refLogIdent = pi;
}
/** @return the hook used while advertising the refs to the client */
public AdvertiseRefsHook getAdvertiseRefsHook() {
return advertiseRefsHook;
}
/** @return the filter used while advertising the refs to the client */
public RefFilter getRefFilter() {
return refFilter;
}
/**
* Set the hook used while advertising the refs to the client.
*
* If the {@link AdvertiseRefsHook} chooses to call
* {@link #setAdvertisedRefs(Map,Set)}, only refs set by this hook
* and selected by the {@link RefFilter} will be shown to the client.
* Clients may still attempt to create or update a reference not advertised by
* the configured {@link AdvertiseRefsHook}. These attempts should be rejected
* by a matching {@link PreReceiveHook}.
*
* @param advertiseRefsHook
* the hook; may be null to show all refs.
*/
public void setAdvertiseRefsHook(final AdvertiseRefsHook advertiseRefsHook) {
if (advertiseRefsHook != null)
this.advertiseRefsHook = advertiseRefsHook;
else
this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
}
/**
* Set the filter used while advertising the refs to the client.
*
* Only refs allowed by this filter will be shown to the client.
* The filter is run against the refs specified by the
* {@link AdvertiseRefsHook} (if applicable).
*
* @param refFilter
* the filter; may be null to show all refs.
*/
public void setRefFilter(final RefFilter refFilter) {
this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
}
/** @return timeout (in seconds) before aborting an IO operation. */
public int getTimeout() {
return timeout;
}
/**
* Set the timeout before willing to abort an IO call.
*
* @param seconds
* number of seconds to wait (with no data transfer occurring)
* before aborting an IO read or write operation with the
* connected client.
*/
public void setTimeout(final int seconds) {
timeout = seconds;
}
/**
* Set the maximum allowed Git object size.
*
* If an object is larger than the given size the pack-parsing will throw an
* exception aborting the receive-pack operation.
*
* @param limit
* the Git object size limit. If zero then there is not limit.
*/
public void setMaxObjectSizeLimit(final long limit) {
maxObjectSizeLimit = limit;
}
/**
* Set the maximum allowed pack size.
*
* A pack exceeding this size will be rejected.
*
* @param limit
* the pack size limit, in bytes
*
* @since 3.3
*/
public void setMaxPackSizeLimit(final long limit) {
if (limit < 0)
throw new IllegalArgumentException(MessageFormat.format(
JGitText.get().receivePackInvalidLimit, Long.valueOf(limit)));
maxPackSizeLimit = limit;
}
/**
* Check whether the client expects a side-band stream.
*
* @return true if the client has advertised a side-band capability, false
* otherwise.
* @throws RequestNotYetReadException
* if the client's request has not yet been read from the wire, so
* we do not know if they expect side-band. Note that the client
* may have already written the request, it just has not been
* read.
*/
public boolean isSideBand() throws RequestNotYetReadException {
if (enabledCapabilities == null)
throw new RequestNotYetReadException();
return enabledCapabilities.contains(CAPABILITY_SIDE_BAND_64K);
}
/** @return all of the command received by the current request. */
public List
* If any error messages are sent before the references are advertised to
* the client, the errors will be sent instead of the advertisement and the
* receive operation will be aborted. All clients should receive and display
* such early stage errors.
*
* If the reference advertisements have already been sent, messages are sent
* in a side channel. If the client doesn't support receiving messages, the
* message will be discarded, with no other indication to the caller or to
* the client.
*
* {@link PreReceiveHook}s should always try to use
* {@link ReceiveCommand#setResult(Result, String)} with a result status of
* {@link Result#REJECTED_OTHER_REASON} to indicate any reasons for
* rejecting an update. Messages attached to a command are much more likely
* to be returned to the client.
*
* @param what
* string describing the problem identified by the hook. The
* string must not end with an LF, and must not contain an LF.
*/
public void sendError(final String what) {
if (refs == null) {
if (advertiseError == null)
advertiseError = new StringBuilder();
advertiseError.append(what).append('\n');
} else {
msgOutWrapper.write(Constants.encode("error: " + what + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Send a message to the client, if it supports receiving them.
*
* If the client doesn't support receiving messages, the message will be
* discarded, with no other indication to the caller or to the client.
*
* @param what
* string describing the problem identified by the hook. The
* string must not end with an LF, and must not contain an LF.
*/
public void sendMessage(final String what) {
msgOutWrapper.write(Constants.encode(what + "\n")); //$NON-NLS-1$
}
/** @return an underlying stream for sending messages to the client. */
public OutputStream getMessageOutputStream() {
return msgOutWrapper;
}
/**
* Get the size of the received pack file including the index size.
*
* This can only be called if the pack is already received.
*
* @return the size of the received pack including index size
* @throws IllegalStateException
* if called before the pack has been received
* @since 3.3
*/
public long getPackSize() {
if (packSize != null)
return packSize.longValue();
throw new IllegalStateException(JGitText.get().packSizeNotSetYet);
}
/** @return true if any commands to be executed have been read. */
protected boolean hasCommands() {
return !commands.isEmpty();
}
/** @return true if an error occurred that should be advertised. */
protected boolean hasError() {
return advertiseError != null;
}
/**
* Initialize the instance with the given streams.
*
* @param input
* raw input to read client commands and pack data from. Caller
* must ensure the input is buffered, otherwise read performance
* may suffer.
* @param output
* response back to the Git network client. Caller must ensure
* the output is buffered, otherwise write performance may
* suffer.
* @param messages
* secondary "notice" channel to send additional messages out
* through. When run over SSH this should be tied back to the
* standard error channel of the command execution. For most
* other network connections this should be null.
*/
protected void init(final InputStream input, final OutputStream output,
final OutputStream messages) {
origOut = output;
rawIn = input;
rawOut = output;
msgOut = messages;
if (timeout > 0) {
final Thread caller = Thread.currentThread();
timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
timeoutIn = new TimeoutInputStream(rawIn, timer);
TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
timeoutIn.setTimeout(timeout * 1000);
o.setTimeout(timeout * 1000);
rawIn = timeoutIn;
rawOut = o;
}
if (maxPackSizeLimit >= 0)
rawIn = new LimitedInputStream(rawIn, maxPackSizeLimit) {
@Override
protected void limitExceeded() throws TooLargePackException {
throw new TooLargePackException(limit);
}
};
pckIn = new PacketLineIn(rawIn);
pckOut = new PacketLineOut(rawOut);
pckOut.setFlushOnEnd(false);
enabledCapabilities = new HashSet