ReceivePack.java

  1. /*
  2.  * Copyright (C) 2008-2010, Google Inc. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.transport;

  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import static org.eclipse.jgit.lib.Constants.HEAD;
  13. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_ATOMIC;
  14. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_DELETE_REFS;
  15. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_OFS_DELTA;
  16. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_PUSH_OPTIONS;
  17. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_QUIET;
  18. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_REPORT_STATUS;
  19. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_SIDE_BAND_64K;
  20. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  21. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_DATA;
  22. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_ERROR;
  23. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_PROGRESS;
  24. import static org.eclipse.jgit.transport.SideBandOutputStream.MAX_BUF;

  25. import java.io.EOFException;
  26. import java.io.IOException;
  27. import java.io.InputStream;
  28. import java.io.OutputStream;
  29. import java.text.MessageFormat;
  30. import java.util.ArrayList;
  31. import java.util.Collections;
  32. import java.util.HashSet;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.Set;
  36. import java.util.concurrent.TimeUnit;

  37. import org.eclipse.jgit.annotations.Nullable;
  38. import org.eclipse.jgit.errors.InvalidObjectIdException;
  39. import org.eclipse.jgit.errors.LargeObjectException;
  40. import org.eclipse.jgit.errors.PackProtocolException;
  41. import org.eclipse.jgit.errors.TooLargePackException;
  42. import org.eclipse.jgit.errors.UnpackException;
  43. import org.eclipse.jgit.internal.JGitText;
  44. import org.eclipse.jgit.internal.storage.file.PackLock;
  45. import org.eclipse.jgit.internal.submodule.SubmoduleValidator;
  46. import org.eclipse.jgit.internal.submodule.SubmoduleValidator.SubmoduleValidationException;
  47. import org.eclipse.jgit.internal.transport.connectivity.FullConnectivityChecker;
  48. import org.eclipse.jgit.internal.transport.parser.FirstCommand;
  49. import org.eclipse.jgit.lib.AnyObjectId;
  50. import org.eclipse.jgit.lib.BatchRefUpdate;
  51. import org.eclipse.jgit.lib.Config;
  52. import org.eclipse.jgit.lib.ConfigConstants;
  53. import org.eclipse.jgit.lib.Constants;
  54. import org.eclipse.jgit.lib.GitmoduleEntry;
  55. import org.eclipse.jgit.lib.NullProgressMonitor;
  56. import org.eclipse.jgit.lib.ObjectChecker;
  57. import org.eclipse.jgit.lib.ObjectDatabase;
  58. import org.eclipse.jgit.lib.ObjectId;
  59. import org.eclipse.jgit.lib.ObjectInserter;
  60. import org.eclipse.jgit.lib.ObjectLoader;
  61. import org.eclipse.jgit.lib.PersonIdent;
  62. import org.eclipse.jgit.lib.ProgressMonitor;
  63. import org.eclipse.jgit.lib.Ref;
  64. import org.eclipse.jgit.lib.Repository;
  65. import org.eclipse.jgit.revwalk.RevCommit;
  66. import org.eclipse.jgit.revwalk.RevObject;
  67. import org.eclipse.jgit.revwalk.RevWalk;
  68. import org.eclipse.jgit.transport.ConnectivityChecker.ConnectivityCheckInfo;
  69. import org.eclipse.jgit.transport.PacketLineIn.InputOverLimitIOException;
  70. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  71. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  72. import org.eclipse.jgit.util.io.InterruptTimer;
  73. import org.eclipse.jgit.util.io.LimitedInputStream;
  74. import org.eclipse.jgit.util.io.TimeoutInputStream;
  75. import org.eclipse.jgit.util.io.TimeoutOutputStream;

  76. /**
  77.  * Implements the server side of a push connection, receiving objects.
  78.  */
  79. public class ReceivePack {
  80.     /**
  81.      * Data in the first line of a request, the line itself plus capabilities.
  82.      *
  83.      * @deprecated Use {@link FirstCommand} instead.
  84.      * @since 5.6
  85.      */
  86.     @Deprecated
  87.     public static class FirstLine {
  88.         private final FirstCommand command;

  89.         /**
  90.          * Parse the first line of a receive-pack request.
  91.          *
  92.          * @param line
  93.          *            line from the client.
  94.          */
  95.         public FirstLine(String line) {
  96.             command = FirstCommand.fromLine(line);
  97.         }

  98.         /** @return non-capabilities part of the line. */
  99.         public String getLine() {
  100.             return command.getLine();
  101.         }

  102.         /** @return capabilities parsed from the line. */
  103.         public Set<String> getCapabilities() {
  104.             return command.getCapabilities();
  105.         }
  106.     }

  107.     /** Database we write the stored objects into. */
  108.     private final Repository db;

  109.     /** Revision traversal support over {@link #db}. */
  110.     private final RevWalk walk;

  111.     /**
  112.      * Is the client connection a bi-directional socket or pipe?
  113.      * <p>
  114.      * If true, this class assumes it can perform multiple read and write cycles
  115.      * with the client over the input and output streams. This matches the
  116.      * functionality available with a standard TCP/IP connection, or a local
  117.      * operating system or in-memory pipe.
  118.      * <p>
  119.      * If false, this class runs in a read everything then output results mode,
  120.      * making it suitable for single round-trip systems RPCs such as HTTP.
  121.      */
  122.     private boolean biDirectionalPipe = true;

  123.     /** Expecting data after the pack footer */
  124.     private boolean expectDataAfterPackFooter;

  125.     /** Should an incoming transfer validate objects? */
  126.     private ObjectChecker objectChecker;

  127.     /** Should an incoming transfer permit create requests? */
  128.     private boolean allowCreates;

  129.     /** Should an incoming transfer permit delete requests? */
  130.     private boolean allowAnyDeletes;

  131.     private boolean allowBranchDeletes;

  132.     /** Should an incoming transfer permit non-fast-forward requests? */
  133.     private boolean allowNonFastForwards;

  134.     /** Should an incoming transfer permit push options? **/
  135.     private boolean allowPushOptions;

  136.     /**
  137.      * Should the requested ref updates be performed as a single atomic
  138.      * transaction?
  139.      */
  140.     private boolean atomic;

  141.     private boolean allowOfsDelta;

  142.     private boolean allowQuiet = true;

  143.     /** Identity to record action as within the reflog. */
  144.     private PersonIdent refLogIdent;

  145.     /** Hook used while advertising the refs to the client. */
  146.     private AdvertiseRefsHook advertiseRefsHook;

  147.     /** Filter used while advertising the refs to the client. */
  148.     private RefFilter refFilter;

  149.     /** Timeout in seconds to wait for client interaction. */
  150.     private int timeout;

  151.     /** Timer to manage {@link #timeout}. */
  152.     private InterruptTimer timer;

  153.     private TimeoutInputStream timeoutIn;

  154.     // Original stream passed to init(), since rawOut may be wrapped in a
  155.     // sideband.
  156.     private OutputStream origOut;

  157.     /** Raw input stream. */
  158.     private InputStream rawIn;

  159.     /** Raw output stream. */
  160.     private OutputStream rawOut;

  161.     /** Optional message output stream. */
  162.     private OutputStream msgOut;

  163.     private SideBandOutputStream errOut;

  164.     /** Packet line input stream around {@link #rawIn}. */
  165.     private PacketLineIn pckIn;

  166.     /** Packet line output stream around {@link #rawOut}. */
  167.     private PacketLineOut pckOut;

  168.     private final MessageOutputWrapper msgOutWrapper = new MessageOutputWrapper();

  169.     private PackParser parser;

  170.     /** The refs we advertised as existing at the start of the connection. */
  171.     private Map<String, Ref> refs;

  172.     /** All SHA-1s shown to the client, which can be possible edges. */
  173.     private Set<ObjectId> advertisedHaves;

  174.     /** Capabilities requested by the client. */
  175.     private Set<String> enabledCapabilities;

  176.     String userAgent;

  177.     private Set<ObjectId> clientShallowCommits;

  178.     private List<ReceiveCommand> commands;

  179.     private long maxCommandBytes;

  180.     private long maxDiscardBytes;

  181.     private StringBuilder advertiseError;

  182.     /**
  183.      * If {@link BasePackPushConnection#CAPABILITY_SIDE_BAND_64K} is enabled.
  184.      */
  185.     private boolean sideBand;

  186.     private boolean quiet;

  187.     /** Lock around the received pack file, while updating refs. */
  188.     private PackLock packLock;

  189.     private boolean checkReferencedAreReachable;

  190.     /** Git object size limit */
  191.     private long maxObjectSizeLimit;

  192.     /** Total pack size limit */
  193.     private long maxPackSizeLimit = -1;

  194.     /** The size of the received pack, including index size */
  195.     private Long packSize;

  196.     private PushCertificateParser pushCertificateParser;

  197.     private SignedPushConfig signedPushConfig;

  198.     private PushCertificate pushCert;

  199.     private ReceivedPackStatistics stats;

  200.     /**
  201.      * Connectivity checker to use.
  202.      * @since 5.7
  203.      */
  204.     protected ConnectivityChecker connectivityChecker = new FullConnectivityChecker();

  205.     /** Hook to validate the update commands before execution. */
  206.     private PreReceiveHook preReceive;

  207.     private ReceiveCommandErrorHandler receiveCommandErrorHandler = new ReceiveCommandErrorHandler() {
  208.         // Use the default implementation.
  209.     };

  210.     private UnpackErrorHandler unpackErrorHandler = new DefaultUnpackErrorHandler();

  211.     /** Hook to report on the commands after execution. */
  212.     private PostReceiveHook postReceive;

  213.     /** If {@link BasePackPushConnection#CAPABILITY_REPORT_STATUS} is enabled. */
  214.     private boolean reportStatus;

  215.     /** Whether the client intends to use push options. */
  216.     private boolean usePushOptions;
  217.     private List<String> pushOptions;

  218.     /**
  219.      * Create a new pack receive for an open repository.
  220.      *
  221.      * @param into
  222.      *            the destination repository.
  223.      */
  224.     public ReceivePack(Repository into) {
  225.         db = into;
  226.         walk = new RevWalk(db);
  227.         walk.setRetainBody(false);

  228.         TransferConfig tc = db.getConfig().get(TransferConfig.KEY);
  229.         objectChecker = tc.newReceiveObjectChecker();

  230.         ReceiveConfig rc = db.getConfig().get(ReceiveConfig::new);
  231.         allowCreates = rc.allowCreates;
  232.         allowAnyDeletes = true;
  233.         allowBranchDeletes = rc.allowDeletes;
  234.         allowNonFastForwards = rc.allowNonFastForwards;
  235.         allowOfsDelta = rc.allowOfsDelta;
  236.         allowPushOptions = rc.allowPushOptions;
  237.         maxCommandBytes = rc.maxCommandBytes;
  238.         maxDiscardBytes = rc.maxDiscardBytes;
  239.         advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  240.         refFilter = RefFilter.DEFAULT;
  241.         advertisedHaves = new HashSet<>();
  242.         clientShallowCommits = new HashSet<>();
  243.         signedPushConfig = rc.signedPush;
  244.         preReceive = PreReceiveHook.NULL;
  245.         postReceive = PostReceiveHook.NULL;
  246.     }

  247.     /** Configuration for receive operations. */
  248.     private static class ReceiveConfig {
  249.         final boolean allowCreates;

  250.         final boolean allowDeletes;

  251.         final boolean allowNonFastForwards;

  252.         final boolean allowOfsDelta;

  253.         final boolean allowPushOptions;

  254.         final long maxCommandBytes;

  255.         final long maxDiscardBytes;

  256.         final SignedPushConfig signedPush;

  257.         ReceiveConfig(Config config) {
  258.             allowCreates = true;
  259.             allowDeletes = !config.getBoolean("receive", "denydeletes", false); //$NON-NLS-1$ //$NON-NLS-2$
  260.             allowNonFastForwards = !config.getBoolean("receive", //$NON-NLS-1$
  261.                     "denynonfastforwards", false); //$NON-NLS-1$
  262.             allowOfsDelta = config.getBoolean("repack", "usedeltabaseoffset", //$NON-NLS-1$ //$NON-NLS-2$
  263.                     true);
  264.             allowPushOptions = config.getBoolean("receive", "pushoptions", //$NON-NLS-1$ //$NON-NLS-2$
  265.                     false);
  266.             maxCommandBytes = config.getLong("receive", //$NON-NLS-1$
  267.                     "maxCommandBytes", //$NON-NLS-1$
  268.                     3 << 20);
  269.             maxDiscardBytes = config.getLong("receive", //$NON-NLS-1$
  270.                     "maxCommandDiscardBytes", //$NON-NLS-1$
  271.                     -1);
  272.             signedPush = SignedPushConfig.KEY.parse(config);
  273.         }
  274.     }

  275.     /**
  276.      * Output stream that wraps the current {@link #msgOut}.
  277.      * <p>
  278.      * We don't want to expose {@link #msgOut} directly because it can change
  279.      * several times over the course of a session.
  280.      */
  281.     class MessageOutputWrapper extends OutputStream {
  282.         @Override
  283.         public void write(int ch) {
  284.             if (msgOut != null) {
  285.                 try {
  286.                     msgOut.write(ch);
  287.                 } catch (IOException e) {
  288.                     // Ignore write failures.
  289.                 }
  290.             }
  291.         }

  292.         @Override
  293.         public void write(byte[] b, int off, int len) {
  294.             if (msgOut != null) {
  295.                 try {
  296.                     msgOut.write(b, off, len);
  297.                 } catch (IOException e) {
  298.                     // Ignore write failures.
  299.                 }
  300.             }
  301.         }

  302.         @Override
  303.         public void write(byte[] b) {
  304.             write(b, 0, b.length);
  305.         }

  306.         @Override
  307.         public void flush() {
  308.             if (msgOut != null) {
  309.                 try {
  310.                     msgOut.flush();
  311.                 } catch (IOException e) {
  312.                     // Ignore write failures.
  313.                 }
  314.             }
  315.         }
  316.     }

  317.     /**
  318.      * Get the repository this receive completes into.
  319.      *
  320.      * @return the repository this receive completes into.
  321.      */
  322.     public Repository getRepository() {
  323.         return db;
  324.     }

  325.     /**
  326.      * Get the RevWalk instance used by this connection.
  327.      *
  328.      * @return the RevWalk instance used by this connection.
  329.      */
  330.     public RevWalk getRevWalk() {
  331.         return walk;
  332.     }

  333.     /**
  334.      * Get refs which were advertised to the client.
  335.      *
  336.      * @return all refs which were advertised to the client, or null if
  337.      *         {@link #setAdvertisedRefs(Map, Set)} has not been called yet.
  338.      */
  339.     public Map<String, Ref> getAdvertisedRefs() {
  340.         return refs;
  341.     }

  342.     /**
  343.      * Set the refs advertised by this ReceivePack.
  344.      * <p>
  345.      * Intended to be called from a
  346.      * {@link org.eclipse.jgit.transport.PreReceiveHook}.
  347.      *
  348.      * @param allRefs
  349.      *            explicit set of references to claim as advertised by this
  350.      *            ReceivePack instance. This overrides any references that may
  351.      *            exist in the source repository. The map is passed to the
  352.      *            configured {@link #getRefFilter()}. If null, assumes all refs
  353.      *            were advertised.
  354.      * @param additionalHaves
  355.      *            explicit set of additional haves to claim as advertised. If
  356.      *            null, assumes the default set of additional haves from the
  357.      *            repository.
  358.      */
  359.     public void setAdvertisedRefs(Map<String, Ref> allRefs,
  360.             Set<ObjectId> additionalHaves) {
  361.         refs = allRefs != null ? allRefs : db.getAllRefs();
  362.         refs = refFilter.filter(refs);
  363.         advertisedHaves.clear();

  364.         Ref head = refs.get(HEAD);
  365.         if (head != null && head.isSymbolic()) {
  366.             refs.remove(HEAD);
  367.         }

  368.         for (Ref ref : refs.values()) {
  369.             if (ref.getObjectId() != null) {
  370.                 advertisedHaves.add(ref.getObjectId());
  371.             }
  372.         }
  373.         if (additionalHaves != null) {
  374.             advertisedHaves.addAll(additionalHaves);
  375.         } else {
  376.             advertisedHaves.addAll(db.getAdditionalHaves());
  377.         }
  378.     }

  379.     /**
  380.      * Get objects advertised to the client.
  381.      *
  382.      * @return the set of objects advertised to the as present in this
  383.      *         repository, or null if {@link #setAdvertisedRefs(Map, Set)} has
  384.      *         not been called yet.
  385.      */
  386.     public final Set<ObjectId> getAdvertisedObjects() {
  387.         return advertisedHaves;
  388.     }

  389.     /**
  390.      * Whether this instance will validate all referenced, but not supplied by
  391.      * the client, objects are reachable from another reference.
  392.      *
  393.      * @return true if this instance will validate all referenced, but not
  394.      *         supplied by the client, objects are reachable from another
  395.      *         reference.
  396.      */
  397.     public boolean isCheckReferencedObjectsAreReachable() {
  398.         return checkReferencedAreReachable;
  399.     }

  400.     /**
  401.      * Validate all referenced but not supplied objects are reachable.
  402.      * <p>
  403.      * If enabled, this instance will verify that references to objects not
  404.      * contained within the received pack are already reachable through at least
  405.      * one other reference displayed as part of {@link #getAdvertisedRefs()}.
  406.      * <p>
  407.      * This feature is useful when the application doesn't trust the client to
  408.      * not provide a forged SHA-1 reference to an object, in an attempt to
  409.      * access parts of the DAG that they aren't allowed to see and which have
  410.      * been hidden from them via the configured
  411.      * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} or
  412.      * {@link org.eclipse.jgit.transport.RefFilter}.
  413.      * <p>
  414.      * Enabling this feature may imply at least some, if not all, of the same
  415.      * functionality performed by {@link #setCheckReceivedObjects(boolean)}.
  416.      * Applications are encouraged to enable both features, if desired.
  417.      *
  418.      * @param b
  419.      *            {@code true} to enable the additional check.
  420.      */
  421.     public void setCheckReferencedObjectsAreReachable(boolean b) {
  422.         this.checkReferencedAreReachable = b;
  423.     }

  424.     /**
  425.      * Whether this class expects a bi-directional pipe opened between the
  426.      * client and itself.
  427.      *
  428.      * @return true if this class expects a bi-directional pipe opened between
  429.      *         the client and itself. The default is true.
  430.      */
  431.     public boolean isBiDirectionalPipe() {
  432.         return biDirectionalPipe;
  433.     }

  434.     /**
  435.      * Whether this class will assume the socket is a fully bidirectional pipe
  436.      * between the two peers and takes advantage of that by first transmitting
  437.      * the known refs, then waiting to read commands.
  438.      *
  439.      * @param twoWay
  440.      *            if true, this class will assume the socket is a fully
  441.      *            bidirectional pipe between the two peers and takes advantage
  442.      *            of that by first transmitting the known refs, then waiting to
  443.      *            read commands. If false, this class assumes it must read the
  444.      *            commands before writing output and does not perform the
  445.      *            initial advertising.
  446.      */
  447.     public void setBiDirectionalPipe(boolean twoWay) {
  448.         biDirectionalPipe = twoWay;
  449.     }

  450.     /**
  451.      * Whether there is data expected after the pack footer.
  452.      *
  453.      * @return {@code true} if there is data expected after the pack footer.
  454.      */
  455.     public boolean isExpectDataAfterPackFooter() {
  456.         return expectDataAfterPackFooter;
  457.     }

  458.     /**
  459.      * Whether there is additional data in InputStream after pack.
  460.      *
  461.      * @param e
  462.      *            {@code true} if there is additional data in InputStream after
  463.      *            pack.
  464.      */
  465.     public void setExpectDataAfterPackFooter(boolean e) {
  466.         expectDataAfterPackFooter = e;
  467.     }

  468.     /**
  469.      * Whether this instance will verify received objects are formatted
  470.      * correctly.
  471.      *
  472.      * @return {@code true} if this instance will verify received objects are
  473.      *         formatted correctly. Validating objects requires more CPU time on
  474.      *         this side of the connection.
  475.      */
  476.     public boolean isCheckReceivedObjects() {
  477.         return objectChecker != null;
  478.     }

  479.     /**
  480.      * Whether to enable checking received objects
  481.      *
  482.      * @param check
  483.      *            {@code true} to enable checking received objects; false to
  484.      *            assume all received objects are valid.
  485.      * @see #setObjectChecker(ObjectChecker)
  486.      */
  487.     public void setCheckReceivedObjects(boolean check) {
  488.         if (check && objectChecker == null)
  489.             setObjectChecker(new ObjectChecker());
  490.         else if (!check && objectChecker != null)
  491.             setObjectChecker(null);
  492.     }

  493.     /**
  494.      * Set the object checking instance to verify each received object with
  495.      *
  496.      * @param impl
  497.      *            if non-null the object checking instance to verify each
  498.      *            received object with; null to disable object checking.
  499.      * @since 3.4
  500.      */
  501.     public void setObjectChecker(ObjectChecker impl) {
  502.         objectChecker = impl;
  503.     }

  504.     /**
  505.      * Whether the client can request refs to be created.
  506.      *
  507.      * @return {@code true} if the client can request refs to be created.
  508.      */
  509.     public boolean isAllowCreates() {
  510.         return allowCreates;
  511.     }

  512.     /**
  513.      * Whether to permit create ref commands to be processed.
  514.      *
  515.      * @param canCreate
  516.      *            {@code true} to permit create ref commands to be processed.
  517.      */
  518.     public void setAllowCreates(boolean canCreate) {
  519.         allowCreates = canCreate;
  520.     }

  521.     /**
  522.      * Whether the client can request refs to be deleted.
  523.      *
  524.      * @return {@code true} if the client can request refs to be deleted.
  525.      */
  526.     public boolean isAllowDeletes() {
  527.         return allowAnyDeletes;
  528.     }

  529.     /**
  530.      * Whether to permit delete ref commands to be processed.
  531.      *
  532.      * @param canDelete
  533.      *            {@code true} to permit delete ref commands to be processed.
  534.      */
  535.     public void setAllowDeletes(boolean canDelete) {
  536.         allowAnyDeletes = canDelete;
  537.     }

  538.     /**
  539.      * Whether the client can delete from {@code refs/heads/}.
  540.      *
  541.      * @return {@code true} if the client can delete from {@code refs/heads/}.
  542.      * @since 3.6
  543.      */
  544.     public boolean isAllowBranchDeletes() {
  545.         return allowBranchDeletes;
  546.     }

  547.     /**
  548.      * Configure whether to permit deletion of branches from the
  549.      * {@code refs/heads/} namespace.
  550.      *
  551.      * @param canDelete
  552.      *            {@code true} to permit deletion of branches from the
  553.      *            {@code refs/heads/} namespace.
  554.      * @since 3.6
  555.      */
  556.     public void setAllowBranchDeletes(boolean canDelete) {
  557.         allowBranchDeletes = canDelete;
  558.     }

  559.     /**
  560.      * Whether the client can request non-fast-forward updates of a ref,
  561.      * possibly making objects unreachable.
  562.      *
  563.      * @return {@code true} if the client can request non-fast-forward updates
  564.      *         of a ref, possibly making objects unreachable.
  565.      */
  566.     public boolean isAllowNonFastForwards() {
  567.         return allowNonFastForwards;
  568.     }

  569.     /**
  570.      * Configure whether to permit the client to ask for non-fast-forward
  571.      * updates of an existing ref.
  572.      *
  573.      * @param canRewind
  574.      *            {@code true} to permit the client to ask for non-fast-forward
  575.      *            updates of an existing ref.
  576.      */
  577.     public void setAllowNonFastForwards(boolean canRewind) {
  578.         allowNonFastForwards = canRewind;
  579.     }

  580.     /**
  581.      * Whether the client's commands should be performed as a single atomic
  582.      * transaction.
  583.      *
  584.      * @return {@code true} if the client's commands should be performed as a
  585.      *         single atomic transaction.
  586.      * @since 4.4
  587.      */
  588.     public boolean isAtomic() {
  589.         return atomic;
  590.     }

  591.     /**
  592.      * Configure whether to perform the client's commands as a single atomic
  593.      * transaction.
  594.      *
  595.      * @param atomic
  596.      *            {@code true} to perform the client's commands as a single
  597.      *            atomic transaction.
  598.      * @since 4.4
  599.      */
  600.     public void setAtomic(boolean atomic) {
  601.         this.atomic = atomic;
  602.     }

  603.     /**
  604.      * Get identity of the user making the changes in the reflog.
  605.      *
  606.      * @return identity of the user making the changes in the reflog.
  607.      */
  608.     public PersonIdent getRefLogIdent() {
  609.         return refLogIdent;
  610.     }

  611.     /**
  612.      * Set the identity of the user appearing in the affected reflogs.
  613.      * <p>
  614.      * The timestamp portion of the identity is ignored. A new identity with the
  615.      * current timestamp will be created automatically when the updates occur
  616.      * and the log records are written.
  617.      *
  618.      * @param pi
  619.      *            identity of the user. If null the identity will be
  620.      *            automatically determined based on the repository
  621.      *            configuration.
  622.      */
  623.     public void setRefLogIdent(PersonIdent pi) {
  624.         refLogIdent = pi;
  625.     }

  626.     /**
  627.      * Get the hook used while advertising the refs to the client
  628.      *
  629.      * @return the hook used while advertising the refs to the client
  630.      */
  631.     public AdvertiseRefsHook getAdvertiseRefsHook() {
  632.         return advertiseRefsHook;
  633.     }

  634.     /**
  635.      * Get the filter used while advertising the refs to the client
  636.      *
  637.      * @return the filter used while advertising the refs to the client
  638.      */
  639.     public RefFilter getRefFilter() {
  640.         return refFilter;
  641.     }

  642.     /**
  643.      * Set the hook used while advertising the refs to the client.
  644.      * <p>
  645.      * If the {@link org.eclipse.jgit.transport.AdvertiseRefsHook} chooses to
  646.      * call {@link #setAdvertisedRefs(Map,Set)}, only refs set by this hook
  647.      * <em>and</em> selected by the {@link org.eclipse.jgit.transport.RefFilter}
  648.      * will be shown to the client. Clients may still attempt to create or
  649.      * update a reference not advertised by the configured
  650.      * {@link org.eclipse.jgit.transport.AdvertiseRefsHook}. These attempts
  651.      * should be rejected by a matching
  652.      * {@link org.eclipse.jgit.transport.PreReceiveHook}.
  653.      *
  654.      * @param advertiseRefsHook
  655.      *            the hook; may be null to show all refs.
  656.      */
  657.     public void setAdvertiseRefsHook(AdvertiseRefsHook advertiseRefsHook) {
  658.         if (advertiseRefsHook != null)
  659.             this.advertiseRefsHook = advertiseRefsHook;
  660.         else
  661.             this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  662.     }

  663.     /**
  664.      * Set the filter used while advertising the refs to the client.
  665.      * <p>
  666.      * Only refs allowed by this filter will be shown to the client. The filter
  667.      * is run against the refs specified by the
  668.      * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} (if applicable).
  669.      *
  670.      * @param refFilter
  671.      *            the filter; may be null to show all refs.
  672.      */
  673.     public void setRefFilter(RefFilter refFilter) {
  674.         this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  675.     }

  676.     /**
  677.      * Get timeout (in seconds) before aborting an IO operation.
  678.      *
  679.      * @return timeout (in seconds) before aborting an IO operation.
  680.      */
  681.     public int getTimeout() {
  682.         return timeout;
  683.     }

  684.     /**
  685.      * Set the timeout before willing to abort an IO call.
  686.      *
  687.      * @param seconds
  688.      *            number of seconds to wait (with no data transfer occurring)
  689.      *            before aborting an IO read or write operation with the
  690.      *            connected client.
  691.      */
  692.     public void setTimeout(int seconds) {
  693.         timeout = seconds;
  694.     }

  695.     /**
  696.      * Set the maximum number of command bytes to read from the client.
  697.      *
  698.      * @param limit
  699.      *            command limit in bytes; if 0 there is no limit.
  700.      * @since 4.7
  701.      */
  702.     public void setMaxCommandBytes(long limit) {
  703.         maxCommandBytes = limit;
  704.     }

  705.     /**
  706.      * Set the maximum number of command bytes to discard from the client.
  707.      * <p>
  708.      * Discarding remaining bytes allows this instance to consume the rest of
  709.      * the command block and send a human readable over-limit error via the
  710.      * side-band channel. If the client sends an excessive number of bytes this
  711.      * limit kicks in and the instance disconnects, resulting in a non-specific
  712.      * 'pipe closed', 'end of stream', or similar generic error at the client.
  713.      * <p>
  714.      * When the limit is set to {@code -1} the implementation will default to
  715.      * the larger of {@code 3 * maxCommandBytes} or {@code 3 MiB}.
  716.      *
  717.      * @param limit
  718.      *            discard limit in bytes; if 0 there is no limit; if -1 the
  719.      *            implementation tries to set a reasonable default.
  720.      * @since 4.7
  721.      */
  722.     public void setMaxCommandDiscardBytes(long limit) {
  723.         maxDiscardBytes = limit;
  724.     }

  725.     /**
  726.      * Set the maximum allowed Git object size.
  727.      * <p>
  728.      * If an object is larger than the given size the pack-parsing will throw an
  729.      * exception aborting the receive-pack operation.
  730.      *
  731.      * @param limit
  732.      *            the Git object size limit. If zero then there is not limit.
  733.      */
  734.     public void setMaxObjectSizeLimit(long limit) {
  735.         maxObjectSizeLimit = limit;
  736.     }

  737.     /**
  738.      * Set the maximum allowed pack size.
  739.      * <p>
  740.      * A pack exceeding this size will be rejected.
  741.      *
  742.      * @param limit
  743.      *            the pack size limit, in bytes
  744.      * @since 3.3
  745.      */
  746.     public void setMaxPackSizeLimit(long limit) {
  747.         if (limit < 0)
  748.             throw new IllegalArgumentException(
  749.                     MessageFormat.format(JGitText.get().receivePackInvalidLimit,
  750.                             Long.valueOf(limit)));
  751.         maxPackSizeLimit = limit;
  752.     }

  753.     /**
  754.      * Check whether the client expects a side-band stream.
  755.      *
  756.      * @return true if the client has advertised a side-band capability, false
  757.      *         otherwise.
  758.      * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  759.      *             if the client's request has not yet been read from the wire,
  760.      *             so we do not know if they expect side-band. Note that the
  761.      *             client may have already written the request, it just has not
  762.      *             been read.
  763.      */
  764.     public boolean isSideBand() throws RequestNotYetReadException {
  765.         checkRequestWasRead();
  766.         return enabledCapabilities.contains(CAPABILITY_SIDE_BAND_64K);
  767.     }

  768.     /**
  769.      * Whether clients may request avoiding noisy progress messages.
  770.      *
  771.      * @return true if clients may request avoiding noisy progress messages.
  772.      * @since 4.0
  773.      */
  774.     public boolean isAllowQuiet() {
  775.         return allowQuiet;
  776.     }

  777.     /**
  778.      * Configure if clients may request the server skip noisy messages.
  779.      *
  780.      * @param allow
  781.      *            true to allow clients to request quiet behavior; false to
  782.      *            refuse quiet behavior and send messages anyway. This may be
  783.      *            necessary if processing is slow and the client-server network
  784.      *            connection can timeout.
  785.      * @since 4.0
  786.      */
  787.     public void setAllowQuiet(boolean allow) {
  788.         allowQuiet = allow;
  789.     }

  790.     /**
  791.      * Whether the server supports receiving push options.
  792.      *
  793.      * @return true if the server supports receiving push options.
  794.      * @since 4.5
  795.      */
  796.     public boolean isAllowPushOptions() {
  797.         return allowPushOptions;
  798.     }

  799.     /**
  800.      * Configure if the server supports receiving push options.
  801.      *
  802.      * @param allow
  803.      *            true to optionally accept option strings from the client.
  804.      * @since 4.5
  805.      */
  806.     public void setAllowPushOptions(boolean allow) {
  807.         allowPushOptions = allow;
  808.     }

  809.     /**
  810.      * True if the client wants less verbose output.
  811.      *
  812.      * @return true if the client has requested the server to be less verbose.
  813.      * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  814.      *             if the client's request has not yet been read from the wire,
  815.      *             so we do not know if they expect side-band. Note that the
  816.      *             client may have already written the request, it just has not
  817.      *             been read.
  818.      * @since 4.0
  819.      */
  820.     public boolean isQuiet() throws RequestNotYetReadException {
  821.         checkRequestWasRead();
  822.         return quiet;
  823.     }

  824.     /**
  825.      * Set the configuration for push certificate verification.
  826.      *
  827.      * @param cfg
  828.      *            new configuration; if this object is null or its
  829.      *            {@link SignedPushConfig#getCertNonceSeed()} is null, push
  830.      *            certificate verification will be disabled.
  831.      * @since 4.1
  832.      */
  833.     public void setSignedPushConfig(SignedPushConfig cfg) {
  834.         signedPushConfig = cfg;
  835.     }

  836.     private PushCertificateParser getPushCertificateParser() {
  837.         if (pushCertificateParser == null) {
  838.             pushCertificateParser = new PushCertificateParser(db,
  839.                     signedPushConfig);
  840.         }
  841.         return pushCertificateParser;
  842.     }

  843.     /**
  844.      * Get the user agent of the client.
  845.      * <p>
  846.      * If the client is new enough to use {@code agent=} capability that value
  847.      * will be returned. Older HTTP clients may also supply their version using
  848.      * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  849.      * header if both are available.
  850.      * <p>
  851.      * When an HTTP request has been received this method returns the HTTP
  852.      * {@code User-Agent} header value until capabilities have been parsed.
  853.      *
  854.      * @return user agent supplied by the client. Available only if the client
  855.      *         is new enough to advertise its user agent.
  856.      * @since 4.0
  857.      */
  858.     public String getPeerUserAgent() {
  859.         return UserAgent.getAgent(enabledCapabilities, userAgent);
  860.     }

  861.     /**
  862.      * Get all of the command received by the current request.
  863.      *
  864.      * @return all of the command received by the current request.
  865.      */
  866.     public List<ReceiveCommand> getAllCommands() {
  867.         return Collections.unmodifiableList(commands);
  868.     }

  869.     /**
  870.      * Set an error handler for {@link ReceiveCommand}.
  871.      *
  872.      * @param receiveCommandErrorHandler
  873.      * @since 5.7
  874.      */
  875.     public void setReceiveCommandErrorHandler(
  876.             ReceiveCommandErrorHandler receiveCommandErrorHandler) {
  877.         this.receiveCommandErrorHandler = receiveCommandErrorHandler;
  878.     }

  879.     /**
  880.      * Send an error message to the client.
  881.      * <p>
  882.      * If any error messages are sent before the references are advertised to
  883.      * the client, the errors will be sent instead of the advertisement and the
  884.      * receive operation will be aborted. All clients should receive and display
  885.      * such early stage errors.
  886.      * <p>
  887.      * If the reference advertisements have already been sent, messages are sent
  888.      * in a side channel. If the client doesn't support receiving messages, the
  889.      * message will be discarded, with no other indication to the caller or to
  890.      * the client.
  891.      * <p>
  892.      * {@link org.eclipse.jgit.transport.PreReceiveHook}s should always try to
  893.      * use
  894.      * {@link org.eclipse.jgit.transport.ReceiveCommand#setResult(Result, String)}
  895.      * with a result status of
  896.      * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#REJECTED_OTHER_REASON}
  897.      * to indicate any reasons for rejecting an update. Messages attached to a
  898.      * command are much more likely to be returned to the client.
  899.      *
  900.      * @param what
  901.      *            string describing the problem identified by the hook. The
  902.      *            string must not end with an LF, and must not contain an LF.
  903.      */
  904.     public void sendError(String what) {
  905.         if (refs == null) {
  906.             if (advertiseError == null)
  907.                 advertiseError = new StringBuilder();
  908.             advertiseError.append(what).append('\n');
  909.         } else {
  910.             msgOutWrapper.write(Constants.encode("error: " + what + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
  911.         }
  912.     }

  913.     private void fatalError(String msg) {
  914.         if (errOut != null) {
  915.             try {
  916.                 errOut.write(Constants.encode(msg));
  917.                 errOut.flush();
  918.             } catch (IOException e) {
  919.                 // Ignore write failures
  920.             }
  921.         } else {
  922.             sendError(msg);
  923.         }
  924.     }

  925.     /**
  926.      * Send a message to the client, if it supports receiving them.
  927.      * <p>
  928.      * If the client doesn't support receiving messages, the message will be
  929.      * discarded, with no other indication to the caller or to the client.
  930.      *
  931.      * @param what
  932.      *            string describing the problem identified by the hook. The
  933.      *            string must not end with an LF, and must not contain an LF.
  934.      */
  935.     public void sendMessage(String what) {
  936.         msgOutWrapper.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  937.     }

  938.     /**
  939.      * Get an underlying stream for sending messages to the client.
  940.      *
  941.      * @return an underlying stream for sending messages to the client.
  942.      */
  943.     public OutputStream getMessageOutputStream() {
  944.         return msgOutWrapper;
  945.     }

  946.     /**
  947.      * Get whether or not a pack has been received.
  948.      *
  949.      * This can be called before calling {@link #getPackSize()} to avoid causing
  950.      * {@code IllegalStateException} when the pack size was not set because no
  951.      * pack was received.
  952.      *
  953.      * @return true if a pack has been received.
  954.      * @since 5.6
  955.      */
  956.     public boolean hasReceivedPack() {
  957.         return packSize != null;
  958.     }

  959.     /**
  960.      * Get the size of the received pack file including the index size.
  961.      *
  962.      * This can only be called if the pack is already received.
  963.      *
  964.      * @return the size of the received pack including index size
  965.      * @throws java.lang.IllegalStateException
  966.      *             if called before the pack has been received
  967.      * @since 3.3
  968.      */
  969.     public long getPackSize() {
  970.         if (packSize != null)
  971.             return packSize.longValue();
  972.         throw new IllegalStateException(JGitText.get().packSizeNotSetYet);
  973.     }

  974.     /**
  975.      * Get the commits from the client's shallow file.
  976.      *
  977.      * @return if the client is a shallow repository, the list of edge commits
  978.      *         that define the client's shallow boundary. Empty set if the
  979.      *         client is earlier than Git 1.9, or is a full clone.
  980.      */
  981.     private Set<ObjectId> getClientShallowCommits() {
  982.         return clientShallowCommits;
  983.     }

  984.     /**
  985.      * Whether any commands to be executed have been read.
  986.      *
  987.      * @return {@code true} if any commands to be executed have been read.
  988.      */
  989.     private boolean hasCommands() {
  990.         return !commands.isEmpty();
  991.     }

  992.     /**
  993.      * Whether an error occurred that should be advertised.
  994.      *
  995.      * @return true if an error occurred that should be advertised.
  996.      */
  997.     private boolean hasError() {
  998.         return advertiseError != null;
  999.     }

  1000.     /**
  1001.      * Initialize the instance with the given streams.
  1002.      *
  1003.      * Visible for out-of-tree subclasses (e.g. tests that need to set the
  1004.      * streams without going through the {@link #service()} method).
  1005.      *
  1006.      * @param input
  1007.      *            raw input to read client commands and pack data from. Caller
  1008.      *            must ensure the input is buffered, otherwise read performance
  1009.      *            may suffer.
  1010.      * @param output
  1011.      *            response back to the Git network client. Caller must ensure
  1012.      *            the output is buffered, otherwise write performance may
  1013.      *            suffer.
  1014.      * @param messages
  1015.      *            secondary "notice" channel to send additional messages out
  1016.      *            through. When run over SSH this should be tied back to the
  1017.      *            standard error channel of the command execution. For most
  1018.      *            other network connections this should be null.
  1019.      */
  1020.     protected void init(final InputStream input, final OutputStream output,
  1021.             final OutputStream messages) {
  1022.         origOut = output;
  1023.         rawIn = input;
  1024.         rawOut = output;
  1025.         msgOut = messages;

  1026.         if (timeout > 0) {
  1027.             final Thread caller = Thread.currentThread();
  1028.             timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  1029.             timeoutIn = new TimeoutInputStream(rawIn, timer);
  1030.             TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  1031.             timeoutIn.setTimeout(timeout * 1000);
  1032.             o.setTimeout(timeout * 1000);
  1033.             rawIn = timeoutIn;
  1034.             rawOut = o;
  1035.         }

  1036.         pckIn = new PacketLineIn(rawIn);
  1037.         pckOut = new PacketLineOut(rawOut);
  1038.         pckOut.setFlushOnEnd(false);

  1039.         enabledCapabilities = new HashSet<>();
  1040.         commands = new ArrayList<>();
  1041.     }

  1042.     /**
  1043.      * Get advertised refs, or the default if not explicitly advertised.
  1044.      *
  1045.      * @return advertised refs, or the default if not explicitly advertised.
  1046.      */
  1047.     private Map<String, Ref> getAdvertisedOrDefaultRefs() {
  1048.         if (refs == null)
  1049.             setAdvertisedRefs(null, null);
  1050.         return refs;
  1051.     }

  1052.     /**
  1053.      * Receive a pack from the stream and check connectivity if necessary.
  1054.      *
  1055.      * Visible for out-of-tree subclasses. Subclasses overriding this method
  1056.      * should invoke this implementation, as it alters the instance state (e.g.
  1057.      * it reads the pack from the input and parses it before running the
  1058.      * connectivity checks).
  1059.      *
  1060.      * @throws java.io.IOException
  1061.      *             an error occurred during unpacking or connectivity checking.
  1062.      * @throws LargeObjectException
  1063.      *             an large object needs to be opened for the check.
  1064.      * @throws SubmoduleValidationException
  1065.      *             fails to validate the submodule.
  1066.      */
  1067.     protected void receivePackAndCheckConnectivity() throws IOException,
  1068.             LargeObjectException, SubmoduleValidationException {
  1069.         receivePack();
  1070.         if (needCheckConnectivity()) {
  1071.             checkSubmodules();
  1072.             checkConnectivity();
  1073.         }
  1074.         parser = null;
  1075.     }

  1076.     /**
  1077.      * Unlock the pack written by this object.
  1078.      *
  1079.      * @throws java.io.IOException
  1080.      *             the pack could not be unlocked.
  1081.      */
  1082.     private void unlockPack() throws IOException {
  1083.         if (packLock != null) {
  1084.             packLock.unlock();
  1085.             packLock = null;
  1086.         }
  1087.     }

  1088.     /**
  1089.      * Generate an advertisement of available refs and capabilities.
  1090.      *
  1091.      * @param adv
  1092.      *            the advertisement formatter.
  1093.      * @throws java.io.IOException
  1094.      *             the formatter failed to write an advertisement.
  1095.      * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1096.      *             the hook denied advertisement.
  1097.      */
  1098.     public void sendAdvertisedRefs(RefAdvertiser adv)
  1099.             throws IOException, ServiceMayNotContinueException {
  1100.         if (advertiseError != null) {
  1101.             adv.writeOne("ERR " + advertiseError); //$NON-NLS-1$
  1102.             return;
  1103.         }

  1104.         try {
  1105.             advertiseRefsHook.advertiseRefs(this);
  1106.         } catch (ServiceMayNotContinueException fail) {
  1107.             if (fail.getMessage() != null) {
  1108.                 adv.writeOne("ERR " + fail.getMessage()); //$NON-NLS-1$
  1109.                 fail.setOutput();
  1110.             }
  1111.             throw fail;
  1112.         }

  1113.         adv.init(db);
  1114.         adv.advertiseCapability(CAPABILITY_SIDE_BAND_64K);
  1115.         adv.advertiseCapability(CAPABILITY_DELETE_REFS);
  1116.         adv.advertiseCapability(CAPABILITY_REPORT_STATUS);
  1117.         if (allowQuiet)
  1118.             adv.advertiseCapability(CAPABILITY_QUIET);
  1119.         String nonce = getPushCertificateParser().getAdvertiseNonce();
  1120.         if (nonce != null) {
  1121.             adv.advertiseCapability(nonce);
  1122.         }
  1123.         if (db.getRefDatabase().performsAtomicTransactions())
  1124.             adv.advertiseCapability(CAPABILITY_ATOMIC);
  1125.         if (allowOfsDelta)
  1126.             adv.advertiseCapability(CAPABILITY_OFS_DELTA);
  1127.         if (allowPushOptions) {
  1128.             adv.advertiseCapability(CAPABILITY_PUSH_OPTIONS);
  1129.         }
  1130.         adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  1131.         adv.send(getAdvertisedOrDefaultRefs().values());
  1132.         for (ObjectId obj : advertisedHaves)
  1133.             adv.advertiseHave(obj);
  1134.         if (adv.isEmpty())
  1135.             adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  1136.         adv.end();
  1137.     }

  1138.     /**
  1139.      * Returns the statistics on the received pack if available. This should be
  1140.      * called after {@link #receivePack} is called.
  1141.      *
  1142.      * @return ReceivedPackStatistics
  1143.      * @since 4.6
  1144.      */
  1145.     @Nullable
  1146.     public ReceivedPackStatistics getReceivedPackStatistics() {
  1147.         return stats;
  1148.     }

  1149.     /**
  1150.      * Receive a list of commands from the input.
  1151.      *
  1152.      * @throws java.io.IOException
  1153.      */
  1154.     private void recvCommands() throws IOException {
  1155.         PacketLineIn pck = maxCommandBytes > 0
  1156.                 ? new PacketLineIn(rawIn, maxCommandBytes)
  1157.                 : pckIn;
  1158.         PushCertificateParser certParser = getPushCertificateParser();
  1159.         boolean firstPkt = true;
  1160.         try {
  1161.             for (;;) {
  1162.                 String line;
  1163.                 try {
  1164.                     line = pck.readString();
  1165.                 } catch (EOFException eof) {
  1166.                     if (commands.isEmpty())
  1167.                         return;
  1168.                     throw eof;
  1169.                 }
  1170.                 if (PacketLineIn.isEnd(line)) {
  1171.                     break;
  1172.                 }

  1173.                 if (line.length() >= 48 && line.startsWith("shallow ")) { //$NON-NLS-1$
  1174.                     parseShallow(line.substring(8, 48));
  1175.                     continue;
  1176.                 }

  1177.                 if (firstPkt) {
  1178.                     firstPkt = false;
  1179.                     FirstCommand firstLine = FirstCommand.fromLine(line);
  1180.                     enabledCapabilities = firstLine.getCapabilities();
  1181.                     line = firstLine.getLine();
  1182.                     enableCapabilities();

  1183.                     if (line.equals(GitProtocolConstants.OPTION_PUSH_CERT)) {
  1184.                         certParser.receiveHeader(pck, !isBiDirectionalPipe());
  1185.                         continue;
  1186.                     }
  1187.                 }

  1188.                 if (line.equals(PushCertificateParser.BEGIN_SIGNATURE)) {
  1189.                     certParser.receiveSignature(pck);
  1190.                     continue;
  1191.                 }

  1192.                 ReceiveCommand cmd = parseCommand(line);
  1193.                 if (cmd.getRefName().equals(Constants.HEAD)) {
  1194.                     cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
  1195.                 } else {
  1196.                     cmd.setRef(refs.get(cmd.getRefName()));
  1197.                 }
  1198.                 commands.add(cmd);
  1199.                 if (certParser.enabled()) {
  1200.                     certParser.addCommand(cmd);
  1201.                 }
  1202.             }
  1203.             pushCert = certParser.build();
  1204.             if (hasCommands()) {
  1205.                 readPostCommands(pck);
  1206.             }
  1207.         } catch (Throwable t) {
  1208.             discardCommands();
  1209.             throw t;
  1210.         }
  1211.     }

  1212.     private void discardCommands() {
  1213.         if (sideBand) {
  1214.             long max = maxDiscardBytes;
  1215.             if (max < 0) {
  1216.                 max = Math.max(3 * maxCommandBytes, 3L << 20);
  1217.             }
  1218.             try {
  1219.                 new PacketLineIn(rawIn, max).discardUntilEnd();
  1220.             } catch (IOException e) {
  1221.                 // Ignore read failures attempting to discard.
  1222.             }
  1223.         }
  1224.     }

  1225.     private void parseShallow(String idStr) throws PackProtocolException {
  1226.         ObjectId id;
  1227.         try {
  1228.             id = ObjectId.fromString(idStr);
  1229.         } catch (InvalidObjectIdException e) {
  1230.             throw new PackProtocolException(e.getMessage(), e);
  1231.         }
  1232.         clientShallowCommits.add(id);
  1233.     }

  1234.     /**
  1235.      * @param in
  1236.      *            request stream.
  1237.      * @throws IOException
  1238.      *             request line cannot be read.
  1239.      */
  1240.     void readPostCommands(PacketLineIn in) throws IOException {
  1241.         if (usePushOptions) {
  1242.             pushOptions = new ArrayList<>(4);
  1243.             for (;;) {
  1244.                 String option = in.readString();
  1245.                 if (PacketLineIn.isEnd(option)) {
  1246.                     break;
  1247.                 }
  1248.                 pushOptions.add(option);
  1249.             }
  1250.         }
  1251.     }

  1252.     /**
  1253.      * Enable capabilities based on a previously read capabilities line.
  1254.      */
  1255.     private void enableCapabilities() {
  1256.         reportStatus = isCapabilityEnabled(CAPABILITY_REPORT_STATUS);
  1257.         usePushOptions = isCapabilityEnabled(CAPABILITY_PUSH_OPTIONS);
  1258.         sideBand = isCapabilityEnabled(CAPABILITY_SIDE_BAND_64K);
  1259.         quiet = allowQuiet && isCapabilityEnabled(CAPABILITY_QUIET);
  1260.         if (sideBand) {
  1261.             OutputStream out = rawOut;

  1262.             rawOut = new SideBandOutputStream(CH_DATA, MAX_BUF, out);
  1263.             msgOut = new SideBandOutputStream(CH_PROGRESS, MAX_BUF, out);
  1264.             errOut = new SideBandOutputStream(CH_ERROR, MAX_BUF, out);

  1265.             pckOut = new PacketLineOut(rawOut);
  1266.             pckOut.setFlushOnEnd(false);
  1267.         }
  1268.     }

  1269.     /**
  1270.      * Check if the peer requested a capability.
  1271.      *
  1272.      * @param name
  1273.      *            protocol name identifying the capability.
  1274.      * @return true if the peer requested the capability to be enabled.
  1275.      */
  1276.     private boolean isCapabilityEnabled(String name) {
  1277.         return enabledCapabilities.contains(name);
  1278.     }

  1279.     private void checkRequestWasRead() {
  1280.         if (enabledCapabilities == null)
  1281.             throw new RequestNotYetReadException();
  1282.     }

  1283.     /**
  1284.      * Whether a pack is expected based on the list of commands.
  1285.      *
  1286.      * @return {@code true} if a pack is expected based on the list of commands.
  1287.      */
  1288.     private boolean needPack() {
  1289.         for (ReceiveCommand cmd : commands) {
  1290.             if (cmd.getType() != ReceiveCommand.Type.DELETE)
  1291.                 return true;
  1292.         }
  1293.         return false;
  1294.     }

  1295.     /**
  1296.      * Receive a pack from the input and store it in the repository.
  1297.      *
  1298.      * @throws IOException
  1299.      *             an error occurred reading or indexing the pack.
  1300.      */
  1301.     private void receivePack() throws IOException {
  1302.         // It might take the client a while to pack the objects it needs
  1303.         // to send to us. We should increase our timeout so we don't
  1304.         // abort while the client is computing.
  1305.         //
  1306.         if (timeoutIn != null)
  1307.             timeoutIn.setTimeout(10 * timeout * 1000);

  1308.         ProgressMonitor receiving = NullProgressMonitor.INSTANCE;
  1309.         ProgressMonitor resolving = NullProgressMonitor.INSTANCE;
  1310.         if (sideBand && !quiet)
  1311.             resolving = new SideBandProgressMonitor(msgOut);

  1312.         try (ObjectInserter ins = db.newObjectInserter()) {
  1313.             String lockMsg = "jgit receive-pack"; //$NON-NLS-1$
  1314.             if (getRefLogIdent() != null)
  1315.                 lockMsg += " from " + getRefLogIdent().toExternalString(); //$NON-NLS-1$

  1316.             parser = ins.newPackParser(packInputStream());
  1317.             parser.setAllowThin(true);
  1318.             parser.setNeedNewObjectIds(checkReferencedAreReachable);
  1319.             parser.setNeedBaseObjectIds(checkReferencedAreReachable);
  1320.             parser.setCheckEofAfterPackFooter(!biDirectionalPipe
  1321.                     && !isExpectDataAfterPackFooter());
  1322.             parser.setExpectDataAfterPackFooter(isExpectDataAfterPackFooter());
  1323.             parser.setObjectChecker(objectChecker);
  1324.             parser.setLockMessage(lockMsg);
  1325.             parser.setMaxObjectSizeLimit(maxObjectSizeLimit);
  1326.             packLock = parser.parse(receiving, resolving);
  1327.             packSize = Long.valueOf(parser.getPackSize());
  1328.             stats = parser.getReceivedPackStatistics();
  1329.             ins.flush();
  1330.         }

  1331.         if (timeoutIn != null)
  1332.             timeoutIn.setTimeout(timeout * 1000);
  1333.     }

  1334.     private InputStream packInputStream() {
  1335.         InputStream packIn = rawIn;
  1336.         if (maxPackSizeLimit >= 0) {
  1337.             packIn = new LimitedInputStream(packIn, maxPackSizeLimit) {
  1338.                 @Override
  1339.                 protected void limitExceeded() throws TooLargePackException {
  1340.                     throw new TooLargePackException(limit);
  1341.                 }
  1342.             };
  1343.         }
  1344.         return packIn;
  1345.     }

  1346.     private boolean needCheckConnectivity() {
  1347.         return isCheckReceivedObjects()
  1348.                 || isCheckReferencedObjectsAreReachable()
  1349.                 || !getClientShallowCommits().isEmpty();
  1350.     }

  1351.     private void checkSubmodules() throws IOException, LargeObjectException,
  1352.             SubmoduleValidationException {
  1353.         ObjectDatabase odb = db.getObjectDatabase();
  1354.         if (objectChecker == null) {
  1355.             return;
  1356.         }
  1357.         for (GitmoduleEntry entry : objectChecker.getGitsubmodules()) {
  1358.             AnyObjectId blobId = entry.getBlobId();
  1359.             ObjectLoader blob = odb.open(blobId, Constants.OBJ_BLOB);

  1360.             SubmoduleValidator.assertValidGitModulesFile(
  1361.                     new String(blob.getBytes(), UTF_8));
  1362.         }
  1363.     }

  1364.     private void checkConnectivity() throws IOException {
  1365.         ProgressMonitor checking = NullProgressMonitor.INSTANCE;
  1366.         if (sideBand && !quiet) {
  1367.             SideBandProgressMonitor m = new SideBandProgressMonitor(msgOut);
  1368.             m.setDelayStart(750, TimeUnit.MILLISECONDS);
  1369.             checking = m;
  1370.         }

  1371.         connectivityChecker.checkConnectivity(createConnectivityCheckInfo(),
  1372.                 advertisedHaves, checking);
  1373.     }

  1374.     private ConnectivityCheckInfo createConnectivityCheckInfo() {
  1375.         ConnectivityCheckInfo info = new ConnectivityCheckInfo();
  1376.         info.setCheckObjects(checkReferencedAreReachable);
  1377.         info.setCommands(getAllCommands());
  1378.         info.setRepository(db);
  1379.         info.setParser(parser);
  1380.         info.setWalk(walk);
  1381.         return info;
  1382.     }

  1383.     /**
  1384.      * Validate the command list.
  1385.      */
  1386.     private void validateCommands() {
  1387.         for (ReceiveCommand cmd : commands) {
  1388.             final Ref ref = cmd.getRef();
  1389.             if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1390.                 continue;

  1391.             if (cmd.getType() == ReceiveCommand.Type.DELETE) {
  1392.                 if (!isAllowDeletes()) {
  1393.                     // Deletes are not supported on this repository.
  1394.                     cmd.setResult(Result.REJECTED_NODELETE);
  1395.                     continue;
  1396.                 }
  1397.                 if (!isAllowBranchDeletes()
  1398.                         && ref.getName().startsWith(Constants.R_HEADS)) {
  1399.                     // Branches cannot be deleted, but other refs can.
  1400.                     cmd.setResult(Result.REJECTED_NODELETE);
  1401.                     continue;
  1402.                 }
  1403.             }

  1404.             if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  1405.                 if (!isAllowCreates()) {
  1406.                     cmd.setResult(Result.REJECTED_NOCREATE);
  1407.                     continue;
  1408.                 }

  1409.                 if (ref != null && !isAllowNonFastForwards()) {
  1410.                     // Creation over an existing ref is certainly not going
  1411.                     // to be a fast-forward update. We can reject it early.
  1412.                     //
  1413.                     cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1414.                     continue;
  1415.                 }

  1416.                 if (ref != null) {
  1417.                     // A well behaved client shouldn't have sent us a
  1418.                     // create command for a ref we advertised to it.
  1419.                     //
  1420.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1421.                             JGitText.get().refAlreadyExists);
  1422.                     continue;
  1423.                 }
  1424.             }

  1425.             if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null) {
  1426.                 ObjectId id = ref.getObjectId();
  1427.                 if (id == null) {
  1428.                     id = ObjectId.zeroId();
  1429.                 }
  1430.                 if (!ObjectId.zeroId().equals(cmd.getOldId())
  1431.                         && !id.equals(cmd.getOldId())) {
  1432.                     // Delete commands can be sent with the old id matching our
  1433.                     // advertised value, *OR* with the old id being 0{40}. Any
  1434.                     // other requested old id is invalid.
  1435.                     //
  1436.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1437.                             JGitText.get().invalidOldIdSent);
  1438.                     continue;
  1439.                 }
  1440.             }

  1441.             if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
  1442.                 if (ref == null) {
  1443.                     // The ref must have been advertised in order to be updated.
  1444.                     //
  1445.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1446.                             JGitText.get().noSuchRef);
  1447.                     continue;
  1448.                 }
  1449.                 ObjectId id = ref.getObjectId();
  1450.                 if (id == null) {
  1451.                     // We cannot update unborn branch
  1452.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1453.                             JGitText.get().cannotUpdateUnbornBranch);
  1454.                     continue;
  1455.                 }

  1456.                 if (!id.equals(cmd.getOldId())) {
  1457.                     // A properly functioning client will send the same
  1458.                     // object id we advertised.
  1459.                     //
  1460.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1461.                             JGitText.get().invalidOldIdSent);
  1462.                     continue;
  1463.                 }

  1464.                 // Is this possibly a non-fast-forward style update?
  1465.                 //
  1466.                 RevObject oldObj, newObj;
  1467.                 try {
  1468.                     oldObj = walk.parseAny(cmd.getOldId());
  1469.                 } catch (IOException e) {
  1470.                     receiveCommandErrorHandler
  1471.                             .handleOldIdValidationException(cmd, e);
  1472.                     continue;
  1473.                 }

  1474.                 try {
  1475.                     newObj = walk.parseAny(cmd.getNewId());
  1476.                 } catch (IOException e) {
  1477.                     receiveCommandErrorHandler
  1478.                             .handleNewIdValidationException(cmd, e);
  1479.                     continue;
  1480.                 }

  1481.                 if (oldObj instanceof RevCommit
  1482.                         && newObj instanceof RevCommit) {
  1483.                     try {
  1484.                         if (walk.isMergedInto((RevCommit) oldObj,
  1485.                                 (RevCommit) newObj)) {
  1486.                             cmd.setTypeFastForwardUpdate();
  1487.                         } else {
  1488.                             cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1489.                         }
  1490.                     } catch (IOException e) {
  1491.                         receiveCommandErrorHandler
  1492.                                 .handleFastForwardCheckException(cmd, e);
  1493.                     }
  1494.                 } else {
  1495.                     cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1496.                 }

  1497.                 if (cmd.getType() == ReceiveCommand.Type.UPDATE_NONFASTFORWARD
  1498.                         && !isAllowNonFastForwards()) {
  1499.                     cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1500.                     continue;
  1501.                 }
  1502.             }

  1503.             if (!cmd.getRefName().startsWith(Constants.R_REFS)
  1504.                     || !Repository.isValidRefName(cmd.getRefName())) {
  1505.                 cmd.setResult(Result.REJECTED_OTHER_REASON,
  1506.                         JGitText.get().funnyRefname);
  1507.             }
  1508.         }
  1509.     }

  1510.     /**
  1511.      * Whether any commands have been rejected so far.
  1512.      *
  1513.      * @return if any commands have been rejected so far.
  1514.      */
  1515.     private boolean anyRejects() {
  1516.         for (ReceiveCommand cmd : commands) {
  1517.             if (cmd.getResult() != Result.NOT_ATTEMPTED
  1518.                     && cmd.getResult() != Result.OK)
  1519.                 return true;
  1520.         }
  1521.         return false;
  1522.     }

  1523.     /**
  1524.      * Set the result to fail for any command that was not processed yet.
  1525.      *
  1526.      */
  1527.     private void failPendingCommands() {
  1528.         ReceiveCommand.abort(commands);
  1529.     }

  1530.     /**
  1531.      * Filter the list of commands according to result.
  1532.      *
  1533.      * @param want
  1534.      *            desired status to filter by.
  1535.      * @return a copy of the command list containing only those commands with
  1536.      *         the desired status.
  1537.      * @since 5.7
  1538.      */
  1539.     protected List<ReceiveCommand> filterCommands(Result want) {
  1540.         return ReceiveCommand.filter(commands, want);
  1541.     }

  1542.     /**
  1543.      * Execute commands to update references.
  1544.      * @since 5.7
  1545.      */
  1546.     protected void executeCommands() {
  1547.         List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED);
  1548.         if (toApply.isEmpty())
  1549.             return;

  1550.         ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  1551.         if (sideBand) {
  1552.             SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  1553.             pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  1554.             updating = pm;
  1555.         }

  1556.         BatchRefUpdate batch = db.getRefDatabase().newBatchUpdate();
  1557.         batch.setAllowNonFastForwards(isAllowNonFastForwards());
  1558.         batch.setAtomic(isAtomic());
  1559.         batch.setRefLogIdent(getRefLogIdent());
  1560.         batch.setRefLogMessage("push", true); //$NON-NLS-1$
  1561.         batch.addCommand(toApply);
  1562.         try {
  1563.             batch.setPushCertificate(getPushCertificate());
  1564.             batch.execute(walk, updating);
  1565.         } catch (IOException e) {
  1566.             receiveCommandErrorHandler.handleBatchRefUpdateException(toApply,
  1567.                     e);
  1568.         }
  1569.     }

  1570.     /**
  1571.      * Send a status report.
  1572.      *
  1573.      * @param unpackError
  1574.      *            an error that occurred during unpacking, or {@code null}
  1575.      * @throws java.io.IOException
  1576.      *             an error occurred writing the status report.
  1577.      * @since 5.6
  1578.      */
  1579.     private void sendStatusReport(Throwable unpackError) throws IOException {
  1580.         Reporter out = new Reporter() {
  1581.             @Override
  1582.             void sendString(String s) throws IOException {
  1583.                 if (reportStatus) {
  1584.                     pckOut.writeString(s + "\n"); //$NON-NLS-1$
  1585.                 } else if (msgOut != null) {
  1586.                     msgOut.write(Constants.encode(s + "\n")); //$NON-NLS-1$
  1587.                 }
  1588.             }
  1589.         };

  1590.         try {
  1591.             if (unpackError != null) {
  1592.                 out.sendString("unpack error " + unpackError.getMessage()); //$NON-NLS-1$
  1593.                 if (reportStatus) {
  1594.                     for (ReceiveCommand cmd : commands) {
  1595.                         out.sendString("ng " + cmd.getRefName() //$NON-NLS-1$
  1596.                                 + " n/a (unpacker error)"); //$NON-NLS-1$
  1597.                     }
  1598.                 }
  1599.                 return;
  1600.             }

  1601.             if (reportStatus) {
  1602.                 out.sendString("unpack ok"); //$NON-NLS-1$
  1603.             }
  1604.             for (ReceiveCommand cmd : commands) {
  1605.                 if (cmd.getResult() == Result.OK) {
  1606.                     if (reportStatus) {
  1607.                         out.sendString("ok " + cmd.getRefName()); //$NON-NLS-1$
  1608.                     }
  1609.                     continue;
  1610.                 }

  1611.                 final StringBuilder r = new StringBuilder();
  1612.                 if (reportStatus) {
  1613.                     r.append("ng ").append(cmd.getRefName()).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
  1614.                 } else {
  1615.                     r.append(" ! [rejected] ").append(cmd.getRefName()) //$NON-NLS-1$
  1616.                             .append(" ("); //$NON-NLS-1$
  1617.                 }

  1618.                 if (cmd.getResult() == Result.REJECTED_MISSING_OBJECT) {
  1619.                     if (cmd.getMessage() == null)
  1620.                         r.append("missing object(s)"); //$NON-NLS-1$
  1621.                     else if (cmd.getMessage()
  1622.                             .length() == Constants.OBJECT_ID_STRING_LENGTH) {
  1623.                         // TODO: Using get/setMessage to store an OID is a
  1624.                         // misuse. The caller should set a full error message.
  1625.                         r.append("object "); //$NON-NLS-1$
  1626.                         r.append(cmd.getMessage());
  1627.                         r.append(" missing"); //$NON-NLS-1$
  1628.                     } else {
  1629.                         r.append(cmd.getMessage());
  1630.                     }
  1631.                 } else if (cmd.getMessage() != null) {
  1632.                     r.append(cmd.getMessage());
  1633.                 } else {
  1634.                     switch (cmd.getResult()) {
  1635.                     case NOT_ATTEMPTED:
  1636.                         r.append("server bug; ref not processed"); //$NON-NLS-1$
  1637.                         break;

  1638.                     case REJECTED_NOCREATE:
  1639.                         r.append("creation prohibited"); //$NON-NLS-1$
  1640.                         break;

  1641.                     case REJECTED_NODELETE:
  1642.                         r.append("deletion prohibited"); //$NON-NLS-1$
  1643.                         break;

  1644.                     case REJECTED_NONFASTFORWARD:
  1645.                         r.append("non-fast forward"); //$NON-NLS-1$
  1646.                         break;

  1647.                     case REJECTED_CURRENT_BRANCH:
  1648.                         r.append("branch is currently checked out"); //$NON-NLS-1$
  1649.                         break;

  1650.                     case REJECTED_OTHER_REASON:
  1651.                         r.append("unspecified reason"); //$NON-NLS-1$
  1652.                         break;

  1653.                     case LOCK_FAILURE:
  1654.                         r.append("failed to lock"); //$NON-NLS-1$
  1655.                         break;

  1656.                     case REJECTED_MISSING_OBJECT:
  1657.                     case OK:
  1658.                         // We shouldn't have reached this case (see 'ok' case
  1659.                         // above and if-statement above).
  1660.                         throw new AssertionError();
  1661.                     }
  1662.                 }

  1663.                 if (!reportStatus) {
  1664.                     r.append(")"); //$NON-NLS-1$
  1665.                 }
  1666.                 out.sendString(r.toString());
  1667.             }
  1668.         } finally {
  1669.             if (reportStatus) {
  1670.                 pckOut.end();
  1671.             }
  1672.         }
  1673.     }

  1674.     /**
  1675.      * Close and flush (if necessary) the underlying streams.
  1676.      *
  1677.      * @throws java.io.IOException
  1678.      */
  1679.     private void close() throws IOException {
  1680.         if (sideBand) {
  1681.             // If we are using side band, we need to send a final
  1682.             // flush-pkt to tell the remote peer the side band is
  1683.             // complete and it should stop decoding. We need to
  1684.             // use the original output stream as rawOut is now the
  1685.             // side band data channel.
  1686.             //
  1687.             ((SideBandOutputStream) msgOut).flushBuffer();
  1688.             ((SideBandOutputStream) rawOut).flushBuffer();

  1689.             PacketLineOut plo = new PacketLineOut(origOut);
  1690.             plo.setFlushOnEnd(false);
  1691.             plo.end();
  1692.         }

  1693.         if (biDirectionalPipe) {
  1694.             // If this was a native git connection, flush the pipe for
  1695.             // the caller. For smart HTTP we don't do this flush and
  1696.             // instead let the higher level HTTP servlet code do it.
  1697.             //
  1698.             if (!sideBand && msgOut != null)
  1699.                 msgOut.flush();
  1700.             rawOut.flush();
  1701.         }
  1702.     }

  1703.     /**
  1704.      * Release any resources used by this object.
  1705.      *
  1706.      * @throws java.io.IOException
  1707.      *             the pack could not be unlocked.
  1708.      */
  1709.     private void release() throws IOException {
  1710.         walk.close();
  1711.         unlockPack();
  1712.         timeoutIn = null;
  1713.         rawIn = null;
  1714.         rawOut = null;
  1715.         msgOut = null;
  1716.         pckIn = null;
  1717.         pckOut = null;
  1718.         refs = null;
  1719.         // Keep the capabilities. If responses are sent after this release
  1720.         // we need to remember at least whether sideband communication has to be
  1721.         // used
  1722.         commands = null;
  1723.         if (timer != null) {
  1724.             try {
  1725.                 timer.terminate();
  1726.             } finally {
  1727.                 timer = null;
  1728.             }
  1729.         }
  1730.     }

  1731.     /** Interface for reporting status messages. */
  1732.     abstract static class Reporter {
  1733.         abstract void sendString(String s) throws IOException;
  1734.     }

  1735.     /**
  1736.      * Get the push certificate used to verify the pusher's identity.
  1737.      * <p>
  1738.      * Only valid after commands are read from the wire.
  1739.      *
  1740.      * @return the parsed certificate, or null if push certificates are disabled
  1741.      *         or no cert was presented by the client.
  1742.      * @since 4.1
  1743.      */
  1744.     public PushCertificate getPushCertificate() {
  1745.         return pushCert;
  1746.     }

  1747.     /**
  1748.      * Set the push certificate used to verify the pusher's identity.
  1749.      * <p>
  1750.      * Should only be called if reconstructing an instance without going through
  1751.      * the normal {@link #recvCommands()} flow.
  1752.      *
  1753.      * @param cert
  1754.      *            the push certificate to set.
  1755.      * @since 4.1
  1756.      */
  1757.     public void setPushCertificate(PushCertificate cert) {
  1758.         pushCert = cert;
  1759.     }

  1760.     /**
  1761.      * Gets an unmodifiable view of the option strings associated with the push.
  1762.      *
  1763.      * @return an unmodifiable view of pushOptions, or null (if pushOptions is).
  1764.      * @since 4.5
  1765.      */
  1766.     @Nullable
  1767.     public List<String> getPushOptions() {
  1768.         if (isAllowPushOptions() && usePushOptions) {
  1769.             return Collections.unmodifiableList(pushOptions);
  1770.         }

  1771.         // The client doesn't support push options. Return null to
  1772.         // distinguish this from the case where the client declared support
  1773.         // for push options and sent an empty list of them.
  1774.         return null;
  1775.     }

  1776.     /**
  1777.      * Set the push options supplied by the client.
  1778.      * <p>
  1779.      * Should only be called if reconstructing an instance without going through
  1780.      * the normal {@link #recvCommands()} flow.
  1781.      *
  1782.      * @param options
  1783.      *            the list of options supplied by the client. The
  1784.      *            {@code ReceivePack} instance takes ownership of this list.
  1785.      *            Callers are encouraged to first create a copy if the list may
  1786.      *            be modified later.
  1787.      * @since 4.5
  1788.      */
  1789.     public void setPushOptions(@Nullable List<String> options) {
  1790.         usePushOptions = options != null;
  1791.         pushOptions = options;
  1792.     }

  1793.     /**
  1794.      * Get the hook invoked before updates occur.
  1795.      *
  1796.      * @return the hook invoked before updates occur.
  1797.      */
  1798.     public PreReceiveHook getPreReceiveHook() {
  1799.         return preReceive;
  1800.     }

  1801.     /**
  1802.      * Set the hook which is invoked prior to commands being executed.
  1803.      * <p>
  1804.      * Only valid commands (those which have no obvious errors according to the
  1805.      * received input and this instance's configuration) are passed into the
  1806.      * hook. The hook may mark a command with a result of any value other than
  1807.      * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#NOT_ATTEMPTED} to
  1808.      * block its execution.
  1809.      * <p>
  1810.      * The hook may be called with an empty command collection if the current
  1811.      * set is completely invalid.
  1812.      *
  1813.      * @param h
  1814.      *            the hook instance; may be null to disable the hook.
  1815.      */
  1816.     public void setPreReceiveHook(PreReceiveHook h) {
  1817.         preReceive = h != null ? h : PreReceiveHook.NULL;
  1818.     }

  1819.     /**
  1820.      * Get the hook invoked after updates occur.
  1821.      *
  1822.      * @return the hook invoked after updates occur.
  1823.      */
  1824.     public PostReceiveHook getPostReceiveHook() {
  1825.         return postReceive;
  1826.     }

  1827.     /**
  1828.      * Set the hook which is invoked after commands are executed.
  1829.      * <p>
  1830.      * Only successful commands (type is
  1831.      * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#OK}) are passed
  1832.      * into the hook. The hook may be called with an empty command collection if
  1833.      * the current set all resulted in an error.
  1834.      *
  1835.      * @param h
  1836.      *            the hook instance; may be null to disable the hook.
  1837.      */
  1838.     public void setPostReceiveHook(PostReceiveHook h) {
  1839.         postReceive = h != null ? h : PostReceiveHook.NULL;
  1840.     }

  1841.     /**
  1842.      * Get the current unpack error handler.
  1843.      *
  1844.      * @return the current unpack error handler.
  1845.      * @since 5.8
  1846.      */
  1847.     public UnpackErrorHandler getUnpackErrorHandler() {
  1848.         return unpackErrorHandler;
  1849.     }

  1850.     /**
  1851.      * @param unpackErrorHandler
  1852.      *            the unpackErrorHandler to set
  1853.      * @since 5.7
  1854.      */
  1855.     public void setUnpackErrorHandler(UnpackErrorHandler unpackErrorHandler) {
  1856.         this.unpackErrorHandler = unpackErrorHandler;
  1857.     }

  1858.     /**
  1859.      * Set whether this class will report command failures as warning messages
  1860.      * before sending the command results.
  1861.      *
  1862.      * @param echo
  1863.      *            if true this class will report command failures as warning
  1864.      *            messages before sending the command results. This is usually
  1865.      *            not necessary, but may help buggy Git clients that discard the
  1866.      *            errors when all branches fail.
  1867.      * @deprecated no widely used Git versions need this any more
  1868.      */
  1869.     @Deprecated
  1870.     public void setEchoCommandFailures(boolean echo) {
  1871.         // No-op.
  1872.     }

  1873.     /**
  1874.      * Execute the receive task on the socket.
  1875.      *
  1876.      * @param input
  1877.      *            raw input to read client commands and pack data from. Caller
  1878.      *            must ensure the input is buffered, otherwise read performance
  1879.      *            may suffer.
  1880.      * @param output
  1881.      *            response back to the Git network client. Caller must ensure
  1882.      *            the output is buffered, otherwise write performance may
  1883.      *            suffer.
  1884.      * @param messages
  1885.      *            secondary "notice" channel to send additional messages out
  1886.      *            through. When run over SSH this should be tied back to the
  1887.      *            standard error channel of the command execution. For most
  1888.      *            other network connections this should be null.
  1889.      * @throws java.io.IOException
  1890.      */
  1891.     public void receive(final InputStream input, final OutputStream output,
  1892.             final OutputStream messages) throws IOException {
  1893.         init(input, output, messages);
  1894.         try {
  1895.             service();
  1896.         } catch (PackProtocolException e) {
  1897.             fatalError(e.getMessage());
  1898.             throw e;
  1899.         } catch (InputOverLimitIOException e) {
  1900.             String msg = JGitText.get().tooManyCommands;
  1901.             fatalError(msg);
  1902.             throw new PackProtocolException(msg, e);
  1903.         } finally {
  1904.             try {
  1905.                 close();
  1906.             } finally {
  1907.                 release();
  1908.             }
  1909.         }
  1910.     }

  1911.     /**
  1912.      * Execute the receive task on the socket.
  1913.      *
  1914.      * <p>
  1915.      * Same as {@link #receive}, but the exceptions are not reported to the
  1916.      * client yet.
  1917.      *
  1918.      * @param input
  1919.      *            raw input to read client commands and pack data from. Caller
  1920.      *            must ensure the input is buffered, otherwise read performance
  1921.      *            may suffer.
  1922.      * @param output
  1923.      *            response back to the Git network client. Caller must ensure
  1924.      *            the output is buffered, otherwise write performance may
  1925.      *            suffer.
  1926.      * @param messages
  1927.      *            secondary "notice" channel to send additional messages out
  1928.      *            through. When run over SSH this should be tied back to the
  1929.      *            standard error channel of the command execution. For most
  1930.      *            other network connections this should be null.
  1931.      * @throws java.io.IOException
  1932.      * @since 5.7
  1933.      */
  1934.     public void receiveWithExceptionPropagation(InputStream input,
  1935.             OutputStream output, OutputStream messages) throws IOException {
  1936.         init(input, output, messages);
  1937.         try {
  1938.             service();
  1939.         } finally {
  1940.             try {
  1941.                 close();
  1942.             } finally {
  1943.                 release();
  1944.             }
  1945.         }
  1946.     }

  1947.     private void service() throws IOException {
  1948.         if (isBiDirectionalPipe()) {
  1949.             sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  1950.             pckOut.flush();
  1951.         } else
  1952.             getAdvertisedOrDefaultRefs();
  1953.         if (hasError())
  1954.             return;

  1955.         recvCommands();

  1956.         if (hasCommands()) {
  1957.             try (PostReceiveExecutor e = new PostReceiveExecutor()) {
  1958.                 if (needPack()) {
  1959.                     try {
  1960.                         receivePackAndCheckConnectivity();
  1961.                     } catch (IOException | RuntimeException
  1962.                             | SubmoduleValidationException | Error err) {
  1963.                         unlockPack();
  1964.                         unpackErrorHandler.handleUnpackException(err);
  1965.                         throw new UnpackException(err);
  1966.                     }
  1967.                 }

  1968.                 try {
  1969.                     setAtomic(isCapabilityEnabled(CAPABILITY_ATOMIC));

  1970.                     validateCommands();
  1971.                     if (atomic && anyRejects()) {
  1972.                         failPendingCommands();
  1973.                     }

  1974.                     preReceive.onPreReceive(
  1975.                             this, filterCommands(Result.NOT_ATTEMPTED));
  1976.                     if (atomic && anyRejects()) {
  1977.                         failPendingCommands();
  1978.                     }
  1979.                     executeCommands();
  1980.                 } finally {
  1981.                     unlockPack();
  1982.                 }

  1983.                 sendStatusReport(null);
  1984.             }
  1985.             autoGc();
  1986.         }
  1987.     }

  1988.     private void autoGc() {
  1989.         Repository repo = getRepository();
  1990.         if (!repo.getConfig().getBoolean(ConfigConstants.CONFIG_RECEIVE_SECTION,
  1991.                 ConfigConstants.CONFIG_KEY_AUTOGC, true)) {
  1992.             return;
  1993.         }
  1994.         repo.autoGC(NullProgressMonitor.INSTANCE);
  1995.     }

  1996.     static ReceiveCommand parseCommand(String line)
  1997.             throws PackProtocolException {
  1998.         if (line == null || line.length() < 83) {
  1999.             throw new PackProtocolException(
  2000.                     JGitText.get().errorInvalidProtocolWantedOldNewRef);
  2001.         }
  2002.         String oldStr = line.substring(0, 40);
  2003.         String newStr = line.substring(41, 81);
  2004.         ObjectId oldId, newId;
  2005.         try {
  2006.             oldId = ObjectId.fromString(oldStr);
  2007.             newId = ObjectId.fromString(newStr);
  2008.         } catch (InvalidObjectIdException e) {
  2009.             throw new PackProtocolException(
  2010.                     JGitText.get().errorInvalidProtocolWantedOldNewRef, e);
  2011.         }
  2012.         String name = line.substring(82);
  2013.         if (!Repository.isValidRefName(name)) {
  2014.             throw new PackProtocolException(
  2015.                     JGitText.get().errorInvalidProtocolWantedOldNewRef);
  2016.         }
  2017.         return new ReceiveCommand(oldId, newId, name);
  2018.     }

  2019.     private class PostReceiveExecutor implements AutoCloseable {
  2020.         @Override
  2021.         public void close() {
  2022.             postReceive.onPostReceive(ReceivePack.this,
  2023.                     filterCommands(Result.OK));
  2024.         }
  2025.     }

  2026.     private class DefaultUnpackErrorHandler implements UnpackErrorHandler {
  2027.         @Override
  2028.         public void handleUnpackException(Throwable t) throws IOException {
  2029.             sendStatusReport(t);
  2030.         }
  2031.     }
  2032. }