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.

HttpClientConnection.java 12KB

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