Class ReceivePack
- java.lang.Object
-
- org.eclipse.jgit.transport.ReceivePack
-
public class ReceivePack extends java.lang.Object
Implements the server side of a push connection, receiving objects.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private class
ReceivePack.DefaultUnpackErrorHandler
static class
ReceivePack.FirstLine
Deprecated.UseFirstCommand
instead.(package private) class
ReceivePack.MessageOutputWrapper
Output stream that wraps the currentmsgOut
.private class
ReceivePack.PostReceiveExecutor
private static class
ReceivePack.ReceiveConfig
Configuration for receive operations.(package private) static class
ReceivePack.Reporter
Interface for reporting status messages.
-
Field Summary
Fields Modifier and Type Field Description private java.util.Set<ObjectId>
advertisedHaves
All SHA-1s shown to the client, which can be possible edges.private java.lang.StringBuilder
advertiseError
private AdvertiseRefsHook
advertiseRefsHook
Hook used while advertising the refs to the client.private boolean
allowAnyDeletes
Should an incoming transfer permit delete requests?private boolean
allowBranchDeletes
private boolean
allowCreates
Should an incoming transfer permit create requests?private boolean
allowNonFastForwards
Should an incoming transfer permit non-fast-forward requests?private boolean
allowOfsDelta
private boolean
allowPushOptions
Should an incoming transfer permit push options?private boolean
allowQuiet
private boolean
atomic
Should the requested ref updates be performed as a single atomic transaction?private boolean
biDirectionalPipe
Is the client connection a bi-directional socket or pipe?private boolean
checkReferencedAreReachable
private java.util.Set<ObjectId>
clientShallowCommits
private java.util.List<ReceiveCommand>
commands
protected ConnectivityChecker
connectivityChecker
Connectivity checker to use.private Repository
db
Database we write the stored objects into.private java.util.Set<java.lang.String>
enabledCapabilities
Capabilities requested by the client.private SideBandOutputStream
errOut
private boolean
expectDataAfterPackFooter
Expecting data after the pack footerprivate long
maxCommandBytes
private long
maxDiscardBytes
private long
maxObjectSizeLimit
Git object size limitprivate long
maxPackSizeLimit
Total pack size limitprivate java.io.OutputStream
msgOut
Optional message output stream.private ReceivePack.MessageOutputWrapper
msgOutWrapper
private ObjectChecker
objectChecker
Should an incoming transfer validate objects?private java.io.OutputStream
origOut
private PackLock
packLock
Lock around the received pack file, while updating refs.private java.lang.Long
packSize
The size of the received pack, including index sizeprivate PackParser
parser
private PacketLineIn
pckIn
Packet line input stream aroundrawIn
.private PacketLineOut
pckOut
Packet line output stream aroundrawOut
.private PostReceiveHook
postReceive
Hook to report on the commands after execution.private PreReceiveHook
preReceive
Hook to validate the update commands before execution.private PushCertificate
pushCert
private PushCertificateParser
pushCertificateParser
private java.util.List<java.lang.String>
pushOptions
private boolean
quiet
private java.io.InputStream
rawIn
Raw input stream.private java.io.OutputStream
rawOut
Raw output stream.private ReceiveCommandErrorHandler
receiveCommandErrorHandler
private RefFilter
refFilter
Filter used while advertising the refs to the client.private PersonIdent
refLogIdent
Identity to record action as within the reflog.private java.util.Map<java.lang.String,Ref>
refs
The refs we advertised as existing at the start of the connection.private boolean
reportStatus
IfBasePackPushConnection.CAPABILITY_REPORT_STATUS
is enabled.private boolean
sideBand
IfBasePackPushConnection.CAPABILITY_SIDE_BAND_64K
is enabled.private SignedPushConfig
signedPushConfig
private ReceivedPackStatistics
stats
private int
timeout
Timeout in seconds to wait for client interaction.private TimeoutInputStream
timeoutIn
private InterruptTimer
timer
Timer to managetimeout
.private UnpackErrorHandler
unpackErrorHandler
private boolean
usePushOptions
Whether the client intends to use push options.(package private) java.lang.String
userAgent
private RevWalk
walk
Revision traversal support overdb
.
-
Constructor Summary
Constructors Constructor Description ReceivePack(Repository into)
Create a new pack receive for an open repository.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description private boolean
anyRejects()
Whether any commands have been rejected so far.private void
autoGc()
private void
checkConnectivity()
private void
checkRequestWasRead()
private void
checkSubmodules()
private void
close()
Close and flush (if necessary) the underlying streams.private ConnectivityChecker.ConnectivityCheckInfo
createConnectivityCheckInfo()
private void
discardCommands()
private void
enableCapabilities()
Enable capabilities based on a previously read capabilities line.protected void
executeCommands()
Execute commands to update references.private void
failPendingCommands()
Set the result to fail for any command that was not processed yet.private void
fatalError(java.lang.String msg)
protected java.util.List<ReceiveCommand>
filterCommands(ReceiveCommand.Result want)
Filter the list of commands according to result.java.util.Set<ObjectId>
getAdvertisedObjects()
Get objects advertised to the client.private java.util.Map<java.lang.String,Ref>
getAdvertisedOrDefaultRefs()
Get advertised refs, or the default if not explicitly advertised.java.util.Map<java.lang.String,Ref>
getAdvertisedRefs()
Get refs which were advertised to the client.AdvertiseRefsHook
getAdvertiseRefsHook()
Get the hook used while advertising the refs to the clientjava.util.List<ReceiveCommand>
getAllCommands()
Get all of the command received by the current request.private java.util.Map<java.lang.String,Ref>
getAllRefs()
Extract the full list of refs from the ref-db.private java.util.Set<ObjectId>
getClientShallowCommits()
Get the commits from the client's shallow file.java.io.OutputStream
getMessageOutputStream()
Get an underlying stream for sending messages to the client.long
getPackSize()
Get the size of the received pack file including the index size.java.lang.String
getPeerUserAgent()
Get the user agent of the client.PostReceiveHook
getPostReceiveHook()
Get the hook invoked after updates occur.PreReceiveHook
getPreReceiveHook()
Get the hook invoked before updates occur.PushCertificate
getPushCertificate()
Get the push certificate used to verify the pusher's identity.private PushCertificateParser
getPushCertificateParser()
java.util.List<java.lang.String>
getPushOptions()
Gets an unmodifiable view of the option strings associated with the push.ReceivedPackStatistics
getReceivedPackStatistics()
Returns the statistics on the received pack if available.RefFilter
getRefFilter()
Get the filter used while advertising the refs to the clientPersonIdent
getRefLogIdent()
Get identity of the user making the changes in the reflog.Repository
getRepository()
Get the repository this receive completes into.RevWalk
getRevWalk()
Get the RevWalk instance used by this connection.int
getTimeout()
Get timeout (in seconds) before aborting an IO operation.UnpackErrorHandler
getUnpackErrorHandler()
Get the current unpack error handler.private boolean
hasCommands()
Whether any commands to be executed have been read.private boolean
hasError()
Whether an error occurred that should be advertised.boolean
hasReceivedPack()
Get whether or not a pack has been received.protected void
init(java.io.InputStream input, java.io.OutputStream output, java.io.OutputStream messages)
Initialize the instance with the given streams.boolean
isAllowBranchDeletes()
Whether the client can delete fromrefs/heads/
.boolean
isAllowCreates()
Whether the client can request refs to be created.boolean
isAllowDeletes()
Whether the client can request refs to be deleted.boolean
isAllowNonFastForwards()
Whether the client can request non-fast-forward updates of a ref, possibly making objects unreachable.boolean
isAllowPushOptions()
Whether the server supports receiving push options.boolean
isAllowQuiet()
Whether clients may request avoiding noisy progress messages.boolean
isAtomic()
Whether the client's commands should be performed as a single atomic transaction.boolean
isBiDirectionalPipe()
Whether this class expects a bi-directional pipe opened between the client and itself.private boolean
isCapabilityEnabled(java.lang.String name)
Check if the peer requested a capability.boolean
isCheckReceivedObjects()
Whether this instance will verify received objects are formatted correctly.boolean
isCheckReferencedObjectsAreReachable()
Whether this instance will validate all referenced, but not supplied by the client, objects are reachable from another reference.boolean
isExpectDataAfterPackFooter()
Whether there is data expected after the pack footer.boolean
isQuiet()
True if the client wants less verbose output.boolean
isSideBand()
Check whether the client expects a side-band stream.private boolean
needCheckConnectivity()
private boolean
needPack()
Whether a pack is expected based on the list of commands.private java.io.InputStream
packInputStream()
(package private) static ReceiveCommand
parseCommand(java.lang.String line)
private void
parseShallow(java.lang.String idStr)
(package private) void
readPostCommands(PacketLineIn in)
void
receive(java.io.InputStream input, java.io.OutputStream output, java.io.OutputStream messages)
Execute the receive task on the socket.private void
receivePack()
Receive a pack from the input and store it in the repository.protected void
receivePackAndCheckConnectivity()
Receive a pack from the stream and check connectivity if necessary.void
receiveWithExceptionPropagation(java.io.InputStream input, java.io.OutputStream output, java.io.OutputStream messages)
Execute the receive task on the socket.private void
recvCommands()
Receive a list of commands from the input.private void
release()
Release any resources used by this object.void
sendAdvertisedRefs(RefAdvertiser adv)
Generate an advertisement of available refs and capabilities.void
sendError(java.lang.String what)
Send an error message to the client.void
sendMessage(java.lang.String what)
Send a message to the client, if it supports receiving them.private void
sendStatusReport(java.lang.Throwable unpackError)
Send a status report.private void
service()
void
setAdvertisedRefs(java.util.Map<java.lang.String,Ref> allRefs, java.util.Set<ObjectId> additionalHaves)
Set the refs advertised by this ReceivePack.void
setAdvertiseRefsHook(AdvertiseRefsHook advertiseRefsHook)
Set the hook used while advertising the refs to the client.void
setAllowBranchDeletes(boolean canDelete)
Configure whether to permit deletion of branches from therefs/heads/
namespace.void
setAllowCreates(boolean canCreate)
Whether to permit create ref commands to be processed.void
setAllowDeletes(boolean canDelete)
Whether to permit delete ref commands to be processed.void
setAllowNonFastForwards(boolean canRewind)
Configure whether to permit the client to ask for non-fast-forward updates of an existing ref.void
setAllowPushOptions(boolean allow)
Configure if the server supports receiving push options.void
setAllowQuiet(boolean allow)
Configure if clients may request the server skip noisy messages.void
setAtomic(boolean atomic)
Configure whether to perform the client's commands as a single atomic transaction.void
setBiDirectionalPipe(boolean twoWay)
Whether 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.void
setCheckReceivedObjects(boolean check)
Whether to enable checking received objectsvoid
setCheckReferencedObjectsAreReachable(boolean b)
Validate all referenced but not supplied objects are reachable.void
setEchoCommandFailures(boolean echo)
Deprecated.no widely used Git versions need this any morevoid
setExpectDataAfterPackFooter(boolean e)
Whether there is additional data in InputStream after pack.void
setMaxCommandBytes(long limit)
Set the maximum number of command bytes to read from the client.void
setMaxCommandDiscardBytes(long limit)
Set the maximum number of command bytes to discard from the client.void
setMaxObjectSizeLimit(long limit)
Set the maximum allowed Git object size.void
setMaxPackSizeLimit(long limit)
Set the maximum allowed pack size.void
setObjectChecker(ObjectChecker impl)
Set the object checking instance to verify each received object withvoid
setPostReceiveHook(PostReceiveHook h)
Set the hook which is invoked after commands are executed.void
setPreReceiveHook(PreReceiveHook h)
Set the hook which is invoked prior to commands being executed.void
setPushCertificate(PushCertificate cert)
Set the push certificate used to verify the pusher's identity.void
setPushOptions(java.util.List<java.lang.String> options)
Set the push options supplied by the client.void
setReceiveCommandErrorHandler(ReceiveCommandErrorHandler receiveCommandErrorHandler)
Set an error handler forReceiveCommand
.void
setRefFilter(RefFilter refFilter)
Set the filter used while advertising the refs to the client.void
setRefLogIdent(PersonIdent pi)
Set the identity of the user appearing in the affected reflogs.void
setSignedPushConfig(SignedPushConfig cfg)
Set the configuration for push certificate verification.void
setTimeout(int seconds)
Set the timeout before willing to abort an IO call.void
setUnpackErrorHandler(UnpackErrorHandler unpackErrorHandler)
private void
unlockPack()
Unlock the pack written by this object.private void
validateCommands()
Validate the command list.
-
-
-
Field Detail
-
db
private final Repository db
Database we write the stored objects into.
-
biDirectionalPipe
private boolean biDirectionalPipe
Is the client connection a bi-directional socket or pipe?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.
-
expectDataAfterPackFooter
private boolean expectDataAfterPackFooter
Expecting data after the pack footer
-
objectChecker
private ObjectChecker objectChecker
Should an incoming transfer validate objects?
-
allowCreates
private boolean allowCreates
Should an incoming transfer permit create requests?
-
allowAnyDeletes
private boolean allowAnyDeletes
Should an incoming transfer permit delete requests?
-
allowBranchDeletes
private boolean allowBranchDeletes
-
allowNonFastForwards
private boolean allowNonFastForwards
Should an incoming transfer permit non-fast-forward requests?
-
allowPushOptions
private boolean allowPushOptions
Should an incoming transfer permit push options?
-
atomic
private boolean atomic
Should the requested ref updates be performed as a single atomic transaction?
-
allowOfsDelta
private boolean allowOfsDelta
-
allowQuiet
private boolean allowQuiet
-
refLogIdent
private PersonIdent refLogIdent
Identity to record action as within the reflog.
-
advertiseRefsHook
private AdvertiseRefsHook advertiseRefsHook
Hook used while advertising the refs to the client.
-
refFilter
private RefFilter refFilter
Filter used while advertising the refs to the client.
-
timeout
private int timeout
Timeout in seconds to wait for client interaction.
-
timer
private InterruptTimer timer
Timer to managetimeout
.
-
timeoutIn
private TimeoutInputStream timeoutIn
-
origOut
private java.io.OutputStream origOut
-
rawIn
private java.io.InputStream rawIn
Raw input stream.
-
rawOut
private java.io.OutputStream rawOut
Raw output stream.
-
msgOut
private java.io.OutputStream msgOut
Optional message output stream.
-
errOut
private SideBandOutputStream errOut
-
pckIn
private PacketLineIn pckIn
Packet line input stream aroundrawIn
.
-
pckOut
private PacketLineOut pckOut
Packet line output stream aroundrawOut
.
-
msgOutWrapper
private final ReceivePack.MessageOutputWrapper msgOutWrapper
-
parser
private PackParser parser
-
refs
private java.util.Map<java.lang.String,Ref> refs
The refs we advertised as existing at the start of the connection.
-
advertisedHaves
private java.util.Set<ObjectId> advertisedHaves
All SHA-1s shown to the client, which can be possible edges.
-
enabledCapabilities
private java.util.Set<java.lang.String> enabledCapabilities
Capabilities requested by the client.
-
userAgent
java.lang.String userAgent
-
clientShallowCommits
private java.util.Set<ObjectId> clientShallowCommits
-
commands
private java.util.List<ReceiveCommand> commands
-
maxCommandBytes
private long maxCommandBytes
-
maxDiscardBytes
private long maxDiscardBytes
-
advertiseError
private java.lang.StringBuilder advertiseError
-
sideBand
private boolean sideBand
IfBasePackPushConnection.CAPABILITY_SIDE_BAND_64K
is enabled.
-
quiet
private boolean quiet
-
packLock
private PackLock packLock
Lock around the received pack file, while updating refs.
-
checkReferencedAreReachable
private boolean checkReferencedAreReachable
-
maxObjectSizeLimit
private long maxObjectSizeLimit
Git object size limit
-
maxPackSizeLimit
private long maxPackSizeLimit
Total pack size limit
-
packSize
private java.lang.Long packSize
The size of the received pack, including index size
-
pushCertificateParser
private PushCertificateParser pushCertificateParser
-
signedPushConfig
private SignedPushConfig signedPushConfig
-
pushCert
private PushCertificate pushCert
-
stats
private ReceivedPackStatistics stats
-
connectivityChecker
protected ConnectivityChecker connectivityChecker
Connectivity checker to use.- Since:
- 5.7
-
preReceive
private PreReceiveHook preReceive
Hook to validate the update commands before execution.
-
receiveCommandErrorHandler
private ReceiveCommandErrorHandler receiveCommandErrorHandler
-
unpackErrorHandler
private UnpackErrorHandler unpackErrorHandler
-
postReceive
private PostReceiveHook postReceive
Hook to report on the commands after execution.
-
reportStatus
private boolean reportStatus
IfBasePackPushConnection.CAPABILITY_REPORT_STATUS
is enabled.
-
usePushOptions
private boolean usePushOptions
Whether the client intends to use push options.
-
pushOptions
private java.util.List<java.lang.String> pushOptions
-
-
Constructor Detail
-
ReceivePack
public ReceivePack(Repository into)
Create a new pack receive for an open repository.- Parameters:
into
- the destination repository.
-
-
Method Detail
-
getRepository
public Repository getRepository()
Get the repository this receive completes into.- Returns:
- the repository this receive completes into.
-
getRevWalk
public RevWalk getRevWalk()
Get the RevWalk instance used by this connection.- Returns:
- the RevWalk instance used by this connection.
-
getAdvertisedRefs
public java.util.Map<java.lang.String,Ref> getAdvertisedRefs()
Get refs which were advertised to the client.- Returns:
- all refs which were advertised to the client, or null if
setAdvertisedRefs(Map, Set)
has not been called yet.
-
setAdvertisedRefs
public void setAdvertisedRefs(java.util.Map<java.lang.String,Ref> allRefs, java.util.Set<ObjectId> additionalHaves) throws java.io.IOException
Set the refs advertised by this ReceivePack.Intended to be called from a
PreReceiveHook
.- Parameters:
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 configuredgetRefFilter()
. If null, assumes all refs were advertised.additionalHaves
- explicit set of additional haves to claim as advertised. If null, assumes the default set of additional haves from the repository.- Throws:
java.io.IOException
-
getAdvertisedObjects
public final java.util.Set<ObjectId> getAdvertisedObjects()
Get objects advertised to the client.- Returns:
- the set of objects advertised to the as present in this
repository, or null if
setAdvertisedRefs(Map, Set)
has not been called yet.
-
isCheckReferencedObjectsAreReachable
public boolean isCheckReferencedObjectsAreReachable()
Whether this instance will validate all referenced, but not supplied by the client, objects are reachable from another reference.- Returns:
- true if this instance will validate all referenced, but not supplied by the client, objects are reachable from another reference.
-
setCheckReferencedObjectsAreReachable
public void setCheckReferencedObjectsAreReachable(boolean b)
Validate all referenced but not supplied objects are reachable.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
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
AdvertiseRefsHook
orRefFilter
.Enabling this feature may imply at least some, if not all, of the same functionality performed by
setCheckReceivedObjects(boolean)
. Applications are encouraged to enable both features, if desired.- Parameters:
b
-true
to enable the additional check.
-
isBiDirectionalPipe
public boolean isBiDirectionalPipe()
Whether this class expects a bi-directional pipe opened between the client and itself.- Returns:
- true if this class expects a bi-directional pipe opened between the client and itself. The default is true.
-
setBiDirectionalPipe
public void setBiDirectionalPipe(boolean twoWay)
Whether 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.- Parameters:
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.
-
isExpectDataAfterPackFooter
public boolean isExpectDataAfterPackFooter()
Whether there is data expected after the pack footer.- Returns:
true
if there is data expected after the pack footer.
-
setExpectDataAfterPackFooter
public void setExpectDataAfterPackFooter(boolean e)
Whether there is additional data in InputStream after pack.- Parameters:
e
-true
if there is additional data in InputStream after pack.
-
isCheckReceivedObjects
public boolean isCheckReceivedObjects()
Whether this instance will verify received objects are formatted correctly.- Returns:
true
if this instance will verify received objects are formatted correctly. Validating objects requires more CPU time on this side of the connection.
-
setCheckReceivedObjects
public void setCheckReceivedObjects(boolean check)
Whether to enable checking received objects- Parameters:
check
-true
to enable checking received objects; false to assume all received objects are valid.- See Also:
setObjectChecker(ObjectChecker)
-
setObjectChecker
public void setObjectChecker(ObjectChecker impl)
Set the object checking instance to verify each received object with- Parameters:
impl
- if non-null the object checking instance to verify each received object with; null to disable object checking.- Since:
- 3.4
-
isAllowCreates
public boolean isAllowCreates()
Whether the client can request refs to be created.- Returns:
true
if the client can request refs to be created.
-
setAllowCreates
public void setAllowCreates(boolean canCreate)
Whether to permit create ref commands to be processed.- Parameters:
canCreate
-true
to permit create ref commands to be processed.
-
isAllowDeletes
public boolean isAllowDeletes()
Whether the client can request refs to be deleted.- Returns:
true
if the client can request refs to be deleted.
-
setAllowDeletes
public void setAllowDeletes(boolean canDelete)
Whether to permit delete ref commands to be processed.- Parameters:
canDelete
-true
to permit delete ref commands to be processed.
-
isAllowBranchDeletes
public boolean isAllowBranchDeletes()
Whether the client can delete fromrefs/heads/
.- Returns:
true
if the client can delete fromrefs/heads/
.- Since:
- 3.6
-
setAllowBranchDeletes
public void setAllowBranchDeletes(boolean canDelete)
Configure whether to permit deletion of branches from therefs/heads/
namespace.- Parameters:
canDelete
-true
to permit deletion of branches from therefs/heads/
namespace.- Since:
- 3.6
-
isAllowNonFastForwards
public boolean isAllowNonFastForwards()
Whether the client can request non-fast-forward updates of a ref, possibly making objects unreachable.- Returns:
true
if the client can request non-fast-forward updates of a ref, possibly making objects unreachable.
-
setAllowNonFastForwards
public void setAllowNonFastForwards(boolean canRewind)
Configure whether to permit the client to ask for non-fast-forward updates of an existing ref.- Parameters:
canRewind
-true
to permit the client to ask for non-fast-forward updates of an existing ref.
-
isAtomic
public boolean isAtomic()
Whether the client's commands should be performed as a single atomic transaction.- Returns:
true
if the client's commands should be performed as a single atomic transaction.- Since:
- 4.4
-
setAtomic
public void setAtomic(boolean atomic)
Configure whether to perform the client's commands as a single atomic transaction.- Parameters:
atomic
-true
to perform the client's commands as a single atomic transaction.- Since:
- 4.4
-
getRefLogIdent
public PersonIdent getRefLogIdent()
Get identity of the user making the changes in the reflog.- Returns:
- identity of the user making the changes in the reflog.
-
setRefLogIdent
public void setRefLogIdent(PersonIdent pi)
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.
- Parameters:
pi
- identity of the user. If null the identity will be automatically determined based on the repository configuration.
-
getAdvertiseRefsHook
public AdvertiseRefsHook getAdvertiseRefsHook()
Get the hook used while advertising the refs to the client- Returns:
- the hook used while advertising the refs to the client
-
getRefFilter
public RefFilter getRefFilter()
Get the filter used while advertising the refs to the client- Returns:
- the filter used while advertising the refs to the client
-
setAdvertiseRefsHook
public void setAdvertiseRefsHook(AdvertiseRefsHook advertiseRefsHook)
Set the hook used while advertising the refs to the client.If the
AdvertiseRefsHook
chooses to callsetAdvertisedRefs(Map,Set)
, only refs set by this hook and selected by theRefFilter
will be shown to the client. Clients may still attempt to create or update a reference not advertised by the configuredAdvertiseRefsHook
. These attempts should be rejected by a matchingPreReceiveHook
.- Parameters:
advertiseRefsHook
- the hook; may be null to show all refs.
-
setRefFilter
public void setRefFilter(RefFilter refFilter)
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
AdvertiseRefsHook
(if applicable).- Parameters:
refFilter
- the filter; may be null to show all refs.
-
getTimeout
public int getTimeout()
Get timeout (in seconds) before aborting an IO operation.- Returns:
- timeout (in seconds) before aborting an IO operation.
-
setTimeout
public void setTimeout(int seconds)
Set the timeout before willing to abort an IO call.- Parameters:
seconds
- number of seconds to wait (with no data transfer occurring) before aborting an IO read or write operation with the connected client.
-
setMaxCommandBytes
public void setMaxCommandBytes(long limit)
Set the maximum number of command bytes to read from the client.- Parameters:
limit
- command limit in bytes; if 0 there is no limit.- Since:
- 4.7
-
setMaxCommandDiscardBytes
public void setMaxCommandDiscardBytes(long limit)
Set the maximum number of command bytes to discard from the client.Discarding remaining bytes allows this instance to consume the rest of the command block and send a human readable over-limit error via the side-band channel. If the client sends an excessive number of bytes this limit kicks in and the instance disconnects, resulting in a non-specific 'pipe closed', 'end of stream', or similar generic error at the client.
When the limit is set to
-1
the implementation will default to the larger of3 * maxCommandBytes
or3 MiB
.- Parameters:
limit
- discard limit in bytes; if 0 there is no limit; if -1 the implementation tries to set a reasonable default.- Since:
- 4.7
-
setMaxObjectSizeLimit
public void setMaxObjectSizeLimit(long limit)
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.
- Parameters:
limit
- the Git object size limit. If zero then there is not limit.
-
setMaxPackSizeLimit
public void setMaxPackSizeLimit(long limit)
Set the maximum allowed pack size.A pack exceeding this size will be rejected.
- Parameters:
limit
- the pack size limit, in bytes- Since:
- 3.3
-
isSideBand
public boolean isSideBand() throws RequestNotYetReadException
Check whether the client expects a side-band stream.- Returns:
- 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.
-
isAllowQuiet
public boolean isAllowQuiet()
Whether clients may request avoiding noisy progress messages.- Returns:
- true if clients may request avoiding noisy progress messages.
- Since:
- 4.0
-
setAllowQuiet
public void setAllowQuiet(boolean allow)
Configure if clients may request the server skip noisy messages.- Parameters:
allow
- true to allow clients to request quiet behavior; false to refuse quiet behavior and send messages anyway. This may be necessary if processing is slow and the client-server network connection can timeout.- Since:
- 4.0
-
isAllowPushOptions
public boolean isAllowPushOptions()
Whether the server supports receiving push options.- Returns:
- true if the server supports receiving push options.
- Since:
- 4.5
-
setAllowPushOptions
public void setAllowPushOptions(boolean allow)
Configure if the server supports receiving push options.- Parameters:
allow
- true to optionally accept option strings from the client.- Since:
- 4.5
-
isQuiet
public boolean isQuiet() throws RequestNotYetReadException
True if the client wants less verbose output.- Returns:
- true if the client has requested the server to be less verbose.
- 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.- Since:
- 4.0
-
setSignedPushConfig
public void setSignedPushConfig(SignedPushConfig cfg)
Set the configuration for push certificate verification.- Parameters:
cfg
- new configuration; if this object is null or itsSignedPushConfig.getCertNonceSeed()
is null, push certificate verification will be disabled.- Since:
- 4.1
-
getPushCertificateParser
private PushCertificateParser getPushCertificateParser()
-
getPeerUserAgent
public java.lang.String getPeerUserAgent()
Get the user agent of the client.If the client is new enough to use
agent=
capability that value will be returned. Older HTTP clients may also supply their version using the HTTPUser-Agent
header. The capability overrides the HTTP header if both are available.When an HTTP request has been received this method returns the HTTP
User-Agent
header value until capabilities have been parsed.- Returns:
- user agent supplied by the client. Available only if the client is new enough to advertise its user agent.
- Since:
- 4.0
-
getAllCommands
public java.util.List<ReceiveCommand> getAllCommands()
Get all of the command received by the current request.- Returns:
- all of the command received by the current request.
-
setReceiveCommandErrorHandler
public void setReceiveCommandErrorHandler(ReceiveCommandErrorHandler receiveCommandErrorHandler)
Set an error handler forReceiveCommand
.- Parameters:
receiveCommandErrorHandler
-- Since:
- 5.7
-
sendError
public void sendError(java.lang.String what)
Send an error message to the client.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.
PreReceiveHook
s should always try to useReceiveCommand.setResult(Result, String)
with a result status ofReceiveCommand.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.- Parameters:
what
- string describing the problem identified by the hook. The string must not end with an LF, and must not contain an LF.
-
fatalError
private void fatalError(java.lang.String msg)
-
sendMessage
public void sendMessage(java.lang.String what)
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.
- Parameters:
what
- string describing the problem identified by the hook. The string must not end with an LF, and must not contain an LF.
-
getMessageOutputStream
public java.io.OutputStream getMessageOutputStream()
Get an underlying stream for sending messages to the client.- Returns:
- an underlying stream for sending messages to the client.
-
hasReceivedPack
public boolean hasReceivedPack()
Get whether or not a pack has been received. This can be called before callinggetPackSize()
to avoid causingIllegalStateException
when the pack size was not set because no pack was received.- Returns:
- true if a pack has been received.
- Since:
- 5.6
-
getPackSize
public long getPackSize()
Get the size of the received pack file including the index size. This can only be called if the pack is already received.- Returns:
- the size of the received pack including index size
- Throws:
java.lang.IllegalStateException
- if called before the pack has been received- Since:
- 3.3
-
getClientShallowCommits
private java.util.Set<ObjectId> getClientShallowCommits()
Get the commits from the client's shallow file.- Returns:
- if the client is a shallow repository, the list of edge commits that define the client's shallow boundary. Empty set if the client is earlier than Git 1.9, or is a full clone.
-
hasCommands
private boolean hasCommands()
Whether any commands to be executed have been read.- Returns:
true
if any commands to be executed have been read.
-
hasError
private boolean hasError()
Whether an error occurred that should be advertised.- Returns:
- true if an error occurred that should be advertised.
-
init
protected void init(java.io.InputStream input, java.io.OutputStream output, java.io.OutputStream messages)
Initialize the instance with the given streams. Visible for out-of-tree subclasses (e.g. tests that need to set the streams without going through theservice()
method).- Parameters:
input
- raw input to read client commands and pack data from. Caller must ensure the input is buffered, otherwise read performance may suffer.output
- response back to the Git network client. Caller must ensure the output is buffered, otherwise write performance may suffer.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.
-
getAdvertisedOrDefaultRefs
private java.util.Map<java.lang.String,Ref> getAdvertisedOrDefaultRefs() throws java.io.IOException
Get advertised refs, or the default if not explicitly advertised.- Returns:
- advertised refs, or the default if not explicitly advertised.
- Throws:
java.io.IOException
-
receivePackAndCheckConnectivity
protected void receivePackAndCheckConnectivity() throws java.io.IOException, LargeObjectException, SubmoduleValidator.SubmoduleValidationException
Receive a pack from the stream and check connectivity if necessary. Visible for out-of-tree subclasses. Subclasses overriding this method should invoke this implementation, as it alters the instance state (e.g. it reads the pack from the input and parses it before running the connectivity checks).- Throws:
java.io.IOException
- an error occurred during unpacking or connectivity checking.LargeObjectException
- an large object needs to be opened for the check.SubmoduleValidator.SubmoduleValidationException
- fails to validate the submodule.
-
unlockPack
private void unlockPack() throws java.io.IOException
Unlock the pack written by this object.- Throws:
java.io.IOException
- the pack could not be unlocked.
-
sendAdvertisedRefs
public void sendAdvertisedRefs(RefAdvertiser adv) throws java.io.IOException, ServiceMayNotContinueException
Generate an advertisement of available refs and capabilities.- Parameters:
adv
- the advertisement formatter.- Throws:
java.io.IOException
- the formatter failed to write an advertisement.ServiceMayNotContinueException
- the hook denied advertisement.
-
getReceivedPackStatistics
@Nullable public ReceivedPackStatistics getReceivedPackStatistics()
Returns the statistics on the received pack if available. This should be called afterreceivePack()
is called.- Returns:
- ReceivedPackStatistics
- Since:
- 4.6
-
getAllRefs
private java.util.Map<java.lang.String,Ref> getAllRefs()
Extract the full list of refs from the ref-db.- Returns:
- Map of all refname/ref
-
recvCommands
private void recvCommands() throws java.io.IOException
Receive a list of commands from the input.- Throws:
java.io.IOException
-
discardCommands
private void discardCommands()
-
parseShallow
private void parseShallow(java.lang.String idStr) throws PackProtocolException
- Throws:
PackProtocolException
-
readPostCommands
void readPostCommands(PacketLineIn in) throws java.io.IOException
- Parameters:
in
- request stream.- Throws:
java.io.IOException
- request line cannot be read.
-
enableCapabilities
private void enableCapabilities()
Enable capabilities based on a previously read capabilities line.
-
isCapabilityEnabled
private boolean isCapabilityEnabled(java.lang.String name)
Check if the peer requested a capability.- Parameters:
name
- protocol name identifying the capability.- Returns:
- true if the peer requested the capability to be enabled.
-
checkRequestWasRead
private void checkRequestWasRead()
-
needPack
private boolean needPack()
Whether a pack is expected based on the list of commands.- Returns:
true
if a pack is expected based on the list of commands.
-
receivePack
private void receivePack() throws java.io.IOException
Receive a pack from the input and store it in the repository.- Throws:
java.io.IOException
- an error occurred reading or indexing the pack.
-
packInputStream
private java.io.InputStream packInputStream()
-
needCheckConnectivity
private boolean needCheckConnectivity()
-
checkSubmodules
private void checkSubmodules() throws java.io.IOException, LargeObjectException, SubmoduleValidator.SubmoduleValidationException
- Throws:
java.io.IOException
LargeObjectException
SubmoduleValidator.SubmoduleValidationException
-
checkConnectivity
private void checkConnectivity() throws java.io.IOException
- Throws:
java.io.IOException
-
createConnectivityCheckInfo
private ConnectivityChecker.ConnectivityCheckInfo createConnectivityCheckInfo()
-
validateCommands
private void validateCommands()
Validate the command list.
-
anyRejects
private boolean anyRejects()
Whether any commands have been rejected so far.- Returns:
- if any commands have been rejected so far.
-
failPendingCommands
private void failPendingCommands()
Set the result to fail for any command that was not processed yet.
-
filterCommands
protected java.util.List<ReceiveCommand> filterCommands(ReceiveCommand.Result want)
Filter the list of commands according to result.- Parameters:
want
- desired status to filter by.- Returns:
- a copy of the command list containing only those commands with the desired status.
- Since:
- 5.7
-
executeCommands
protected void executeCommands()
Execute commands to update references.- Since:
- 5.7
-
sendStatusReport
private void sendStatusReport(java.lang.Throwable unpackError) throws java.io.IOException
Send a status report.- Parameters:
unpackError
- an error that occurred during unpacking, ornull
- Throws:
java.io.IOException
- an error occurred writing the status report.- Since:
- 5.6
-
close
private void close() throws java.io.IOException
Close and flush (if necessary) the underlying streams.- Throws:
java.io.IOException
-
release
private void release() throws java.io.IOException
Release any resources used by this object.- Throws:
java.io.IOException
- the pack could not be unlocked.
-
getPushCertificate
public PushCertificate getPushCertificate()
Get the push certificate used to verify the pusher's identity.Only valid after commands are read from the wire.
- Returns:
- the parsed certificate, or null if push certificates are disabled or no cert was presented by the client.
- Since:
- 4.1
-
setPushCertificate
public void setPushCertificate(PushCertificate cert)
Set the push certificate used to verify the pusher's identity.Should only be called if reconstructing an instance without going through the normal
recvCommands()
flow.- Parameters:
cert
- the push certificate to set.- Since:
- 4.1
-
getPushOptions
@Nullable public java.util.List<java.lang.String> getPushOptions()
Gets an unmodifiable view of the option strings associated with the push.- Returns:
- an unmodifiable view of pushOptions, or null (if pushOptions is).
- Since:
- 4.5
-
setPushOptions
public void setPushOptions(@Nullable java.util.List<java.lang.String> options)
Set the push options supplied by the client.Should only be called if reconstructing an instance without going through the normal
recvCommands()
flow.- Parameters:
options
- the list of options supplied by the client. TheReceivePack
instance takes ownership of this list. Callers are encouraged to first create a copy if the list may be modified later.- Since:
- 4.5
-
getPreReceiveHook
public PreReceiveHook getPreReceiveHook()
Get the hook invoked before updates occur.- Returns:
- the hook invoked before updates occur.
-
setPreReceiveHook
public void setPreReceiveHook(PreReceiveHook h)
Set the hook which is invoked prior to commands being executed.Only valid commands (those which have no obvious errors according to the received input and this instance's configuration) are passed into the hook. The hook may mark a command with a result of any value other than
ReceiveCommand.Result.NOT_ATTEMPTED
to block its execution.The hook may be called with an empty command collection if the current set is completely invalid.
- Parameters:
h
- the hook instance; may be null to disable the hook.
-
getPostReceiveHook
public PostReceiveHook getPostReceiveHook()
Get the hook invoked after updates occur.- Returns:
- the hook invoked after updates occur.
-
setPostReceiveHook
public void setPostReceiveHook(PostReceiveHook h)
Set the hook which is invoked after commands are executed.Only successful commands (type is
ReceiveCommand.Result.OK
) are passed into the hook. The hook may be called with an empty command collection if the current set all resulted in an error.- Parameters:
h
- the hook instance; may be null to disable the hook.
-
getUnpackErrorHandler
public UnpackErrorHandler getUnpackErrorHandler()
Get the current unpack error handler.- Returns:
- the current unpack error handler.
- Since:
- 5.8
-
setUnpackErrorHandler
public void setUnpackErrorHandler(UnpackErrorHandler unpackErrorHandler)
- Parameters:
unpackErrorHandler
- the unpackErrorHandler to set- Since:
- 5.7
-
setEchoCommandFailures
@Deprecated public void setEchoCommandFailures(boolean echo)
Deprecated.no widely used Git versions need this any moreSet whether this class will report command failures as warning messages before sending the command results.- Parameters:
echo
- if true this class will report command failures as warning messages before sending the command results. This is usually not necessary, but may help buggy Git clients that discard the errors when all branches fail.
-
receive
public void receive(java.io.InputStream input, java.io.OutputStream output, java.io.OutputStream messages) throws java.io.IOException
Execute the receive task on the socket.- Parameters:
input
- raw input to read client commands and pack data from. Caller must ensure the input is buffered, otherwise read performance may suffer.output
- response back to the Git network client. Caller must ensure the output is buffered, otherwise write performance may suffer.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.- Throws:
java.io.IOException
-
receiveWithExceptionPropagation
public void receiveWithExceptionPropagation(java.io.InputStream input, java.io.OutputStream output, java.io.OutputStream messages) throws java.io.IOException
Execute the receive task on the socket.Same as
receive(java.io.InputStream, java.io.OutputStream, java.io.OutputStream)
, but the exceptions are not reported to the client yet.- Parameters:
input
- raw input to read client commands and pack data from. Caller must ensure the input is buffered, otherwise read performance may suffer.output
- response back to the Git network client. Caller must ensure the output is buffered, otherwise write performance may suffer.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.- Throws:
java.io.IOException
- Since:
- 5.7
-
service
private void service() throws java.io.IOException
- Throws:
java.io.IOException
-
autoGc
private void autoGc()
-
parseCommand
static ReceiveCommand parseCommand(java.lang.String line) throws PackProtocolException
- Throws:
PackProtocolException
-
-