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 74KB

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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
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 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412
  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 java.util.Collections.unmodifiableMap;
  45. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  46. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_REF_IN_WANT;
  47. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_SERVER_OPTION;
  48. import static org.eclipse.jgit.transport.GitProtocolConstants.COMMAND_FETCH;
  49. import static org.eclipse.jgit.transport.GitProtocolConstants.COMMAND_LS_REFS;
  50. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  51. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_REACHABLE_SHA1_IN_WANT;
  52. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_TIP_SHA1_IN_WANT;
  53. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_DEEPEN_RELATIVE;
  54. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_FILTER;
  55. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_INCLUDE_TAG;
  56. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK;
  57. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK_DETAILED;
  58. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_DONE;
  59. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_PROGRESS;
  60. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_OFS_DELTA;
  61. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SHALLOW;
  62. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDEBAND_ALL;
  63. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND;
  64. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND_64K;
  65. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_THIN_PACK;
  66. import static org.eclipse.jgit.util.RefMap.toRefMap;
  67. import java.io.ByteArrayOutputStream;
  68. import java.io.EOFException;
  69. import java.io.IOException;
  70. import java.io.InputStream;
  71. import java.io.OutputStream;
  72. import java.io.UncheckedIOException;
  73. import java.text.MessageFormat;
  74. import java.util.ArrayList;
  75. import java.util.Collection;
  76. import java.util.Collections;
  77. import java.util.HashSet;
  78. import java.util.List;
  79. import java.util.Map;
  80. import java.util.Objects;
  81. import java.util.Optional;
  82. import java.util.Set;
  83. import java.util.TreeMap;
  84. import java.util.stream.Collectors;
  85. import org.eclipse.jgit.annotations.NonNull;
  86. import org.eclipse.jgit.annotations.Nullable;
  87. import org.eclipse.jgit.errors.CorruptObjectException;
  88. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  89. import org.eclipse.jgit.errors.MissingObjectException;
  90. import org.eclipse.jgit.errors.PackProtocolException;
  91. import org.eclipse.jgit.internal.JGitText;
  92. import org.eclipse.jgit.internal.storage.pack.CachedPackUriProvider;
  93. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  94. import org.eclipse.jgit.internal.transport.parser.FirstWant;
  95. import org.eclipse.jgit.lib.BitmapIndex;
  96. import org.eclipse.jgit.lib.BitmapIndex.BitmapBuilder;
  97. import org.eclipse.jgit.lib.Constants;
  98. import org.eclipse.jgit.lib.NullProgressMonitor;
  99. import org.eclipse.jgit.lib.ObjectId;
  100. import org.eclipse.jgit.lib.ObjectReader;
  101. import org.eclipse.jgit.lib.ProgressMonitor;
  102. import org.eclipse.jgit.lib.Ref;
  103. import org.eclipse.jgit.lib.RefDatabase;
  104. import org.eclipse.jgit.lib.Repository;
  105. import org.eclipse.jgit.revwalk.AsyncRevObjectQueue;
  106. import org.eclipse.jgit.revwalk.BitmapWalker;
  107. import org.eclipse.jgit.revwalk.DepthWalk;
  108. import org.eclipse.jgit.revwalk.ObjectWalk;
  109. import org.eclipse.jgit.revwalk.ReachabilityChecker;
  110. import org.eclipse.jgit.revwalk.RevCommit;
  111. import org.eclipse.jgit.revwalk.RevFlag;
  112. import org.eclipse.jgit.revwalk.RevFlagSet;
  113. import org.eclipse.jgit.revwalk.RevObject;
  114. import org.eclipse.jgit.revwalk.RevSort;
  115. import org.eclipse.jgit.revwalk.RevTag;
  116. import org.eclipse.jgit.revwalk.RevWalk;
  117. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  118. import org.eclipse.jgit.storage.pack.PackConfig;
  119. import org.eclipse.jgit.storage.pack.PackStatistics;
  120. import org.eclipse.jgit.transport.GitProtocolConstants.MultiAck;
  121. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  122. import org.eclipse.jgit.transport.TransferConfig.ProtocolVersion;
  123. import org.eclipse.jgit.util.io.InterruptTimer;
  124. import org.eclipse.jgit.util.io.NullOutputStream;
  125. import org.eclipse.jgit.util.io.TimeoutInputStream;
  126. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  127. /**
  128. * Implements the server side of a fetch connection, transmitting objects.
  129. */
  130. public class UploadPack {
  131. /** Policy the server uses to validate client requests */
  132. public static enum RequestPolicy {
  133. /** Client may only ask for objects the server advertised a reference for. */
  134. ADVERTISED,
  135. /**
  136. * Client may ask for any commit reachable from a reference advertised by
  137. * the server.
  138. */
  139. REACHABLE_COMMIT,
  140. /**
  141. * Client may ask for objects that are the tip of any reference, even if not
  142. * advertised.
  143. * <p>
  144. * This may happen, for example, when a custom {@link RefFilter} is set.
  145. *
  146. * @since 3.1
  147. */
  148. TIP,
  149. /**
  150. * Client may ask for any commit reachable from any reference, even if that
  151. * reference wasn't advertised.
  152. *
  153. * @since 3.1
  154. */
  155. REACHABLE_COMMIT_TIP,
  156. /** Client may ask for any SHA-1 in the repository. */
  157. ANY;
  158. }
  159. /**
  160. * Validator for client requests.
  161. *
  162. * @since 3.1
  163. */
  164. public interface RequestValidator {
  165. /**
  166. * Check a list of client wants against the request policy.
  167. *
  168. * @param up
  169. * {@link UploadPack} instance.
  170. * @param wants
  171. * objects the client requested that were not advertised.
  172. *
  173. * @throws PackProtocolException
  174. * if one or more wants is not valid.
  175. * @throws IOException
  176. * if a low-level exception occurred.
  177. * @since 3.1
  178. */
  179. void checkWants(UploadPack up, List<ObjectId> wants)
  180. throws PackProtocolException, IOException;
  181. }
  182. /**
  183. * Data in the first line of a want-list, the line itself plus options.
  184. *
  185. * @deprecated Use {@link FirstWant} instead
  186. */
  187. @Deprecated
  188. public static class FirstLine {
  189. private final FirstWant firstWant;
  190. /**
  191. * @param line
  192. * line from the client.
  193. */
  194. public FirstLine(String line) {
  195. try {
  196. firstWant = FirstWant.fromLine(line);
  197. } catch (PackProtocolException e) {
  198. throw new UncheckedIOException(e);
  199. }
  200. }
  201. /** @return non-capabilities part of the line. */
  202. public String getLine() {
  203. return firstWant.getLine();
  204. }
  205. /** @return capabilities parsed from the line. */
  206. public Set<String> getOptions() {
  207. if (firstWant.getAgent() != null) {
  208. Set<String> caps = new HashSet<>(firstWant.getCapabilities());
  209. caps.add(OPTION_AGENT + '=' + firstWant.getAgent());
  210. return caps;
  211. }
  212. return firstWant.getCapabilities();
  213. }
  214. }
  215. /*
  216. * {@link java.util.function.Consumer} doesn't allow throwing checked
  217. * exceptions. Define our own to propagate IOExceptions.
  218. */
  219. @FunctionalInterface
  220. private static interface IOConsumer<R> {
  221. void accept(R t) throws IOException;
  222. }
  223. /** Database we read the objects from. */
  224. private final Repository db;
  225. /** Revision traversal support over {@link #db}. */
  226. private final RevWalk walk;
  227. /** Configuration to pass into the PackWriter. */
  228. private PackConfig packConfig;
  229. /** Configuration for various transfer options. */
  230. private TransferConfig transferConfig;
  231. /** Timeout in seconds to wait for client interaction. */
  232. private int timeout;
  233. /**
  234. * Is the client connection a bi-directional socket or pipe?
  235. * <p>
  236. * If true, this class assumes it can perform multiple read and write cycles
  237. * with the client over the input and output streams. This matches the
  238. * functionality available with a standard TCP/IP connection, or a local
  239. * operating system or in-memory pipe.
  240. * <p>
  241. * If false, this class runs in a read everything then output results mode,
  242. * making it suitable for single round-trip systems RPCs such as HTTP.
  243. */
  244. private boolean biDirectionalPipe = true;
  245. /** Timer to manage {@link #timeout}. */
  246. private InterruptTimer timer;
  247. /**
  248. * Whether the client requested to use protocol V2 through a side
  249. * channel (such as the Git-Protocol HTTP header).
  250. */
  251. private boolean clientRequestedV2;
  252. private InputStream rawIn;
  253. private ResponseBufferedOutputStream rawOut;
  254. private PacketLineIn pckIn;
  255. private OutputStream msgOut = NullOutputStream.INSTANCE;
  256. /**
  257. * Refs eligible for advertising to the client, set using
  258. * {@link #setAdvertisedRefs}.
  259. */
  260. private Map<String, Ref> refs;
  261. /** Hook used while processing Git protocol v2 requests. */
  262. private ProtocolV2Hook protocolV2Hook = ProtocolV2Hook.DEFAULT;
  263. /** Hook used while advertising the refs to the client. */
  264. private AdvertiseRefsHook advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  265. /** Whether the {@link #advertiseRefsHook} has been invoked. */
  266. private boolean advertiseRefsHookCalled;
  267. /** Filter used while advertising the refs to the client. */
  268. private RefFilter refFilter = RefFilter.DEFAULT;
  269. /** Hook handling the various upload phases. */
  270. private PreUploadHook preUploadHook = PreUploadHook.NULL;
  271. /** Hook for taking post upload actions. */
  272. private PostUploadHook postUploadHook = PostUploadHook.NULL;
  273. /** Caller user agent */
  274. String userAgent;
  275. /** Raw ObjectIds the client has asked for, before validating them. */
  276. private Set<ObjectId> wantIds = new HashSet<>();
  277. /** Objects the client wants to obtain. */
  278. private final Set<RevObject> wantAll = new HashSet<>();
  279. /** Objects on both sides, these don't have to be sent. */
  280. private final Set<RevObject> commonBase = new HashSet<>();
  281. /** Commit time of the oldest common commit, in seconds. */
  282. private int oldestTime;
  283. /** null if {@link #commonBase} should be examined again. */
  284. private Boolean okToGiveUp;
  285. private boolean sentReady;
  286. /** Objects we sent in our advertisement list, clients can ask for these. */
  287. private Set<ObjectId> advertised;
  288. /** Marked on objects the client has asked us to give them. */
  289. private final RevFlag WANT;
  290. /** Marked on objects both we and the client have. */
  291. private final RevFlag PEER_HAS;
  292. /** Marked on objects in {@link #commonBase}. */
  293. private final RevFlag COMMON;
  294. /** Objects where we found a path from the want list to a common base. */
  295. private final RevFlag SATISFIED;
  296. private final RevFlagSet SAVE;
  297. private RequestValidator requestValidator = new AdvertisedRequestValidator();
  298. private MultiAck multiAck = MultiAck.OFF;
  299. private boolean noDone;
  300. private PackStatistics statistics;
  301. /**
  302. * Request this instance is handling.
  303. *
  304. * We need to keep a reference to it for {@link PreUploadHook pre upload
  305. * hooks}. They receive a reference this instance and invoke methods like
  306. * getDepth() to get information about the request.
  307. */
  308. private FetchRequest currentRequest;
  309. private CachedPackUriProvider cachedPackUriProvider;
  310. /**
  311. * Create a new pack upload for an open repository.
  312. *
  313. * @param copyFrom
  314. * the source repository.
  315. */
  316. public UploadPack(Repository copyFrom) {
  317. db = copyFrom;
  318. walk = new RevWalk(db);
  319. walk.setRetainBody(false);
  320. WANT = walk.newFlag("WANT"); //$NON-NLS-1$
  321. PEER_HAS = walk.newFlag("PEER_HAS"); //$NON-NLS-1$
  322. COMMON = walk.newFlag("COMMON"); //$NON-NLS-1$
  323. SATISFIED = walk.newFlag("SATISFIED"); //$NON-NLS-1$
  324. walk.carry(PEER_HAS);
  325. SAVE = new RevFlagSet();
  326. SAVE.add(WANT);
  327. SAVE.add(PEER_HAS);
  328. SAVE.add(COMMON);
  329. SAVE.add(SATISFIED);
  330. setTransferConfig(null);
  331. }
  332. /**
  333. * Get the repository this upload is reading from.
  334. *
  335. * @return the repository this upload is reading from.
  336. */
  337. public final Repository getRepository() {
  338. return db;
  339. }
  340. /**
  341. * Get the RevWalk instance used by this connection.
  342. *
  343. * @return the RevWalk instance used by this connection.
  344. */
  345. public final RevWalk getRevWalk() {
  346. return walk;
  347. }
  348. /**
  349. * Get refs which were advertised to the client.
  350. *
  351. * @return all refs which were advertised to the client, or null if
  352. * {@link #setAdvertisedRefs(Map)} has not been called yet.
  353. */
  354. public final Map<String, Ref> getAdvertisedRefs() {
  355. return refs;
  356. }
  357. /**
  358. * Set the refs advertised by this UploadPack.
  359. * <p>
  360. * Intended to be called from a
  361. * {@link org.eclipse.jgit.transport.PreUploadHook}.
  362. *
  363. * @param allRefs
  364. * explicit set of references to claim as advertised by this
  365. * UploadPack instance. This overrides any references that may
  366. * exist in the source repository. The map is passed to the
  367. * configured {@link #getRefFilter()}. If null, assumes all refs
  368. * were advertised.
  369. */
  370. public void setAdvertisedRefs(@Nullable Map<String, Ref> allRefs) {
  371. if (allRefs != null)
  372. refs = allRefs;
  373. else
  374. refs = db.getAllRefs();
  375. if (refFilter == RefFilter.DEFAULT)
  376. refs = transferConfig.getRefFilter().filter(refs);
  377. else
  378. refs = refFilter.filter(refs);
  379. }
  380. /**
  381. * Get timeout (in seconds) before aborting an IO operation.
  382. *
  383. * @return timeout (in seconds) before aborting an IO operation.
  384. */
  385. public int getTimeout() {
  386. return timeout;
  387. }
  388. /**
  389. * Set the timeout before willing to abort an IO call.
  390. *
  391. * @param seconds
  392. * number of seconds to wait (with no data transfer occurring)
  393. * before aborting an IO read or write operation with the
  394. * connected client.
  395. */
  396. public void setTimeout(int seconds) {
  397. timeout = seconds;
  398. }
  399. /**
  400. * Whether this class expects a bi-directional pipe opened between the
  401. * client and itself.
  402. *
  403. * @return true if this class expects a bi-directional pipe opened between
  404. * the client and itself. The default is true.
  405. */
  406. public boolean isBiDirectionalPipe() {
  407. return biDirectionalPipe;
  408. }
  409. /**
  410. * Set whether this class will assume the socket is a fully bidirectional
  411. * pipe between the two peers
  412. *
  413. * @param twoWay
  414. * if true, this class will assume the socket is a fully
  415. * bidirectional pipe between the two peers and takes advantage
  416. * of that by first transmitting the known refs, then waiting to
  417. * read commands. If false, this class assumes it must read the
  418. * commands before writing output and does not perform the
  419. * initial advertising.
  420. */
  421. public void setBiDirectionalPipe(boolean twoWay) {
  422. biDirectionalPipe = twoWay;
  423. }
  424. /**
  425. * Get policy used by the service to validate client requests
  426. *
  427. * @return policy used by the service to validate client requests, or null
  428. * for a custom request validator.
  429. */
  430. public RequestPolicy getRequestPolicy() {
  431. if (requestValidator instanceof AdvertisedRequestValidator)
  432. return RequestPolicy.ADVERTISED;
  433. if (requestValidator instanceof ReachableCommitRequestValidator)
  434. return RequestPolicy.REACHABLE_COMMIT;
  435. if (requestValidator instanceof TipRequestValidator)
  436. return RequestPolicy.TIP;
  437. if (requestValidator instanceof ReachableCommitTipRequestValidator)
  438. return RequestPolicy.REACHABLE_COMMIT_TIP;
  439. if (requestValidator instanceof AnyRequestValidator)
  440. return RequestPolicy.ANY;
  441. return null;
  442. }
  443. /**
  444. * Set the policy used to enforce validation of a client's want list.
  445. *
  446. * @param policy
  447. * the policy used to enforce validation of a client's want list.
  448. * By default the policy is
  449. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#ADVERTISED},
  450. * which is the Git default requiring clients to only ask for an
  451. * object that a reference directly points to. This may be
  452. * relaxed to
  453. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT}
  454. * or
  455. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT_TIP}
  456. * when callers have {@link #setBiDirectionalPipe(boolean)} set
  457. * to false. Overrides any policy specified in a
  458. * {@link org.eclipse.jgit.transport.TransferConfig}.
  459. */
  460. public void setRequestPolicy(RequestPolicy policy) {
  461. switch (policy) {
  462. case ADVERTISED:
  463. default:
  464. requestValidator = new AdvertisedRequestValidator();
  465. break;
  466. case REACHABLE_COMMIT:
  467. requestValidator = new ReachableCommitRequestValidator();
  468. break;
  469. case TIP:
  470. requestValidator = new TipRequestValidator();
  471. break;
  472. case REACHABLE_COMMIT_TIP:
  473. requestValidator = new ReachableCommitTipRequestValidator();
  474. break;
  475. case ANY:
  476. requestValidator = new AnyRequestValidator();
  477. break;
  478. }
  479. }
  480. /**
  481. * Set custom validator for client want list.
  482. *
  483. * @param validator
  484. * custom validator for client want list.
  485. * @since 3.1
  486. */
  487. public void setRequestValidator(@Nullable RequestValidator validator) {
  488. requestValidator = validator != null ? validator
  489. : new AdvertisedRequestValidator();
  490. }
  491. /**
  492. * Get the hook used while advertising the refs to the client.
  493. *
  494. * @return the hook used while advertising the refs to the client.
  495. */
  496. public AdvertiseRefsHook getAdvertiseRefsHook() {
  497. return advertiseRefsHook;
  498. }
  499. /**
  500. * Get the filter used while advertising the refs to the client.
  501. *
  502. * @return the filter used while advertising the refs to the client.
  503. */
  504. public RefFilter getRefFilter() {
  505. return refFilter;
  506. }
  507. /**
  508. * Set the hook used while advertising the refs to the client.
  509. * <p>
  510. * If the {@link org.eclipse.jgit.transport.AdvertiseRefsHook} chooses to
  511. * call {@link #setAdvertisedRefs(Map)}, only refs set by this hook
  512. * <em>and</em> selected by the {@link org.eclipse.jgit.transport.RefFilter}
  513. * will be shown to the client.
  514. *
  515. * @param advertiseRefsHook
  516. * the hook; may be null to show all refs.
  517. */
  518. public void setAdvertiseRefsHook(
  519. @Nullable AdvertiseRefsHook advertiseRefsHook) {
  520. this.advertiseRefsHook = advertiseRefsHook != null ? advertiseRefsHook
  521. : AdvertiseRefsHook.DEFAULT;
  522. }
  523. /**
  524. * Set the protocol V2 hook.
  525. *
  526. * @param hook
  527. * the hook; if null no special actions are taken.
  528. * @since 5.1
  529. */
  530. public void setProtocolV2Hook(@Nullable ProtocolV2Hook hook) {
  531. this.protocolV2Hook = hook != null ? hook : ProtocolV2Hook.DEFAULT;
  532. }
  533. /**
  534. * Get the currently installed protocol v2 hook.
  535. *
  536. * @return the hook or a default implementation if none installed.
  537. *
  538. * @since 5.5
  539. */
  540. public ProtocolV2Hook getProtocolV2Hook() {
  541. return this.protocolV2Hook != null ? this.protocolV2Hook
  542. : ProtocolV2Hook.DEFAULT;
  543. }
  544. /**
  545. * Set the filter used while advertising the refs to the client.
  546. * <p>
  547. * Only refs allowed by this filter will be sent to the client. The filter
  548. * is run against the refs specified by the
  549. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} (if applicable). If
  550. * null or not set, uses the filter implied by the
  551. * {@link org.eclipse.jgit.transport.TransferConfig}.
  552. *
  553. * @param refFilter
  554. * the filter; may be null to show all refs.
  555. */
  556. public void setRefFilter(@Nullable RefFilter refFilter) {
  557. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  558. }
  559. /**
  560. * Get the configured pre upload hook.
  561. *
  562. * @return the configured pre upload hook.
  563. */
  564. public PreUploadHook getPreUploadHook() {
  565. return preUploadHook;
  566. }
  567. /**
  568. * Set the hook that controls how this instance will behave.
  569. *
  570. * @param hook
  571. * the hook; if null no special actions are taken.
  572. */
  573. public void setPreUploadHook(@Nullable PreUploadHook hook) {
  574. preUploadHook = hook != null ? hook : PreUploadHook.NULL;
  575. }
  576. /**
  577. * Get the configured post upload hook.
  578. *
  579. * @return the configured post upload hook.
  580. * @since 4.1
  581. */
  582. public PostUploadHook getPostUploadHook() {
  583. return postUploadHook;
  584. }
  585. /**
  586. * Set the hook for post upload actions (logging, repacking).
  587. *
  588. * @param hook
  589. * the hook; if null no special actions are taken.
  590. * @since 4.1
  591. */
  592. public void setPostUploadHook(@Nullable PostUploadHook hook) {
  593. postUploadHook = hook != null ? hook : PostUploadHook.NULL;
  594. }
  595. /**
  596. * Set the configuration used by the pack generator.
  597. *
  598. * @param pc
  599. * configuration controlling packing parameters. If null the
  600. * source repository's settings will be used.
  601. */
  602. public void setPackConfig(@Nullable PackConfig pc) {
  603. this.packConfig = pc;
  604. }
  605. /**
  606. * Set configuration controlling transfer options.
  607. *
  608. * @param tc
  609. * configuration controlling transfer options. If null the source
  610. * repository's settings will be used.
  611. * @since 3.1
  612. */
  613. public void setTransferConfig(@Nullable TransferConfig tc) {
  614. this.transferConfig = tc != null ? tc : new TransferConfig(db);
  615. if (transferConfig.isAllowTipSha1InWant()) {
  616. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  617. ? RequestPolicy.REACHABLE_COMMIT_TIP : RequestPolicy.TIP);
  618. } else {
  619. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  620. ? RequestPolicy.REACHABLE_COMMIT : RequestPolicy.ADVERTISED);
  621. }
  622. }
  623. /**
  624. * Check whether the client expects a side-band stream.
  625. *
  626. * @return true if the client has advertised a side-band capability, false
  627. * otherwise.
  628. * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  629. * if the client's request has not yet been read from the wire, so
  630. * we do not know if they expect side-band. Note that the client
  631. * may have already written the request, it just has not been
  632. * read.
  633. */
  634. public boolean isSideBand() throws RequestNotYetReadException {
  635. if (currentRequest == null) {
  636. throw new RequestNotYetReadException();
  637. }
  638. Set<String> caps = currentRequest.getClientCapabilities();
  639. return caps.contains(OPTION_SIDE_BAND)
  640. || caps.contains(OPTION_SIDE_BAND_64K);
  641. }
  642. /**
  643. * Set the Extra Parameters provided by the client.
  644. *
  645. * <p>These are parameters passed by the client through a side channel
  646. * such as the Git-Protocol HTTP header, to allow a client to request
  647. * a newer response format while remaining compatible with older servers
  648. * that do not understand different request formats.
  649. *
  650. * @param params
  651. * parameters supplied by the client, split at colons or NUL
  652. * bytes.
  653. * @since 5.0
  654. */
  655. public void setExtraParameters(Collection<String> params) {
  656. this.clientRequestedV2 = params.contains("version=2"); //$NON-NLS-1$
  657. }
  658. /**
  659. * @param p provider of URIs corresponding to cached packs (to support
  660. * the packfile URIs feature)
  661. * @since 5.5
  662. */
  663. public void setCachedPackUriProvider(@Nullable CachedPackUriProvider p) {
  664. cachedPackUriProvider = p;
  665. }
  666. private boolean useProtocolV2() {
  667. return ProtocolVersion.V2.equals(transferConfig.protocolVersion)
  668. && clientRequestedV2;
  669. }
  670. /**
  671. * Execute the upload task on the socket.
  672. *
  673. * <p>If the client passed extra parameters (e.g., "version=2") through a
  674. * side channel, the caller must call setExtraParameters first to supply
  675. * them.
  676. *
  677. * @param input
  678. * raw input to read client commands from. Caller must ensure the
  679. * input is buffered, otherwise read performance may suffer.
  680. * @param output
  681. * response back to the Git network client, to write the pack
  682. * data onto. Caller must ensure the output is buffered,
  683. * otherwise write performance may suffer.
  684. * @param messages
  685. * secondary "notice" channel to send additional messages out
  686. * through. When run over SSH this should be tied back to the
  687. * standard error channel of the command execution. For most
  688. * other network connections this should be null.
  689. * @throws java.io.IOException
  690. */
  691. public void upload(InputStream input, OutputStream output,
  692. @Nullable OutputStream messages) throws IOException {
  693. PacketLineOut pckOut = null;
  694. try {
  695. rawIn = input;
  696. if (messages != null)
  697. msgOut = messages;
  698. if (timeout > 0) {
  699. final Thread caller = Thread.currentThread();
  700. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  701. TimeoutInputStream i = new TimeoutInputStream(rawIn, timer);
  702. @SuppressWarnings("resource")
  703. TimeoutOutputStream o = new TimeoutOutputStream(output, timer);
  704. i.setTimeout(timeout * 1000);
  705. o.setTimeout(timeout * 1000);
  706. rawIn = i;
  707. output = o;
  708. }
  709. rawOut = new ResponseBufferedOutputStream(output);
  710. if (biDirectionalPipe) {
  711. rawOut.stopBuffering();
  712. }
  713. pckIn = new PacketLineIn(rawIn);
  714. pckOut = new PacketLineOut(rawOut);
  715. if (useProtocolV2()) {
  716. serviceV2(pckOut);
  717. } else {
  718. service(pckOut);
  719. }
  720. } catch (UploadPackInternalServerErrorException err) {
  721. // UploadPackInternalServerErrorException is a special exception
  722. // that indicates an error is already written to the client. Do
  723. // nothing.
  724. throw err;
  725. } catch (ServiceMayNotContinueException err) {
  726. if (!err.isOutput() && err.getMessage() != null && pckOut != null) {
  727. try {
  728. pckOut.writeString("ERR " + err.getMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  729. } catch (IOException e) {
  730. err.addSuppressed(e);
  731. throw err;
  732. }
  733. err.setOutput();
  734. }
  735. throw err;
  736. } catch (IOException | RuntimeException | Error err) {
  737. if (pckOut != null) {
  738. String msg = err instanceof PackProtocolException
  739. ? err.getMessage()
  740. : JGitText.get().internalServerError;
  741. try {
  742. pckOut.writeString("ERR " + msg + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  743. } catch (IOException e) {
  744. err.addSuppressed(e);
  745. throw err;
  746. }
  747. throw new UploadPackInternalServerErrorException(err);
  748. }
  749. throw err;
  750. } finally {
  751. msgOut = NullOutputStream.INSTANCE;
  752. walk.close();
  753. if (timer != null) {
  754. try {
  755. timer.terminate();
  756. } finally {
  757. timer = null;
  758. }
  759. }
  760. }
  761. }
  762. /**
  763. * Get the PackWriter's statistics if a pack was sent to the client.
  764. *
  765. * @return statistics about pack output, if a pack was sent. Null if no pack
  766. * was sent, such as during the negotiation phase of a smart HTTP
  767. * connection, or if the client was already up-to-date.
  768. * @since 4.1
  769. */
  770. public PackStatistics getStatistics() {
  771. return statistics;
  772. }
  773. private Map<String, Ref> getAdvertisedOrDefaultRefs() throws IOException {
  774. if (refs != null) {
  775. return refs;
  776. }
  777. if (!advertiseRefsHookCalled) {
  778. advertiseRefsHook.advertiseRefs(this);
  779. advertiseRefsHookCalled = true;
  780. }
  781. if (refs == null) {
  782. // Fall back to all refs.
  783. setAdvertisedRefs(
  784. db.getRefDatabase().getRefs().stream()
  785. .collect(toRefMap((a, b) -> b)));
  786. }
  787. return refs;
  788. }
  789. private Map<String, Ref> getFilteredRefs(Collection<String> refPrefixes)
  790. throws IOException {
  791. if (refPrefixes.isEmpty()) {
  792. return getAdvertisedOrDefaultRefs();
  793. }
  794. if (refs == null && !advertiseRefsHookCalled) {
  795. advertiseRefsHook.advertiseRefs(this);
  796. advertiseRefsHookCalled = true;
  797. }
  798. if (refs == null) {
  799. // Fast path: the advertised refs hook did not set advertised refs.
  800. String[] prefixes = refPrefixes.toArray(new String[0]);
  801. Map<String, Ref> rs =
  802. db.getRefDatabase().getRefsByPrefix(prefixes).stream()
  803. .collect(toRefMap((a, b) -> b));
  804. if (refFilter != RefFilter.DEFAULT) {
  805. return refFilter.filter(rs);
  806. }
  807. return transferConfig.getRefFilter().filter(rs);
  808. }
  809. // Slow path: filter the refs provided by the advertised refs hook.
  810. // refFilter has already been applied to refs.
  811. return refs.values().stream()
  812. .filter(ref -> refPrefixes.stream()
  813. .anyMatch(ref.getName()::startsWith))
  814. .collect(toRefMap((a, b) -> b));
  815. }
  816. /**
  817. * Returns the specified references.
  818. * <p>
  819. * This produces an immutable map containing whatever subset of the
  820. * refs named by the caller are present in the supplied {@code refs}
  821. * map.
  822. *
  823. * @param refs
  824. * Map to search for refs to return.
  825. * @param names
  826. * which refs to search for in {@code refs}.
  827. * @return the requested Refs, omitting any that are null or missing.
  828. */
  829. @NonNull
  830. private static Map<String, Ref> mapRefs(
  831. Map<String, Ref> refs, List<String> names) {
  832. return unmodifiableMap(
  833. names.stream()
  834. .map(refs::get)
  835. .filter(Objects::nonNull)
  836. .collect(toRefMap((a, b) -> b)));
  837. }
  838. /**
  839. * Read refs on behalf of the client.
  840. * <p>
  841. * This checks whether the refs are present in the ref advertisement
  842. * since otherwise the client might not be supposed to be able to
  843. * read them.
  844. *
  845. * @param names
  846. * unabbreviated names of references.
  847. * @return the requested Refs, omitting any that are not visible or
  848. * do not exist.
  849. * @throws java.io.IOException
  850. * on failure to read a ref or check it for visibility.
  851. */
  852. @NonNull
  853. private Map<String, Ref> exactRefs(List<String> names) throws IOException {
  854. if (refs != null) {
  855. return mapRefs(refs, names);
  856. }
  857. if (!advertiseRefsHookCalled) {
  858. advertiseRefsHook.advertiseRefs(this);
  859. advertiseRefsHookCalled = true;
  860. }
  861. if (refs == null &&
  862. refFilter == RefFilter.DEFAULT &&
  863. transferConfig.hasDefaultRefFilter()) {
  864. // Fast path: no ref filtering is needed.
  865. String[] ns = names.toArray(new String[0]);
  866. return unmodifiableMap(db.getRefDatabase().exactRef(ns));
  867. }
  868. return mapRefs(getAdvertisedOrDefaultRefs(), names);
  869. }
  870. /**
  871. * Find a ref in the usual search path on behalf of the client.
  872. * <p>
  873. * This checks that the ref is present in the ref advertisement since
  874. * otherwise the client might not be supposed to be able to read it.
  875. *
  876. * @param name
  877. * short name of the ref to find, e.g. "master" to find
  878. * "refs/heads/master".
  879. * @return the requested Ref, or {@code null} if it is not visible or
  880. * does not exist.
  881. * @throws java.io.IOException
  882. * on failure to read the ref or check it for visibility.
  883. */
  884. @Nullable
  885. private Ref findRef(String name) throws IOException {
  886. if (refs != null) {
  887. return RefDatabase.findRef(refs, name);
  888. }
  889. if (!advertiseRefsHookCalled) {
  890. advertiseRefsHook.advertiseRefs(this);
  891. advertiseRefsHookCalled = true;
  892. }
  893. if (refs == null &&
  894. refFilter == RefFilter.DEFAULT &&
  895. transferConfig.hasDefaultRefFilter()) {
  896. // Fast path: no ref filtering is needed.
  897. return db.getRefDatabase().findRef(name);
  898. }
  899. return RefDatabase.findRef(getAdvertisedOrDefaultRefs(), name);
  900. }
  901. private void service(PacketLineOut pckOut) throws IOException {
  902. boolean sendPack = false;
  903. // If it's a non-bidi request, we need to read the entire request before
  904. // writing a response. Buffer the response until then.
  905. PackStatistics.Accumulator accumulator = new PackStatistics.Accumulator();
  906. List<ObjectId> unshallowCommits = new ArrayList<>();
  907. FetchRequest req;
  908. try {
  909. if (biDirectionalPipe)
  910. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  911. else if (requestValidator instanceof AnyRequestValidator)
  912. advertised = Collections.emptySet();
  913. else
  914. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  915. long negotiateStart = System.currentTimeMillis();
  916. accumulator.advertised = advertised.size();
  917. ProtocolV0Parser parser = new ProtocolV0Parser(transferConfig);
  918. req = parser.recvWants(pckIn);
  919. currentRequest = req;
  920. wantIds = req.getWantIds();
  921. if (req.getWantIds().isEmpty()) {
  922. preUploadHook.onBeginNegotiateRound(this, req.getWantIds(), 0);
  923. preUploadHook.onEndNegotiateRound(this, req.getWantIds(), 0, 0,
  924. false);
  925. return;
  926. }
  927. accumulator.wants = req.getWantIds().size();
  928. if (req.getClientCapabilities().contains(OPTION_MULTI_ACK_DETAILED)) {
  929. multiAck = MultiAck.DETAILED;
  930. noDone = req.getClientCapabilities().contains(OPTION_NO_DONE);
  931. } else if (req.getClientCapabilities().contains(OPTION_MULTI_ACK))
  932. multiAck = MultiAck.CONTINUE;
  933. else
  934. multiAck = MultiAck.OFF;
  935. if (!req.getClientShallowCommits().isEmpty()) {
  936. verifyClientShallow(req.getClientShallowCommits());
  937. }
  938. if (req.getDepth() != 0 || req.getDeepenSince() != 0) {
  939. computeShallowsAndUnshallows(req, shallow -> {
  940. pckOut.writeString("shallow " + shallow.name() + '\n'); //$NON-NLS-1$
  941. }, unshallow -> {
  942. pckOut.writeString("unshallow " + unshallow.name() + '\n'); //$NON-NLS-1$
  943. unshallowCommits.add(unshallow);
  944. }, Collections.emptyList());
  945. pckOut.end();
  946. }
  947. if (!req.getClientShallowCommits().isEmpty())
  948. walk.assumeShallow(req.getClientShallowCommits());
  949. sendPack = negotiate(req, accumulator, pckOut);
  950. accumulator.timeNegotiating += System.currentTimeMillis()
  951. - negotiateStart;
  952. if (sendPack && !biDirectionalPipe) {
  953. // Ensure the request was fully consumed. Any remaining input must
  954. // be a protocol error. If we aren't at EOF the implementation is broken.
  955. int eof = rawIn.read();
  956. if (0 <= eof) {
  957. sendPack = false;
  958. throw new CorruptObjectException(MessageFormat.format(
  959. JGitText.get().expectedEOFReceived,
  960. "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  961. }
  962. }
  963. } finally {
  964. if (!sendPack && !biDirectionalPipe) {
  965. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  966. // Discard until EOF.
  967. }
  968. }
  969. rawOut.stopBuffering();
  970. }
  971. if (sendPack) {
  972. sendPack(accumulator, req, refs == null ? null : refs.values(),
  973. unshallowCommits, Collections.emptyList(), pckOut);
  974. }
  975. }
  976. private void lsRefsV2(PacketLineOut pckOut) throws IOException {
  977. ProtocolV2Parser parser = new ProtocolV2Parser(transferConfig);
  978. LsRefsV2Request req = parser.parseLsRefsRequest(pckIn);
  979. protocolV2Hook.onLsRefs(req);
  980. rawOut.stopBuffering();
  981. PacketLineOutRefAdvertiser adv = new PacketLineOutRefAdvertiser(pckOut);
  982. adv.setUseProtocolV2(true);
  983. if (req.getPeel()) {
  984. adv.setDerefTags(true);
  985. }
  986. Map<String, Ref> refsToSend = getFilteredRefs(req.getRefPrefixes());
  987. if (req.getSymrefs()) {
  988. findSymrefs(adv, refsToSend);
  989. }
  990. adv.send(refsToSend.values());
  991. adv.end();
  992. }
  993. // Resolves ref names from the request's want-ref lines to
  994. // object ids, throwing PackProtocolException if any are missing.
  995. private Map<String, ObjectId> wantedRefs(FetchV2Request req)
  996. throws IOException {
  997. Map<String, ObjectId> result = new TreeMap<>();
  998. List<String> wanted = req.getWantedRefs();
  999. Map<String, Ref> resolved = exactRefs(wanted);
  1000. for (String refName : wanted) {
  1001. Ref ref = resolved.get(refName);
  1002. if (ref == null) {
  1003. throw new PackProtocolException(MessageFormat
  1004. .format(JGitText.get().invalidRefName, refName));
  1005. }
  1006. ObjectId oid = ref.getObjectId();
  1007. if (oid == null) {
  1008. throw new PackProtocolException(MessageFormat
  1009. .format(JGitText.get().invalidRefName, refName));
  1010. }
  1011. result.put(refName, oid);
  1012. }
  1013. return result;
  1014. }
  1015. private void fetchV2(PacketLineOut pckOut) throws IOException {
  1016. // Depending on the requestValidator, #processHaveLines may
  1017. // require that advertised be set. Set it only in the required
  1018. // circumstances (to avoid a full ref lookup in the case that
  1019. // we don't need it).
  1020. if (requestValidator instanceof TipRequestValidator ||
  1021. requestValidator instanceof ReachableCommitTipRequestValidator ||
  1022. requestValidator instanceof AnyRequestValidator) {
  1023. advertised = Collections.emptySet();
  1024. } else {
  1025. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  1026. }
  1027. ProtocolV2Parser parser = new ProtocolV2Parser(transferConfig);
  1028. FetchV2Request req = parser.parseFetchRequest(pckIn);
  1029. currentRequest = req;
  1030. rawOut.stopBuffering();
  1031. protocolV2Hook.onFetch(req);
  1032. if (req.getSidebandAll()) {
  1033. pckOut.setUsingSideband(true);
  1034. }
  1035. // TODO(ifrade): Refactor to pass around the Request object, instead of
  1036. // copying data back to class fields
  1037. List<ObjectId> deepenNots = new ArrayList<>();
  1038. for (String s : req.getDeepenNotRefs()) {
  1039. Ref ref = findRef(s);
  1040. if (ref == null) {
  1041. throw new PackProtocolException(MessageFormat
  1042. .format(JGitText.get().invalidRefName, s));
  1043. }
  1044. deepenNots.add(ref.getObjectId());
  1045. }
  1046. Map<String, ObjectId> wantedRefs = wantedRefs(req);
  1047. // TODO(ifrade): Avoid mutating the parsed request.
  1048. req.getWantIds().addAll(wantedRefs.values());
  1049. wantIds = req.getWantIds();
  1050. boolean sectionSent = false;
  1051. boolean mayHaveShallow = req.getDepth() != 0
  1052. || req.getDeepenSince() != 0
  1053. || !req.getDeepenNotRefs().isEmpty();
  1054. List<ObjectId> shallowCommits = new ArrayList<>();
  1055. List<ObjectId> unshallowCommits = new ArrayList<>();
  1056. if (!req.getClientShallowCommits().isEmpty()) {
  1057. verifyClientShallow(req.getClientShallowCommits());
  1058. }
  1059. if (mayHaveShallow) {
  1060. computeShallowsAndUnshallows(req,
  1061. shallowCommit -> shallowCommits.add(shallowCommit),
  1062. unshallowCommit -> unshallowCommits.add(unshallowCommit),
  1063. deepenNots);
  1064. }
  1065. if (!req.getClientShallowCommits().isEmpty())
  1066. walk.assumeShallow(req.getClientShallowCommits());
  1067. if (req.wasDoneReceived()) {
  1068. processHaveLines(req.getPeerHas(), ObjectId.zeroId(),
  1069. new PacketLineOut(NullOutputStream.INSTANCE));
  1070. } else {
  1071. pckOut.writeString("acknowledgments\n"); //$NON-NLS-1$
  1072. for (ObjectId id : req.getPeerHas()) {
  1073. if (walk.getObjectReader().has(id)) {
  1074. pckOut.writeString("ACK " + id.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1075. }
  1076. }
  1077. processHaveLines(req.getPeerHas(), ObjectId.zeroId(),
  1078. new PacketLineOut(NullOutputStream.INSTANCE));
  1079. if (okToGiveUp()) {
  1080. pckOut.writeString("ready\n"); //$NON-NLS-1$
  1081. } else if (commonBase.isEmpty()) {
  1082. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1083. }
  1084. sectionSent = true;
  1085. }
  1086. if (req.wasDoneReceived() || okToGiveUp()) {
  1087. if (mayHaveShallow) {
  1088. if (sectionSent)
  1089. pckOut.writeDelim();
  1090. pckOut.writeString("shallow-info\n"); //$NON-NLS-1$
  1091. for (ObjectId o : shallowCommits) {
  1092. pckOut.writeString("shallow " + o.getName() + '\n'); //$NON-NLS-1$
  1093. }
  1094. for (ObjectId o : unshallowCommits) {
  1095. pckOut.writeString("unshallow " + o.getName() + '\n'); //$NON-NLS-1$
  1096. }
  1097. sectionSent = true;
  1098. }
  1099. if (!wantedRefs.isEmpty()) {
  1100. if (sectionSent) {
  1101. pckOut.writeDelim();
  1102. }
  1103. pckOut.writeString("wanted-refs\n"); //$NON-NLS-1$
  1104. for (Map.Entry<String, ObjectId> entry :
  1105. wantedRefs.entrySet()) {
  1106. pckOut.writeString(entry.getValue().getName() + ' ' +
  1107. entry.getKey() + '\n');
  1108. }
  1109. sectionSent = true;
  1110. }
  1111. if (sectionSent)
  1112. pckOut.writeDelim();
  1113. if (!pckOut.isUsingSideband()) {
  1114. // sendPack will write "packfile\n" for us if sideband-all is used.
  1115. // But sideband-all is not used, so we have to write it ourselves.
  1116. pckOut.writeString("packfile\n"); //$NON-NLS-1$
  1117. }
  1118. sendPack(new PackStatistics.Accumulator(),
  1119. req,
  1120. req.getClientCapabilities().contains(OPTION_INCLUDE_TAG)
  1121. ? db.getRefDatabase().getRefsByPrefix(R_TAGS)
  1122. : null,
  1123. unshallowCommits, deepenNots, pckOut);
  1124. // sendPack invokes pckOut.end() for us, so we do not
  1125. // need to invoke it here.
  1126. } else {
  1127. // Invoke pckOut.end() by ourselves.
  1128. pckOut.end();
  1129. }
  1130. }
  1131. /*
  1132. * Returns true if this is the last command and we should tear down the
  1133. * connection.
  1134. */
  1135. private boolean serveOneCommandV2(PacketLineOut pckOut) throws IOException {
  1136. String command;
  1137. try {
  1138. command = pckIn.readString();
  1139. } catch (EOFException eof) {
  1140. /* EOF when awaiting command is fine */
  1141. return true;
  1142. }
  1143. if (PacketLineIn.isEnd(command)) {
  1144. // A blank request is valid according
  1145. // to the protocol; do nothing in this
  1146. // case.
  1147. return true;
  1148. }
  1149. if (command.equals("command=" + COMMAND_LS_REFS)) { //$NON-NLS-1$
  1150. lsRefsV2(pckOut);
  1151. return false;
  1152. }
  1153. if (command.equals("command=" + COMMAND_FETCH)) { //$NON-NLS-1$
  1154. fetchV2(pckOut);
  1155. return false;
  1156. }
  1157. throw new PackProtocolException(MessageFormat
  1158. .format(JGitText.get().unknownTransportCommand, command));
  1159. }
  1160. private List<String> getV2CapabilityAdvertisement() {
  1161. ArrayList<String> caps = new ArrayList<>();
  1162. caps.add("version 2"); //$NON-NLS-1$
  1163. caps.add(COMMAND_LS_REFS);
  1164. boolean advertiseRefInWant = transferConfig.isAllowRefInWant() &&
  1165. db.getConfig().getBoolean("uploadpack", null, //$NON-NLS-1$
  1166. "advertiserefinwant", true); //$NON-NLS-1$
  1167. caps.add(
  1168. COMMAND_FETCH + '=' +
  1169. (transferConfig.isAllowFilter() ? OPTION_FILTER + ' ' : "") + //$NON-NLS-1$
  1170. (advertiseRefInWant ? CAPABILITY_REF_IN_WANT + ' ' : "") + //$NON-NLS-1$
  1171. (transferConfig.isAllowSidebandAll() ? OPTION_SIDEBAND_ALL + ' ' : "") + //$NON-NLS-1$
  1172. (cachedPackUriProvider != null ? "packfile-uris " : "") + // $NON-NLS-1$
  1173. OPTION_SHALLOW);
  1174. caps.add(CAPABILITY_SERVER_OPTION);
  1175. return caps;
  1176. }
  1177. private void serviceV2(PacketLineOut pckOut) throws IOException {
  1178. if (biDirectionalPipe) {
  1179. // Just like in service(), the capability advertisement
  1180. // is sent only if this is a bidirectional pipe. (If
  1181. // not, the client is expected to call
  1182. // sendAdvertisedRefs() on its own.)
  1183. protocolV2Hook
  1184. .onCapabilities(CapabilitiesV2Request.builder().build());
  1185. for (String s : getV2CapabilityAdvertisement()) {
  1186. pckOut.writeString(s + "\n"); //$NON-NLS-1$
  1187. }
  1188. pckOut.end();
  1189. while (!serveOneCommandV2(pckOut)) {
  1190. // Repeat until an empty command or EOF.
  1191. }
  1192. return;
  1193. }
  1194. try {
  1195. serveOneCommandV2(pckOut);
  1196. } finally {
  1197. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  1198. // Discard until EOF.
  1199. }
  1200. rawOut.stopBuffering();
  1201. }
  1202. }
  1203. private static Set<ObjectId> refIdSet(Collection<Ref> refs) {
  1204. Set<ObjectId> ids = new HashSet<>(refs.size());
  1205. for (Ref ref : refs) {
  1206. ObjectId id = ref.getObjectId();
  1207. if (id != null) {
  1208. ids.add(id);
  1209. }
  1210. id = ref.getPeeledObjectId();
  1211. if (id != null) {
  1212. ids.add(id);
  1213. }
  1214. }
  1215. return ids;
  1216. }
  1217. /*
  1218. * Determines what object ids must be marked as shallow or unshallow for the
  1219. * client.
  1220. */
  1221. private void computeShallowsAndUnshallows(FetchRequest req,
  1222. IOConsumer<ObjectId> shallowFunc,
  1223. IOConsumer<ObjectId> unshallowFunc,
  1224. List<ObjectId> deepenNots)
  1225. throws IOException {
  1226. if (req.getClientCapabilities().contains(OPTION_DEEPEN_RELATIVE)) {
  1227. // TODO(jonathantanmy): Implement deepen-relative
  1228. throw new UnsupportedOperationException();
  1229. }
  1230. int walkDepth = req.getDepth() == 0 ? Integer.MAX_VALUE
  1231. : req.getDepth() - 1;
  1232. try (DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(
  1233. walk.getObjectReader(), walkDepth)) {
  1234. depthWalk.setDeepenSince(req.getDeepenSince());
  1235. // Find all the commits which will be shallow
  1236. for (ObjectId o : req.getWantIds()) {
  1237. try {
  1238. depthWalk.markRoot(depthWalk.parseCommit(o));
  1239. } catch (IncorrectObjectTypeException notCommit) {
  1240. // Ignore non-commits in this loop.
  1241. }
  1242. }
  1243. depthWalk.setDeepenNots(deepenNots);
  1244. RevCommit o;
  1245. boolean atLeastOne = false;
  1246. while ((o = depthWalk.next()) != null) {
  1247. DepthWalk.Commit c = (DepthWalk.Commit) o;
  1248. atLeastOne = true;
  1249. boolean isBoundary = (c.getDepth() == walkDepth) || c.isBoundary();
  1250. // Commits at the boundary which aren't already shallow in
  1251. // the client need to be marked as such
  1252. if (isBoundary && !req.getClientShallowCommits().contains(c)) {
  1253. shallowFunc.accept(c.copy());
  1254. }
  1255. // Commits not on the boundary which are shallow in the client
  1256. // need to become unshallowed
  1257. if (!isBoundary && req.getClientShallowCommits().remove(c)) {
  1258. unshallowFunc.accept(c.copy());
  1259. }
  1260. }
  1261. if (!atLeastOne) {
  1262. throw new PackProtocolException(
  1263. JGitText.get().noCommitsSelectedForShallow);
  1264. }
  1265. }
  1266. }
  1267. /*
  1268. * Verify all shallow lines refer to commits
  1269. *
  1270. * It can mutate the input set (removing missing object ids from it)
  1271. */
  1272. private void verifyClientShallow(Set<ObjectId> shallowCommits)
  1273. throws IOException, PackProtocolException {
  1274. AsyncRevObjectQueue q = walk.parseAny(shallowCommits, true);
  1275. try {
  1276. for (;;) {
  1277. try {
  1278. // Shallow objects named by the client must be commits.
  1279. RevObject o = q.next();
  1280. if (o == null) {
  1281. break;
  1282. }
  1283. if (!(o instanceof RevCommit)) {
  1284. throw new PackProtocolException(
  1285. MessageFormat.format(
  1286. JGitText.get().invalidShallowObject,
  1287. o.name()));
  1288. }
  1289. } catch (MissingObjectException notCommit) {
  1290. // shallow objects not known at the server are ignored
  1291. // by git-core upload-pack, match that behavior.
  1292. shallowCommits.remove(notCommit.getObjectId());
  1293. continue;
  1294. }
  1295. }
  1296. } finally {
  1297. q.release();
  1298. }
  1299. }
  1300. /**
  1301. * Generate an advertisement of available refs and capabilities.
  1302. *
  1303. * @param adv
  1304. * the advertisement formatter.
  1305. * @throws java.io.IOException
  1306. * the formatter failed to write an advertisement.
  1307. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1308. * the hook denied advertisement.
  1309. */
  1310. public void sendAdvertisedRefs(RefAdvertiser adv) throws IOException,
  1311. ServiceMayNotContinueException {
  1312. sendAdvertisedRefs(adv, null);
  1313. }
  1314. /**
  1315. * Generate an advertisement of available refs and capabilities.
  1316. *
  1317. * @param adv
  1318. * the advertisement formatter.
  1319. * @param serviceName
  1320. * if not null, also output "# service=serviceName" followed by a
  1321. * flush packet before the advertisement. This is required
  1322. * in v0 of the HTTP protocol, described in Git's
  1323. * Documentation/technical/http-protocol.txt.
  1324. * @throws java.io.IOException
  1325. * the formatter failed to write an advertisement.
  1326. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1327. * the hook denied advertisement.
  1328. * @since 5.0
  1329. */
  1330. public void sendAdvertisedRefs(RefAdvertiser adv,
  1331. @Nullable String serviceName) throws IOException,
  1332. ServiceMayNotContinueException {
  1333. if (useProtocolV2()) {
  1334. // The equivalent in v2 is only the capabilities
  1335. // advertisement.
  1336. protocolV2Hook
  1337. .onCapabilities(CapabilitiesV2Request.builder().build());
  1338. for (String s : getV2CapabilityAdvertisement()) {
  1339. adv.writeOne(s);
  1340. }
  1341. adv.end();
  1342. return;
  1343. }
  1344. Map<String, Ref> advertisedOrDefaultRefs = getAdvertisedOrDefaultRefs();
  1345. if (serviceName != null) {
  1346. adv.writeOne("# service=" + serviceName + '\n'); //$NON-NLS-1$
  1347. adv.end();
  1348. }
  1349. adv.init(db);
  1350. adv.advertiseCapability(OPTION_INCLUDE_TAG);
  1351. adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED);
  1352. adv.advertiseCapability(OPTION_MULTI_ACK);
  1353. adv.advertiseCapability(OPTION_OFS_DELTA);
  1354. adv.advertiseCapability(OPTION_SIDE_BAND);
  1355. adv.advertiseCapability(OPTION_SIDE_BAND_64K);
  1356. adv.advertiseCapability(OPTION_THIN_PACK);
  1357. adv.advertiseCapability(OPTION_NO_PROGRESS);
  1358. adv.advertiseCapability(OPTION_SHALLOW);
  1359. if (!biDirectionalPipe)
  1360. adv.advertiseCapability(OPTION_NO_DONE);
  1361. RequestPolicy policy = getRequestPolicy();
  1362. if (policy == RequestPolicy.TIP
  1363. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  1364. || policy == null)
  1365. adv.advertiseCapability(OPTION_ALLOW_TIP_SHA1_IN_WANT);
  1366. if (policy == RequestPolicy.REACHABLE_COMMIT
  1367. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  1368. || policy == null)
  1369. adv.advertiseCapability(OPTION_ALLOW_REACHABLE_SHA1_IN_WANT);
  1370. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  1371. if (transferConfig.isAllowFilter()) {
  1372. adv.advertiseCapability(OPTION_FILTER);
  1373. }
  1374. adv.setDerefTags(true);
  1375. findSymrefs(adv, advertisedOrDefaultRefs);
  1376. advertised = adv.send(advertisedOrDefaultRefs.values());
  1377. if (adv.isEmpty())
  1378. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  1379. adv.end();
  1380. }
  1381. /**
  1382. * Send a message to the client, if it supports receiving them.
  1383. * <p>
  1384. * If the client doesn't support receiving messages, the message will be
  1385. * discarded, with no other indication to the caller or to the client.
  1386. *
  1387. * @param what
  1388. * string describing the problem identified by the hook. The
  1389. * string must not end with an LF, and must not contain an LF.
  1390. * @since 3.1
  1391. */
  1392. public void sendMessage(String what) {
  1393. try {
  1394. msgOut.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  1395. } catch (IOException e) {
  1396. // Ignore write failures.
  1397. }
  1398. }
  1399. /**
  1400. * Get an underlying stream for sending messages to the client
  1401. *
  1402. * @return an underlying stream for sending messages to the client, or null.
  1403. * @since 3.1
  1404. */
  1405. public OutputStream getMessageOutputStream() {
  1406. return msgOut;
  1407. }
  1408. /**
  1409. * Returns the clone/fetch depth. Valid only after calling recvWants(). A
  1410. * depth of 1 means return only the wants.
  1411. *
  1412. * @return the depth requested by the client, or 0 if unbounded.
  1413. * @since 4.0
  1414. */
  1415. public int getDepth() {
  1416. if (currentRequest == null)
  1417. throw new RequestNotYetReadException();
  1418. return currentRequest.getDepth();
  1419. }
  1420. /**
  1421. * Deprecated synonym for {@code getFilterSpec().getBlobLimit()}.
  1422. *
  1423. * @return filter blob limit requested by the client, or -1 if no limit
  1424. * @since 5.3
  1425. * @deprecated Use {@link #getFilterSpec()} instead
  1426. */
  1427. @Deprecated
  1428. public final long getFilterBlobLimit() {
  1429. return getFilterSpec().getBlobLimit();
  1430. }
  1431. /**
  1432. * Returns the filter spec for the current request. Valid only after
  1433. * calling recvWants(). This may be a no-op filter spec, but it won't be
  1434. * null.
  1435. *
  1436. * @return filter requested by the client
  1437. * @since 5.4
  1438. */
  1439. public final FilterSpec getFilterSpec() {
  1440. if (currentRequest == null) {
  1441. throw new RequestNotYetReadException();
  1442. }
  1443. return currentRequest.getFilterSpec();
  1444. }
  1445. /**
  1446. * Get the user agent of the client.
  1447. * <p>
  1448. * If the client is new enough to use {@code agent=} capability that value
  1449. * will be returned. Older HTTP clients may also supply their version using
  1450. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  1451. * header if both are available.
  1452. * <p>
  1453. * When an HTTP request has been received this method returns the HTTP
  1454. * {@code User-Agent} header value until capabilities have been parsed.
  1455. *
  1456. * @return user agent supplied by the client. Available only if the client
  1457. * is new enough to advertise its user agent.
  1458. * @since 4.0
  1459. */
  1460. public String getPeerUserAgent() {
  1461. if (currentRequest != null && currentRequest.getAgent() != null) {
  1462. return currentRequest.getAgent();
  1463. }
  1464. return userAgent;
  1465. }
  1466. private boolean negotiate(FetchRequest req,
  1467. PackStatistics.Accumulator accumulator,
  1468. PacketLineOut pckOut)
  1469. throws IOException {
  1470. okToGiveUp = Boolean.FALSE;
  1471. ObjectId last = ObjectId.zeroId();
  1472. List<ObjectId> peerHas = new ArrayList<>(64);
  1473. for (;;) {
  1474. String line;
  1475. try {
  1476. line = pckIn.readString();
  1477. } catch (EOFException eof) {
  1478. // EOF on stateless RPC (aka smart HTTP) and non-shallow request
  1479. // means the client asked for the updated shallow/unshallow data,
  1480. // disconnected, and will try another request with actual want/have.
  1481. // Don't report the EOF here, its a bug in the protocol that the client
  1482. // just disconnects without sending an END.
  1483. if (!biDirectionalPipe && req.getDepth() > 0)
  1484. return false;
  1485. throw eof;
  1486. }
  1487. if (PacketLineIn.isEnd(line)) {
  1488. last = processHaveLines(peerHas, last, pckOut);
  1489. if (commonBase.isEmpty() || multiAck != MultiAck.OFF)
  1490. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1491. if (noDone && sentReady) {
  1492. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1493. return true;
  1494. }
  1495. if (!biDirectionalPipe)
  1496. return false;
  1497. pckOut.flush();
  1498. } else if (line.startsWith("have ") && line.length() == 45) { //$NON-NLS-1$
  1499. peerHas.add(ObjectId.fromString(line.substring(5)));
  1500. accumulator.haves++;
  1501. } else if (line.equals("done")) { //$NON-NLS-1$
  1502. last = processHaveLines(peerHas, last, pckOut);
  1503. if (commonBase.isEmpty())
  1504. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1505. else if (multiAck != MultiAck.OFF)
  1506. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1507. return true;
  1508. } else {
  1509. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "have", line)); //$NON-NLS-1$
  1510. }
  1511. }
  1512. }
  1513. private ObjectId processHaveLines(List<ObjectId> peerHas, ObjectId last, PacketLineOut out)
  1514. throws IOException {
  1515. preUploadHook.onBeginNegotiateRound(this, wantIds, peerHas.size());
  1516. if (wantAll.isEmpty() && !wantIds.isEmpty())
  1517. parseWants();
  1518. if (peerHas.isEmpty())
  1519. return last;
  1520. sentReady = false;
  1521. int haveCnt = 0;
  1522. walk.getObjectReader().setAvoidUnreachableObjects(true);
  1523. AsyncRevObjectQueue q = walk.parseAny(peerHas, false);
  1524. try {
  1525. for (;;) {
  1526. RevObject obj;
  1527. try {
  1528. obj = q.next();
  1529. } catch (MissingObjectException notFound) {
  1530. continue;
  1531. }
  1532. if (obj == null)
  1533. break;
  1534. last = obj;
  1535. haveCnt++;
  1536. if (obj instanceof RevCommit) {
  1537. RevCommit c = (RevCommit) obj;
  1538. if (oldestTime == 0 || c.getCommitTime() < oldestTime)
  1539. oldestTime = c.getCommitTime();
  1540. }
  1541. if (obj.has(PEER_HAS))
  1542. continue;
  1543. obj.add(PEER_HAS);
  1544. if (obj instanceof RevCommit)
  1545. ((RevCommit) obj).carry(PEER_HAS);
  1546. addCommonBase(obj);
  1547. // If both sides have the same object; let the client know.
  1548. //
  1549. switch (multiAck) {
  1550. case OFF:
  1551. if (commonBase.size() == 1)
  1552. out.writeString("ACK " + obj.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1553. break;
  1554. case CONTINUE:
  1555. out.writeString("ACK " + obj.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1556. break;
  1557. case DETAILED:
  1558. out.writeString("ACK " + obj.name() + " common\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1559. break;
  1560. }
  1561. }
  1562. } finally {
  1563. q.release();
  1564. walk.getObjectReader().setAvoidUnreachableObjects(false);
  1565. }
  1566. int missCnt = peerHas.size() - haveCnt;
  1567. // If we don't have one of the objects but we're also willing to
  1568. // create a pack at this point, let the client know so it stops
  1569. // telling us about its history.
  1570. //
  1571. boolean didOkToGiveUp = false;
  1572. if (0 < missCnt) {
  1573. for (int i = peerHas.size() - 1; i >= 0; i--) {
  1574. ObjectId id = peerHas.get(i);
  1575. if (walk.lookupOrNull(id) == null) {
  1576. didOkToGiveUp = true;
  1577. if (okToGiveUp()) {
  1578. switch (multiAck) {
  1579. case OFF:
  1580. break;
  1581. case CONTINUE:
  1582. out.writeString("ACK " + id.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1583. break;
  1584. case DETAILED:
  1585. out.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1586. sentReady = true;
  1587. break;
  1588. }
  1589. }
  1590. break;
  1591. }
  1592. }
  1593. }
  1594. if (multiAck == MultiAck.DETAILED && !didOkToGiveUp && okToGiveUp()) {
  1595. ObjectId id = peerHas.get(peerHas.size() - 1);
  1596. out.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1597. sentReady = true;
  1598. }
  1599. preUploadHook.onEndNegotiateRound(this, wantAll, haveCnt, missCnt, sentReady);
  1600. peerHas.clear();
  1601. return last;
  1602. }
  1603. private void parseWants() throws IOException {
  1604. List<ObjectId> notAdvertisedWants = null;
  1605. for (ObjectId obj : wantIds) {
  1606. if (!advertised.contains(obj)) {
  1607. if (notAdvertisedWants == null)
  1608. notAdvertisedWants = new ArrayList<>();
  1609. notAdvertisedWants.add(obj);
  1610. }
  1611. }
  1612. if (notAdvertisedWants != null)
  1613. requestValidator.checkWants(this, notAdvertisedWants);
  1614. AsyncRevObjectQueue q = walk.parseAny(wantIds, true);
  1615. try {
  1616. RevObject obj;
  1617. while ((obj = q.next()) != null) {
  1618. want(obj);
  1619. if (!(obj instanceof RevCommit))
  1620. obj.add(SATISFIED);
  1621. if (obj instanceof RevTag) {
  1622. obj = walk.peel(obj);
  1623. if (obj instanceof RevCommit)
  1624. want(obj);
  1625. }
  1626. }
  1627. wantIds.clear();
  1628. } catch (MissingObjectException notFound) {
  1629. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1630. } finally {
  1631. q.release();
  1632. }
  1633. }
  1634. private void want(RevObject obj) {
  1635. if (!obj.has(WANT)) {
  1636. obj.add(WANT);
  1637. wantAll.add(obj);
  1638. }
  1639. }
  1640. /**
  1641. * Validator corresponding to {@link RequestPolicy#ADVERTISED}.
  1642. *
  1643. * @since 3.1
  1644. */
  1645. public static final class AdvertisedRequestValidator
  1646. implements RequestValidator {
  1647. @Override
  1648. public void checkWants(UploadPack up, List<ObjectId> wants)
  1649. throws PackProtocolException, IOException {
  1650. if (!up.isBiDirectionalPipe())
  1651. new ReachableCommitRequestValidator().checkWants(up, wants);
  1652. else if (!wants.isEmpty())
  1653. throw new WantNotValidException(wants.iterator().next());
  1654. }
  1655. }
  1656. /**
  1657. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT}.
  1658. *
  1659. * @since 3.1
  1660. */
  1661. public static final class ReachableCommitRequestValidator
  1662. implements RequestValidator {
  1663. @Override
  1664. public void checkWants(UploadPack up, List<ObjectId> wants)
  1665. throws PackProtocolException, IOException {
  1666. checkNotAdvertisedWants(up, wants,
  1667. refIdSet(up.getAdvertisedRefs().values()));
  1668. }
  1669. }
  1670. /**
  1671. * Validator corresponding to {@link RequestPolicy#TIP}.
  1672. *
  1673. * @since 3.1
  1674. */
  1675. public static final class TipRequestValidator implements RequestValidator {
  1676. @Override
  1677. public void checkWants(UploadPack up, List<ObjectId> wants)
  1678. throws PackProtocolException, IOException {
  1679. if (!up.isBiDirectionalPipe())
  1680. new ReachableCommitTipRequestValidator().checkWants(up, wants);
  1681. else if (!wants.isEmpty()) {
  1682. Set<ObjectId> refIds =
  1683. refIdSet(up.getRepository().getRefDatabase().getRefs());
  1684. for (ObjectId obj : wants) {
  1685. if (!refIds.contains(obj))
  1686. throw new WantNotValidException(obj);
  1687. }
  1688. }
  1689. }
  1690. }
  1691. /**
  1692. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT_TIP}.
  1693. *
  1694. * @since 3.1
  1695. */
  1696. public static final class ReachableCommitTipRequestValidator
  1697. implements RequestValidator {
  1698. @Override
  1699. public void checkWants(UploadPack up, List<ObjectId> wants)
  1700. throws PackProtocolException, IOException {
  1701. checkNotAdvertisedWants(up, wants,
  1702. refIdSet(up.getRepository().getRefDatabase().getRefs()));
  1703. }
  1704. }
  1705. /**
  1706. * Validator corresponding to {@link RequestPolicy#ANY}.
  1707. *
  1708. * @since 3.1
  1709. */
  1710. public static final class AnyRequestValidator implements RequestValidator {
  1711. @Override
  1712. public void checkWants(UploadPack up, List<ObjectId> wants)
  1713. throws PackProtocolException, IOException {
  1714. // All requests are valid.
  1715. }
  1716. }
  1717. private static void checkNotAdvertisedWantsUsingBitmap(ObjectReader reader,
  1718. BitmapIndex bitmapIndex, List<ObjectId> notAdvertisedWants,
  1719. Set<ObjectId> reachableFrom) throws IOException {
  1720. BitmapWalker bitmapWalker = new BitmapWalker(new ObjectWalk(reader), bitmapIndex, null);
  1721. BitmapBuilder reachables = bitmapWalker.findObjects(reachableFrom, null, false);
  1722. for (ObjectId oid : notAdvertisedWants) {
  1723. if (!reachables.contains(oid)) {
  1724. throw new WantNotValidException(oid);
  1725. }
  1726. }
  1727. }
  1728. private static void checkReachabilityByWalkingObjects(ObjectWalk walk,
  1729. List<RevObject> wants, Set<ObjectId> reachableFrom) throws IOException {
  1730. walk.sort(RevSort.TOPO);
  1731. for (RevObject want : wants) {
  1732. walk.markStart(want);
  1733. }
  1734. for (ObjectId have : reachableFrom) {
  1735. RevObject o = walk.parseAny(have);
  1736. walk.markUninteresting(o);
  1737. RevObject peeled = walk.peel(o);
  1738. if (peeled instanceof RevCommit) {
  1739. // By default, for performance reasons, ObjectWalk does not mark a
  1740. // tree as uninteresting when we mark a commit. Mark it ourselves so
  1741. // that we can determine reachability exactly.
  1742. walk.markUninteresting(((RevCommit) peeled).getTree());
  1743. }
  1744. }
  1745. RevCommit commit = walk.next();
  1746. if (commit != null) {
  1747. throw new WantNotValidException(commit);
  1748. }
  1749. RevObject object = walk.nextObject();
  1750. if (object != null) {
  1751. throw new WantNotValidException(object);
  1752. }
  1753. }
  1754. private static void checkNotAdvertisedWants(UploadPack up,
  1755. List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom)
  1756. throws IOException {
  1757. ObjectReader reader = up.getRevWalk().getObjectReader();
  1758. try (RevWalk walk = new RevWalk(reader)) {
  1759. walk.setRetainBody(false);
  1760. // Missing "wants" throw exception here
  1761. List<RevObject> wantsAsObjs = objectIdsToRevObjects(walk,
  1762. notAdvertisedWants);
  1763. List<RevCommit> wantsAsCommits = wantsAsObjs.stream()
  1764. .filter(obj -> obj instanceof RevCommit)
  1765. .map(obj -> (RevCommit) obj)
  1766. .collect(Collectors.toList());
  1767. boolean allWantsAreCommits = wantsAsObjs.size() == wantsAsCommits
  1768. .size();
  1769. boolean repoHasBitmaps = reader.getBitmapIndex() != null;
  1770. if (!allWantsAreCommits) {
  1771. if (!repoHasBitmaps) {
  1772. if (up.transferConfig.isAllowFilter()) {
  1773. // Use allowFilter as an indication that the server
  1774. // operator is willing to pay the cost of these
  1775. // reachability checks.
  1776. try (ObjectWalk objWalk = walk.toObjectWalkWithSameObjects()) {
  1777. checkReachabilityByWalkingObjects(objWalk,
  1778. wantsAsObjs, reachableFrom);
  1779. }
  1780. return;
  1781. }
  1782. // If unadvertized non-commits are requested, use
  1783. // bitmaps. If there are no bitmaps, instead of
  1784. // incurring the expense of a manual walk, reject
  1785. // the request.
  1786. RevObject nonCommit = wantsAsObjs
  1787. .stream()
  1788. .filter(obj -> !(obj instanceof RevCommit))
  1789. .limit(1)
  1790. .collect(Collectors.toList()).get(0);
  1791. throw new WantNotValidException(nonCommit);
  1792. }
  1793. checkNotAdvertisedWantsUsingBitmap(reader,
  1794. reader.getBitmapIndex(), notAdvertisedWants,
  1795. reachableFrom);
  1796. return;
  1797. }
  1798. // All wants are commits, we can use ReachabilityChecker
  1799. ReachabilityChecker reachabilityChecker = walk
  1800. .createReachabilityChecker();
  1801. List<RevCommit> starters = objectIdsToRevCommits(walk,
  1802. reachableFrom);
  1803. Optional<RevCommit> unreachable = reachabilityChecker
  1804. .areAllReachable(wantsAsCommits, starters);
  1805. if (unreachable.isPresent()) {
  1806. throw new WantNotValidException(unreachable.get());
  1807. }
  1808. } catch (MissingObjectException notFound) {
  1809. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1810. }
  1811. }
  1812. // Resolve the ObjectIds into RevObjects. Any missing object raises an
  1813. // exception
  1814. private static List<RevObject> objectIdsToRevObjects(RevWalk walk,
  1815. Iterable<ObjectId> objectIds)
  1816. throws MissingObjectException, IOException {
  1817. List<RevObject> result = new ArrayList<>();
  1818. for (ObjectId objectId : objectIds) {
  1819. result.add(walk.parseAny(objectId));
  1820. }
  1821. return result;
  1822. }
  1823. // Get commits from object ids. If the id is not a commit, ignore it. If the
  1824. // id doesn't exist, report the missing object in a exception.
  1825. private static List<RevCommit> objectIdsToRevCommits(RevWalk walk,
  1826. Iterable<ObjectId> objectIds)
  1827. throws MissingObjectException, IOException {
  1828. List<RevCommit> result = new ArrayList<>();
  1829. for (ObjectId objectId : objectIds) {
  1830. try {
  1831. result.add(walk.parseCommit(objectId));
  1832. } catch (IncorrectObjectTypeException e) {
  1833. continue;
  1834. }
  1835. }
  1836. return result;
  1837. }
  1838. private void addCommonBase(RevObject o) {
  1839. if (!o.has(COMMON)) {
  1840. o.add(COMMON);
  1841. commonBase.add(o);
  1842. okToGiveUp = null;
  1843. }
  1844. }
  1845. private boolean okToGiveUp() throws PackProtocolException {
  1846. if (okToGiveUp == null)
  1847. okToGiveUp = Boolean.valueOf(okToGiveUpImp());
  1848. return okToGiveUp.booleanValue();
  1849. }
  1850. private boolean okToGiveUpImp() throws PackProtocolException {
  1851. if (commonBase.isEmpty())
  1852. return false;
  1853. try {
  1854. for (RevObject obj : wantAll) {
  1855. if (!wantSatisfied(obj))
  1856. return false;
  1857. }
  1858. return true;
  1859. } catch (IOException e) {
  1860. throw new PackProtocolException(JGitText.get().internalRevisionError, e);
  1861. }
  1862. }
  1863. private boolean wantSatisfied(RevObject want) throws IOException {
  1864. if (want.has(SATISFIED))
  1865. return true;
  1866. walk.resetRetain(SAVE);
  1867. walk.markStart((RevCommit) want);
  1868. if (oldestTime != 0)
  1869. walk.setRevFilter(CommitTimeRevFilter.after(oldestTime * 1000L));
  1870. for (;;) {
  1871. final RevCommit c = walk.next();
  1872. if (c == null)
  1873. break;
  1874. if (c.has(PEER_HAS)) {
  1875. addCommonBase(c);
  1876. want.add(SATISFIED);
  1877. return true;
  1878. }
  1879. }
  1880. return false;
  1881. }
  1882. /**
  1883. * Send the requested objects to the client.
  1884. *
  1885. * @param accumulator
  1886. * where to write statistics about the content of the pack.
  1887. * @param req
  1888. * request in process
  1889. * @param allTags
  1890. * refs to search for annotated tags to include in the pack if
  1891. * the {@link #OPTION_INCLUDE_TAG} capability was requested.
  1892. * @param unshallowCommits
  1893. * shallow commits on the client that are now becoming unshallow
  1894. * @param deepenNots
  1895. * objects that the client specified using --shallow-exclude
  1896. * @param pckOut
  1897. * output writer
  1898. * @throws IOException
  1899. * if an error occurred while generating or writing the pack.
  1900. */
  1901. private void sendPack(PackStatistics.Accumulator accumulator,
  1902. FetchRequest req,
  1903. @Nullable Collection<Ref> allTags,
  1904. List<ObjectId> unshallowCommits,
  1905. List<ObjectId> deepenNots,
  1906. PacketLineOut pckOut) throws IOException {
  1907. Set<String> caps = req.getClientCapabilities();
  1908. boolean sideband = caps.contains(OPTION_SIDE_BAND)
  1909. || caps.contains(OPTION_SIDE_BAND_64K);
  1910. if (sideband) {
  1911. try {
  1912. sendPack(true, req, accumulator, allTags, unshallowCommits,
  1913. deepenNots, pckOut);
  1914. } catch (ServiceMayNotContinueException err) {
  1915. String message = err.getMessage();
  1916. if (message == null) {
  1917. message = JGitText.get().internalServerError;
  1918. }
  1919. try {
  1920. reportInternalServerErrorOverSideband(message);
  1921. } catch (IOException e) {
  1922. err.addSuppressed(e);
  1923. throw err;
  1924. }
  1925. throw new UploadPackInternalServerErrorException(err);
  1926. } catch (IOException | RuntimeException | Error err) {
  1927. try {
  1928. reportInternalServerErrorOverSideband(
  1929. JGitText.get().internalServerError);
  1930. } catch (IOException e) {
  1931. err.addSuppressed(e);
  1932. throw err;
  1933. }
  1934. throw new UploadPackInternalServerErrorException(err);
  1935. }
  1936. } else {
  1937. sendPack(false, req, accumulator, allTags, unshallowCommits, deepenNots,
  1938. pckOut);
  1939. }
  1940. }
  1941. private void reportInternalServerErrorOverSideband(String message)
  1942. throws IOException {
  1943. @SuppressWarnings("resource" /* java 7 */)
  1944. SideBandOutputStream err = new SideBandOutputStream(
  1945. SideBandOutputStream.CH_ERROR, SideBandOutputStream.SMALL_BUF,
  1946. rawOut);
  1947. err.write(Constants.encode(message));
  1948. err.flush();
  1949. }
  1950. /**
  1951. * Send the requested objects to the client.
  1952. *
  1953. * @param sideband
  1954. * whether to wrap the pack in side-band pkt-lines, interleaved
  1955. * with progress messages and errors.
  1956. * @param req
  1957. * request being processed
  1958. * @param accumulator
  1959. * where to write statistics about the content of the pack.
  1960. * @param allTags
  1961. * refs to search for annotated tags to include in the pack if
  1962. * the {@link #OPTION_INCLUDE_TAG} capability was requested.
  1963. * @param unshallowCommits
  1964. * shallow commits on the client that are now becoming unshallow
  1965. * @param deepenNots
  1966. * objects that the client specified using --shallow-exclude
  1967. * @param pckOut
  1968. * output writer
  1969. * @throws IOException
  1970. * if an error occurred while generating or writing the pack.
  1971. */
  1972. private void sendPack(final boolean sideband,
  1973. FetchRequest req,
  1974. PackStatistics.Accumulator accumulator,
  1975. @Nullable Collection<Ref> allTags,
  1976. List<ObjectId> unshallowCommits,
  1977. List<ObjectId> deepenNots,
  1978. PacketLineOut pckOut) throws IOException {
  1979. ProgressMonitor pm = NullProgressMonitor.INSTANCE;
  1980. OutputStream packOut = rawOut;
  1981. if (sideband) {
  1982. int bufsz = SideBandOutputStream.SMALL_BUF;
  1983. if (req.getClientCapabilities().contains(OPTION_SIDE_BAND_64K))
  1984. bufsz = SideBandOutputStream.MAX_BUF;
  1985. packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA,
  1986. bufsz, rawOut);
  1987. if (!req.getClientCapabilities().contains(OPTION_NO_PROGRESS)) {
  1988. msgOut = new SideBandOutputStream(
  1989. SideBandOutputStream.CH_PROGRESS, bufsz, rawOut);
  1990. pm = new SideBandProgressMonitor(msgOut);
  1991. }
  1992. }
  1993. if (wantAll.isEmpty()) {
  1994. preUploadHook.onSendPack(this, wantIds, commonBase);
  1995. } else {
  1996. preUploadHook.onSendPack(this, wantAll, commonBase);
  1997. }
  1998. msgOut.flush();
  1999. PackConfig cfg = packConfig;
  2000. if (cfg == null)
  2001. cfg = new PackConfig(db);
  2002. @SuppressWarnings("resource") // PackWriter is referenced in the finally
  2003. // block, and is closed there
  2004. final PackWriter pw = new PackWriter(cfg, walk.getObjectReader(),
  2005. accumulator);
  2006. try {
  2007. pw.setIndexDisabled(true);
  2008. if (req.getFilterSpec().isNoOp()) {
  2009. pw.setUseCachedPacks(true);
  2010. } else {
  2011. pw.setFilterSpec(req.getFilterSpec());
  2012. pw.setUseCachedPacks(false);
  2013. }
  2014. pw.setUseBitmaps(
  2015. req.getDepth() == 0
  2016. && req.getClientShallowCommits().isEmpty()
  2017. && req.getFilterSpec().getTreeDepthLimit() == -1);
  2018. pw.setClientShallowCommits(req.getClientShallowCommits());
  2019. pw.setReuseDeltaCommits(true);
  2020. pw.setDeltaBaseAsOffset(
  2021. req.getClientCapabilities().contains(OPTION_OFS_DELTA));
  2022. pw.setThin(req.getClientCapabilities().contains(OPTION_THIN_PACK));
  2023. pw.setReuseValidatingObjects(false);
  2024. // Objects named directly by references go at the beginning
  2025. // of the pack.
  2026. if (commonBase.isEmpty() && refs != null) {
  2027. Set<ObjectId> tagTargets = new HashSet<>();
  2028. for (Ref ref : refs.values()) {
  2029. if (ref.getPeeledObjectId() != null)
  2030. tagTargets.add(ref.getPeeledObjectId());
  2031. else if (ref.getObjectId() == null)
  2032. continue;
  2033. else if (ref.getName().startsWith(Constants.R_HEADS))
  2034. tagTargets.add(ref.getObjectId());
  2035. }
  2036. pw.setTagTargets(tagTargets);
  2037. }
  2038. RevWalk rw = walk;
  2039. if (req.getDepth() > 0 || req.getDeepenSince() != 0 || !deepenNots.isEmpty()) {
  2040. int walkDepth = req.getDepth() == 0 ? Integer.MAX_VALUE
  2041. : req.getDepth() - 1;
  2042. pw.setShallowPack(req.getDepth(), unshallowCommits);
  2043. @SuppressWarnings("resource") // Ownership is transferred below
  2044. DepthWalk.RevWalk dw = new DepthWalk.RevWalk(
  2045. walk.getObjectReader(), walkDepth);
  2046. dw.setDeepenSince(req.getDeepenSince());
  2047. dw.setDeepenNots(deepenNots);
  2048. dw.assumeShallow(req.getClientShallowCommits());
  2049. rw = dw;
  2050. }
  2051. if (wantAll.isEmpty()) {
  2052. pw.preparePack(pm, wantIds, commonBase,
  2053. req.getClientShallowCommits());
  2054. } else {
  2055. walk.reset();
  2056. ObjectWalk ow = rw.toObjectWalkWithSameObjects();
  2057. pw.preparePack(pm, ow, wantAll, commonBase, PackWriter.NONE);
  2058. rw = ow;
  2059. }
  2060. if (req.getClientCapabilities().contains(OPTION_INCLUDE_TAG)
  2061. && allTags != null) {
  2062. for (Ref ref : allTags) {
  2063. ObjectId objectId = ref.getObjectId();
  2064. if (objectId == null) {
  2065. // skip unborn branch
  2066. continue;
  2067. }
  2068. // If the object was already requested, skip it.
  2069. if (wantAll.isEmpty()) {
  2070. if (wantIds.contains(objectId))
  2071. continue;
  2072. } else {
  2073. RevObject obj = rw.lookupOrNull(objectId);
  2074. if (obj != null && obj.has(WANT))
  2075. continue;
  2076. }
  2077. if (!ref.isPeeled())
  2078. ref = db.getRefDatabase().peel(ref);
  2079. ObjectId peeledId = ref.getPeeledObjectId();
  2080. objectId = ref.getObjectId();
  2081. if (peeledId == null || objectId == null)
  2082. continue;
  2083. objectId = ref.getObjectId();
  2084. if (pw.willInclude(peeledId) && !pw.willInclude(objectId)) {
  2085. RevObject o = rw.parseAny(objectId);
  2086. addTagChain(o, pw);
  2087. pw.addObject(o);
  2088. }
  2089. }
  2090. }
  2091. if (pckOut.isUsingSideband()) {
  2092. if (req instanceof FetchV2Request &&
  2093. cachedPackUriProvider != null &&
  2094. !((FetchV2Request) req).getPackfileUriProtocols().isEmpty()) {
  2095. FetchV2Request reqV2 = (FetchV2Request) req;
  2096. pw.setPackfileUriConfig(new PackWriter.PackfileUriConfig(
  2097. pckOut,
  2098. reqV2.getPackfileUriProtocols(),
  2099. cachedPackUriProvider));
  2100. } else {
  2101. // PackWriter will write "packfile-uris\n" and "packfile\n"
  2102. // for us if provided a PackfileUriConfig. In this case, we
  2103. // are not providing a PackfileUriConfig, so we have to
  2104. // write this line ourselves.
  2105. pckOut.writeString("packfile\n"); //$NON-NLS-1$
  2106. }
  2107. }
  2108. pw.writePack(pm, NullProgressMonitor.INSTANCE, packOut);
  2109. if (msgOut != NullOutputStream.INSTANCE) {
  2110. String msg = pw.getStatistics().getMessage() + '\n';
  2111. msgOut.write(Constants.encode(msg));
  2112. msgOut.flush();
  2113. }
  2114. } finally {
  2115. statistics = pw.getStatistics();
  2116. if (statistics != null) {
  2117. postUploadHook.onPostUpload(statistics);
  2118. }
  2119. pw.close();
  2120. }
  2121. if (sideband)
  2122. pckOut.end();
  2123. }
  2124. private static void findSymrefs(
  2125. final RefAdvertiser adv, final Map<String, Ref> refs) {
  2126. Ref head = refs.get(Constants.HEAD);
  2127. if (head != null && head.isSymbolic()) {
  2128. adv.addSymref(Constants.HEAD, head.getLeaf().getName());
  2129. }
  2130. }
  2131. private void addTagChain(
  2132. RevObject o, PackWriter pw) throws IOException {
  2133. while (Constants.OBJ_TAG == o.getType()) {
  2134. RevTag t = (RevTag) o;
  2135. o = t.getObject();
  2136. if (o.getType() == Constants.OBJ_TAG && !pw.willInclude(o.getId())) {
  2137. walk.parseBody(o);
  2138. pw.addObject(o);
  2139. }
  2140. }
  2141. }
  2142. private static class ResponseBufferedOutputStream extends OutputStream {
  2143. private final OutputStream rawOut;
  2144. private OutputStream out;
  2145. ResponseBufferedOutputStream(OutputStream rawOut) {
  2146. this.rawOut = rawOut;
  2147. this.out = new ByteArrayOutputStream();
  2148. }
  2149. @Override
  2150. public void write(int b) throws IOException {
  2151. out.write(b);
  2152. }
  2153. @Override
  2154. public void write(byte b[]) throws IOException {
  2155. out.write(b);
  2156. }
  2157. @Override
  2158. public void write(byte b[], int off, int len) throws IOException {
  2159. out.write(b, off, len);
  2160. }
  2161. @Override
  2162. public void flush() throws IOException {
  2163. out.flush();
  2164. }
  2165. @Override
  2166. public void close() throws IOException {
  2167. out.close();
  2168. }
  2169. void stopBuffering() throws IOException {
  2170. if (out != rawOut) {
  2171. ((ByteArrayOutputStream) out).writeTo(rawOut);
  2172. out = rawOut;
  2173. }
  2174. }
  2175. }
  2176. }