View Javadoc
1   /*
2    * Copyright (C) 2013 Christian Halstrick <christian.halstrick@sap.com>
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.http.apache;
44  
45  import java.io.IOException;
46  import java.io.InputStream;
47  import java.io.OutputStream;
48  import java.net.InetSocketAddress;
49  import java.net.MalformedURLException;
50  import java.net.ProtocolException;
51  import java.net.Proxy;
52  import java.net.URL;
53  import java.security.KeyManagementException;
54  import java.security.NoSuchAlgorithmException;
55  import java.security.SecureRandom;
56  import java.security.cert.X509Certificate;
57  import java.util.HashMap;
58  import java.util.LinkedList;
59  import java.util.List;
60  import java.util.Map;
61  
62  import javax.net.ssl.HostnameVerifier;
63  import javax.net.ssl.KeyManager;
64  import javax.net.ssl.SSLContext;
65  import javax.net.ssl.SSLException;
66  import javax.net.ssl.SSLSession;
67  import javax.net.ssl.SSLSocket;
68  import javax.net.ssl.TrustManager;
69  
70  import org.apache.http.Header;
71  import org.apache.http.HeaderElement;
72  import org.apache.http.HttpEntity;
73  import org.apache.http.HttpEntityEnclosingRequest;
74  import org.apache.http.HttpHost;
75  import org.apache.http.HttpResponse;
76  import org.apache.http.client.ClientProtocolException;
77  import org.apache.http.client.HttpClient;
78  import org.apache.http.client.methods.HttpGet;
79  import org.apache.http.client.methods.HttpPost;
80  import org.apache.http.client.methods.HttpPut;
81  import org.apache.http.client.methods.HttpUriRequest;
82  import org.apache.http.client.params.ClientPNames;
83  import org.apache.http.conn.params.ConnRoutePNames;
84  import org.apache.http.conn.scheme.Scheme;
85  import org.apache.http.conn.ssl.SSLSocketFactory;
86  import org.apache.http.conn.ssl.X509HostnameVerifier;
87  import org.apache.http.impl.client.DefaultHttpClient;
88  import org.apache.http.params.CoreConnectionPNames;
89  import org.apache.http.params.HttpParams;
90  import org.eclipse.jgit.transport.http.HttpConnection;
91  import org.eclipse.jgit.transport.http.apache.internal.HttpApacheText;
92  import org.eclipse.jgit.util.TemporaryBuffer;
93  import org.eclipse.jgit.util.TemporaryBuffer.LocalFile;
94  
95  /**
96   * A {@link HttpConnection} which uses {@link HttpClient}
97   *
98   * @since 3.3
99   */
100 public class HttpClientConnection implements HttpConnection {
101 	HttpClient client;
102 
103 	String urlStr;
104 
105 	HttpUriRequest req;
106 
107 	HttpResponse resp = null;
108 
109 	String method = "GET"; //$NON-NLS-1$
110 
111 	private TemporaryBufferEntity entity;
112 
113 	private boolean isUsingProxy = false;
114 
115 	private Proxy proxy;
116 
117 	private Integer timeout = null;
118 
119 	private Integer readTimeout;
120 
121 	private Boolean followRedirects;
122 
123 	private X509HostnameVerifier hostnameverifier;
124 
125 	SSLContext ctx;
126 
127 	private HttpClient getClient() {
128 		if (client == null)
129 			client = new DefaultHttpClient();
130 		HttpParams params = client.getParams();
131 		if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
132 			isUsingProxy = true;
133 			InetSocketAddress adr = (InetSocketAddress) proxy.address();
134 			params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
135 					new HttpHost(adr.getHostName(), adr.getPort()));
136 		}
137 		if (timeout != null)
138 			params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
139 					timeout.intValue());
140 		if (readTimeout != null)
141 			params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
142 					readTimeout.intValue());
143 		if (followRedirects != null)
144 			params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,
145 					followRedirects.booleanValue());
146 		if (hostnameverifier != null) {
147 			SSLSocketFactory sf;
148 			sf = new SSLSocketFactory(getSSLContext(), hostnameverifier);
149 			Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
150 			client.getConnectionManager().getSchemeRegistry().register(https);
151 		}
152 
153 		return client;
154 	}
155 
156 	private SSLContext getSSLContext() {
157 		if (ctx == null) {
158 			try {
159 				ctx = SSLContext.getInstance("TLS"); //$NON-NLS-1$
160 			} catch (NoSuchAlgorithmException e) {
161 				throw new IllegalStateException(
162 						HttpApacheText.get().unexpectedSSLContextException, e);
163 			}
164 		}
165 		return ctx;
166 	}
167 
168 	/**
169 	 * Sets the buffer from which to take the request body
170 	 *
171 	 * @param buffer
172 	 */
173 	public void setBuffer(TemporaryBuffer buffer) {
174 		this.entity = new TemporaryBufferEntity(buffer);
175 	}
176 
177 	/**
178 	 * @param urlStr
179 	 */
180 	public HttpClientConnection(String urlStr) {
181 		this(urlStr, null);
182 	}
183 
184 	/**
185 	 * @param urlStr
186 	 * @param proxy
187 	 */
188 	public HttpClientConnection(String urlStr, Proxy proxy) {
189 		this(urlStr, proxy, null);
190 	}
191 
192 	/**
193 	 * @param urlStr
194 	 * @param proxy
195 	 * @param cl
196 	 */
197 	public HttpClientConnection(String urlStr, Proxy proxy, HttpClient cl) {
198 		this.client = cl;
199 		this.urlStr = urlStr;
200 		this.proxy = proxy;
201 	}
202 
203 	public int getResponseCode() throws IOException {
204 		execute();
205 		return resp.getStatusLine().getStatusCode();
206 	}
207 
208 	public URL getURL() {
209 		try {
210 			return new URL(urlStr);
211 		} catch (MalformedURLException e) {
212 			return null;
213 		}
214 	}
215 
216 	public String getResponseMessage() throws IOException {
217 		execute();
218 		return resp.getStatusLine().getReasonPhrase();
219 	}
220 
221 	private void execute() throws IOException, ClientProtocolException {
222 		if (resp == null)
223 			if (entity != null) {
224 				if (req instanceof HttpEntityEnclosingRequest) {
225 					HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req;
226 					eReq.setEntity(entity);
227 				}
228 				resp = getClient().execute(req);
229 				entity.getBuffer().close();
230 				entity = null;
231 			} else
232 				resp = getClient().execute(req);
233 	}
234 
235 	public Map<String, List<String>> getHeaderFields() {
236 		Map<String, List<String>> ret = new HashMap<String, List<String>>();
237 		for (Header hdr : resp.getAllHeaders()) {
238 			List<String> list = new LinkedList<String>();
239 			for (HeaderElement hdrElem : hdr.getElements())
240 				list.add(hdrElem.toString());
241 			ret.put(hdr.getName(), list);
242 		}
243 		return ret;
244 	}
245 
246 	public void setRequestProperty(String name, String value) {
247 		req.addHeader(name, value);
248 	}
249 
250 	public void setRequestMethod(String method) throws ProtocolException {
251 		this.method = method;
252 		if ("GET".equalsIgnoreCase(method)) //$NON-NLS-1$
253 			req = new HttpGet(urlStr);
254 		else if ("PUT".equalsIgnoreCase(method)) //$NON-NLS-1$
255 			req = new HttpPut(urlStr);
256 		else if ("POST".equalsIgnoreCase(method)) //$NON-NLS-1$
257 			req = new HttpPost(urlStr);
258 		else {
259 			this.method = null;
260 			throw new UnsupportedOperationException();
261 		}
262 	}
263 
264 	public void setUseCaches(boolean usecaches) {
265 		// not needed
266 	}
267 
268 	public void setConnectTimeout(int timeout) {
269 		this.timeout = new Integer(timeout);
270 	}
271 
272 	public void setReadTimeout(int readTimeout) {
273 		this.readTimeout = new Integer(readTimeout);
274 	}
275 
276 	public String getContentType() {
277 		HttpEntity responseEntity = resp.getEntity();
278 		if (responseEntity != null) {
279 			Header contentType = responseEntity.getContentType();
280 			if (contentType != null)
281 				return contentType.getValue();
282 		}
283 		return null;
284 	}
285 
286 	public InputStream getInputStream() throws IOException {
287 		return resp.getEntity().getContent();
288 	}
289 
290 	// will return only the first field
291 	public String getHeaderField(String name) {
292 		Header header = resp.getFirstHeader(name);
293 		return (header == null) ? null : header.getValue();
294 	}
295 
296 	public int getContentLength() {
297 		return Integer.parseInt(resp.getFirstHeader("content-length") //$NON-NLS-1$
298 				.getValue());
299 	}
300 
301 	public void setInstanceFollowRedirects(boolean followRedirects) {
302 		this.followRedirects = new Boolean(followRedirects);
303 	}
304 
305 	public void setDoOutput(boolean dooutput) {
306 		// TODO: check whether we can really ignore this.
307 	}
308 
309 	public void setFixedLengthStreamingMode(int contentLength) {
310 		if (entity != null)
311 			throw new IllegalArgumentException();
312 		entity = new TemporaryBufferEntity(new LocalFile(null));
313 		entity.setContentLength(contentLength);
314 	}
315 
316 	public OutputStream getOutputStream() throws IOException {
317 		if (entity == null)
318 			entity = new TemporaryBufferEntity(new LocalFile(null));
319 		return entity.getBuffer();
320 	}
321 
322 	public void setChunkedStreamingMode(int chunklen) {
323 		if (entity == null)
324 			entity = new TemporaryBufferEntity(new LocalFile(null));
325 		entity.setChunked(true);
326 	}
327 
328 	public String getRequestMethod() {
329 		return method;
330 	}
331 
332 	public boolean usingProxy() {
333 		return isUsingProxy;
334 	}
335 
336 	public void connect() throws IOException {
337 		execute();
338 	}
339 
340 	public void setHostnameVerifier(final HostnameVerifier hostnameverifier) {
341 		this.hostnameverifier = new X509HostnameVerifier() {
342 			public boolean verify(String hostname, SSLSession session) {
343 				return hostnameverifier.verify(hostname, session);
344 			}
345 
346 			public void verify(String host, String[] cns, String[] subjectAlts)
347 					throws SSLException {
348 				throw new UnsupportedOperationException(); // TODO message
349 			}
350 
351 			public void verify(String host, X509Certificate cert)
352 					throws SSLException {
353 				throw new UnsupportedOperationException(); // TODO message
354 			}
355 
356 			public void verify(String host, SSLSocket ssl) throws IOException {
357 				hostnameverifier.verify(host, ssl.getSession());
358 			}
359 		};
360 	}
361 
362 	public void configure(KeyManager[] km, TrustManager[] tm,
363 			SecureRandom random) throws KeyManagementException {
364 		getSSLContext().init(km, tm, random);
365 	}
366 }