Class ReceivePack


  • public class ReceivePack
    extends Object
    Implements the server side of a push connection, receiving objects.
    • Field Detail

      • connectivityChecker

        protected ConnectivityChecker connectivityChecker
        Connectivity checker to use.
        Since:
        5.7
    • 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 Map<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​(Map<String,​Ref> allRefs,
                                      Set<ObjectId> additionalHaves)
                               throws 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 configured getRefFilter(). 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:
        IOException
      • getAdvertisedObjects

        public final 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 or RefFilter.

        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 from refs/heads/.
        Returns:
        true if the client can delete from refs/heads/.
        Since:
        3.6
      • setAllowBranchDeletes

        public void setAllowBranchDeletes​(boolean canDelete)
        Configure whether to permit deletion of branches from the refs/heads/ namespace.
        Parameters:
        canDelete - true to permit deletion of branches from the refs/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 call setAdvertisedRefs(Map,Set), only refs set by this hook and selected by the RefFilter will be shown to the client. Clients may still attempt to create or update a reference not advertised by the configured AdvertiseRefsHook. These attempts should be rejected by a matching PreReceiveHook.

        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 of 3 * maxCommandBytes or 3 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 its SignedPushConfig.getCertNonceSeed() is null, push certificate verification will be disabled.
        Since:
        4.1
      • getPeerUserAgent

        public 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 HTTP User-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 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 for ReceiveCommand.
        Parameters:
        receiveCommandErrorHandler -
        Since:
        5.7
      • sendError

        public void sendError​(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.

        PreReceiveHooks should always try to use ReceiveCommand.setResult(Result, String) with a result status of ReceiveCommand.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.
      • sendMessage

        public void sendMessage​(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 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 calling getPackSize() to avoid causing IllegalStateException 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:
        IllegalStateException - if called before the pack has been received
        Since:
        3.3
      • init

        protected void init​(InputStream input,
                            OutputStream output,
                            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 the service() 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.
      • getReceivedPackStatistics

        @Nullable
        public ReceivedPackStatistics getReceivedPackStatistics()
        Returns the statistics on the received pack if available. This should be called after receivePack() is called.
        Returns:
        ReceivedPackStatistics
        Since:
        4.6
      • filterCommands

        protected 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
      • 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 List<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
                                   List<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. The ReceivePack 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 more
        Set 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​(InputStream input,
                            OutputStream output,
                            OutputStream messages)
                     throws 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:
        IOException
      • receiveWithExceptionPropagation

        public void receiveWithExceptionPropagation​(InputStream input,
                                                    OutputStream output,
                                                    OutputStream messages)
                                             throws 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:
        IOException
        Since:
        5.7