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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. /*
  2. * Copyright (C) 2013, 2020 Christian Halstrick <christian.halstrick@sap.com> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.transport.http.apache;
  11. import static org.eclipse.jgit.util.HttpSupport.METHOD_GET;
  12. import static org.eclipse.jgit.util.HttpSupport.METHOD_HEAD;
  13. import static org.eclipse.jgit.util.HttpSupport.METHOD_POST;
  14. import static org.eclipse.jgit.util.HttpSupport.METHOD_PUT;
  15. import java.io.IOException;
  16. import java.io.InputStream;
  17. import java.io.OutputStream;
  18. import java.net.InetSocketAddress;
  19. import java.net.MalformedURLException;
  20. import java.net.ProtocolException;
  21. import java.net.Proxy;
  22. import java.net.URL;
  23. import java.security.KeyManagementException;
  24. import java.security.NoSuchAlgorithmException;
  25. import java.security.SecureRandom;
  26. import java.util.Arrays;
  27. import java.util.Collections;
  28. import java.util.HashMap;
  29. import java.util.LinkedList;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.stream.Collectors;
  33. import javax.net.ssl.HostnameVerifier;
  34. import javax.net.ssl.KeyManager;
  35. import javax.net.ssl.SSLContext;
  36. import javax.net.ssl.SSLSocket;
  37. import javax.net.ssl.TrustManager;
  38. import org.apache.http.Header;
  39. import org.apache.http.HeaderElement;
  40. import org.apache.http.HttpEntity;
  41. import org.apache.http.HttpEntityEnclosingRequest;
  42. import org.apache.http.HttpHost;
  43. import org.apache.http.HttpResponse;
  44. import org.apache.http.client.ClientProtocolException;
  45. import org.apache.http.client.HttpClient;
  46. import org.apache.http.client.config.RequestConfig;
  47. import org.apache.http.client.methods.HttpGet;
  48. import org.apache.http.client.methods.HttpHead;
  49. import org.apache.http.client.methods.HttpPost;
  50. import org.apache.http.client.methods.HttpPut;
  51. import org.apache.http.client.methods.HttpUriRequest;
  52. import org.apache.http.config.Registry;
  53. import org.apache.http.config.RegistryBuilder;
  54. import org.apache.http.conn.socket.ConnectionSocketFactory;
  55. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  56. import org.apache.http.conn.ssl.DefaultHostnameVerifier;
  57. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  58. import org.apache.http.conn.util.PublicSuffixMatcherLoader;
  59. import org.apache.http.impl.client.HttpClientBuilder;
  60. import org.apache.http.impl.client.HttpClients;
  61. import org.apache.http.impl.client.SystemDefaultCredentialsProvider;
  62. import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
  63. import org.apache.http.ssl.SSLContexts;
  64. import org.eclipse.jgit.annotations.NonNull;
  65. import org.eclipse.jgit.transport.http.HttpConnection;
  66. import org.eclipse.jgit.transport.http.apache.internal.HttpApacheText;
  67. import org.eclipse.jgit.util.HttpSupport;
  68. import org.eclipse.jgit.util.TemporaryBuffer;
  69. import org.eclipse.jgit.util.TemporaryBuffer.LocalFile;
  70. /**
  71. * A {@link org.eclipse.jgit.transport.http.HttpConnection} which uses
  72. * {@link org.apache.http.client.HttpClient}
  73. *
  74. * @since 3.3
  75. */
  76. public class HttpClientConnection implements HttpConnection {
  77. HttpClient client;
  78. URL url;
  79. HttpUriRequest req;
  80. HttpResponse resp = null;
  81. String method = "GET"; //$NON-NLS-1$
  82. private TemporaryBufferEntity entity;
  83. private boolean isUsingProxy = false;
  84. private Proxy proxy;
  85. private Integer timeout = null;
  86. private Integer readTimeout;
  87. private Boolean followRedirects;
  88. private HostnameVerifier hostnameverifier;
  89. SSLContext ctx;
  90. private HttpClient getClient() {
  91. if (client == null) {
  92. HttpClientBuilder clientBuilder = HttpClients.custom();
  93. RequestConfig.Builder configBuilder = RequestConfig.custom();
  94. if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
  95. isUsingProxy = true;
  96. InetSocketAddress adr = (InetSocketAddress) proxy.address();
  97. clientBuilder.setProxy(
  98. new HttpHost(adr.getHostName(), adr.getPort()));
  99. }
  100. if (timeout != null) {
  101. configBuilder.setConnectTimeout(timeout.intValue());
  102. }
  103. if (readTimeout != null) {
  104. configBuilder.setSocketTimeout(readTimeout.intValue());
  105. }
  106. if (followRedirects != null) {
  107. configBuilder
  108. .setRedirectsEnabled(followRedirects.booleanValue());
  109. }
  110. SSLConnectionSocketFactory sslConnectionFactory = getSSLSocketFactory();
  111. clientBuilder.setSSLSocketFactory(sslConnectionFactory);
  112. if (hostnameverifier != null) {
  113. // Using a custom verifier: we don't want pooled connections
  114. // with this.
  115. Registry<ConnectionSocketFactory> registry = RegistryBuilder
  116. .<ConnectionSocketFactory> create()
  117. .register("https", sslConnectionFactory)
  118. .register("http", PlainConnectionSocketFactory.INSTANCE)
  119. .build();
  120. clientBuilder.setConnectionManager(
  121. new BasicHttpClientConnectionManager(registry));
  122. }
  123. clientBuilder.setDefaultRequestConfig(configBuilder.build());
  124. clientBuilder.setDefaultCredentialsProvider(
  125. new SystemDefaultCredentialsProvider());
  126. client = clientBuilder.build();
  127. }
  128. return client;
  129. }
  130. private SSLConnectionSocketFactory getSSLSocketFactory() {
  131. HostnameVerifier verifier = hostnameverifier;
  132. SSLContext context;
  133. if (verifier == null) {
  134. // Use defaults
  135. context = SSLContexts.createDefault();
  136. verifier = new DefaultHostnameVerifier(
  137. PublicSuffixMatcherLoader.getDefault());
  138. } else {
  139. // Using a custom verifier. Attention: configure() must have been
  140. // called already, otherwise one gets a "context not initialized"
  141. // exception. In JGit this branch is reached only when hostname
  142. // verification is switched off, and JGit _does_ call configure()
  143. // before we get here.
  144. context = getSSLContext();
  145. }
  146. return new SSLConnectionSocketFactory(context, verifier) {
  147. @Override
  148. protected void prepareSocket(SSLSocket socket) throws IOException {
  149. super.prepareSocket(socket);
  150. HttpSupport.configureTLS(socket);
  151. }
  152. };
  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. * Constructor for HttpClientConnection.
  175. *
  176. * @param urlStr
  177. * @throws MalformedURLException
  178. */
  179. public HttpClientConnection(String urlStr) throws MalformedURLException {
  180. this(urlStr, null);
  181. }
  182. /**
  183. * Constructor for HttpClientConnection.
  184. *
  185. * @param urlStr
  186. * @param proxy
  187. * @throws MalformedURLException
  188. */
  189. public HttpClientConnection(String urlStr, Proxy proxy)
  190. throws MalformedURLException {
  191. this(urlStr, proxy, null);
  192. }
  193. /**
  194. * Constructor for HttpClientConnection.
  195. *
  196. * @param urlStr
  197. * @param proxy
  198. * @param cl
  199. * @throws MalformedURLException
  200. */
  201. public HttpClientConnection(String urlStr, Proxy proxy, HttpClient cl)
  202. throws MalformedURLException {
  203. this.client = cl;
  204. this.url = new URL(urlStr);
  205. this.proxy = proxy;
  206. }
  207. /** {@inheritDoc} */
  208. @Override
  209. public int getResponseCode() throws IOException {
  210. execute();
  211. return resp.getStatusLine().getStatusCode();
  212. }
  213. /** {@inheritDoc} */
  214. @Override
  215. public URL getURL() {
  216. return url;
  217. }
  218. /** {@inheritDoc} */
  219. @Override
  220. public String getResponseMessage() throws IOException {
  221. execute();
  222. return resp.getStatusLine().getReasonPhrase();
  223. }
  224. private void execute() throws IOException, ClientProtocolException {
  225. if (resp != null) {
  226. return;
  227. }
  228. if (entity == null) {
  229. resp = getClient().execute(req);
  230. return;
  231. }
  232. try {
  233. if (req instanceof HttpEntityEnclosingRequest) {
  234. HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req;
  235. eReq.setEntity(entity);
  236. }
  237. resp = getClient().execute(req);
  238. } finally {
  239. entity.close();
  240. entity = null;
  241. }
  242. }
  243. /** {@inheritDoc} */
  244. @Override
  245. public Map<String, List<String>> getHeaderFields() {
  246. Map<String, List<String>> ret = new HashMap<>();
  247. for (Header hdr : resp.getAllHeaders()) {
  248. List<String> list = ret.get(hdr.getName());
  249. if (list == null) {
  250. list = new LinkedList<>();
  251. ret.put(hdr.getName(), list);
  252. }
  253. for (HeaderElement hdrElem : hdr.getElements()) {
  254. list.add(hdrElem.toString());
  255. }
  256. }
  257. return ret;
  258. }
  259. /** {@inheritDoc} */
  260. @Override
  261. public void setRequestProperty(String name, String value) {
  262. req.addHeader(name, value);
  263. }
  264. /** {@inheritDoc} */
  265. @Override
  266. public void setRequestMethod(String method) throws ProtocolException {
  267. this.method = method;
  268. if (METHOD_GET.equalsIgnoreCase(method)) {
  269. req = new HttpGet(url.toString());
  270. } else if (METHOD_HEAD.equalsIgnoreCase(method)) {
  271. req = new HttpHead(url.toString());
  272. } else if (METHOD_PUT.equalsIgnoreCase(method)) {
  273. req = new HttpPut(url.toString());
  274. } else if (METHOD_POST.equalsIgnoreCase(method)) {
  275. req = new HttpPost(url.toString());
  276. } else {
  277. this.method = null;
  278. throw new UnsupportedOperationException();
  279. }
  280. }
  281. /** {@inheritDoc} */
  282. @Override
  283. public void setUseCaches(boolean usecaches) {
  284. // not needed
  285. }
  286. /** {@inheritDoc} */
  287. @Override
  288. public void setConnectTimeout(int timeout) {
  289. this.timeout = Integer.valueOf(timeout);
  290. }
  291. /** {@inheritDoc} */
  292. @Override
  293. public void setReadTimeout(int readTimeout) {
  294. this.readTimeout = Integer.valueOf(readTimeout);
  295. }
  296. /** {@inheritDoc} */
  297. @Override
  298. public String getContentType() {
  299. HttpEntity responseEntity = resp.getEntity();
  300. if (responseEntity != null) {
  301. Header contentType = responseEntity.getContentType();
  302. if (contentType != null)
  303. return contentType.getValue();
  304. }
  305. return null;
  306. }
  307. /** {@inheritDoc} */
  308. @Override
  309. public InputStream getInputStream() throws IOException {
  310. execute();
  311. return resp.getEntity().getContent();
  312. }
  313. // will return only the first field
  314. /** {@inheritDoc} */
  315. @Override
  316. public String getHeaderField(@NonNull String name) {
  317. Header header = resp.getFirstHeader(name);
  318. return (header == null) ? null : header.getValue();
  319. }
  320. @Override
  321. public List<String> getHeaderFields(@NonNull String name) {
  322. return Collections.unmodifiableList(Arrays.asList(resp.getHeaders(name))
  323. .stream().map(Header::getValue).collect(Collectors.toList()));
  324. }
  325. /** {@inheritDoc} */
  326. @Override
  327. public int getContentLength() {
  328. Header contentLength = resp.getFirstHeader("content-length"); //$NON-NLS-1$
  329. if (contentLength == null) {
  330. return -1;
  331. }
  332. try {
  333. int l = Integer.parseInt(contentLength.getValue());
  334. return l < 0 ? -1 : l;
  335. } catch (NumberFormatException e) {
  336. return -1;
  337. }
  338. }
  339. /** {@inheritDoc} */
  340. @Override
  341. public void setInstanceFollowRedirects(boolean followRedirects) {
  342. this.followRedirects = Boolean.valueOf(followRedirects);
  343. }
  344. /** {@inheritDoc} */
  345. @Override
  346. public void setDoOutput(boolean dooutput) {
  347. // TODO: check whether we can really ignore this.
  348. }
  349. /** {@inheritDoc} */
  350. @Override
  351. public void setFixedLengthStreamingMode(int contentLength) {
  352. if (entity != null)
  353. throw new IllegalArgumentException();
  354. entity = new TemporaryBufferEntity(new LocalFile(null));
  355. entity.setContentLength(contentLength);
  356. }
  357. /** {@inheritDoc} */
  358. @Override
  359. public OutputStream getOutputStream() throws IOException {
  360. if (entity == null)
  361. entity = new TemporaryBufferEntity(new LocalFile(null));
  362. return entity.getBuffer();
  363. }
  364. /** {@inheritDoc} */
  365. @Override
  366. public void setChunkedStreamingMode(int chunklen) {
  367. if (entity == null)
  368. entity = new TemporaryBufferEntity(new LocalFile(null));
  369. entity.setChunked(true);
  370. }
  371. /** {@inheritDoc} */
  372. @Override
  373. public String getRequestMethod() {
  374. return method;
  375. }
  376. /** {@inheritDoc} */
  377. @Override
  378. public boolean usingProxy() {
  379. return isUsingProxy;
  380. }
  381. /** {@inheritDoc} */
  382. @Override
  383. public void connect() throws IOException {
  384. execute();
  385. }
  386. /** {@inheritDoc} */
  387. @Override
  388. public void setHostnameVerifier(HostnameVerifier hostnameverifier) {
  389. this.hostnameverifier = hostnameverifier;
  390. }
  391. /** {@inheritDoc} */
  392. @Override
  393. public void configure(KeyManager[] km, TrustManager[] tm,
  394. SecureRandom random) throws KeyManagementException {
  395. getSSLContext().init(km, tm, random);
  396. }
  397. }