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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. @Override
  202. public int getResponseCode() throws IOException {
  203. execute();
  204. return resp.getStatusLine().getStatusCode();
  205. }
  206. @Override
  207. public URL getURL() {
  208. return url;
  209. }
  210. @Override
  211. public String getResponseMessage() throws IOException {
  212. execute();
  213. return resp.getStatusLine().getReasonPhrase();
  214. }
  215. private void execute() throws IOException, ClientProtocolException {
  216. if (resp != null) {
  217. return;
  218. }
  219. if (entity == null) {
  220. resp = getClient().execute(req);
  221. return;
  222. }
  223. try {
  224. if (req instanceof HttpEntityEnclosingRequest) {
  225. HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req;
  226. eReq.setEntity(entity);
  227. }
  228. resp = getClient().execute(req);
  229. } finally {
  230. entity.close();
  231. entity = null;
  232. }
  233. }
  234. @Override
  235. public Map<String, List<String>> getHeaderFields() {
  236. Map<String, List<String>> ret = new HashMap<>();
  237. for (Header hdr : resp.getAllHeaders()) {
  238. List<String> list = new LinkedList<>();
  239. for (HeaderElement hdrElem : hdr.getElements())
  240. list.add(hdrElem.toString());
  241. ret.put(hdr.getName(), list);
  242. }
  243. return ret;
  244. }
  245. @Override
  246. public void setRequestProperty(String name, String value) {
  247. req.addHeader(name, value);
  248. }
  249. @Override
  250. public void setRequestMethod(String method) throws ProtocolException {
  251. this.method = method;
  252. if (METHOD_GET.equalsIgnoreCase(method)) {
  253. req = new HttpGet(url.toString());
  254. } else if (METHOD_HEAD.equalsIgnoreCase(method)) {
  255. req = new HttpHead(url.toString());
  256. } else if (METHOD_PUT.equalsIgnoreCase(method)) {
  257. req = new HttpPut(url.toString());
  258. } else if (METHOD_POST.equalsIgnoreCase(method)) {
  259. req = new HttpPost(url.toString());
  260. } else {
  261. this.method = null;
  262. throw new UnsupportedOperationException();
  263. }
  264. }
  265. @Override
  266. public void setUseCaches(boolean usecaches) {
  267. // not needed
  268. }
  269. @Override
  270. public void setConnectTimeout(int timeout) {
  271. this.timeout = Integer.valueOf(timeout);
  272. }
  273. @Override
  274. public void setReadTimeout(int readTimeout) {
  275. this.readTimeout = Integer.valueOf(readTimeout);
  276. }
  277. @Override
  278. public String getContentType() {
  279. HttpEntity responseEntity = resp.getEntity();
  280. if (responseEntity != null) {
  281. Header contentType = responseEntity.getContentType();
  282. if (contentType != null)
  283. return contentType.getValue();
  284. }
  285. return null;
  286. }
  287. @Override
  288. public InputStream getInputStream() throws IOException {
  289. return resp.getEntity().getContent();
  290. }
  291. // will return only the first field
  292. @Override
  293. public String getHeaderField(String name) {
  294. Header header = resp.getFirstHeader(name);
  295. return (header == null) ? null : header.getValue();
  296. }
  297. @Override
  298. public int getContentLength() {
  299. Header contentLength = resp.getFirstHeader("content-length"); //$NON-NLS-1$
  300. if (contentLength == null) {
  301. return -1;
  302. }
  303. try {
  304. int l = Integer.parseInt(contentLength.getValue());
  305. return l < 0 ? -1 : l;
  306. } catch (NumberFormatException e) {
  307. return -1;
  308. }
  309. }
  310. @Override
  311. public void setInstanceFollowRedirects(boolean followRedirects) {
  312. this.followRedirects = Boolean.valueOf(followRedirects);
  313. }
  314. @Override
  315. public void setDoOutput(boolean dooutput) {
  316. // TODO: check whether we can really ignore this.
  317. }
  318. @Override
  319. public void setFixedLengthStreamingMode(int contentLength) {
  320. if (entity != null)
  321. throw new IllegalArgumentException();
  322. entity = new TemporaryBufferEntity(new LocalFile(null));
  323. entity.setContentLength(contentLength);
  324. }
  325. @Override
  326. public OutputStream getOutputStream() throws IOException {
  327. if (entity == null)
  328. entity = new TemporaryBufferEntity(new LocalFile(null));
  329. return entity.getBuffer();
  330. }
  331. @Override
  332. public void setChunkedStreamingMode(int chunklen) {
  333. if (entity == null)
  334. entity = new TemporaryBufferEntity(new LocalFile(null));
  335. entity.setChunked(true);
  336. }
  337. @Override
  338. public String getRequestMethod() {
  339. return method;
  340. }
  341. @Override
  342. public boolean usingProxy() {
  343. return isUsingProxy;
  344. }
  345. @Override
  346. public void connect() throws IOException {
  347. execute();
  348. }
  349. @Override
  350. public void setHostnameVerifier(final HostnameVerifier hostnameverifier) {
  351. this.hostnameverifier = new X509HostnameVerifier() {
  352. @Override
  353. public boolean verify(String hostname, SSLSession session) {
  354. return hostnameverifier.verify(hostname, session);
  355. }
  356. @Override
  357. public void verify(String host, String[] cns, String[] subjectAlts)
  358. throws SSLException {
  359. throw new UnsupportedOperationException(); // TODO message
  360. }
  361. @Override
  362. public void verify(String host, X509Certificate cert)
  363. throws SSLException {
  364. throw new UnsupportedOperationException(); // TODO message
  365. }
  366. @Override
  367. public void verify(String host, SSLSocket ssl) throws IOException {
  368. hostnameverifier.verify(host, ssl.getSession());
  369. }
  370. };
  371. }
  372. @Override
  373. public void configure(KeyManager[] km, TrustManager[] tm,
  374. SecureRandom random) throws KeyManagementException {
  375. getSSLContext().init(km, tm, random);
  376. }
  377. }