You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UploadPack.java 51KB

UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
PackWriter: Support reuse of entire packs The most expensive part of packing a repository for transport to another system is enumerating all of the objects in the repository. Once this gets to the size of the linux-2.6 repository (1.8 million objects), enumeration can take several CPU minutes and costs a lot of temporary working set memory. Teach PackWriter to efficiently reuse an existing "cached pack" by answering a clone request with a thin pack followed by a larger cached pack appended to the end. This requires the repository owner to first construct the cached pack by hand, and record the tip commits inside of $GIT_DIR/objects/info/cached-packs: cd $GIT_DIR root=$(git rev-parse master) tmp=objects/.tmp-$$ names=$(echo $root | git pack-objects --keep-true-parents --revs $tmp) for n in $names; do chmod a-w $tmp-$n.pack $tmp-$n.idx touch objects/pack/pack-$n.keep mv $tmp-$n.pack objects/pack/pack-$n.pack mv $tmp-$n.idx objects/pack/pack-$n.idx done (echo "+ $root"; for n in $names; do echo "P $n"; done; echo) >>objects/info/cached-packs git repack -a -d When a clone request needs to include $root, the corresponding cached pack will be copied as-is, rather than enumerating all of the objects that are reachable from $root. For a linux-2.6 kernel repository that should be about 376 MiB, the above process creates two packs of 368 MiB and 38 MiB[1]. This is a local disk usage increase of ~26 MiB, due to reduced delta compression between the large cached pack and the smaller recent activity pack. The overhead is similar to 1 full copy of the compressed project sources. With this cached pack in hand, JGit daemon completes a clone request in 1m17s less time, but a slightly larger data transfer (+2.39 MiB): Before: remote: Counting objects: 1861830, done remote: Finding sources: 100% (1861830/1861830) remote: Getting sizes: 100% (88243/88243) remote: Compressing objects: 100% (88184/88184) Receiving objects: 100% (1861830/1861830), 376.01 MiB | 19.01 MiB/s, done. remote: Total 1861830 (delta 4706), reused 1851053 (delta 1553844) Resolving deltas: 100% (1564621/1564621), done. real 3m19.005s After: remote: Counting objects: 1601, done remote: Counting objects: 1828460, done remote: Finding sources: 100% (50475/50475) remote: Getting sizes: 100% (18843/18843) remote: Compressing objects: 100% (7585/7585) remote: Total 1861830 (delta 2407), reused 1856197 (delta 37510) Receiving objects: 100% (1861830/1861830), 378.40 MiB | 31.31 MiB/s, done. Resolving deltas: 100% (1559477/1559477), done. real 2m2.938s Repository owners can periodically refresh their cached packs by repacking their repository, folding all newer objects into a larger cached pack. Since repacking is already considered to be a normal Git maintenance activity, this isn't a very big burden. [1] In this test $root was set back about two weeks. Change-Id: Ib87131d5c4b5e8c5cacb0f4fe16ff4ece554734b Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 年之前
PackWriter: Don't reuse commit or tag deltas JGit doesn't generate deltas for commit or tag objects when it packs a repository from scratch. This is an explicit design decision that is (mostly) justified by the fact that these objects do not delta compress well. Annotated tags are made once on stable points of the project history, it is unlikely they will ever appear again with sufficient common text to justify using a delta over just deflating the raw content. JGit never tries to delta compress annotated tags and I take the stance that these are best stored as non-deltas given how frequently they might be accessed by repository viewers. Commits only have sufficient common text when they are cherry-picked to forward-port or back-port a change from one branch to another. Even in these cases the distance between the commits as returned by the log traversal has to be small enough that they would both appear in the delta search window at the same time in order to delta compress one of the messages against the other. JGit never tries to delta compress commits, as it requires a lot of CPU time but typically does not produce a smaller pack file. Avoid reusing deltas for either of these types when constructing a new pack. To avoid killing performance during serving of network clients, UploadPack disables this code change by allowing PackWriter to reuse delta commits. Repositories that were already repacked by C Git will not have their delta commits decompressed and recompressed on the fly during object writing, saving server-side CPU resources. Change-Id: I749407e7c5c677e05e4d054b40db7656cfa7fca8 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
PackWriter: Hoist and cluster reference targets Many source browsers and network related tools like UploadPack need to find and parse the target of all branches and annotated tags within the repository during their startup phase. Clustering these together into the same part of the pack file will improve locality, reducing thrashing when an application starts and needs to load all of these into memory at once. To prevent bottlenecking basic log viewing tools that are scannning backwards from the tip of a current branch (and don't need tags) we place this cluster of older targets after 4096 newer commits have already been placed into the pack stream. 4096 was chosen as a rough guess, but was based on a few factors: - log viewers typically show 5-200 commits per page - users only view the first page or two - DHT can cram 2200-4000 commits per 1 MiB chunk thus these will fall into the second commit chunk (roughly) Unfortunately this placement hurts history tools that are scanning backwards through the commit graph and completely ignored tags or branch heads when they started. An ancient tagged commit is no longer positioned behind its first child (its now much earlier), resulting in a page fault for the parser to reload this cluster of objects on demand. This may be an acceptable loss. If a user is walking backwards and has already scanned through more than 4096 commits of history, waiting for the region to reload isn't really that bad compared to the amount of time already spent. If the repository is so small that there are less than 4096 commits, this change has no impact on the placement of objects. Change-Id: If3052e430d305e17878d94145c93754f56b74c61 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 年之前
UploadPack: Fix races in smart HTTP negotiation Clients cache the set of advertised references at the start of a negotiation, and keep replaying the same "want SHA1" list to the server on each negotiation step. If another client pushes into a branch and moves it by fast-forward, any request to obtain that branch's prior SHA-1 is still valid, the commit is reachable from the new position of the reference. Unfortunately the fast-forward causes smart HTTP negotations to fail, as the server no longer is advertising that prior SHA-1. Instead of causing clients to fail out with a "want invalid" error and forcing the end-user retry, possibly getting into a never ending try-fail-retry race while other clients are pushing into the same busy repository, allow the slightly stale want request so long as it is still reachable. C Git implemented this same change recently to fix races on the smart HTTP protocol when the C Git git-http-backend is used. The new RequestPolicy feature also allows server authors to make an even more lenient configuration that exports any SHA-1 to the client. This might be useful in certain settings where a server has authenticated the client as the "repository owner" and wants to allow them to grab any content from the server as a complete unbroken history chain. The new setAdvertisedRefs() method allows server authors to manually fix the references that are advertised, possibly bypassing the getAllRefs() call on the Repository object. Change-Id: I7cdb563bf9c55c83653f217f6e53c3add55a0541 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
12 年之前
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport;
  44. import static org.eclipse.jgit.lib.RefDatabase.ALL;
  45. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  46. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_REACHABLE_SHA1_IN_WANT;
  47. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_TIP_SHA1_IN_WANT;
  48. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_INCLUDE_TAG;
  49. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK;
  50. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK_DETAILED;
  51. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_DONE;
  52. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_PROGRESS;
  53. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_OFS_DELTA;
  54. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SHALLOW;
  55. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND;
  56. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND_64K;
  57. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_THIN_PACK;
  58. import java.io.ByteArrayOutputStream;
  59. import java.io.EOFException;
  60. import java.io.IOException;
  61. import java.io.InputStream;
  62. import java.io.OutputStream;
  63. import java.text.MessageFormat;
  64. import java.util.ArrayList;
  65. import java.util.Collection;
  66. import java.util.Collections;
  67. import java.util.HashSet;
  68. import java.util.List;
  69. import java.util.Map;
  70. import java.util.Set;
  71. import org.eclipse.jgit.errors.CorruptObjectException;
  72. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  73. import org.eclipse.jgit.errors.MissingObjectException;
  74. import org.eclipse.jgit.errors.PackProtocolException;
  75. import org.eclipse.jgit.internal.JGitText;
  76. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  77. import org.eclipse.jgit.lib.BitmapIndex;
  78. import org.eclipse.jgit.lib.BitmapIndex.BitmapBuilder;
  79. import org.eclipse.jgit.lib.Constants;
  80. import org.eclipse.jgit.lib.NullProgressMonitor;
  81. import org.eclipse.jgit.lib.ObjectId;
  82. import org.eclipse.jgit.lib.ObjectReader;
  83. import org.eclipse.jgit.lib.ProgressMonitor;
  84. import org.eclipse.jgit.lib.Ref;
  85. import org.eclipse.jgit.lib.Repository;
  86. import org.eclipse.jgit.revwalk.AsyncRevObjectQueue;
  87. import org.eclipse.jgit.revwalk.BitmapWalker;
  88. import org.eclipse.jgit.revwalk.DepthWalk;
  89. import org.eclipse.jgit.revwalk.ObjectWalk;
  90. import org.eclipse.jgit.revwalk.RevCommit;
  91. import org.eclipse.jgit.revwalk.RevFlag;
  92. import org.eclipse.jgit.revwalk.RevFlagSet;
  93. import org.eclipse.jgit.revwalk.RevObject;
  94. import org.eclipse.jgit.revwalk.RevTag;
  95. import org.eclipse.jgit.revwalk.RevWalk;
  96. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  97. import org.eclipse.jgit.storage.pack.PackConfig;
  98. import org.eclipse.jgit.storage.pack.PackStatistics;
  99. import org.eclipse.jgit.transport.GitProtocolConstants.MultiAck;
  100. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  101. import org.eclipse.jgit.util.io.InterruptTimer;
  102. import org.eclipse.jgit.util.io.NullOutputStream;
  103. import org.eclipse.jgit.util.io.TimeoutInputStream;
  104. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  105. /**
  106. * Implements the server side of a fetch connection, transmitting objects.
  107. */
  108. public class UploadPack {
  109. /** Policy the server uses to validate client requests */
  110. public static enum RequestPolicy {
  111. /** Client may only ask for objects the server advertised a reference for. */
  112. ADVERTISED,
  113. /**
  114. * Client may ask for any commit reachable from a reference advertised by
  115. * the server.
  116. */
  117. REACHABLE_COMMIT,
  118. /**
  119. * Client may ask for objects that are the tip of any reference, even if not
  120. * advertised.
  121. * <p>
  122. * This may happen, for example, when a custom {@link RefFilter} is set.
  123. *
  124. * @since 3.1
  125. */
  126. TIP,
  127. /**
  128. * Client may ask for any commit reachable from any reference, even if that
  129. * reference wasn't advertised.
  130. *
  131. * @since 3.1
  132. */
  133. REACHABLE_COMMIT_TIP,
  134. /** Client may ask for any SHA-1 in the repository. */
  135. ANY;
  136. }
  137. /**
  138. * Validator for client requests.
  139. *
  140. * @since 3.1
  141. */
  142. public interface RequestValidator {
  143. /**
  144. * Check a list of client wants against the request policy.
  145. *
  146. * @param up
  147. * {@link UploadPack} instance.
  148. * @param wants
  149. * objects the client requested that were not advertised.
  150. *
  151. * @throws PackProtocolException
  152. * if one or more wants is not valid.
  153. * @throws IOException
  154. * if a low-level exception occurred.
  155. * @since 3.1
  156. */
  157. void checkWants(UploadPack up, List<ObjectId> wants)
  158. throws PackProtocolException, IOException;
  159. }
  160. /** Data in the first line of a request, the line itself plus options. */
  161. public static class FirstLine {
  162. private final String line;
  163. private final Set<String> options;
  164. /**
  165. * Parse the first line of a receive-pack request.
  166. *
  167. * @param line
  168. * line from the client.
  169. */
  170. public FirstLine(String line) {
  171. if (line.length() > 45) {
  172. final HashSet<String> opts = new HashSet<>();
  173. String opt = line.substring(45);
  174. if (opt.startsWith(" ")) //$NON-NLS-1$
  175. opt = opt.substring(1);
  176. for (String c : opt.split(" ")) //$NON-NLS-1$
  177. opts.add(c);
  178. this.line = line.substring(0, 45);
  179. this.options = Collections.unmodifiableSet(opts);
  180. } else {
  181. this.line = line;
  182. this.options = Collections.emptySet();
  183. }
  184. }
  185. /** @return non-capabilities part of the line. */
  186. public String getLine() {
  187. return line;
  188. }
  189. /** @return options parsed from the line. */
  190. public Set<String> getOptions() {
  191. return options;
  192. }
  193. }
  194. /** Database we read the objects from. */
  195. private final Repository db;
  196. /** Revision traversal support over {@link #db}. */
  197. private final RevWalk walk;
  198. /** Configuration to pass into the PackWriter. */
  199. private PackConfig packConfig;
  200. /** Configuration for various transfer options. */
  201. private TransferConfig transferConfig;
  202. /** Timeout in seconds to wait for client interaction. */
  203. private int timeout;
  204. /**
  205. * Is the client connection a bi-directional socket or pipe?
  206. * <p>
  207. * If true, this class assumes it can perform multiple read and write cycles
  208. * with the client over the input and output streams. This matches the
  209. * functionality available with a standard TCP/IP connection, or a local
  210. * operating system or in-memory pipe.
  211. * <p>
  212. * If false, this class runs in a read everything then output results mode,
  213. * making it suitable for single round-trip systems RPCs such as HTTP.
  214. */
  215. private boolean biDirectionalPipe = true;
  216. /** Timer to manage {@link #timeout}. */
  217. private InterruptTimer timer;
  218. private InputStream rawIn;
  219. private ResponseBufferedOutputStream rawOut;
  220. private PacketLineIn pckIn;
  221. private PacketLineOut pckOut;
  222. private OutputStream msgOut = NullOutputStream.INSTANCE;
  223. /** The refs we advertised as existing at the start of the connection. */
  224. private Map<String, Ref> refs;
  225. /** Hook used while advertising the refs to the client. */
  226. private AdvertiseRefsHook advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  227. /** Filter used while advertising the refs to the client. */
  228. private RefFilter refFilter = RefFilter.DEFAULT;
  229. /** Hook handling the various upload phases. */
  230. private PreUploadHook preUploadHook = PreUploadHook.NULL;
  231. /** Hook for taking post upload actions. */
  232. private PostUploadHook postUploadHook = PostUploadHook.NULL;
  233. /** Capabilities requested by the client. */
  234. private Set<String> options;
  235. String userAgent;
  236. /** Raw ObjectIds the client has asked for, before validating them. */
  237. private final Set<ObjectId> wantIds = new HashSet<>();
  238. /** Objects the client wants to obtain. */
  239. private final Set<RevObject> wantAll = new HashSet<>();
  240. /** Objects on both sides, these don't have to be sent. */
  241. private final Set<RevObject> commonBase = new HashSet<>();
  242. /** Shallow commits the client already has. */
  243. private final Set<ObjectId> clientShallowCommits = new HashSet<>();
  244. /** Shallow commits on the client which are now becoming unshallow */
  245. private final List<ObjectId> unshallowCommits = new ArrayList<>();
  246. /** Desired depth from the client on a shallow request. */
  247. private int depth;
  248. /** Commit time of the oldest common commit, in seconds. */
  249. private int oldestTime;
  250. /** null if {@link #commonBase} should be examined again. */
  251. private Boolean okToGiveUp;
  252. private boolean sentReady;
  253. /** Objects we sent in our advertisement list, clients can ask for these. */
  254. private Set<ObjectId> advertised;
  255. /** Marked on objects the client has asked us to give them. */
  256. private final RevFlag WANT;
  257. /** Marked on objects both we and the client have. */
  258. private final RevFlag PEER_HAS;
  259. /** Marked on objects in {@link #commonBase}. */
  260. private final RevFlag COMMON;
  261. /** Objects where we found a path from the want list to a common base. */
  262. private final RevFlag SATISFIED;
  263. private final RevFlagSet SAVE;
  264. private RequestValidator requestValidator = new AdvertisedRequestValidator();
  265. private MultiAck multiAck = MultiAck.OFF;
  266. private boolean noDone;
  267. private PackStatistics statistics;
  268. @SuppressWarnings("deprecation")
  269. private UploadPackLogger logger = UploadPackLogger.NULL;
  270. /**
  271. * Create a new pack upload for an open repository.
  272. *
  273. * @param copyFrom
  274. * the source repository.
  275. */
  276. public UploadPack(final Repository copyFrom) {
  277. db = copyFrom;
  278. walk = new RevWalk(db);
  279. walk.setRetainBody(false);
  280. WANT = walk.newFlag("WANT"); //$NON-NLS-1$
  281. PEER_HAS = walk.newFlag("PEER_HAS"); //$NON-NLS-1$
  282. COMMON = walk.newFlag("COMMON"); //$NON-NLS-1$
  283. SATISFIED = walk.newFlag("SATISFIED"); //$NON-NLS-1$
  284. walk.carry(PEER_HAS);
  285. SAVE = new RevFlagSet();
  286. SAVE.add(WANT);
  287. SAVE.add(PEER_HAS);
  288. SAVE.add(COMMON);
  289. SAVE.add(SATISFIED);
  290. setTransferConfig(null);
  291. }
  292. /**
  293. * Get the repository this upload is reading from.
  294. *
  295. * @return the repository this upload is reading from.
  296. */
  297. public final Repository getRepository() {
  298. return db;
  299. }
  300. /**
  301. * Get the RevWalk instance used by this connection.
  302. *
  303. * @return the RevWalk instance used by this connection.
  304. */
  305. public final RevWalk getRevWalk() {
  306. return walk;
  307. }
  308. /**
  309. * Get refs which were advertised to the client.
  310. *
  311. * @return all refs which were advertised to the client, or null if
  312. * {@link #setAdvertisedRefs(Map)} has not been called yet.
  313. */
  314. public final Map<String, Ref> getAdvertisedRefs() {
  315. return refs;
  316. }
  317. /**
  318. * Set the refs advertised by this UploadPack.
  319. * <p>
  320. * Intended to be called from a
  321. * {@link org.eclipse.jgit.transport.PreUploadHook}.
  322. *
  323. * @param allRefs
  324. * explicit set of references to claim as advertised by this
  325. * UploadPack instance. This overrides any references that may
  326. * exist in the source repository. The map is passed to the
  327. * configured {@link #getRefFilter()}. If null, assumes all refs
  328. * were advertised.
  329. */
  330. public void setAdvertisedRefs(Map<String, Ref> allRefs) {
  331. if (allRefs != null)
  332. refs = allRefs;
  333. else
  334. refs = db.getAllRefs();
  335. if (refFilter == RefFilter.DEFAULT)
  336. refs = transferConfig.getRefFilter().filter(refs);
  337. else
  338. refs = refFilter.filter(refs);
  339. }
  340. /**
  341. * Get timeout (in seconds) before aborting an IO operation.
  342. *
  343. * @return timeout (in seconds) before aborting an IO operation.
  344. */
  345. public int getTimeout() {
  346. return timeout;
  347. }
  348. /**
  349. * Set the timeout before willing to abort an IO call.
  350. *
  351. * @param seconds
  352. * number of seconds to wait (with no data transfer occurring)
  353. * before aborting an IO read or write operation with the
  354. * connected client.
  355. */
  356. public void setTimeout(final int seconds) {
  357. timeout = seconds;
  358. }
  359. /**
  360. * Whether this class expects a bi-directional pipe opened between the
  361. * client and itself.
  362. *
  363. * @return true if this class expects a bi-directional pipe opened between
  364. * the client and itself. The default is true.
  365. */
  366. public boolean isBiDirectionalPipe() {
  367. return biDirectionalPipe;
  368. }
  369. /**
  370. * Set whether this class will assume the socket is a fully bidirectional
  371. * pipe between the two peers
  372. *
  373. * @param twoWay
  374. * if true, this class will assume the socket is a fully
  375. * bidirectional pipe between the two peers and takes advantage
  376. * of that by first transmitting the known refs, then waiting to
  377. * read commands. If false, this class assumes it must read the
  378. * commands before writing output and does not perform the
  379. * initial advertising.
  380. */
  381. public void setBiDirectionalPipe(final boolean twoWay) {
  382. biDirectionalPipe = twoWay;
  383. }
  384. /**
  385. * Get policy used by the service to validate client requests
  386. *
  387. * @return policy used by the service to validate client requests, or null
  388. * for a custom request validator.
  389. */
  390. public RequestPolicy getRequestPolicy() {
  391. if (requestValidator instanceof AdvertisedRequestValidator)
  392. return RequestPolicy.ADVERTISED;
  393. if (requestValidator instanceof ReachableCommitRequestValidator)
  394. return RequestPolicy.REACHABLE_COMMIT;
  395. if (requestValidator instanceof TipRequestValidator)
  396. return RequestPolicy.TIP;
  397. if (requestValidator instanceof ReachableCommitTipRequestValidator)
  398. return RequestPolicy.REACHABLE_COMMIT_TIP;
  399. if (requestValidator instanceof AnyRequestValidator)
  400. return RequestPolicy.ANY;
  401. return null;
  402. }
  403. /**
  404. * Set the policy used to enforce validation of a client's want list.
  405. *
  406. * @param policy
  407. * the policy used to enforce validation of a client's want list.
  408. * By default the policy is
  409. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#ADVERTISED},
  410. * which is the Git default requiring clients to only ask for an
  411. * object that a reference directly points to. This may be
  412. * relaxed to
  413. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT}
  414. * or
  415. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT_TIP}
  416. * when callers have {@link #setBiDirectionalPipe(boolean)} set
  417. * to false. Overrides any policy specified in a
  418. * {@link org.eclipse.jgit.transport.TransferConfig}.
  419. */
  420. public void setRequestPolicy(RequestPolicy policy) {
  421. switch (policy) {
  422. case ADVERTISED:
  423. default:
  424. requestValidator = new AdvertisedRequestValidator();
  425. break;
  426. case REACHABLE_COMMIT:
  427. requestValidator = new ReachableCommitRequestValidator();
  428. break;
  429. case TIP:
  430. requestValidator = new TipRequestValidator();
  431. break;
  432. case REACHABLE_COMMIT_TIP:
  433. requestValidator = new ReachableCommitTipRequestValidator();
  434. break;
  435. case ANY:
  436. requestValidator = new AnyRequestValidator();
  437. break;
  438. }
  439. }
  440. /**
  441. * Set custom validator for client want list.
  442. *
  443. * @param validator
  444. * custom validator for client want list.
  445. * @since 3.1
  446. */
  447. public void setRequestValidator(RequestValidator validator) {
  448. requestValidator = validator != null ? validator
  449. : new AdvertisedRequestValidator();
  450. }
  451. /**
  452. * Get the hook used while advertising the refs to the client.
  453. *
  454. * @return the hook used while advertising the refs to the client.
  455. */
  456. public AdvertiseRefsHook getAdvertiseRefsHook() {
  457. return advertiseRefsHook;
  458. }
  459. /**
  460. * Get the filter used while advertising the refs to the client.
  461. *
  462. * @return the filter used while advertising the refs to the client.
  463. */
  464. public RefFilter getRefFilter() {
  465. return refFilter;
  466. }
  467. /**
  468. * Set the hook used while advertising the refs to the client.
  469. * <p>
  470. * If the {@link org.eclipse.jgit.transport.AdvertiseRefsHook} chooses to
  471. * call {@link #setAdvertisedRefs(Map)}, only refs set by this hook
  472. * <em>and</em> selected by the {@link org.eclipse.jgit.transport.RefFilter}
  473. * will be shown to the client.
  474. *
  475. * @param advertiseRefsHook
  476. * the hook; may be null to show all refs.
  477. */
  478. public void setAdvertiseRefsHook(final AdvertiseRefsHook advertiseRefsHook) {
  479. if (advertiseRefsHook != null)
  480. this.advertiseRefsHook = advertiseRefsHook;
  481. else
  482. this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  483. }
  484. /**
  485. * Set the filter used while advertising the refs to the client.
  486. * <p>
  487. * Only refs allowed by this filter will be sent to the client. The filter
  488. * is run against the refs specified by the
  489. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} (if applicable). If
  490. * null or not set, uses the filter implied by the
  491. * {@link org.eclipse.jgit.transport.TransferConfig}.
  492. *
  493. * @param refFilter
  494. * the filter; may be null to show all refs.
  495. */
  496. public void setRefFilter(final RefFilter refFilter) {
  497. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  498. }
  499. /**
  500. * Get the configured pre upload hook.
  501. *
  502. * @return the configured pre upload hook.
  503. */
  504. public PreUploadHook getPreUploadHook() {
  505. return preUploadHook;
  506. }
  507. /**
  508. * Set the hook that controls how this instance will behave.
  509. *
  510. * @param hook
  511. * the hook; if null no special actions are taken.
  512. */
  513. public void setPreUploadHook(PreUploadHook hook) {
  514. preUploadHook = hook != null ? hook : PreUploadHook.NULL;
  515. }
  516. /**
  517. * Get the configured post upload hook.
  518. *
  519. * @return the configured post upload hook.
  520. * @since 4.1
  521. */
  522. public PostUploadHook getPostUploadHook() {
  523. return postUploadHook;
  524. }
  525. /**
  526. * Set the hook for post upload actions (logging, repacking).
  527. *
  528. * @param hook
  529. * the hook; if null no special actions are taken.
  530. * @since 4.1
  531. */
  532. public void setPostUploadHook(PostUploadHook hook) {
  533. postUploadHook = hook != null ? hook : PostUploadHook.NULL;
  534. }
  535. /**
  536. * Set the configuration used by the pack generator.
  537. *
  538. * @param pc
  539. * configuration controlling packing parameters. If null the
  540. * source repository's settings will be used.
  541. */
  542. public void setPackConfig(PackConfig pc) {
  543. this.packConfig = pc;
  544. }
  545. /**
  546. * Set configuration controlling transfer options.
  547. *
  548. * @param tc
  549. * configuration controlling transfer options. If null the source
  550. * repository's settings will be used.
  551. * @since 3.1
  552. */
  553. public void setTransferConfig(TransferConfig tc) {
  554. this.transferConfig = tc != null ? tc : new TransferConfig(db);
  555. if (transferConfig.isAllowTipSha1InWant()) {
  556. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  557. ? RequestPolicy.REACHABLE_COMMIT_TIP : RequestPolicy.TIP);
  558. } else {
  559. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  560. ? RequestPolicy.REACHABLE_COMMIT : RequestPolicy.ADVERTISED);
  561. }
  562. }
  563. /**
  564. * Get the configured logger.
  565. *
  566. * @return the configured logger.
  567. * @deprecated Use {@link #getPreUploadHook()}.
  568. */
  569. @Deprecated
  570. public UploadPackLogger getLogger() {
  571. return logger;
  572. }
  573. /**
  574. * Set the logger.
  575. *
  576. * @param logger
  577. * the logger instance. If null, no logging occurs.
  578. * @deprecated Use {@link #setPreUploadHook(PreUploadHook)}.
  579. */
  580. @Deprecated
  581. public void setLogger(UploadPackLogger logger) {
  582. this.logger = logger;
  583. }
  584. /**
  585. * Check whether the client expects a side-band stream.
  586. *
  587. * @return true if the client has advertised a side-band capability, false
  588. * otherwise.
  589. * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  590. * if the client's request has not yet been read from the wire, so
  591. * we do not know if they expect side-band. Note that the client
  592. * may have already written the request, it just has not been
  593. * read.
  594. */
  595. public boolean isSideBand() throws RequestNotYetReadException {
  596. if (options == null)
  597. throw new RequestNotYetReadException();
  598. return (options.contains(OPTION_SIDE_BAND)
  599. || options.contains(OPTION_SIDE_BAND_64K));
  600. }
  601. /**
  602. * Execute the upload task on the socket.
  603. *
  604. * @param input
  605. * raw input to read client commands from. Caller must ensure the
  606. * input is buffered, otherwise read performance may suffer.
  607. * @param output
  608. * response back to the Git network client, to write the pack
  609. * data onto. Caller must ensure the output is buffered,
  610. * otherwise write performance may suffer.
  611. * @param messages
  612. * secondary "notice" channel to send additional messages out
  613. * through. When run over SSH this should be tied back to the
  614. * standard error channel of the command execution. For most
  615. * other network connections this should be null.
  616. * @throws java.io.IOException
  617. */
  618. public void upload(final InputStream input, OutputStream output,
  619. final OutputStream messages) throws IOException {
  620. try {
  621. rawIn = input;
  622. if (messages != null)
  623. msgOut = messages;
  624. if (timeout > 0) {
  625. final Thread caller = Thread.currentThread();
  626. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  627. TimeoutInputStream i = new TimeoutInputStream(rawIn, timer);
  628. @SuppressWarnings("resource")
  629. TimeoutOutputStream o = new TimeoutOutputStream(output, timer);
  630. i.setTimeout(timeout * 1000);
  631. o.setTimeout(timeout * 1000);
  632. rawIn = i;
  633. output = o;
  634. }
  635. rawOut = new ResponseBufferedOutputStream(output);
  636. if (biDirectionalPipe) {
  637. rawOut.stopBuffering();
  638. }
  639. pckIn = new PacketLineIn(rawIn);
  640. pckOut = new PacketLineOut(rawOut);
  641. service();
  642. } finally {
  643. msgOut = NullOutputStream.INSTANCE;
  644. walk.close();
  645. if (timer != null) {
  646. try {
  647. timer.terminate();
  648. } finally {
  649. timer = null;
  650. }
  651. }
  652. }
  653. }
  654. /**
  655. * Get the PackWriter's statistics if a pack was sent to the client.
  656. *
  657. * @return statistics about pack output, if a pack was sent. Null if no pack
  658. * was sent, such as during the negotiation phase of a smart HTTP
  659. * connection, or if the client was already up-to-date.
  660. * @since 3.0
  661. * @deprecated Use {@link #getStatistics()}.
  662. */
  663. @Deprecated
  664. public PackWriter.Statistics getPackStatistics() {
  665. return statistics == null ? null
  666. : new PackWriter.Statistics(statistics);
  667. }
  668. /**
  669. * Get the PackWriter's statistics if a pack was sent to the client.
  670. *
  671. * @return statistics about pack output, if a pack was sent. Null if no pack
  672. * was sent, such as during the negotiation phase of a smart HTTP
  673. * connection, or if the client was already up-to-date.
  674. * @since 4.1
  675. */
  676. public PackStatistics getStatistics() {
  677. return statistics;
  678. }
  679. private Map<String, Ref> getAdvertisedOrDefaultRefs() throws IOException {
  680. if (refs != null) {
  681. return refs;
  682. }
  683. advertiseRefsHook.advertiseRefs(this);
  684. if (refs == null) {
  685. setAdvertisedRefs(db.getRefDatabase().getRefs(ALL));
  686. }
  687. return refs;
  688. }
  689. private void service() throws IOException {
  690. boolean sendPack = false;
  691. // If it's a non-bidi request, we need to read the entire request before
  692. // writing a response. Buffer the response until then.
  693. try {
  694. if (biDirectionalPipe)
  695. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  696. else if (requestValidator instanceof AnyRequestValidator)
  697. advertised = Collections.emptySet();
  698. else
  699. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  700. recvWants();
  701. if (wantIds.isEmpty()) {
  702. preUploadHook.onBeginNegotiateRound(this, wantIds, 0);
  703. preUploadHook.onEndNegotiateRound(this, wantIds, 0, 0, false);
  704. return;
  705. }
  706. if (options.contains(OPTION_MULTI_ACK_DETAILED)) {
  707. multiAck = MultiAck.DETAILED;
  708. noDone = options.contains(OPTION_NO_DONE);
  709. } else if (options.contains(OPTION_MULTI_ACK))
  710. multiAck = MultiAck.CONTINUE;
  711. else
  712. multiAck = MultiAck.OFF;
  713. if (!clientShallowCommits.isEmpty())
  714. verifyClientShallow();
  715. if (depth != 0)
  716. processShallow();
  717. if (!clientShallowCommits.isEmpty())
  718. walk.assumeShallow(clientShallowCommits);
  719. sendPack = negotiate();
  720. if (sendPack && !biDirectionalPipe) {
  721. // Ensure the request was fully consumed. Any remaining input must
  722. // be a protocol error. If we aren't at EOF the implementation is broken.
  723. int eof = rawIn.read();
  724. if (0 <= eof) {
  725. sendPack = false;
  726. throw new CorruptObjectException(MessageFormat.format(
  727. JGitText.get().expectedEOFReceived,
  728. "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  729. }
  730. }
  731. } catch (ServiceMayNotContinueException err) {
  732. if (!err.isOutput() && err.getMessage() != null) {
  733. try {
  734. pckOut.writeString("ERR " + err.getMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  735. err.setOutput();
  736. } catch (Throwable err2) {
  737. // Ignore this secondary failure (and not mark output).
  738. }
  739. }
  740. throw err;
  741. } catch (IOException | RuntimeException | Error err) {
  742. boolean output = false;
  743. try {
  744. String msg = err instanceof PackProtocolException
  745. ? err.getMessage()
  746. : JGitText.get().internalServerError;
  747. pckOut.writeString("ERR " + msg + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  748. output = true;
  749. } catch (Throwable err2) {
  750. // Ignore this secondary failure, leave output false.
  751. }
  752. if (output) {
  753. throw new UploadPackInternalServerErrorException(err);
  754. }
  755. throw err;
  756. } finally {
  757. if (!sendPack && !biDirectionalPipe) {
  758. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  759. // Discard until EOF.
  760. }
  761. }
  762. rawOut.stopBuffering();
  763. }
  764. if (sendPack)
  765. sendPack();
  766. }
  767. private static Set<ObjectId> refIdSet(Collection<Ref> refs) {
  768. Set<ObjectId> ids = new HashSet<>(refs.size());
  769. for (Ref ref : refs) {
  770. ObjectId id = ref.getObjectId();
  771. if (id != null) {
  772. ids.add(id);
  773. }
  774. id = ref.getPeeledObjectId();
  775. if (id != null) {
  776. ids.add(id);
  777. }
  778. }
  779. return ids;
  780. }
  781. private void processShallow() throws IOException {
  782. int walkDepth = depth - 1;
  783. try (DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(
  784. walk.getObjectReader(), walkDepth)) {
  785. // Find all the commits which will be shallow
  786. for (ObjectId o : wantIds) {
  787. try {
  788. depthWalk.markRoot(depthWalk.parseCommit(o));
  789. } catch (IncorrectObjectTypeException notCommit) {
  790. // Ignore non-commits in this loop.
  791. }
  792. }
  793. RevCommit o;
  794. while ((o = depthWalk.next()) != null) {
  795. DepthWalk.Commit c = (DepthWalk.Commit) o;
  796. // Commits at the boundary which aren't already shallow in
  797. // the client need to be marked as such
  798. if (c.getDepth() == walkDepth
  799. && !clientShallowCommits.contains(c))
  800. pckOut.writeString("shallow " + o.name()); //$NON-NLS-1$
  801. // Commits not on the boundary which are shallow in the client
  802. // need to become unshallowed
  803. if (c.getDepth() < walkDepth
  804. && clientShallowCommits.remove(c)) {
  805. unshallowCommits.add(c.copy());
  806. pckOut.writeString("unshallow " + c.name()); //$NON-NLS-1$
  807. }
  808. }
  809. }
  810. pckOut.end();
  811. }
  812. private void verifyClientShallow()
  813. throws IOException, PackProtocolException {
  814. AsyncRevObjectQueue q = walk.parseAny(clientShallowCommits, true);
  815. try {
  816. for (;;) {
  817. try {
  818. // Shallow objects named by the client must be commits.
  819. RevObject o = q.next();
  820. if (o == null) {
  821. break;
  822. }
  823. if (!(o instanceof RevCommit)) {
  824. throw new PackProtocolException(
  825. MessageFormat.format(
  826. JGitText.get().invalidShallowObject,
  827. o.name()));
  828. }
  829. } catch (MissingObjectException notCommit) {
  830. // shallow objects not known at the server are ignored
  831. // by git-core upload-pack, match that behavior.
  832. clientShallowCommits.remove(notCommit.getObjectId());
  833. continue;
  834. }
  835. }
  836. } finally {
  837. q.release();
  838. }
  839. }
  840. /**
  841. * Generate an advertisement of available refs and capabilities.
  842. *
  843. * @param adv
  844. * the advertisement formatter.
  845. * @throws java.io.IOException
  846. * the formatter failed to write an advertisement.
  847. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  848. * the hook denied advertisement.
  849. */
  850. public void sendAdvertisedRefs(final RefAdvertiser adv) throws IOException,
  851. ServiceMayNotContinueException {
  852. Map<String, Ref> advertisedOrDefaultRefs = getAdvertisedOrDefaultRefs();
  853. adv.init(db);
  854. adv.advertiseCapability(OPTION_INCLUDE_TAG);
  855. adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED);
  856. adv.advertiseCapability(OPTION_MULTI_ACK);
  857. adv.advertiseCapability(OPTION_OFS_DELTA);
  858. adv.advertiseCapability(OPTION_SIDE_BAND);
  859. adv.advertiseCapability(OPTION_SIDE_BAND_64K);
  860. adv.advertiseCapability(OPTION_THIN_PACK);
  861. adv.advertiseCapability(OPTION_NO_PROGRESS);
  862. adv.advertiseCapability(OPTION_SHALLOW);
  863. if (!biDirectionalPipe)
  864. adv.advertiseCapability(OPTION_NO_DONE);
  865. RequestPolicy policy = getRequestPolicy();
  866. if (policy == RequestPolicy.TIP
  867. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  868. || policy == null)
  869. adv.advertiseCapability(OPTION_ALLOW_TIP_SHA1_IN_WANT);
  870. if (policy == RequestPolicy.REACHABLE_COMMIT
  871. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  872. || policy == null)
  873. adv.advertiseCapability(OPTION_ALLOW_REACHABLE_SHA1_IN_WANT);
  874. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  875. adv.setDerefTags(true);
  876. findSymrefs(adv, advertisedOrDefaultRefs);
  877. advertised = adv.send(advertisedOrDefaultRefs);
  878. if (adv.isEmpty())
  879. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  880. adv.end();
  881. }
  882. /**
  883. * Send a message to the client, if it supports receiving them.
  884. * <p>
  885. * If the client doesn't support receiving messages, the message will be
  886. * discarded, with no other indication to the caller or to the client.
  887. *
  888. * @param what
  889. * string describing the problem identified by the hook. The
  890. * string must not end with an LF, and must not contain an LF.
  891. * @since 3.1
  892. */
  893. public void sendMessage(String what) {
  894. try {
  895. msgOut.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  896. } catch (IOException e) {
  897. // Ignore write failures.
  898. }
  899. }
  900. /**
  901. * Get an underlying stream for sending messages to the client
  902. *
  903. * @return an underlying stream for sending messages to the client, or null.
  904. * @since 3.1
  905. */
  906. public OutputStream getMessageOutputStream() {
  907. return msgOut;
  908. }
  909. private void recvWants() throws IOException {
  910. boolean isFirst = true;
  911. for (;;) {
  912. String line;
  913. try {
  914. line = pckIn.readString();
  915. } catch (EOFException eof) {
  916. if (isFirst)
  917. break;
  918. throw eof;
  919. }
  920. if (line == PacketLineIn.END)
  921. break;
  922. if (line.startsWith("deepen ")) { //$NON-NLS-1$
  923. depth = Integer.parseInt(line.substring(7));
  924. if (depth <= 0) {
  925. throw new PackProtocolException(
  926. MessageFormat.format(JGitText.get().invalidDepth,
  927. Integer.valueOf(depth)));
  928. }
  929. continue;
  930. }
  931. if (line.startsWith("shallow ")) { //$NON-NLS-1$
  932. clientShallowCommits.add(ObjectId.fromString(line.substring(8)));
  933. continue;
  934. }
  935. if (!line.startsWith("want ") || line.length() < 45) //$NON-NLS-1$
  936. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "want", line)); //$NON-NLS-1$
  937. if (isFirst) {
  938. if (line.length() > 45) {
  939. FirstLine firstLine = new FirstLine(line);
  940. options = firstLine.getOptions();
  941. line = firstLine.getLine();
  942. } else
  943. options = Collections.emptySet();
  944. }
  945. wantIds.add(ObjectId.fromString(line.substring(5)));
  946. isFirst = false;
  947. }
  948. }
  949. /**
  950. * Returns the clone/fetch depth. Valid only after calling recvWants(). A
  951. * depth of 1 means return only the wants.
  952. *
  953. * @return the depth requested by the client, or 0 if unbounded.
  954. * @since 4.0
  955. */
  956. public int getDepth() {
  957. if (options == null)
  958. throw new RequestNotYetReadException();
  959. return depth;
  960. }
  961. /**
  962. * Get the user agent of the client.
  963. * <p>
  964. * If the client is new enough to use {@code agent=} capability that value
  965. * will be returned. Older HTTP clients may also supply their version using
  966. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  967. * header if both are available.
  968. * <p>
  969. * When an HTTP request has been received this method returns the HTTP
  970. * {@code User-Agent} header value until capabilities have been parsed.
  971. *
  972. * @return user agent supplied by the client. Available only if the client
  973. * is new enough to advertise its user agent.
  974. * @since 4.0
  975. */
  976. public String getPeerUserAgent() {
  977. return UserAgent.getAgent(options, userAgent);
  978. }
  979. private boolean negotiate() throws IOException {
  980. okToGiveUp = Boolean.FALSE;
  981. ObjectId last = ObjectId.zeroId();
  982. List<ObjectId> peerHas = new ArrayList<>(64);
  983. for (;;) {
  984. String line;
  985. try {
  986. line = pckIn.readString();
  987. } catch (EOFException eof) {
  988. // EOF on stateless RPC (aka smart HTTP) and non-shallow request
  989. // means the client asked for the updated shallow/unshallow data,
  990. // disconnected, and will try another request with actual want/have.
  991. // Don't report the EOF here, its a bug in the protocol that the client
  992. // just disconnects without sending an END.
  993. if (!biDirectionalPipe && depth > 0)
  994. return false;
  995. throw eof;
  996. }
  997. if (line == PacketLineIn.END) {
  998. last = processHaveLines(peerHas, last);
  999. if (commonBase.isEmpty() || multiAck != MultiAck.OFF)
  1000. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1001. if (noDone && sentReady) {
  1002. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1003. return true;
  1004. }
  1005. if (!biDirectionalPipe)
  1006. return false;
  1007. pckOut.flush();
  1008. } else if (line.startsWith("have ") && line.length() == 45) { //$NON-NLS-1$
  1009. peerHas.add(ObjectId.fromString(line.substring(5)));
  1010. } else if (line.equals("done")) { //$NON-NLS-1$
  1011. last = processHaveLines(peerHas, last);
  1012. if (commonBase.isEmpty())
  1013. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1014. else if (multiAck != MultiAck.OFF)
  1015. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1016. return true;
  1017. } else {
  1018. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "have", line)); //$NON-NLS-1$
  1019. }
  1020. }
  1021. }
  1022. private ObjectId processHaveLines(List<ObjectId> peerHas, ObjectId last)
  1023. throws IOException {
  1024. preUploadHook.onBeginNegotiateRound(this, wantIds, peerHas.size());
  1025. if (wantAll.isEmpty() && !wantIds.isEmpty())
  1026. parseWants();
  1027. if (peerHas.isEmpty())
  1028. return last;
  1029. sentReady = false;
  1030. int haveCnt = 0;
  1031. walk.getObjectReader().setAvoidUnreachableObjects(true);
  1032. AsyncRevObjectQueue q = walk.parseAny(peerHas, false);
  1033. try {
  1034. for (;;) {
  1035. RevObject obj;
  1036. try {
  1037. obj = q.next();
  1038. } catch (MissingObjectException notFound) {
  1039. continue;
  1040. }
  1041. if (obj == null)
  1042. break;
  1043. last = obj;
  1044. haveCnt++;
  1045. if (obj instanceof RevCommit) {
  1046. RevCommit c = (RevCommit) obj;
  1047. if (oldestTime == 0 || c.getCommitTime() < oldestTime)
  1048. oldestTime = c.getCommitTime();
  1049. }
  1050. if (obj.has(PEER_HAS))
  1051. continue;
  1052. obj.add(PEER_HAS);
  1053. if (obj instanceof RevCommit)
  1054. ((RevCommit) obj).carry(PEER_HAS);
  1055. addCommonBase(obj);
  1056. // If both sides have the same object; let the client know.
  1057. //
  1058. switch (multiAck) {
  1059. case OFF:
  1060. if (commonBase.size() == 1)
  1061. pckOut.writeString("ACK " + obj.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1062. break;
  1063. case CONTINUE:
  1064. pckOut.writeString("ACK " + obj.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1065. break;
  1066. case DETAILED:
  1067. pckOut.writeString("ACK " + obj.name() + " common\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1068. break;
  1069. }
  1070. }
  1071. } finally {
  1072. q.release();
  1073. walk.getObjectReader().setAvoidUnreachableObjects(false);
  1074. }
  1075. int missCnt = peerHas.size() - haveCnt;
  1076. // If we don't have one of the objects but we're also willing to
  1077. // create a pack at this point, let the client know so it stops
  1078. // telling us about its history.
  1079. //
  1080. boolean didOkToGiveUp = false;
  1081. if (0 < missCnt) {
  1082. for (int i = peerHas.size() - 1; i >= 0; i--) {
  1083. ObjectId id = peerHas.get(i);
  1084. if (walk.lookupOrNull(id) == null) {
  1085. didOkToGiveUp = true;
  1086. if (okToGiveUp()) {
  1087. switch (multiAck) {
  1088. case OFF:
  1089. break;
  1090. case CONTINUE:
  1091. pckOut.writeString("ACK " + id.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1092. break;
  1093. case DETAILED:
  1094. pckOut.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1095. sentReady = true;
  1096. break;
  1097. }
  1098. }
  1099. break;
  1100. }
  1101. }
  1102. }
  1103. if (multiAck == MultiAck.DETAILED && !didOkToGiveUp && okToGiveUp()) {
  1104. ObjectId id = peerHas.get(peerHas.size() - 1);
  1105. pckOut.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1106. sentReady = true;
  1107. }
  1108. preUploadHook.onEndNegotiateRound(this, wantAll, haveCnt, missCnt, sentReady);
  1109. peerHas.clear();
  1110. return last;
  1111. }
  1112. private void parseWants() throws IOException {
  1113. List<ObjectId> notAdvertisedWants = null;
  1114. for (ObjectId obj : wantIds) {
  1115. if (!advertised.contains(obj)) {
  1116. if (notAdvertisedWants == null)
  1117. notAdvertisedWants = new ArrayList<>();
  1118. notAdvertisedWants.add(obj);
  1119. }
  1120. }
  1121. if (notAdvertisedWants != null)
  1122. requestValidator.checkWants(this, notAdvertisedWants);
  1123. AsyncRevObjectQueue q = walk.parseAny(wantIds, true);
  1124. try {
  1125. RevObject obj;
  1126. while ((obj = q.next()) != null) {
  1127. want(obj);
  1128. if (!(obj instanceof RevCommit))
  1129. obj.add(SATISFIED);
  1130. if (obj instanceof RevTag) {
  1131. obj = walk.peel(obj);
  1132. if (obj instanceof RevCommit)
  1133. want(obj);
  1134. }
  1135. }
  1136. wantIds.clear();
  1137. } catch (MissingObjectException notFound) {
  1138. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1139. } finally {
  1140. q.release();
  1141. }
  1142. }
  1143. private void want(RevObject obj) {
  1144. if (!obj.has(WANT)) {
  1145. obj.add(WANT);
  1146. wantAll.add(obj);
  1147. }
  1148. }
  1149. /**
  1150. * Validator corresponding to {@link RequestPolicy#ADVERTISED}.
  1151. *
  1152. * @since 3.1
  1153. */
  1154. public static final class AdvertisedRequestValidator
  1155. implements RequestValidator {
  1156. @Override
  1157. public void checkWants(UploadPack up, List<ObjectId> wants)
  1158. throws PackProtocolException, IOException {
  1159. if (!up.isBiDirectionalPipe())
  1160. new ReachableCommitRequestValidator().checkWants(up, wants);
  1161. else if (!wants.isEmpty())
  1162. throw new WantNotValidException(wants.iterator().next());
  1163. }
  1164. }
  1165. /**
  1166. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT}.
  1167. *
  1168. * @since 3.1
  1169. */
  1170. public static final class ReachableCommitRequestValidator
  1171. implements RequestValidator {
  1172. @Override
  1173. public void checkWants(UploadPack up, List<ObjectId> wants)
  1174. throws PackProtocolException, IOException {
  1175. checkNotAdvertisedWants(up, wants,
  1176. refIdSet(up.getAdvertisedRefs().values()));
  1177. }
  1178. }
  1179. /**
  1180. * Validator corresponding to {@link RequestPolicy#TIP}.
  1181. *
  1182. * @since 3.1
  1183. */
  1184. public static final class TipRequestValidator implements RequestValidator {
  1185. @Override
  1186. public void checkWants(UploadPack up, List<ObjectId> wants)
  1187. throws PackProtocolException, IOException {
  1188. if (!up.isBiDirectionalPipe())
  1189. new ReachableCommitTipRequestValidator().checkWants(up, wants);
  1190. else if (!wants.isEmpty()) {
  1191. Set<ObjectId> refIds =
  1192. refIdSet(up.getRepository().getRefDatabase().getRefs(ALL).values());
  1193. for (ObjectId obj : wants) {
  1194. if (!refIds.contains(obj))
  1195. throw new WantNotValidException(obj);
  1196. }
  1197. }
  1198. }
  1199. }
  1200. /**
  1201. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT_TIP}.
  1202. *
  1203. * @since 3.1
  1204. */
  1205. public static final class ReachableCommitTipRequestValidator
  1206. implements RequestValidator {
  1207. @Override
  1208. public void checkWants(UploadPack up, List<ObjectId> wants)
  1209. throws PackProtocolException, IOException {
  1210. checkNotAdvertisedWants(up, wants,
  1211. refIdSet(up.getRepository().getRefDatabase().getRefs(ALL).values()));
  1212. }
  1213. }
  1214. /**
  1215. * Validator corresponding to {@link RequestPolicy#ANY}.
  1216. *
  1217. * @since 3.1
  1218. */
  1219. public static final class AnyRequestValidator implements RequestValidator {
  1220. @Override
  1221. public void checkWants(UploadPack up, List<ObjectId> wants)
  1222. throws PackProtocolException, IOException {
  1223. // All requests are valid.
  1224. }
  1225. }
  1226. private static void checkNotAdvertisedWantsUsingBitmap(ObjectReader reader,
  1227. BitmapIndex bitmapIndex, List<ObjectId> notAdvertisedWants,
  1228. Set<ObjectId> reachableFrom) throws IOException {
  1229. BitmapWalker bitmapWalker = new BitmapWalker(new ObjectWalk(reader), bitmapIndex, null);
  1230. BitmapBuilder reachables = bitmapWalker.findObjects(reachableFrom, null, false);
  1231. for (ObjectId oid : notAdvertisedWants) {
  1232. if (!reachables.contains(oid)) {
  1233. throw new WantNotValidException(oid);
  1234. }
  1235. }
  1236. }
  1237. private static void checkNotAdvertisedWants(UploadPack up,
  1238. List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom)
  1239. throws MissingObjectException, IncorrectObjectTypeException, IOException {
  1240. // Walk the requested commits back to the provided set of commits. If any
  1241. // commit exists, a branch was deleted or rewound and the repository owner
  1242. // no longer exports that requested item. If the requested commit is merged
  1243. // into an advertised branch it will be marked UNINTERESTING and no commits
  1244. // return.
  1245. ObjectReader reader = up.getRevWalk().getObjectReader();
  1246. try (RevWalk walk = new RevWalk(reader)) {
  1247. AsyncRevObjectQueue q = walk.parseAny(notAdvertisedWants, true);
  1248. try {
  1249. RevObject obj;
  1250. while ((obj = q.next()) != null) {
  1251. if (!(obj instanceof RevCommit)) {
  1252. // If unadvertized non-commits are requested, use
  1253. // bitmaps. If there are no bitmaps, instead of
  1254. // incurring the expense of a manual walk, reject
  1255. // the request.
  1256. BitmapIndex bitmapIndex = reader.getBitmapIndex();
  1257. if (bitmapIndex != null) {
  1258. checkNotAdvertisedWantsUsingBitmap(
  1259. reader,
  1260. bitmapIndex,
  1261. notAdvertisedWants,
  1262. reachableFrom);
  1263. return;
  1264. }
  1265. throw new WantNotValidException(obj);
  1266. }
  1267. walk.markStart((RevCommit) obj);
  1268. }
  1269. } catch (MissingObjectException notFound) {
  1270. throw new WantNotValidException(notFound.getObjectId(),
  1271. notFound);
  1272. } finally {
  1273. q.release();
  1274. }
  1275. for (ObjectId id : reachableFrom) {
  1276. try {
  1277. walk.markUninteresting(walk.parseCommit(id));
  1278. } catch (IncorrectObjectTypeException notCommit) {
  1279. continue;
  1280. }
  1281. }
  1282. RevCommit bad = walk.next();
  1283. if (bad != null) {
  1284. throw new WantNotValidException(bad);
  1285. }
  1286. }
  1287. }
  1288. private void addCommonBase(final RevObject o) {
  1289. if (!o.has(COMMON)) {
  1290. o.add(COMMON);
  1291. commonBase.add(o);
  1292. okToGiveUp = null;
  1293. }
  1294. }
  1295. private boolean okToGiveUp() throws PackProtocolException {
  1296. if (okToGiveUp == null)
  1297. okToGiveUp = Boolean.valueOf(okToGiveUpImp());
  1298. return okToGiveUp.booleanValue();
  1299. }
  1300. private boolean okToGiveUpImp() throws PackProtocolException {
  1301. if (commonBase.isEmpty())
  1302. return false;
  1303. try {
  1304. for (RevObject obj : wantAll) {
  1305. if (!wantSatisfied(obj))
  1306. return false;
  1307. }
  1308. return true;
  1309. } catch (IOException e) {
  1310. throw new PackProtocolException(JGitText.get().internalRevisionError, e);
  1311. }
  1312. }
  1313. private boolean wantSatisfied(final RevObject want) throws IOException {
  1314. if (want.has(SATISFIED))
  1315. return true;
  1316. walk.resetRetain(SAVE);
  1317. walk.markStart((RevCommit) want);
  1318. if (oldestTime != 0)
  1319. walk.setRevFilter(CommitTimeRevFilter.after(oldestTime * 1000L));
  1320. for (;;) {
  1321. final RevCommit c = walk.next();
  1322. if (c == null)
  1323. break;
  1324. if (c.has(PEER_HAS)) {
  1325. addCommonBase(c);
  1326. want.add(SATISFIED);
  1327. return true;
  1328. }
  1329. }
  1330. return false;
  1331. }
  1332. private void sendPack() throws IOException {
  1333. final boolean sideband = options.contains(OPTION_SIDE_BAND)
  1334. || options.contains(OPTION_SIDE_BAND_64K);
  1335. if (sideband) {
  1336. try {
  1337. sendPack(true);
  1338. } catch (ServiceMayNotContinueException noPack) {
  1339. // This was already reported on (below).
  1340. throw noPack;
  1341. } catch (IOException err) {
  1342. if (reportInternalServerErrorOverSideband())
  1343. throw new UploadPackInternalServerErrorException(err);
  1344. else
  1345. throw err;
  1346. } catch (RuntimeException err) {
  1347. if (reportInternalServerErrorOverSideband())
  1348. throw new UploadPackInternalServerErrorException(err);
  1349. else
  1350. throw err;
  1351. } catch (Error err) {
  1352. if (reportInternalServerErrorOverSideband())
  1353. throw new UploadPackInternalServerErrorException(err);
  1354. else
  1355. throw err;
  1356. }
  1357. } else {
  1358. sendPack(false);
  1359. }
  1360. }
  1361. private boolean reportInternalServerErrorOverSideband() {
  1362. try {
  1363. @SuppressWarnings("resource" /* java 7 */)
  1364. SideBandOutputStream err = new SideBandOutputStream(
  1365. SideBandOutputStream.CH_ERROR,
  1366. SideBandOutputStream.SMALL_BUF,
  1367. rawOut);
  1368. err.write(Constants.encode(JGitText.get().internalServerError));
  1369. err.flush();
  1370. return true;
  1371. } catch (Throwable cannotReport) {
  1372. // Ignore the reason. This is a secondary failure.
  1373. return false;
  1374. }
  1375. }
  1376. @SuppressWarnings("deprecation")
  1377. private void sendPack(final boolean sideband) throws IOException {
  1378. ProgressMonitor pm = NullProgressMonitor.INSTANCE;
  1379. OutputStream packOut = rawOut;
  1380. if (sideband) {
  1381. int bufsz = SideBandOutputStream.SMALL_BUF;
  1382. if (options.contains(OPTION_SIDE_BAND_64K))
  1383. bufsz = SideBandOutputStream.MAX_BUF;
  1384. packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA,
  1385. bufsz, rawOut);
  1386. if (!options.contains(OPTION_NO_PROGRESS)) {
  1387. msgOut = new SideBandOutputStream(
  1388. SideBandOutputStream.CH_PROGRESS, bufsz, rawOut);
  1389. pm = new SideBandProgressMonitor(msgOut);
  1390. }
  1391. }
  1392. try {
  1393. if (wantAll.isEmpty()) {
  1394. preUploadHook.onSendPack(this, wantIds, commonBase);
  1395. } else {
  1396. preUploadHook.onSendPack(this, wantAll, commonBase);
  1397. }
  1398. msgOut.flush();
  1399. } catch (ServiceMayNotContinueException noPack) {
  1400. if (sideband && noPack.getMessage() != null) {
  1401. noPack.setOutput();
  1402. @SuppressWarnings("resource" /* java 7 */)
  1403. SideBandOutputStream err = new SideBandOutputStream(
  1404. SideBandOutputStream.CH_ERROR,
  1405. SideBandOutputStream.SMALL_BUF, rawOut);
  1406. err.write(Constants.encode(noPack.getMessage()));
  1407. err.flush();
  1408. }
  1409. throw noPack;
  1410. }
  1411. PackConfig cfg = packConfig;
  1412. if (cfg == null)
  1413. cfg = new PackConfig(db);
  1414. final PackWriter pw = new PackWriter(cfg, walk.getObjectReader());
  1415. try {
  1416. pw.setIndexDisabled(true);
  1417. pw.setUseCachedPacks(true);
  1418. pw.setUseBitmaps(depth == 0 && clientShallowCommits.isEmpty());
  1419. pw.setClientShallowCommits(clientShallowCommits);
  1420. pw.setReuseDeltaCommits(true);
  1421. pw.setDeltaBaseAsOffset(options.contains(OPTION_OFS_DELTA));
  1422. pw.setThin(options.contains(OPTION_THIN_PACK));
  1423. pw.setReuseValidatingObjects(false);
  1424. if (commonBase.isEmpty() && refs != null) {
  1425. Set<ObjectId> tagTargets = new HashSet<>();
  1426. for (Ref ref : refs.values()) {
  1427. if (ref.getPeeledObjectId() != null)
  1428. tagTargets.add(ref.getPeeledObjectId());
  1429. else if (ref.getObjectId() == null)
  1430. continue;
  1431. else if (ref.getName().startsWith(Constants.R_HEADS))
  1432. tagTargets.add(ref.getObjectId());
  1433. }
  1434. pw.setTagTargets(tagTargets);
  1435. }
  1436. RevWalk rw = walk;
  1437. if (depth > 0) {
  1438. pw.setShallowPack(depth, unshallowCommits);
  1439. rw = new DepthWalk.RevWalk(walk.getObjectReader(), depth - 1);
  1440. rw.assumeShallow(clientShallowCommits);
  1441. }
  1442. if (wantAll.isEmpty()) {
  1443. pw.preparePack(pm, wantIds, commonBase, clientShallowCommits);
  1444. } else {
  1445. walk.reset();
  1446. ObjectWalk ow = rw.toObjectWalkWithSameObjects();
  1447. pw.preparePack(pm, ow, wantAll, commonBase, PackWriter.NONE);
  1448. rw = ow;
  1449. }
  1450. if (options.contains(OPTION_INCLUDE_TAG) && refs != null) {
  1451. for (Ref ref : refs.values()) {
  1452. ObjectId objectId = ref.getObjectId();
  1453. // If the object was already requested, skip it.
  1454. if (wantAll.isEmpty()) {
  1455. if (wantIds.contains(objectId))
  1456. continue;
  1457. } else {
  1458. RevObject obj = rw.lookupOrNull(objectId);
  1459. if (obj != null && obj.has(WANT))
  1460. continue;
  1461. }
  1462. if (!ref.isPeeled())
  1463. ref = db.peel(ref);
  1464. ObjectId peeledId = ref.getPeeledObjectId();
  1465. if (peeledId == null)
  1466. continue;
  1467. objectId = ref.getObjectId();
  1468. if (pw.willInclude(peeledId) && !pw.willInclude(objectId))
  1469. pw.addObject(rw.parseAny(objectId));
  1470. }
  1471. }
  1472. pw.writePack(pm, NullProgressMonitor.INSTANCE, packOut);
  1473. if (msgOut != NullOutputStream.INSTANCE) {
  1474. String msg = pw.getStatistics().getMessage() + '\n';
  1475. msgOut.write(Constants.encode(msg));
  1476. msgOut.flush();
  1477. }
  1478. } finally {
  1479. statistics = pw.getStatistics();
  1480. if (statistics != null) {
  1481. postUploadHook.onPostUpload(statistics);
  1482. logger.onPackStatistics(new PackWriter.Statistics(statistics));
  1483. }
  1484. pw.close();
  1485. }
  1486. if (sideband)
  1487. pckOut.end();
  1488. }
  1489. private static void findSymrefs(
  1490. final RefAdvertiser adv, final Map<String, Ref> refs) {
  1491. Ref head = refs.get(Constants.HEAD);
  1492. if (head != null && head.isSymbolic()) {
  1493. adv.addSymref(Constants.HEAD, head.getLeaf().getName());
  1494. }
  1495. }
  1496. private static class ResponseBufferedOutputStream extends OutputStream {
  1497. private final OutputStream rawOut;
  1498. private OutputStream out;
  1499. ResponseBufferedOutputStream(OutputStream rawOut) {
  1500. this.rawOut = rawOut;
  1501. this.out = new ByteArrayOutputStream();
  1502. }
  1503. @Override
  1504. public void write(int b) throws IOException {
  1505. out.write(b);
  1506. }
  1507. @Override
  1508. public void write(byte b[]) throws IOException {
  1509. out.write(b);
  1510. }
  1511. @Override
  1512. public void write(byte b[], int off, int len) throws IOException {
  1513. out.write(b, off, len);
  1514. }
  1515. @Override
  1516. public void flush() throws IOException {
  1517. out.flush();
  1518. }
  1519. @Override
  1520. public void close() throws IOException {
  1521. out.close();
  1522. }
  1523. void stopBuffering() throws IOException {
  1524. if (out != rawOut) {
  1525. ((ByteArrayOutputStream) out).writeTo(rawOut);
  1526. out = rawOut;
  1527. }
  1528. }
  1529. }
  1530. }