client side smart HTTP
[jgit.git] / org.eclipse.jgit / src / org / eclipse / jgit / transport / BasePackConnection.java
blob90634d207a7008c34b1e261df5a514ec5ab53772
1 /*
2 * Copyright (C) 2009, Constantine Plotnikov <constantine.plotnikov@gmail.com>
3 * Copyright (C) 2008-2010, Google Inc.
4 * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
5 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
6 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
7 * and other copyright owners as documented in the project's IP log.
9 * This program and the accompanying materials are made available
10 * under the terms of the Eclipse Distribution License v1.0 which
11 * accompanies this distribution, is reproduced below, and is
12 * available at http://www.eclipse.org/org/documents/edl-v10.php
14 * All rights reserved.
16 * Redistribution and use in source and binary forms, with or
17 * without modification, are permitted provided that the following
18 * conditions are met:
20 * - Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
23 * - Redistributions in binary form must reproduce the above
24 * copyright notice, this list of conditions and the following
25 * disclaimer in the documentation and/or other materials provided
26 * with the distribution.
28 * - Neither the name of the Eclipse Foundation, Inc. nor the
29 * names of its contributors may be used to endorse or promote
30 * products derived from this software without specific prior
31 * written permission.
33 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
34 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
35 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
38 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
39 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
40 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
41 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
42 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
43 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
44 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
45 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48 package org.eclipse.jgit.transport;
50 import java.io.BufferedInputStream;
51 import java.io.BufferedOutputStream;
52 import java.io.EOFException;
53 import java.io.IOException;
54 import java.io.InputStream;
55 import java.io.OutputStream;
56 import java.util.HashSet;
57 import java.util.LinkedHashMap;
58 import java.util.Set;
60 import org.eclipse.jgit.errors.NoRemoteRepositoryException;
61 import org.eclipse.jgit.errors.PackProtocolException;
62 import org.eclipse.jgit.errors.TransportException;
63 import org.eclipse.jgit.lib.ObjectId;
64 import org.eclipse.jgit.lib.Ref;
65 import org.eclipse.jgit.lib.Repository;
66 import org.eclipse.jgit.util.io.InterruptTimer;
67 import org.eclipse.jgit.util.io.TimeoutInputStream;
68 import org.eclipse.jgit.util.io.TimeoutOutputStream;
70 /**
71 * Base helper class for pack-based operations implementations. Provides partial
72 * implementation of pack-protocol - refs advertising and capabilities support,
73 * and some other helper methods.
75 * @see BasePackFetchConnection
76 * @see BasePackPushConnection
78 abstract class BasePackConnection extends BaseConnection {
80 /** The repository this transport fetches into, or pushes out of. */
81 protected final Repository local;
83 /** Remote repository location. */
84 protected final URIish uri;
86 /** A transport connected to {@link #uri}. */
87 protected final Transport transport;
89 /** Low-level input stream, if a timeout was configured. */
90 protected TimeoutInputStream timeoutIn;
92 /** Low-level output stream, if a timeout was configured. */
93 protected TimeoutOutputStream timeoutOut;
95 /** Timer to manage {@link #timeoutIn} and {@link #timeoutOut}. */
96 private InterruptTimer myTimer;
98 /** Buffered input stream reading from the remote. */
99 protected InputStream in;
101 /** Buffered output stream sending to the remote. */
102 protected OutputStream out;
104 /** Packet line decoder around {@link #in}. */
105 protected PacketLineIn pckIn;
107 /** Packet line encoder around {@link #out}. */
108 protected PacketLineOut pckOut;
110 /** Send {@link PacketLineOut#end()} before closing {@link #out}? */
111 protected boolean outNeedsEnd;
113 /** True if this is a stateless RPC connection. */
114 protected boolean statelessRPC;
116 /** Capability tokens advertised by the remote side. */
117 private final Set<String> remoteCapablities = new HashSet<String>();
119 /** Extra objects the remote has, but which aren't offered as refs. */
120 protected final Set<ObjectId> additionalHaves = new HashSet<ObjectId>();
122 BasePackConnection(final PackTransport packTransport) {
123 transport = (Transport) packTransport;
124 local = transport.local;
125 uri = transport.uri;
128 protected final void init(InputStream myIn, OutputStream myOut) {
129 final int timeout = transport.getTimeout();
130 if (timeout > 0) {
131 final Thread caller = Thread.currentThread();
132 myTimer = new InterruptTimer(caller.getName() + "-Timer");
133 timeoutIn = new TimeoutInputStream(myIn, myTimer);
134 timeoutOut = new TimeoutOutputStream(myOut, myTimer);
135 timeoutIn.setTimeout(timeout * 1000);
136 timeoutOut.setTimeout(timeout * 1000);
137 myIn = timeoutIn;
138 myOut = timeoutOut;
141 in = myIn instanceof BufferedInputStream ? myIn
142 : new BufferedInputStream(myIn, IndexPack.BUFFER_SIZE);
143 out = myOut instanceof BufferedOutputStream ? myOut
144 : new BufferedOutputStream(myOut);
146 pckIn = new PacketLineIn(in);
147 pckOut = new PacketLineOut(out);
148 outNeedsEnd = true;
151 protected void readAdvertisedRefs() throws TransportException {
152 try {
153 readAdvertisedRefsImpl();
154 } catch (TransportException err) {
155 close();
156 throw err;
157 } catch (IOException err) {
158 close();
159 throw new TransportException(err.getMessage(), err);
160 } catch (RuntimeException err) {
161 close();
162 throw new TransportException(err.getMessage(), err);
166 private void readAdvertisedRefsImpl() throws IOException {
167 final LinkedHashMap<String, Ref> avail = new LinkedHashMap<String, Ref>();
168 for (;;) {
169 String line;
171 try {
172 line = pckIn.readString();
173 } catch (EOFException eof) {
174 if (avail.isEmpty())
175 throw noRepository();
176 throw eof;
178 if (line == PacketLineIn.END)
179 break;
181 if (avail.isEmpty()) {
182 final int nul = line.indexOf('\0');
183 if (nul >= 0) {
184 // The first line (if any) may contain "hidden"
185 // capability values after a NUL byte.
186 for (String c : line.substring(nul + 1).split(" "))
187 remoteCapablities.add(c);
188 line = line.substring(0, nul);
192 String name = line.substring(41, line.length());
193 if (avail.isEmpty() && name.equals("capabilities^{}")) {
194 // special line from git-receive-pack to show
195 // capabilities when there are no refs to advertise
196 continue;
199 final ObjectId id = ObjectId.fromString(line.substring(0, 40));
200 if (name.equals(".have")) {
201 additionalHaves.add(id);
202 } else if (name.endsWith("^{}")) {
203 name = name.substring(0, name.length() - 3);
204 final Ref prior = avail.get(name);
205 if (prior == null)
206 throw new PackProtocolException(uri, "advertisement of "
207 + name + "^{} came before " + name);
209 if (prior.getPeeledObjectId() != null)
210 throw duplicateAdvertisement(name + "^{}");
212 avail.put(name, new Ref(Ref.Storage.NETWORK, name, prior
213 .getObjectId(), id, true));
214 } else {
215 final Ref prior;
216 prior = avail.put(name, new Ref(Ref.Storage.NETWORK, name, id));
217 if (prior != null)
218 throw duplicateAdvertisement(name);
221 available(avail);
225 * Create an exception to indicate problems finding a remote repository. The
226 * caller is expected to throw the returned exception.
228 * Subclasses may override this method to provide better diagnostics.
230 * @return a TransportException saying a repository cannot be found and
231 * possibly why.
233 protected TransportException noRepository() {
234 return new NoRemoteRepositoryException(uri, "not found.");
237 protected boolean isCapableOf(final String option) {
238 return remoteCapablities.contains(option);
241 protected boolean wantCapability(final StringBuilder b, final String option) {
242 if (!isCapableOf(option))
243 return false;
244 b.append(' ');
245 b.append(option);
246 return true;
249 private PackProtocolException duplicateAdvertisement(final String name) {
250 return new PackProtocolException(uri, "duplicate advertisements of "
251 + name);
254 @Override
255 public void close() {
256 if (out != null) {
257 try {
258 if (outNeedsEnd)
259 pckOut.end();
260 out.close();
261 } catch (IOException err) {
262 // Ignore any close errors.
263 } finally {
264 out = null;
265 pckOut = null;
269 if (in != null) {
270 try {
271 in.close();
272 } catch (IOException err) {
273 // Ignore any close errors.
274 } finally {
275 in = null;
276 pckIn = null;
280 if (myTimer != null) {
281 try {
282 myTimer.terminate();
283 } finally {
284 myTimer = null;
285 timeoutIn = null;
286 timeoutOut = null;