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.GitProtocolConstants.PACKET_ERR;
  22. import static org.eclipse.jgit.transport.GitProtocolConstants.PACKET_SHALLOW;
  23. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SESSION_ID;
  24. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_DATA;
  25. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_ERROR;
  26. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_PROGRESS;
  27. import static org.eclipse.jgit.transport.SideBandOutputStream.MAX_BUF;

  28. import java.io.EOFException;
  29. import java.io.IOException;
  30. import java.io.InputStream;
  31. import java.io.OutputStream;
  32. import java.io.UncheckedIOException;
  33. import java.text.MessageFormat;
  34. import java.util.ArrayList;
  35. import java.util.Collections;
  36. import java.util.HashMap;
  37. import java.util.HashSet;
  38. import java.util.List;
  39. import java.util.Map;
  40. import java.util.Set;
  41. import java.util.concurrent.TimeUnit;
  42. import java.util.function.Function;
  43. import java.util.stream.Collectors;

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

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

  95.         /**
  96.          * Parse the first line of a receive-pack request.
  97.          *
  98.          * @param line
  99.          *            line from the client.
  100.          */
  101.         public FirstLine(String line) {
  102.             command = FirstCommand.fromLine(line);
  103.         }

  104.         /** @return non-capabilities part of the line. */
  105.         public String getLine() {
  106.             return command.getLine();
  107.         }

  108.         /** @return capabilities parsed from the line. */
  109.         public Set<String> getCapabilities() {
  110.             Set<String> reconstructedCapabilites = new HashSet<>();
  111.             for (Map.Entry<String, String> e : command.getCapabilities()
  112.                     .entrySet()) {
  113.                 String cap = e.getValue() == null ? e.getKey()
  114.                         : e.getKey() + "=" + e.getValue(); //$NON-NLS-1$
  115.                 reconstructedCapabilites.add(cap);
  116.             }

  117.             return reconstructedCapabilites;
  118.         }
  119.     }

  120.     /** Database we write the stored objects into. */
  121.     private final Repository db;

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

  124.     /**
  125.      * Is the client connection a bi-directional socket or pipe?
  126.      * <p>
  127.      * If true, this class assumes it can perform multiple read and write cycles
  128.      * with the client over the input and output streams. This matches the
  129.      * functionality available with a standard TCP/IP connection, or a local
  130.      * operating system or in-memory pipe.
  131.      * <p>
  132.      * If false, this class runs in a read everything then output results mode,
  133.      * making it suitable for single round-trip systems RPCs such as HTTP.
  134.      */
  135.     private boolean biDirectionalPipe = true;

  136.     /** Expecting data after the pack footer */
  137.     private boolean expectDataAfterPackFooter;

  138.     /** Should an incoming transfer validate objects? */
  139.     private ObjectChecker objectChecker;

  140.     /** Should an incoming transfer permit create requests? */
  141.     private boolean allowCreates;

  142.     /** Should an incoming transfer permit delete requests? */
  143.     private boolean allowAnyDeletes;

  144.     private boolean allowBranchDeletes;

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

  147.     /** Should an incoming transfer permit push options? **/
  148.     private boolean allowPushOptions;

  149.     /**
  150.      * Should the requested ref updates be performed as a single atomic
  151.      * transaction?
  152.      */
  153.     private boolean atomic;

  154.     private boolean allowOfsDelta;

  155.     private boolean allowQuiet = true;

  156.     /** Should the server advertise and accept the session-id capability. */
  157.     private boolean allowReceiveClientSID;

  158.     /** Identity to record action as within the reflog. */
  159.     private PersonIdent refLogIdent;

  160.     /** Hook used while advertising the refs to the client. */
  161.     private AdvertiseRefsHook advertiseRefsHook;

  162.     /** Filter used while advertising the refs to the client. */
  163.     private RefFilter refFilter;

  164.     /** Timeout in seconds to wait for client interaction. */
  165.     private int timeout;

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

  168.     private TimeoutInputStream timeoutIn;

  169.     // Original stream passed to init(), since rawOut may be wrapped in a
  170.     // sideband.
  171.     private OutputStream origOut;

  172.     /** Raw input stream. */
  173.     private InputStream rawIn;

  174.     /** Raw output stream. */
  175.     private OutputStream rawOut;

  176.     /** Optional message output stream. */
  177.     private OutputStream msgOut;

  178.     private SideBandOutputStream errOut;

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

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

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

  184.     private PackParser parser;

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

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

  189.     /** Capabilities requested by the client. */
  190.     private Map<String, String> enabledCapabilities;

  191.     /** Session ID sent from the client. Null if none was received. */
  192.     private String clientSID;

  193.     String userAgent;

  194.     private Set<ObjectId> clientShallowCommits;

  195.     private List<ReceiveCommand> commands;

  196.     private long maxCommandBytes;

  197.     private long maxDiscardBytes;

  198.     private StringBuilder advertiseError;

  199.     /**
  200.      * If {@link BasePackPushConnection#CAPABILITY_SIDE_BAND_64K} is enabled.
  201.      */
  202.     private boolean sideBand;

  203.     private boolean quiet;

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

  206.     private boolean checkReferencedAreReachable;

  207.     /** Git object size limit */
  208.     private long maxObjectSizeLimit;

  209.     /** Total pack size limit */
  210.     private long maxPackSizeLimit = -1;

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

  213.     private PushCertificateParser pushCertificateParser;

  214.     private SignedPushConfig signedPushConfig;

  215.     private PushCertificate pushCert;

  216.     private ReceivedPackStatistics stats;

  217.     /**
  218.      * Connectivity checker to use.
  219.      * @since 5.7
  220.      */
  221.     protected ConnectivityChecker connectivityChecker = new FullConnectivityChecker();

  222.     /** Hook to validate the update commands before execution. */
  223.     private PreReceiveHook preReceive;

  224.     private ReceiveCommandErrorHandler receiveCommandErrorHandler = new ReceiveCommandErrorHandler() {
  225.         // Use the default implementation.
  226.     };

  227.     private UnpackErrorHandler unpackErrorHandler = new DefaultUnpackErrorHandler();

  228.     /** Hook to report on the commands after execution. */
  229.     private PostReceiveHook postReceive;

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

  232.     /** Whether the client intends to use push options. */
  233.     private boolean usePushOptions;
  234.     private List<String> pushOptions;

  235.     /**
  236.      * Create a new pack receive for an open repository.
  237.      *
  238.      * @param into
  239.      *            the destination repository.
  240.      */
  241.     public ReceivePack(Repository into) {
  242.         db = into;
  243.         walk = new RevWalk(db);
  244.         walk.setRetainBody(false);

  245.         TransferConfig tc = db.getConfig().get(TransferConfig.KEY);
  246.         objectChecker = tc.newReceiveObjectChecker();
  247.         allowReceiveClientSID = tc.isAllowReceiveClientSID();

  248.         ReceiveConfig rc = db.getConfig().get(ReceiveConfig::new);
  249.         allowCreates = rc.allowCreates;
  250.         allowAnyDeletes = true;
  251.         allowBranchDeletes = rc.allowDeletes;
  252.         allowNonFastForwards = rc.allowNonFastForwards;
  253.         allowOfsDelta = rc.allowOfsDelta;
  254.         allowPushOptions = rc.allowPushOptions;
  255.         maxCommandBytes = rc.maxCommandBytes;
  256.         maxDiscardBytes = rc.maxDiscardBytes;
  257.         advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  258.         refFilter = RefFilter.DEFAULT;
  259.         advertisedHaves = new HashSet<>();
  260.         clientShallowCommits = new HashSet<>();
  261.         signedPushConfig = rc.signedPush;
  262.         preReceive = PreReceiveHook.NULL;
  263.         postReceive = PostReceiveHook.NULL;
  264.     }

  265.     /** Configuration for receive operations. */
  266.     private static class ReceiveConfig {
  267.         final boolean allowCreates;

  268.         final boolean allowDeletes;

  269.         final boolean allowNonFastForwards;

  270.         final boolean allowOfsDelta;

  271.         final boolean allowPushOptions;

  272.         final long maxCommandBytes;

  273.         final long maxDiscardBytes;

  274.         final SignedPushConfig signedPush;

  275.         ReceiveConfig(Config config) {
  276.             allowCreates = true;
  277.             allowDeletes = !config.getBoolean("receive", "denydeletes", false); //$NON-NLS-1$ //$NON-NLS-2$
  278.             allowNonFastForwards = !config.getBoolean("receive", //$NON-NLS-1$
  279.                     "denynonfastforwards", false); //$NON-NLS-1$
  280.             allowOfsDelta = config.getBoolean("repack", "usedeltabaseoffset", //$NON-NLS-1$ //$NON-NLS-2$
  281.                     true);
  282.             allowPushOptions = config.getBoolean("receive", "pushoptions", //$NON-NLS-1$ //$NON-NLS-2$
  283.                     false);
  284.             maxCommandBytes = config.getLong("receive", //$NON-NLS-1$
  285.                     "maxCommandBytes", //$NON-NLS-1$
  286.                     3 << 20);
  287.             maxDiscardBytes = config.getLong("receive", //$NON-NLS-1$
  288.                     "maxCommandDiscardBytes", //$NON-NLS-1$
  289.                     -1);
  290.             signedPush = SignedPushConfig.KEY.parse(config);
  291.         }
  292.     }

  293.     /**
  294.      * Output stream that wraps the current {@link #msgOut}.
  295.      * <p>
  296.      * We don't want to expose {@link #msgOut} directly because it can change
  297.      * several times over the course of a session.
  298.      */
  299.     class MessageOutputWrapper extends OutputStream {
  300.         @Override
  301.         public void write(int ch) {
  302.             if (msgOut != null) {
  303.                 try {
  304.                     msgOut.write(ch);
  305.                 } catch (IOException e) {
  306.                     // Ignore write failures.
  307.                 }
  308.             }
  309.         }

  310.         @Override
  311.         public void write(byte[] b, int off, int len) {
  312.             if (msgOut != null) {
  313.                 try {
  314.                     msgOut.write(b, off, len);
  315.                 } catch (IOException e) {
  316.                     // Ignore write failures.
  317.                 }
  318.             }
  319.         }

  320.         @Override
  321.         public void write(byte[] b) {
  322.             write(b, 0, b.length);
  323.         }

  324.         @Override
  325.         public void flush() {
  326.             if (msgOut != null) {
  327.                 try {
  328.                     msgOut.flush();
  329.                 } catch (IOException e) {
  330.                     // Ignore write failures.
  331.                 }
  332.             }
  333.         }
  334.     }

  335.     /**
  336.      * Get the repository this receive completes into.
  337.      *
  338.      * @return the repository this receive completes into.
  339.      */
  340.     public Repository getRepository() {
  341.         return db;
  342.     }

  343.     /**
  344.      * Get the RevWalk instance used by this connection.
  345.      *
  346.      * @return the RevWalk instance used by this connection.
  347.      */
  348.     public RevWalk getRevWalk() {
  349.         return walk;
  350.     }

  351.     /**
  352.      * Get refs which were advertised to the client.
  353.      *
  354.      * @return all refs which were advertised to the client, or null if
  355.      *         {@link #setAdvertisedRefs(Map, Set)} has not been called yet.
  356.      */
  357.     public Map<String, Ref> getAdvertisedRefs() {
  358.         return refs;
  359.     }

  360.     /**
  361.      * Set the refs advertised by this ReceivePack.
  362.      * <p>
  363.      * Intended to be called from a
  364.      * {@link org.eclipse.jgit.transport.PreReceiveHook}.
  365.      *
  366.      * @param allRefs
  367.      *            explicit set of references to claim as advertised by this
  368.      *            ReceivePack instance. This overrides any references that may
  369.      *            exist in the source repository. The map is passed to the
  370.      *            configured {@link #getRefFilter()}. If null, assumes all refs
  371.      *            were advertised.
  372.      * @param additionalHaves
  373.      *            explicit set of additional haves to claim as advertised. If
  374.      *            null, assumes the default set of additional haves from the
  375.      *            repository.
  376.      * @throws IOException
  377.      */
  378.     public void setAdvertisedRefs(Map<String, Ref> allRefs,
  379.             Set<ObjectId> additionalHaves) throws IOException {
  380.         refs = allRefs != null ? allRefs : getAllRefs();
  381.         refs = refFilter.filter(refs);
  382.         advertisedHaves.clear();

  383.         Ref head = refs.get(HEAD);
  384.         if (head != null && head.isSymbolic()) {
  385.             refs.remove(HEAD);
  386.         }

  387.         for (Ref ref : refs.values()) {
  388.             if (ref.getObjectId() != null) {
  389.                 advertisedHaves.add(ref.getObjectId());
  390.             }
  391.         }
  392.         if (additionalHaves != null) {
  393.             advertisedHaves.addAll(additionalHaves);
  394.         } else {
  395.             advertisedHaves.addAll(db.getAdditionalHaves());
  396.         }
  397.     }

  398.     /**
  399.      * Get objects advertised to the client.
  400.      *
  401.      * @return the set of objects advertised to the as present in this
  402.      *         repository, or null if {@link #setAdvertisedRefs(Map, Set)} has
  403.      *         not been called yet.
  404.      */
  405.     public final Set<ObjectId> getAdvertisedObjects() {
  406.         return advertisedHaves;
  407.     }

  408.     /**
  409.      * Whether this instance will validate all referenced, but not supplied by
  410.      * the client, objects are reachable from another reference.
  411.      *
  412.      * @return true if this instance will validate all referenced, but not
  413.      *         supplied by the client, objects are reachable from another
  414.      *         reference.
  415.      */
  416.     public boolean isCheckReferencedObjectsAreReachable() {
  417.         return checkReferencedAreReachable;
  418.     }

  419.     /**
  420.      * Validate all referenced but not supplied objects are reachable.
  421.      * <p>
  422.      * If enabled, this instance will verify that references to objects not
  423.      * contained within the received pack are already reachable through at least
  424.      * one other reference displayed as part of {@link #getAdvertisedRefs()}.
  425.      * <p>
  426.      * This feature is useful when the application doesn't trust the client to
  427.      * not provide a forged SHA-1 reference to an object, in an attempt to
  428.      * access parts of the DAG that they aren't allowed to see and which have
  429.      * been hidden from them via the configured
  430.      * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} or
  431.      * {@link org.eclipse.jgit.transport.RefFilter}.
  432.      * <p>
  433.      * Enabling this feature may imply at least some, if not all, of the same
  434.      * functionality performed by {@link #setCheckReceivedObjects(boolean)}.
  435.      * Applications are encouraged to enable both features, if desired.
  436.      *
  437.      * @param b
  438.      *            {@code true} to enable the additional check.
  439.      */
  440.     public void setCheckReferencedObjectsAreReachable(boolean b) {
  441.         this.checkReferencedAreReachable = b;
  442.     }

  443.     /**
  444.      * Whether this class expects a bi-directional pipe opened between the
  445.      * client and itself.
  446.      *
  447.      * @return true if this class expects a bi-directional pipe opened between
  448.      *         the client and itself. The default is true.
  449.      */
  450.     public boolean isBiDirectionalPipe() {
  451.         return biDirectionalPipe;
  452.     }

  453.     /**
  454.      * Whether this class will assume the socket is a fully bidirectional pipe
  455.      * between the two peers and takes advantage of that by first transmitting
  456.      * the known refs, then waiting to read commands.
  457.      *
  458.      * @param twoWay
  459.      *            if true, this class will assume the socket is a fully
  460.      *            bidirectional pipe between the two peers and takes advantage
  461.      *            of that by first transmitting the known refs, then waiting to
  462.      *            read commands. If false, this class assumes it must read the
  463.      *            commands before writing output and does not perform the
  464.      *            initial advertising.
  465.      */
  466.     public void setBiDirectionalPipe(boolean twoWay) {
  467.         biDirectionalPipe = twoWay;
  468.     }

  469.     /**
  470.      * Whether there is data expected after the pack footer.
  471.      *
  472.      * @return {@code true} if there is data expected after the pack footer.
  473.      */
  474.     public boolean isExpectDataAfterPackFooter() {
  475.         return expectDataAfterPackFooter;
  476.     }

  477.     /**
  478.      * Whether there is additional data in InputStream after pack.
  479.      *
  480.      * @param e
  481.      *            {@code true} if there is additional data in InputStream after
  482.      *            pack.
  483.      */
  484.     public void setExpectDataAfterPackFooter(boolean e) {
  485.         expectDataAfterPackFooter = e;
  486.     }

  487.     /**
  488.      * Whether this instance will verify received objects are formatted
  489.      * correctly.
  490.      *
  491.      * @return {@code true} if this instance will verify received objects are
  492.      *         formatted correctly. Validating objects requires more CPU time on
  493.      *         this side of the connection.
  494.      */
  495.     public boolean isCheckReceivedObjects() {
  496.         return objectChecker != null;
  497.     }

  498.     /**
  499.      * Whether to enable checking received objects
  500.      *
  501.      * @param check
  502.      *            {@code true} to enable checking received objects; false to
  503.      *            assume all received objects are valid.
  504.      * @see #setObjectChecker(ObjectChecker)
  505.      */
  506.     public void setCheckReceivedObjects(boolean check) {
  507.         if (check && objectChecker == null)
  508.             setObjectChecker(new ObjectChecker());
  509.         else if (!check && objectChecker != null)
  510.             setObjectChecker(null);
  511.     }

  512.     /**
  513.      * Set the object checking instance to verify each received object with
  514.      *
  515.      * @param impl
  516.      *            if non-null the object checking instance to verify each
  517.      *            received object with; null to disable object checking.
  518.      * @since 3.4
  519.      */
  520.     public void setObjectChecker(ObjectChecker impl) {
  521.         objectChecker = impl;
  522.     }

  523.     /**
  524.      * Whether the client can request refs to be created.
  525.      *
  526.      * @return {@code true} if the client can request refs to be created.
  527.      */
  528.     public boolean isAllowCreates() {
  529.         return allowCreates;
  530.     }

  531.     /**
  532.      * Whether to permit create ref commands to be processed.
  533.      *
  534.      * @param canCreate
  535.      *            {@code true} to permit create ref commands to be processed.
  536.      */
  537.     public void setAllowCreates(boolean canCreate) {
  538.         allowCreates = canCreate;
  539.     }

  540.     /**
  541.      * Whether the client can request refs to be deleted.
  542.      *
  543.      * @return {@code true} if the client can request refs to be deleted.
  544.      */
  545.     public boolean isAllowDeletes() {
  546.         return allowAnyDeletes;
  547.     }

  548.     /**
  549.      * Whether to permit delete ref commands to be processed.
  550.      *
  551.      * @param canDelete
  552.      *            {@code true} to permit delete ref commands to be processed.
  553.      */
  554.     public void setAllowDeletes(boolean canDelete) {
  555.         allowAnyDeletes = canDelete;
  556.     }

  557.     /**
  558.      * Whether the client can delete from {@code refs/heads/}.
  559.      *
  560.      * @return {@code true} if the client can delete from {@code refs/heads/}.
  561.      * @since 3.6
  562.      */
  563.     public boolean isAllowBranchDeletes() {
  564.         return allowBranchDeletes;
  565.     }

  566.     /**
  567.      * Configure whether to permit deletion of branches from the
  568.      * {@code refs/heads/} namespace.
  569.      *
  570.      * @param canDelete
  571.      *            {@code true} to permit deletion of branches from the
  572.      *            {@code refs/heads/} namespace.
  573.      * @since 3.6
  574.      */
  575.     public void setAllowBranchDeletes(boolean canDelete) {
  576.         allowBranchDeletes = canDelete;
  577.     }

  578.     /**
  579.      * Whether the client can request non-fast-forward updates of a ref,
  580.      * possibly making objects unreachable.
  581.      *
  582.      * @return {@code true} if the client can request non-fast-forward updates
  583.      *         of a ref, possibly making objects unreachable.
  584.      */
  585.     public boolean isAllowNonFastForwards() {
  586.         return allowNonFastForwards;
  587.     }

  588.     /**
  589.      * Configure whether to permit the client to ask for non-fast-forward
  590.      * updates of an existing ref.
  591.      *
  592.      * @param canRewind
  593.      *            {@code true} to permit the client to ask for non-fast-forward
  594.      *            updates of an existing ref.
  595.      */
  596.     public void setAllowNonFastForwards(boolean canRewind) {
  597.         allowNonFastForwards = canRewind;
  598.     }

  599.     /**
  600.      * Whether the client's commands should be performed as a single atomic
  601.      * transaction.
  602.      *
  603.      * @return {@code true} if the client's commands should be performed as a
  604.      *         single atomic transaction.
  605.      * @since 4.4
  606.      */
  607.     public boolean isAtomic() {
  608.         return atomic;
  609.     }

  610.     /**
  611.      * Configure whether to perform the client's commands as a single atomic
  612.      * transaction.
  613.      *
  614.      * @param atomic
  615.      *            {@code true} to perform the client's commands as a single
  616.      *            atomic transaction.
  617.      * @since 4.4
  618.      */
  619.     public void setAtomic(boolean atomic) {
  620.         this.atomic = atomic;
  621.     }

  622.     /**
  623.      * Get identity of the user making the changes in the reflog.
  624.      *
  625.      * @return identity of the user making the changes in the reflog.
  626.      */
  627.     public PersonIdent getRefLogIdent() {
  628.         return refLogIdent;
  629.     }

  630.     /**
  631.      * Set the identity of the user appearing in the affected reflogs.
  632.      * <p>
  633.      * The timestamp portion of the identity is ignored. A new identity with the
  634.      * current timestamp will be created automatically when the updates occur
  635.      * and the log records are written.
  636.      *
  637.      * @param pi
  638.      *            identity of the user. If null the identity will be
  639.      *            automatically determined based on the repository
  640.      *            configuration.
  641.      */
  642.     public void setRefLogIdent(PersonIdent pi) {
  643.         refLogIdent = pi;
  644.     }

  645.     /**
  646.      * Get the hook used while advertising the refs to the client
  647.      *
  648.      * @return the hook used while advertising the refs to the client
  649.      */
  650.     public AdvertiseRefsHook getAdvertiseRefsHook() {
  651.         return advertiseRefsHook;
  652.     }

  653.     /**
  654.      * Get the filter used while advertising the refs to the client
  655.      *
  656.      * @return the filter used while advertising the refs to the client
  657.      */
  658.     public RefFilter getRefFilter() {
  659.         return refFilter;
  660.     }

  661.     /**
  662.      * Set the hook used while advertising the refs to the client.
  663.      * <p>
  664.      * If the {@link org.eclipse.jgit.transport.AdvertiseRefsHook} chooses to
  665.      * call {@link #setAdvertisedRefs(Map,Set)}, only refs set by this hook
  666.      * <em>and</em> selected by the {@link org.eclipse.jgit.transport.RefFilter}
  667.      * will be shown to the client. Clients may still attempt to create or
  668.      * update a reference not advertised by the configured
  669.      * {@link org.eclipse.jgit.transport.AdvertiseRefsHook}. These attempts
  670.      * should be rejected by a matching
  671.      * {@link org.eclipse.jgit.transport.PreReceiveHook}.
  672.      *
  673.      * @param advertiseRefsHook
  674.      *            the hook; may be null to show all refs.
  675.      */
  676.     public void setAdvertiseRefsHook(AdvertiseRefsHook advertiseRefsHook) {
  677.         if (advertiseRefsHook != null)
  678.             this.advertiseRefsHook = advertiseRefsHook;
  679.         else
  680.             this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  681.     }

  682.     /**
  683.      * Set the filter used while advertising the refs to the client.
  684.      * <p>
  685.      * Only refs allowed by this filter will be shown to the client. The filter
  686.      * is run against the refs specified by the
  687.      * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} (if applicable).
  688.      *
  689.      * @param refFilter
  690.      *            the filter; may be null to show all refs.
  691.      */
  692.     public void setRefFilter(RefFilter refFilter) {
  693.         this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  694.     }

  695.     /**
  696.      * Get timeout (in seconds) before aborting an IO operation.
  697.      *
  698.      * @return timeout (in seconds) before aborting an IO operation.
  699.      */
  700.     public int getTimeout() {
  701.         return timeout;
  702.     }

  703.     /**
  704.      * Set the timeout before willing to abort an IO call.
  705.      *
  706.      * @param seconds
  707.      *            number of seconds to wait (with no data transfer occurring)
  708.      *            before aborting an IO read or write operation with the
  709.      *            connected client.
  710.      */
  711.     public void setTimeout(int seconds) {
  712.         timeout = seconds;
  713.     }

  714.     /**
  715.      * Set the maximum number of command bytes to read from the client.
  716.      *
  717.      * @param limit
  718.      *            command limit in bytes; if 0 there is no limit.
  719.      * @since 4.7
  720.      */
  721.     public void setMaxCommandBytes(long limit) {
  722.         maxCommandBytes = limit;
  723.     }

  724.     /**
  725.      * Set the maximum number of command bytes to discard from the client.
  726.      * <p>
  727.      * Discarding remaining bytes allows this instance to consume the rest of
  728.      * the command block and send a human readable over-limit error via the
  729.      * side-band channel. If the client sends an excessive number of bytes this
  730.      * limit kicks in and the instance disconnects, resulting in a non-specific
  731.      * 'pipe closed', 'end of stream', or similar generic error at the client.
  732.      * <p>
  733.      * When the limit is set to {@code -1} the implementation will default to
  734.      * the larger of {@code 3 * maxCommandBytes} or {@code 3 MiB}.
  735.      *
  736.      * @param limit
  737.      *            discard limit in bytes; if 0 there is no limit; if -1 the
  738.      *            implementation tries to set a reasonable default.
  739.      * @since 4.7
  740.      */
  741.     public void setMaxCommandDiscardBytes(long limit) {
  742.         maxDiscardBytes = limit;
  743.     }

  744.     /**
  745.      * Set the maximum allowed Git object size.
  746.      * <p>
  747.      * If an object is larger than the given size the pack-parsing will throw an
  748.      * exception aborting the receive-pack operation.
  749.      *
  750.      * @param limit
  751.      *            the Git object size limit. If zero then there is not limit.
  752.      */
  753.     public void setMaxObjectSizeLimit(long limit) {
  754.         maxObjectSizeLimit = limit;
  755.     }

  756.     /**
  757.      * Set the maximum allowed pack size.
  758.      * <p>
  759.      * A pack exceeding this size will be rejected.
  760.      *
  761.      * @param limit
  762.      *            the pack size limit, in bytes
  763.      * @since 3.3
  764.      */
  765.     public void setMaxPackSizeLimit(long limit) {
  766.         if (limit < 0)
  767.             throw new IllegalArgumentException(
  768.                     MessageFormat.format(JGitText.get().receivePackInvalidLimit,
  769.                             Long.valueOf(limit)));
  770.         maxPackSizeLimit = limit;
  771.     }

  772.     /**
  773.      * Check whether the client expects a side-band stream.
  774.      *
  775.      * @return true if the client has advertised a side-band capability, false
  776.      *         otherwise.
  777.      * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  778.      *             if the client's request has not yet been read from the wire,
  779.      *             so we do not know if they expect side-band. Note that the
  780.      *             client may have already written the request, it just has not
  781.      *             been read.
  782.      */
  783.     public boolean isSideBand() throws RequestNotYetReadException {
  784.         checkRequestWasRead();
  785.         return enabledCapabilities.containsKey(CAPABILITY_SIDE_BAND_64K);
  786.     }

  787.     /**
  788.      * Whether clients may request avoiding noisy progress messages.
  789.      *
  790.      * @return true if clients may request avoiding noisy progress messages.
  791.      * @since 4.0
  792.      */
  793.     public boolean isAllowQuiet() {
  794.         return allowQuiet;
  795.     }

  796.     /**
  797.      * Configure if clients may request the server skip noisy messages.
  798.      *
  799.      * @param allow
  800.      *            true to allow clients to request quiet behavior; false to
  801.      *            refuse quiet behavior and send messages anyway. This may be
  802.      *            necessary if processing is slow and the client-server network
  803.      *            connection can timeout.
  804.      * @since 4.0
  805.      */
  806.     public void setAllowQuiet(boolean allow) {
  807.         allowQuiet = allow;
  808.     }

  809.     /**
  810.      * Whether the server supports receiving push options.
  811.      *
  812.      * @return true if the server supports receiving push options.
  813.      * @since 4.5
  814.      */
  815.     public boolean isAllowPushOptions() {
  816.         return allowPushOptions;
  817.     }

  818.     /**
  819.      * Configure if the server supports receiving push options.
  820.      *
  821.      * @param allow
  822.      *            true to optionally accept option strings from the client.
  823.      * @since 4.5
  824.      */
  825.     public void setAllowPushOptions(boolean allow) {
  826.         allowPushOptions = allow;
  827.     }

  828.     /**
  829.      * True if the client wants less verbose output.
  830.      *
  831.      * @return true if the client has requested the server to be less verbose.
  832.      * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  833.      *             if the client's request has not yet been read from the wire,
  834.      *             so we do not know if they expect side-band. Note that the
  835.      *             client may have already written the request, it just has not
  836.      *             been read.
  837.      * @since 4.0
  838.      */
  839.     public boolean isQuiet() throws RequestNotYetReadException {
  840.         checkRequestWasRead();
  841.         return quiet;
  842.     }

  843.     /**
  844.      * Set the configuration for push certificate verification.
  845.      *
  846.      * @param cfg
  847.      *            new configuration; if this object is null or its
  848.      *            {@link SignedPushConfig#getCertNonceSeed()} is null, push
  849.      *            certificate verification will be disabled.
  850.      * @since 4.1
  851.      */
  852.     public void setSignedPushConfig(SignedPushConfig cfg) {
  853.         signedPushConfig = cfg;
  854.     }

  855.     private PushCertificateParser getPushCertificateParser() {
  856.         if (pushCertificateParser == null) {
  857.             pushCertificateParser = new PushCertificateParser(db,
  858.                     signedPushConfig);
  859.         }
  860.         return pushCertificateParser;
  861.     }

  862.     /**
  863.      * Get the user agent of the client.
  864.      * <p>
  865.      * If the client is new enough to use {@code agent=} capability that value
  866.      * will be returned. Older HTTP clients may also supply their version using
  867.      * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  868.      * header if both are available.
  869.      * <p>
  870.      * When an HTTP request has been received this method returns the HTTP
  871.      * {@code User-Agent} header value until capabilities have been parsed.
  872.      *
  873.      * @return user agent supplied by the client. Available only if the client
  874.      *         is new enough to advertise its user agent.
  875.      * @since 4.0
  876.      */
  877.     public String getPeerUserAgent() {
  878.         if (enabledCapabilities == null || enabledCapabilities.isEmpty()) {
  879.             return userAgent;
  880.         }

  881.         return enabledCapabilities.getOrDefault(OPTION_AGENT, userAgent);
  882.     }

  883.     /**
  884.      * Get all of the command received by the current request.
  885.      *
  886.      * @return all of the command received by the current request.
  887.      */
  888.     public List<ReceiveCommand> getAllCommands() {
  889.         return Collections.unmodifiableList(commands);
  890.     }

  891.     /**
  892.      * Set an error handler for {@link ReceiveCommand}.
  893.      *
  894.      * @param receiveCommandErrorHandler
  895.      * @since 5.7
  896.      */
  897.     public void setReceiveCommandErrorHandler(
  898.             ReceiveCommandErrorHandler receiveCommandErrorHandler) {
  899.         this.receiveCommandErrorHandler = receiveCommandErrorHandler;
  900.     }

  901.     /**
  902.      * Send an error message to the client.
  903.      * <p>
  904.      * If any error messages are sent before the references are advertised to
  905.      * the client, the errors will be sent instead of the advertisement and the
  906.      * receive operation will be aborted. All clients should receive and display
  907.      * such early stage errors.
  908.      * <p>
  909.      * If the reference advertisements have already been sent, messages are sent
  910.      * in a side channel. If the client doesn't support receiving messages, the
  911.      * message will be discarded, with no other indication to the caller or to
  912.      * the client.
  913.      * <p>
  914.      * {@link org.eclipse.jgit.transport.PreReceiveHook}s should always try to
  915.      * use
  916.      * {@link org.eclipse.jgit.transport.ReceiveCommand#setResult(Result, String)}
  917.      * with a result status of
  918.      * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#REJECTED_OTHER_REASON}
  919.      * to indicate any reasons for rejecting an update. Messages attached to a
  920.      * command are much more likely to be returned to the client.
  921.      *
  922.      * @param what
  923.      *            string describing the problem identified by the hook. The
  924.      *            string must not end with an LF, and must not contain an LF.
  925.      */
  926.     public void sendError(String what) {
  927.         if (refs == null) {
  928.             if (advertiseError == null)
  929.                 advertiseError = new StringBuilder();
  930.             advertiseError.append(what).append('\n');
  931.         } else {
  932.             msgOutWrapper.write(Constants.encode("error: " + what + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
  933.         }
  934.     }

  935.     private void fatalError(String msg) {
  936.         if (errOut != null) {
  937.             try {
  938.                 errOut.write(Constants.encode(msg));
  939.                 errOut.flush();
  940.             } catch (IOException e) {
  941.                 // Ignore write failures
  942.             }
  943.         } else {
  944.             sendError(msg);
  945.         }
  946.     }

  947.     /**
  948.      * Send a message to the client, if it supports receiving them.
  949.      * <p>
  950.      * If the client doesn't support receiving messages, the message will be
  951.      * discarded, with no other indication to the caller or to the client.
  952.      *
  953.      * @param what
  954.      *            string describing the problem identified by the hook. The
  955.      *            string must not end with an LF, and must not contain an LF.
  956.      */
  957.     public void sendMessage(String what) {
  958.         msgOutWrapper.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  959.     }

  960.     /**
  961.      * Get an underlying stream for sending messages to the client.
  962.      *
  963.      * @return an underlying stream for sending messages to the client.
  964.      */
  965.     public OutputStream getMessageOutputStream() {
  966.         return msgOutWrapper;
  967.     }

  968.     /**
  969.      * Get whether or not a pack has been received.
  970.      *
  971.      * This can be called before calling {@link #getPackSize()} to avoid causing
  972.      * {@code IllegalStateException} when the pack size was not set because no
  973.      * pack was received.
  974.      *
  975.      * @return true if a pack has been received.
  976.      * @since 5.6
  977.      */
  978.     public boolean hasReceivedPack() {
  979.         return packSize != null;
  980.     }

  981.     /**
  982.      * Get the size of the received pack file including the index size.
  983.      *
  984.      * This can only be called if the pack is already received.
  985.      *
  986.      * @return the size of the received pack including index size
  987.      * @throws java.lang.IllegalStateException
  988.      *             if called before the pack has been received
  989.      * @since 3.3
  990.      */
  991.     public long getPackSize() {
  992.         if (packSize != null)
  993.             return packSize.longValue();
  994.         throw new IllegalStateException(JGitText.get().packSizeNotSetYet);
  995.     }

  996.     /**
  997.      * Get the commits from the client's shallow file.
  998.      *
  999.      * @return if the client is a shallow repository, the list of edge commits
  1000.      *         that define the client's shallow boundary. Empty set if the
  1001.      *         client is earlier than Git 1.9, or is a full clone.
  1002.      */
  1003.     private Set<ObjectId> getClientShallowCommits() {
  1004.         return clientShallowCommits;
  1005.     }

  1006.     /**
  1007.      * Whether any commands to be executed have been read.
  1008.      *
  1009.      * @return {@code true} if any commands to be executed have been read.
  1010.      */
  1011.     private boolean hasCommands() {
  1012.         return !commands.isEmpty();
  1013.     }

  1014.     /**
  1015.      * Whether an error occurred that should be advertised.
  1016.      *
  1017.      * @return true if an error occurred that should be advertised.
  1018.      */
  1019.     private boolean hasError() {
  1020.         return advertiseError != null;
  1021.     }

  1022.     /**
  1023.      * Initialize the instance with the given streams.
  1024.      *
  1025.      * Visible for out-of-tree subclasses (e.g. tests that need to set the
  1026.      * streams without going through the {@link #service()} method).
  1027.      *
  1028.      * @param input
  1029.      *            raw input to read client commands and pack data from. Caller
  1030.      *            must ensure the input is buffered, otherwise read performance
  1031.      *            may suffer.
  1032.      * @param output
  1033.      *            response back to the Git network client. Caller must ensure
  1034.      *            the output is buffered, otherwise write performance may
  1035.      *            suffer.
  1036.      * @param messages
  1037.      *            secondary "notice" channel to send additional messages out
  1038.      *            through. When run over SSH this should be tied back to the
  1039.      *            standard error channel of the command execution. For most
  1040.      *            other network connections this should be null.
  1041.      */
  1042.     protected void init(final InputStream input, final OutputStream output,
  1043.             final OutputStream messages) {
  1044.         origOut = output;
  1045.         rawIn = input;
  1046.         rawOut = output;
  1047.         msgOut = messages;

  1048.         if (timeout > 0) {
  1049.             final Thread caller = Thread.currentThread();
  1050.             timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  1051.             timeoutIn = new TimeoutInputStream(rawIn, timer);
  1052.             TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  1053.             timeoutIn.setTimeout(timeout * 1000);
  1054.             o.setTimeout(timeout * 1000);
  1055.             rawIn = timeoutIn;
  1056.             rawOut = o;
  1057.         }

  1058.         pckIn = new PacketLineIn(rawIn);
  1059.         pckOut = new PacketLineOut(rawOut);
  1060.         pckOut.setFlushOnEnd(false);

  1061.         enabledCapabilities = new HashMap<>();
  1062.         commands = new ArrayList<>();
  1063.     }

  1064.     /**
  1065.      * Get advertised refs, or the default if not explicitly advertised.
  1066.      *
  1067.      * @return advertised refs, or the default if not explicitly advertised.
  1068.      * @throws IOException
  1069.      */
  1070.     private Map<String, Ref> getAdvertisedOrDefaultRefs() throws IOException {
  1071.         if (refs == null)
  1072.             setAdvertisedRefs(null, null);
  1073.         return refs;
  1074.     }

  1075.     /**
  1076.      * Receive a pack from the stream and check connectivity if necessary.
  1077.      *
  1078.      * Visible for out-of-tree subclasses. Subclasses overriding this method
  1079.      * should invoke this implementation, as it alters the instance state (e.g.
  1080.      * it reads the pack from the input and parses it before running the
  1081.      * connectivity checks).
  1082.      *
  1083.      * @throws java.io.IOException
  1084.      *             an error occurred during unpacking or connectivity checking.
  1085.      * @throws LargeObjectException
  1086.      *             an large object needs to be opened for the check.
  1087.      * @throws SubmoduleValidationException
  1088.      *             fails to validate the submodule.
  1089.      */
  1090.     protected void receivePackAndCheckConnectivity() throws IOException,
  1091.             LargeObjectException, SubmoduleValidationException {
  1092.         receivePack();
  1093.         if (needCheckConnectivity()) {
  1094.             checkSubmodules();
  1095.             checkConnectivity();
  1096.         }
  1097.         parser = null;
  1098.     }

  1099.     /**
  1100.      * Unlock the pack written by this object.
  1101.      *
  1102.      * @throws java.io.IOException
  1103.      *             the pack could not be unlocked.
  1104.      */
  1105.     private void unlockPack() throws IOException {
  1106.         if (packLock != null) {
  1107.             packLock.unlock();
  1108.             packLock = null;
  1109.         }
  1110.     }

  1111.     /**
  1112.      * Generate an advertisement of available refs and capabilities.
  1113.      *
  1114.      * @param adv
  1115.      *            the advertisement formatter.
  1116.      * @throws java.io.IOException
  1117.      *             the formatter failed to write an advertisement.
  1118.      * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1119.      *             the hook denied advertisement.
  1120.      */
  1121.     public void sendAdvertisedRefs(RefAdvertiser adv)
  1122.             throws IOException, ServiceMayNotContinueException {
  1123.         if (advertiseError != null) {
  1124.             adv.writeOne(PACKET_ERR + advertiseError);
  1125.             return;
  1126.         }

  1127.         try {
  1128.             advertiseRefsHook.advertiseRefs(this);
  1129.         } catch (ServiceMayNotContinueException fail) {
  1130.             if (fail.getMessage() != null) {
  1131.                 adv.writeOne(PACKET_ERR + fail.getMessage());
  1132.                 fail.setOutput();
  1133.             }
  1134.             throw fail;
  1135.         }

  1136.         adv.init(db);
  1137.         adv.advertiseCapability(CAPABILITY_SIDE_BAND_64K);
  1138.         adv.advertiseCapability(CAPABILITY_DELETE_REFS);
  1139.         adv.advertiseCapability(CAPABILITY_REPORT_STATUS);
  1140.         if (allowReceiveClientSID) {
  1141.             adv.advertiseCapability(OPTION_SESSION_ID);
  1142.         }
  1143.         if (allowQuiet) {
  1144.             adv.advertiseCapability(CAPABILITY_QUIET);
  1145.         }
  1146.         String nonce = getPushCertificateParser().getAdvertiseNonce();
  1147.         if (nonce != null) {
  1148.             adv.advertiseCapability(nonce);
  1149.         }
  1150.         if (db.getRefDatabase().performsAtomicTransactions()) {
  1151.             adv.advertiseCapability(CAPABILITY_ATOMIC);
  1152.         }
  1153.         if (allowOfsDelta) {
  1154.             adv.advertiseCapability(CAPABILITY_OFS_DELTA);
  1155.         }
  1156.         if (allowPushOptions) {
  1157.             adv.advertiseCapability(CAPABILITY_PUSH_OPTIONS);
  1158.         }
  1159.         adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  1160.         adv.send(getAdvertisedOrDefaultRefs().values());
  1161.         for (ObjectId obj : advertisedHaves) {
  1162.             adv.advertiseHave(obj);
  1163.         }
  1164.         if (adv.isEmpty()) {
  1165.             adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  1166.         }
  1167.         adv.end();
  1168.     }

  1169.     /**
  1170.      * Returns the statistics on the received pack if available. This should be
  1171.      * called after {@link #receivePack} is called.
  1172.      *
  1173.      * @return ReceivedPackStatistics
  1174.      * @since 4.6
  1175.      */
  1176.     @Nullable
  1177.     public ReceivedPackStatistics getReceivedPackStatistics() {
  1178.         return stats;
  1179.     }

  1180.     /**
  1181.      * Extract the full list of refs from the ref-db.
  1182.      *
  1183.      * @return Map of all refname/ref
  1184.      */
  1185.     private Map<String, Ref> getAllRefs() {
  1186.         try {
  1187.             return db.getRefDatabase().getRefs().stream()
  1188.                     .collect(Collectors.toMap(Ref::getName,
  1189.                             Function.identity()));
  1190.         } catch (IOException e) {
  1191.             throw new UncheckedIOException(e);
  1192.         }
  1193.     }

  1194.     /**
  1195.      * Receive a list of commands from the input.
  1196.      *
  1197.      * @throws java.io.IOException
  1198.      */
  1199.     private void recvCommands() throws IOException {
  1200.         PacketLineIn pck = maxCommandBytes > 0
  1201.                 ? new PacketLineIn(rawIn, maxCommandBytes)
  1202.                 : pckIn;
  1203.         PushCertificateParser certParser = getPushCertificateParser();
  1204.         boolean firstPkt = true;
  1205.         try {
  1206.             for (;;) {
  1207.                 String line;
  1208.                 try {
  1209.                     line = pck.readString();
  1210.                 } catch (EOFException eof) {
  1211.                     if (commands.isEmpty())
  1212.                         return;
  1213.                     throw eof;
  1214.                 }
  1215.                 if (PacketLineIn.isEnd(line)) {
  1216.                     break;
  1217.                 }

  1218.                 int len = PACKET_SHALLOW.length() + 40;
  1219.                 if (line.length() >= len && line.startsWith(PACKET_SHALLOW)) {
  1220.                     parseShallow(line.substring(PACKET_SHALLOW.length(), len));
  1221.                     continue;
  1222.                 }

  1223.                 if (firstPkt) {
  1224.                     firstPkt = false;
  1225.                     FirstCommand firstLine = FirstCommand.fromLine(line);
  1226.                     enabledCapabilities = firstLine.getCapabilities();
  1227.                     line = firstLine.getLine();
  1228.                     enableCapabilities();

  1229.                     if (line.equals(GitProtocolConstants.OPTION_PUSH_CERT)) {
  1230.                         certParser.receiveHeader(pck, !isBiDirectionalPipe());
  1231.                         continue;
  1232.                     }
  1233.                 }

  1234.                 if (line.equals(PushCertificateParser.BEGIN_SIGNATURE)) {
  1235.                     certParser.receiveSignature(pck);
  1236.                     continue;
  1237.                 }

  1238.                 ReceiveCommand cmd = parseCommand(line);
  1239.                 if (cmd.getRefName().equals(Constants.HEAD)) {
  1240.                     cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
  1241.                 } else {
  1242.                     cmd.setRef(refs.get(cmd.getRefName()));
  1243.                 }
  1244.                 commands.add(cmd);
  1245.                 if (certParser.enabled()) {
  1246.                     certParser.addCommand(cmd);
  1247.                 }
  1248.             }
  1249.             pushCert = certParser.build();
  1250.             if (hasCommands()) {
  1251.                 readPostCommands(pck);
  1252.             }
  1253.         } catch (Throwable t) {
  1254.             discardCommands();
  1255.             throw t;
  1256.         }
  1257.     }

  1258.     private void discardCommands() {
  1259.         if (sideBand) {
  1260.             long max = maxDiscardBytes;
  1261.             if (max < 0) {
  1262.                 max = Math.max(3 * maxCommandBytes, 3L << 20);
  1263.             }
  1264.             try {
  1265.                 new PacketLineIn(rawIn, max).discardUntilEnd();
  1266.             } catch (IOException e) {
  1267.                 // Ignore read failures attempting to discard.
  1268.             }
  1269.         }
  1270.     }

  1271.     private void parseShallow(String idStr) throws PackProtocolException {
  1272.         ObjectId id;
  1273.         try {
  1274.             id = ObjectId.fromString(idStr);
  1275.         } catch (InvalidObjectIdException e) {
  1276.             throw new PackProtocolException(e.getMessage(), e);
  1277.         }
  1278.         clientShallowCommits.add(id);
  1279.     }

  1280.     /**
  1281.      * @param in
  1282.      *            request stream.
  1283.      * @throws IOException
  1284.      *             request line cannot be read.
  1285.      */
  1286.     void readPostCommands(PacketLineIn in) throws IOException {
  1287.         if (usePushOptions) {
  1288.             pushOptions = new ArrayList<>(4);
  1289.             for (;;) {
  1290.                 String option = in.readString();
  1291.                 if (PacketLineIn.isEnd(option)) {
  1292.                     break;
  1293.                 }
  1294.                 pushOptions.add(option);
  1295.             }
  1296.         }
  1297.     }

  1298.     /**
  1299.      * Enable capabilities based on a previously read capabilities line.
  1300.      */
  1301.     private void enableCapabilities() {
  1302.         reportStatus = isCapabilityEnabled(CAPABILITY_REPORT_STATUS);
  1303.         usePushOptions = isCapabilityEnabled(CAPABILITY_PUSH_OPTIONS);
  1304.         sideBand = isCapabilityEnabled(CAPABILITY_SIDE_BAND_64K);
  1305.         quiet = allowQuiet && isCapabilityEnabled(CAPABILITY_QUIET);

  1306.         clientSID = enabledCapabilities.get(OPTION_SESSION_ID);

  1307.         if (sideBand) {
  1308.             OutputStream out = rawOut;

  1309.             rawOut = new SideBandOutputStream(CH_DATA, MAX_BUF, out);
  1310.             msgOut = new SideBandOutputStream(CH_PROGRESS, MAX_BUF, out);
  1311.             errOut = new SideBandOutputStream(CH_ERROR, MAX_BUF, out);

  1312.             pckOut = new PacketLineOut(rawOut);
  1313.             pckOut.setFlushOnEnd(false);
  1314.         }
  1315.     }

  1316.     /**
  1317.      * Check if the peer requested a capability.
  1318.      *
  1319.      * @param name
  1320.      *            protocol name identifying the capability.
  1321.      * @return true if the peer requested the capability to be enabled.
  1322.      */
  1323.     private boolean isCapabilityEnabled(String name) {
  1324.         return enabledCapabilities.containsKey(name);
  1325.     }

  1326.     private void checkRequestWasRead() {
  1327.         if (enabledCapabilities == null)
  1328.             throw new RequestNotYetReadException();
  1329.     }

  1330.     /**
  1331.      * Whether a pack is expected based on the list of commands.
  1332.      *
  1333.      * @return {@code true} if a pack is expected based on the list of commands.
  1334.      */
  1335.     private boolean needPack() {
  1336.         for (ReceiveCommand cmd : commands) {
  1337.             if (cmd.getType() != ReceiveCommand.Type.DELETE)
  1338.                 return true;
  1339.         }
  1340.         return false;
  1341.     }

  1342.     /**
  1343.      * Receive a pack from the input and store it in the repository.
  1344.      *
  1345.      * @throws IOException
  1346.      *             an error occurred reading or indexing the pack.
  1347.      */
  1348.     private void receivePack() throws IOException {
  1349.         // It might take the client a while to pack the objects it needs
  1350.         // to send to us. We should increase our timeout so we don't
  1351.         // abort while the client is computing.
  1352.         //
  1353.         if (timeoutIn != null)
  1354.             timeoutIn.setTimeout(10 * timeout * 1000);

  1355.         ProgressMonitor receiving = NullProgressMonitor.INSTANCE;
  1356.         ProgressMonitor resolving = NullProgressMonitor.INSTANCE;
  1357.         if (sideBand && !quiet)
  1358.             resolving = new SideBandProgressMonitor(msgOut);

  1359.         try (ObjectInserter ins = db.newObjectInserter()) {
  1360.             String lockMsg = "jgit receive-pack"; //$NON-NLS-1$
  1361.             if (getRefLogIdent() != null)
  1362.                 lockMsg += " from " + getRefLogIdent().toExternalString(); //$NON-NLS-1$

  1363.             parser = ins.newPackParser(packInputStream());
  1364.             parser.setAllowThin(true);
  1365.             parser.setNeedNewObjectIds(checkReferencedAreReachable);
  1366.             parser.setNeedBaseObjectIds(checkReferencedAreReachable);
  1367.             parser.setCheckEofAfterPackFooter(!biDirectionalPipe
  1368.                     && !isExpectDataAfterPackFooter());
  1369.             parser.setExpectDataAfterPackFooter(isExpectDataAfterPackFooter());
  1370.             parser.setObjectChecker(objectChecker);
  1371.             parser.setLockMessage(lockMsg);
  1372.             parser.setMaxObjectSizeLimit(maxObjectSizeLimit);
  1373.             packLock = parser.parse(receiving, resolving);
  1374.             packSize = Long.valueOf(parser.getPackSize());
  1375.             stats = parser.getReceivedPackStatistics();
  1376.             ins.flush();
  1377.         }

  1378.         if (timeoutIn != null)
  1379.             timeoutIn.setTimeout(timeout * 1000);
  1380.     }

  1381.     private InputStream packInputStream() {
  1382.         InputStream packIn = rawIn;
  1383.         if (maxPackSizeLimit >= 0) {
  1384.             packIn = new LimitedInputStream(packIn, maxPackSizeLimit) {
  1385.                 @Override
  1386.                 protected void limitExceeded() throws TooLargePackException {
  1387.                     throw new TooLargePackException(limit);
  1388.                 }
  1389.             };
  1390.         }
  1391.         return packIn;
  1392.     }

  1393.     private boolean needCheckConnectivity() {
  1394.         return isCheckReceivedObjects()
  1395.                 || isCheckReferencedObjectsAreReachable()
  1396.                 || !getClientShallowCommits().isEmpty();
  1397.     }

  1398.     private void checkSubmodules() throws IOException, LargeObjectException,
  1399.             SubmoduleValidationException {
  1400.         ObjectDatabase odb = db.getObjectDatabase();
  1401.         if (objectChecker == null) {
  1402.             return;
  1403.         }
  1404.         for (GitmoduleEntry entry : objectChecker.getGitsubmodules()) {
  1405.             AnyObjectId blobId = entry.getBlobId();
  1406.             ObjectLoader blob = odb.open(blobId, Constants.OBJ_BLOB);

  1407.             SubmoduleValidator.assertValidGitModulesFile(
  1408.                     new String(blob.getBytes(), UTF_8));
  1409.         }
  1410.     }

  1411.     private void checkConnectivity() throws IOException {
  1412.         ProgressMonitor checking = NullProgressMonitor.INSTANCE;
  1413.         if (sideBand && !quiet) {
  1414.             SideBandProgressMonitor m = new SideBandProgressMonitor(msgOut);
  1415.             m.setDelayStart(750, TimeUnit.MILLISECONDS);
  1416.             checking = m;
  1417.         }

  1418.         connectivityChecker.checkConnectivity(createConnectivityCheckInfo(),
  1419.                 advertisedHaves, checking);
  1420.     }

  1421.     private ConnectivityCheckInfo createConnectivityCheckInfo() {
  1422.         ConnectivityCheckInfo info = new ConnectivityCheckInfo();
  1423.         info.setCheckObjects(checkReferencedAreReachable);
  1424.         info.setCommands(getAllCommands());
  1425.         info.setRepository(db);
  1426.         info.setParser(parser);
  1427.         info.setWalk(walk);
  1428.         return info;
  1429.     }

  1430.     /**
  1431.      * Validate the command list.
  1432.      */
  1433.     private void validateCommands() {
  1434.         for (ReceiveCommand cmd : commands) {
  1435.             final Ref ref = cmd.getRef();
  1436.             if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1437.                 continue;

  1438.             if (cmd.getType() == ReceiveCommand.Type.DELETE) {
  1439.                 if (!isAllowDeletes()) {
  1440.                     // Deletes are not supported on this repository.
  1441.                     cmd.setResult(Result.REJECTED_NODELETE);
  1442.                     continue;
  1443.                 }
  1444.                 if (!isAllowBranchDeletes()
  1445.                         && ref.getName().startsWith(Constants.R_HEADS)) {
  1446.                     // Branches cannot be deleted, but other refs can.
  1447.                     cmd.setResult(Result.REJECTED_NODELETE);
  1448.                     continue;
  1449.                 }
  1450.             }

  1451.             if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  1452.                 if (!isAllowCreates()) {
  1453.                     cmd.setResult(Result.REJECTED_NOCREATE);
  1454.                     continue;
  1455.                 }

  1456.                 if (ref != null && !isAllowNonFastForwards()) {
  1457.                     // Creation over an existing ref is certainly not going
  1458.                     // to be a fast-forward update. We can reject it early.
  1459.                     //
  1460.                     cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1461.                     continue;
  1462.                 }

  1463.                 if (ref != null) {
  1464.                     // A well behaved client shouldn't have sent us a
  1465.                     // create command for a ref we advertised to it.
  1466.                     //
  1467.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1468.                             JGitText.get().refAlreadyExists);
  1469.                     continue;
  1470.                 }
  1471.             }

  1472.             if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null) {
  1473.                 ObjectId id = ref.getObjectId();
  1474.                 if (id == null) {
  1475.                     id = ObjectId.zeroId();
  1476.                 }
  1477.                 if (!ObjectId.zeroId().equals(cmd.getOldId())
  1478.                         && !id.equals(cmd.getOldId())) {
  1479.                     // Delete commands can be sent with the old id matching our
  1480.                     // advertised value, *OR* with the old id being 0{40}. Any
  1481.                     // other requested old id is invalid.
  1482.                     //
  1483.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1484.                             JGitText.get().invalidOldIdSent);
  1485.                     continue;
  1486.                 }
  1487.             }

  1488.             if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
  1489.                 if (ref == null) {
  1490.                     // The ref must have been advertised in order to be updated.
  1491.                     //
  1492.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1493.                             JGitText.get().noSuchRef);
  1494.                     continue;
  1495.                 }
  1496.                 ObjectId id = ref.getObjectId();
  1497.                 if (id == null) {
  1498.                     // We cannot update unborn branch
  1499.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1500.                             JGitText.get().cannotUpdateUnbornBranch);
  1501.                     continue;
  1502.                 }

  1503.                 if (!id.equals(cmd.getOldId())) {
  1504.                     // A properly functioning client will send the same
  1505.                     // object id we advertised.
  1506.                     //
  1507.                     cmd.setResult(Result.REJECTED_OTHER_REASON,
  1508.                             JGitText.get().invalidOldIdSent);
  1509.                     continue;
  1510.                 }

  1511.                 // Is this possibly a non-fast-forward style update?
  1512.                 //
  1513.                 RevObject oldObj, newObj;
  1514.                 try {
  1515.                     oldObj = walk.parseAny(cmd.getOldId());
  1516.                 } catch (IOException e) {
  1517.                     receiveCommandErrorHandler
  1518.                             .handleOldIdValidationException(cmd, e);
  1519.                     continue;
  1520.                 }

  1521.                 try {
  1522.                     newObj = walk.parseAny(cmd.getNewId());
  1523.                 } catch (IOException e) {
  1524.                     receiveCommandErrorHandler
  1525.                             .handleNewIdValidationException(cmd, e);
  1526.                     continue;
  1527.                 }

  1528.                 if (oldObj instanceof RevCommit
  1529.                         && newObj instanceof RevCommit) {
  1530.                     try {
  1531.                         if (walk.isMergedInto((RevCommit) oldObj,
  1532.                                 (RevCommit) newObj)) {
  1533.                             cmd.setTypeFastForwardUpdate();
  1534.                         } else {
  1535.                             cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1536.                         }
  1537.                     } catch (IOException e) {
  1538.                         receiveCommandErrorHandler
  1539.                                 .handleFastForwardCheckException(cmd, e);
  1540.                     }
  1541.                 } else {
  1542.                     cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1543.                 }

  1544.                 if (cmd.getType() == ReceiveCommand.Type.UPDATE_NONFASTFORWARD
  1545.                         && !isAllowNonFastForwards()) {
  1546.                     cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1547.                     continue;
  1548.                 }
  1549.             }

  1550.             if (!cmd.getRefName().startsWith(Constants.R_REFS)
  1551.                     || !Repository.isValidRefName(cmd.getRefName())) {
  1552.                 cmd.setResult(Result.REJECTED_OTHER_REASON,
  1553.                         JGitText.get().funnyRefname);
  1554.             }
  1555.         }
  1556.     }

  1557.     /**
  1558.      * Whether any commands have been rejected so far.
  1559.      *
  1560.      * @return if any commands have been rejected so far.
  1561.      */
  1562.     private boolean anyRejects() {
  1563.         for (ReceiveCommand cmd : commands) {
  1564.             if (cmd.getResult() != Result.NOT_ATTEMPTED
  1565.                     && cmd.getResult() != Result.OK)
  1566.                 return true;
  1567.         }
  1568.         return false;
  1569.     }

  1570.     /**
  1571.      * Set the result to fail for any command that was not processed yet.
  1572.      *
  1573.      */
  1574.     private void failPendingCommands() {
  1575.         ReceiveCommand.abort(commands);
  1576.     }

  1577.     /**
  1578.      * Filter the list of commands according to result.
  1579.      *
  1580.      * @param want
  1581.      *            desired status to filter by.
  1582.      * @return a copy of the command list containing only those commands with
  1583.      *         the desired status.
  1584.      * @since 5.7
  1585.      */
  1586.     protected List<ReceiveCommand> filterCommands(Result want) {
  1587.         return ReceiveCommand.filter(commands, want);
  1588.     }

  1589.     /**
  1590.      * Execute commands to update references.
  1591.      * @since 5.7
  1592.      */
  1593.     protected void executeCommands() {
  1594.         List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED);
  1595.         if (toApply.isEmpty())
  1596.             return;

  1597.         ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  1598.         if (sideBand) {
  1599.             SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  1600.             pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  1601.             updating = pm;
  1602.         }

  1603.         BatchRefUpdate batch = db.getRefDatabase().newBatchUpdate();
  1604.         batch.setAllowNonFastForwards(isAllowNonFastForwards());
  1605.         batch.setAtomic(isAtomic());
  1606.         batch.setRefLogIdent(getRefLogIdent());
  1607.         batch.setRefLogMessage("push", true); //$NON-NLS-1$
  1608.         batch.addCommand(toApply);
  1609.         try {
  1610.             batch.setPushCertificate(getPushCertificate());
  1611.             batch.execute(walk, updating);
  1612.         } catch (IOException e) {
  1613.             receiveCommandErrorHandler.handleBatchRefUpdateException(toApply,
  1614.                     e);
  1615.         }
  1616.     }

  1617.     /**
  1618.      * Send a status report.
  1619.      *
  1620.      * @param unpackError
  1621.      *            an error that occurred during unpacking, or {@code null}
  1622.      * @throws java.io.IOException
  1623.      *             an error occurred writing the status report.
  1624.      * @since 5.6
  1625.      */
  1626.     private void sendStatusReport(Throwable unpackError) throws IOException {
  1627.         Reporter out = new Reporter() {
  1628.             @Override
  1629.             void sendString(String s) throws IOException {
  1630.                 if (reportStatus) {
  1631.                     pckOut.writeString(s + '\n');
  1632.                 } else if (msgOut != null) {
  1633.                     msgOut.write(Constants.encode(s + '\n'));
  1634.                 }
  1635.             }
  1636.         };

  1637.         try {
  1638.             if (unpackError != null) {
  1639.                 out.sendString("unpack error " + unpackError.getMessage()); //$NON-NLS-1$
  1640.                 if (reportStatus) {
  1641.                     for (ReceiveCommand cmd : commands) {
  1642.                         out.sendString("ng " + cmd.getRefName() //$NON-NLS-1$
  1643.                                 + " n/a (unpacker error)"); //$NON-NLS-1$
  1644.                     }
  1645.                 }
  1646.                 return;
  1647.             }

  1648.             if (reportStatus) {
  1649.                 out.sendString("unpack ok"); //$NON-NLS-1$
  1650.             }
  1651.             for (ReceiveCommand cmd : commands) {
  1652.                 if (cmd.getResult() == Result.OK) {
  1653.                     if (reportStatus) {
  1654.                         out.sendString("ok " + cmd.getRefName()); //$NON-NLS-1$
  1655.                     }
  1656.                     continue;
  1657.                 }

  1658.                 final StringBuilder r = new StringBuilder();
  1659.                 if (reportStatus) {
  1660.                     r.append("ng ").append(cmd.getRefName()).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
  1661.                 } else {
  1662.                     r.append(" ! [rejected] ").append(cmd.getRefName()) //$NON-NLS-1$
  1663.                             .append(" ("); //$NON-NLS-1$
  1664.                 }

  1665.                 if (cmd.getResult() == Result.REJECTED_MISSING_OBJECT) {
  1666.                     if (cmd.getMessage() == null)
  1667.                         r.append("missing object(s)"); //$NON-NLS-1$
  1668.                     else if (cmd.getMessage()
  1669.                             .length() == Constants.OBJECT_ID_STRING_LENGTH) {
  1670.                         // TODO: Using get/setMessage to store an OID is a
  1671.                         // misuse. The caller should set a full error message.
  1672.                         r.append("object "); //$NON-NLS-1$
  1673.                         r.append(cmd.getMessage());
  1674.                         r.append(" missing"); //$NON-NLS-1$
  1675.                     } else {
  1676.                         r.append(cmd.getMessage());
  1677.                     }
  1678.                 } else if (cmd.getMessage() != null) {
  1679.                     r.append(cmd.getMessage());
  1680.                 } else {
  1681.                     switch (cmd.getResult()) {
  1682.                     case NOT_ATTEMPTED:
  1683.                         r.append("server bug; ref not processed"); //$NON-NLS-1$
  1684.                         break;

  1685.                     case REJECTED_NOCREATE:
  1686.                         r.append("creation prohibited"); //$NON-NLS-1$
  1687.                         break;

  1688.                     case REJECTED_NODELETE:
  1689.                         r.append("deletion prohibited"); //$NON-NLS-1$
  1690.                         break;

  1691.                     case REJECTED_NONFASTFORWARD:
  1692.                         r.append("non-fast forward"); //$NON-NLS-1$
  1693.                         break;

  1694.                     case REJECTED_CURRENT_BRANCH:
  1695.                         r.append("branch is currently checked out"); //$NON-NLS-1$
  1696.                         break;

  1697.                     case REJECTED_OTHER_REASON:
  1698.                         r.append("unspecified reason"); //$NON-NLS-1$
  1699.                         break;

  1700.                     case LOCK_FAILURE:
  1701.                         r.append("failed to lock"); //$NON-NLS-1$
  1702.                         break;

  1703.                     case REJECTED_MISSING_OBJECT:
  1704.                     case OK:
  1705.                         // We shouldn't have reached this case (see 'ok' case
  1706.                         // above and if-statement above).
  1707.                         throw new AssertionError();
  1708.                     }
  1709.                 }

  1710.                 if (!reportStatus) {
  1711.                     r.append(")"); //$NON-NLS-1$
  1712.                 }
  1713.                 out.sendString(r.toString());
  1714.             }
  1715.         } finally {
  1716.             if (reportStatus) {
  1717.                 pckOut.end();
  1718.             }
  1719.         }
  1720.     }

  1721.     /**
  1722.      * Close and flush (if necessary) the underlying streams.
  1723.      *
  1724.      * @throws java.io.IOException
  1725.      */
  1726.     private void close() throws IOException {
  1727.         if (sideBand) {
  1728.             // If we are using side band, we need to send a final
  1729.             // flush-pkt to tell the remote peer the side band is
  1730.             // complete and it should stop decoding. We need to
  1731.             // use the original output stream as rawOut is now the
  1732.             // side band data channel.
  1733.             //
  1734.             ((SideBandOutputStream) msgOut).flushBuffer();
  1735.             ((SideBandOutputStream) rawOut).flushBuffer();

  1736.             PacketLineOut plo = new PacketLineOut(origOut);
  1737.             plo.setFlushOnEnd(false);
  1738.             plo.end();
  1739.         }

  1740.         if (biDirectionalPipe) {
  1741.             // If this was a native git connection, flush the pipe for
  1742.             // the caller. For smart HTTP we don't do this flush and
  1743.             // instead let the higher level HTTP servlet code do it.
  1744.             //
  1745.             if (!sideBand && msgOut != null)
  1746.                 msgOut.flush();
  1747.             rawOut.flush();
  1748.         }
  1749.     }

  1750.     /**
  1751.      * Release any resources used by this object.
  1752.      *
  1753.      * @throws java.io.IOException
  1754.      *             the pack could not be unlocked.
  1755.      */
  1756.     private void release() throws IOException {
  1757.         walk.close();
  1758.         unlockPack();
  1759.         timeoutIn = null;
  1760.         rawIn = null;
  1761.         rawOut = null;
  1762.         msgOut = null;
  1763.         pckIn = null;
  1764.         pckOut = null;
  1765.         refs = null;
  1766.         // Keep the capabilities. If responses are sent after this release
  1767.         // we need to remember at least whether sideband communication has to be
  1768.         // used
  1769.         commands = null;
  1770.         if (timer != null) {
  1771.             try {
  1772.                 timer.terminate();
  1773.             } finally {
  1774.                 timer = null;
  1775.             }
  1776.         }
  1777.     }

  1778.     /** Interface for reporting status messages. */
  1779.     abstract static class Reporter {
  1780.         abstract void sendString(String s) throws IOException;
  1781.     }

  1782.     /**
  1783.      * Get the push certificate used to verify the pusher's identity.
  1784.      * <p>
  1785.      * Only valid after commands are read from the wire.
  1786.      *
  1787.      * @return the parsed certificate, or null if push certificates are disabled
  1788.      *         or no cert was presented by the client.
  1789.      * @since 4.1
  1790.      */
  1791.     public PushCertificate getPushCertificate() {
  1792.         return pushCert;
  1793.     }

  1794.     /**
  1795.      * Set the push certificate used to verify the pusher's identity.
  1796.      * <p>
  1797.      * Should only be called if reconstructing an instance without going through
  1798.      * the normal {@link #recvCommands()} flow.
  1799.      *
  1800.      * @param cert
  1801.      *            the push certificate to set.
  1802.      * @since 4.1
  1803.      */
  1804.     public void setPushCertificate(PushCertificate cert) {
  1805.         pushCert = cert;
  1806.     }

  1807.     /**
  1808.      * Gets an unmodifiable view of the option strings associated with the push.
  1809.      *
  1810.      * @return an unmodifiable view of pushOptions, or null (if pushOptions is).
  1811.      * @since 4.5
  1812.      */
  1813.     @Nullable
  1814.     public List<String> getPushOptions() {
  1815.         if (isAllowPushOptions() && usePushOptions) {
  1816.             return Collections.unmodifiableList(pushOptions);
  1817.         }

  1818.         // The client doesn't support push options. Return null to
  1819.         // distinguish this from the case where the client declared support
  1820.         // for push options and sent an empty list of them.
  1821.         return null;
  1822.     }

  1823.     /**
  1824.      * Set the push options supplied by the client.
  1825.      * <p>
  1826.      * Should only be called if reconstructing an instance without going through
  1827.      * the normal {@link #recvCommands()} flow.
  1828.      *
  1829.      * @param options
  1830.      *            the list of options supplied by the client. The
  1831.      *            {@code ReceivePack} instance takes ownership of this list.
  1832.      *            Callers are encouraged to first create a copy if the list may
  1833.      *            be modified later.
  1834.      * @since 4.5
  1835.      */
  1836.     public void setPushOptions(@Nullable List<String> options) {
  1837.         usePushOptions = options != null;
  1838.         pushOptions = options;
  1839.     }

  1840.     /**
  1841.      * Get the hook invoked before updates occur.
  1842.      *
  1843.      * @return the hook invoked before updates occur.
  1844.      */
  1845.     public PreReceiveHook getPreReceiveHook() {
  1846.         return preReceive;
  1847.     }

  1848.     /**
  1849.      * Set the hook which is invoked prior to commands being executed.
  1850.      * <p>
  1851.      * Only valid commands (those which have no obvious errors according to the
  1852.      * received input and this instance's configuration) are passed into the
  1853.      * hook. The hook may mark a command with a result of any value other than
  1854.      * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#NOT_ATTEMPTED} to
  1855.      * block its execution.
  1856.      * <p>
  1857.      * The hook may be called with an empty command collection if the current
  1858.      * set is completely invalid.
  1859.      *
  1860.      * @param h
  1861.      *            the hook instance; may be null to disable the hook.
  1862.      */
  1863.     public void setPreReceiveHook(PreReceiveHook h) {
  1864.         preReceive = h != null ? h : PreReceiveHook.NULL;
  1865.     }

  1866.     /**
  1867.      * Get the hook invoked after updates occur.
  1868.      *
  1869.      * @return the hook invoked after updates occur.
  1870.      */
  1871.     public PostReceiveHook getPostReceiveHook() {
  1872.         return postReceive;
  1873.     }

  1874.     /**
  1875.      * Set the hook which is invoked after commands are executed.
  1876.      * <p>
  1877.      * Only successful commands (type is
  1878.      * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#OK}) are passed
  1879.      * into the hook. The hook may be called with an empty command collection if
  1880.      * the current set all resulted in an error.
  1881.      *
  1882.      * @param h
  1883.      *            the hook instance; may be null to disable the hook.
  1884.      */
  1885.     public void setPostReceiveHook(PostReceiveHook h) {
  1886.         postReceive = h != null ? h : PostReceiveHook.NULL;
  1887.     }

  1888.     /**
  1889.      * Get the current unpack error handler.
  1890.      *
  1891.      * @return the current unpack error handler.
  1892.      * @since 5.8
  1893.      */
  1894.     public UnpackErrorHandler getUnpackErrorHandler() {
  1895.         return unpackErrorHandler;
  1896.     }

  1897.     /**
  1898.      * @param unpackErrorHandler
  1899.      *            the unpackErrorHandler to set
  1900.      * @since 5.7
  1901.      */
  1902.     public void setUnpackErrorHandler(UnpackErrorHandler unpackErrorHandler) {
  1903.         this.unpackErrorHandler = unpackErrorHandler;
  1904.     }

  1905.     /**
  1906.      * Set whether this class will report command failures as warning messages
  1907.      * before sending the command results.
  1908.      *
  1909.      * @param echo
  1910.      *            if true this class will report command failures as warning
  1911.      *            messages before sending the command results. This is usually
  1912.      *            not necessary, but may help buggy Git clients that discard the
  1913.      *            errors when all branches fail.
  1914.      * @deprecated no widely used Git versions need this any more
  1915.      */
  1916.     @Deprecated
  1917.     public void setEchoCommandFailures(boolean echo) {
  1918.         // No-op.
  1919.     }

  1920.     /**
  1921.      * @return The client session-id.
  1922.      * @since 6.4
  1923.      */
  1924.     public String getClientSID() {
  1925.         return clientSID;
  1926.     }

  1927.     /**
  1928.      * Execute the receive task on the socket.
  1929.      *
  1930.      * @param input
  1931.      *            raw input to read client commands and pack data from. Caller
  1932.      *            must ensure the input is buffered, otherwise read performance
  1933.      *            may suffer.
  1934.      * @param output
  1935.      *            response back to the Git network client. Caller must ensure
  1936.      *            the output is buffered, otherwise write performance may
  1937.      *            suffer.
  1938.      * @param messages
  1939.      *            secondary "notice" channel to send additional messages out
  1940.      *            through. When run over SSH this should be tied back to the
  1941.      *            standard error channel of the command execution. For most
  1942.      *            other network connections this should be null.
  1943.      * @throws java.io.IOException
  1944.      */
  1945.     public void receive(final InputStream input, final OutputStream output,
  1946.             final OutputStream messages) throws IOException {
  1947.         init(input, output, messages);
  1948.         try {
  1949.             service();
  1950.         } catch (PackProtocolException e) {
  1951.             fatalError(e.getMessage());
  1952.             throw e;
  1953.         } catch (InputOverLimitIOException e) {
  1954.             String msg = JGitText.get().tooManyCommands;
  1955.             fatalError(msg);
  1956.             throw new PackProtocolException(msg, e);
  1957.         } finally {
  1958.             try {
  1959.                 close();
  1960.             } finally {
  1961.                 release();
  1962.             }
  1963.         }
  1964.     }

  1965.     /**
  1966.      * Execute the receive task on the socket.
  1967.      *
  1968.      * <p>
  1969.      * Same as {@link #receive}, but the exceptions are not reported to the
  1970.      * client yet.
  1971.      *
  1972.      * @param input
  1973.      *            raw input to read client commands and pack data from. Caller
  1974.      *            must ensure the input is buffered, otherwise read performance
  1975.      *            may suffer.
  1976.      * @param output
  1977.      *            response back to the Git network client. Caller must ensure
  1978.      *            the output is buffered, otherwise write performance may
  1979.      *            suffer.
  1980.      * @param messages
  1981.      *            secondary "notice" channel to send additional messages out
  1982.      *            through. When run over SSH this should be tied back to the
  1983.      *            standard error channel of the command execution. For most
  1984.      *            other network connections this should be null.
  1985.      * @throws java.io.IOException
  1986.      * @since 5.7
  1987.      */
  1988.     public void receiveWithExceptionPropagation(InputStream input,
  1989.             OutputStream output, OutputStream messages) throws IOException {
  1990.         init(input, output, messages);
  1991.         try {
  1992.             service();
  1993.         } finally {
  1994.             try {
  1995.                 close();
  1996.             } finally {
  1997.                 release();
  1998.             }
  1999.         }
  2000.     }

  2001.     private void service() throws IOException {
  2002.         if (isBiDirectionalPipe()) {
  2003.             sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  2004.             pckOut.flush();
  2005.         } else
  2006.             getAdvertisedOrDefaultRefs();
  2007.         if (hasError())
  2008.             return;

  2009.         recvCommands();

  2010.         if (hasCommands()) {
  2011.             try (PostReceiveExecutor e = new PostReceiveExecutor()) {
  2012.                 if (needPack()) {
  2013.                     try {
  2014.                         receivePackAndCheckConnectivity();
  2015.                     } catch (IOException | RuntimeException
  2016.                             | SubmoduleValidationException | Error err) {
  2017.                         unlockPack();
  2018.                         unpackErrorHandler.handleUnpackException(err);
  2019.                         throw new UnpackException(err);
  2020.                     }
  2021.                 }

  2022.                 try {
  2023.                     setAtomic(isCapabilityEnabled(CAPABILITY_ATOMIC));

  2024.                     validateCommands();
  2025.                     if (atomic && anyRejects()) {
  2026.                         failPendingCommands();
  2027.                     }

  2028.                     preReceive.onPreReceive(
  2029.                             this, filterCommands(Result.NOT_ATTEMPTED));
  2030.                     if (atomic && anyRejects()) {
  2031.                         failPendingCommands();
  2032.                     }
  2033.                     executeCommands();
  2034.                 } finally {
  2035.                     unlockPack();
  2036.                 }

  2037.                 sendStatusReport(null);
  2038.             }
  2039.             autoGc();
  2040.         }
  2041.     }

  2042.     private void autoGc() {
  2043.         Repository repo = getRepository();
  2044.         if (!repo.getConfig().getBoolean(ConfigConstants.CONFIG_RECEIVE_SECTION,
  2045.                 ConfigConstants.CONFIG_KEY_AUTOGC, true)) {
  2046.             return;
  2047.         }
  2048.         repo.autoGC(NullProgressMonitor.INSTANCE);
  2049.     }

  2050.     static ReceiveCommand parseCommand(String line)
  2051.             throws PackProtocolException {
  2052.         if (line == null || line.length() < 83) {
  2053.             throw new PackProtocolException(
  2054.                     JGitText.get().errorInvalidProtocolWantedOldNewRef);
  2055.         }
  2056.         String oldStr = line.substring(0, 40);
  2057.         String newStr = line.substring(41, 81);
  2058.         ObjectId oldId, newId;
  2059.         try {
  2060.             oldId = ObjectId.fromString(oldStr);
  2061.             newId = ObjectId.fromString(newStr);
  2062.         } catch (InvalidObjectIdException e) {
  2063.             throw new PackProtocolException(
  2064.                     JGitText.get().errorInvalidProtocolWantedOldNewRef, e);
  2065.         }
  2066.         String name = line.substring(82);
  2067.         if (!Repository.isValidRefName(name)) {
  2068.             throw new PackProtocolException(
  2069.                     JGitText.get().errorInvalidProtocolWantedOldNewRef);
  2070.         }
  2071.         return new ReceiveCommand(oldId, newId, name);
  2072.     }

  2073.     private class PostReceiveExecutor implements AutoCloseable {
  2074.         @Override
  2075.         public void close() {
  2076.             postReceive.onPostReceive(ReceivePack.this,
  2077.                     filterCommands(Result.OK));
  2078.         }
  2079.     }

  2080.     private class DefaultUnpackErrorHandler implements UnpackErrorHandler {
  2081.         @Override
  2082.         public void handleUnpackException(Throwable t) throws IOException {
  2083.             sendStatusReport(t);
  2084.         }
  2085.     }
  2086. }