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.

HttpSupport.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /*
  2. * Copyright (C) 2010, Google Inc.
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.util;
  45. import static java.nio.charset.StandardCharsets.UTF_8;
  46. import java.io.IOException;
  47. import java.io.UnsupportedEncodingException;
  48. import java.net.ConnectException;
  49. import java.net.Proxy;
  50. import java.net.ProxySelector;
  51. import java.net.URISyntaxException;
  52. import java.net.URL;
  53. import java.net.URLEncoder;
  54. import java.security.KeyManagementException;
  55. import java.security.NoSuchAlgorithmException;
  56. import java.security.cert.X509Certificate;
  57. import java.text.MessageFormat;
  58. import javax.net.ssl.HostnameVerifier;
  59. import javax.net.ssl.SSLSession;
  60. import javax.net.ssl.TrustManager;
  61. import javax.net.ssl.X509TrustManager;
  62. import org.eclipse.jgit.internal.JGitText;
  63. import org.eclipse.jgit.transport.http.HttpConnection;
  64. /**
  65. * Extra utilities to support usage of HTTP.
  66. */
  67. public class HttpSupport {
  68. /** The {@code GET} HTTP method. */
  69. public static final String METHOD_GET = "GET"; //$NON-NLS-1$
  70. /** The {@code HEAD} HTTP method.
  71. * @since 4.3 */
  72. public static final String METHOD_HEAD = "HEAD"; //$NON-NLS-1$
  73. /** The {@code POST} HTTP method.
  74. * @since 4.3 */
  75. public static final String METHOD_PUT = "PUT"; //$NON-NLS-1$
  76. /** The {@code POST} HTTP method. */
  77. public static final String METHOD_POST = "POST"; //$NON-NLS-1$
  78. /** The {@code Cache-Control} header. */
  79. public static final String HDR_CACHE_CONTROL = "Cache-Control"; //$NON-NLS-1$
  80. /** The {@code Pragma} header. */
  81. public static final String HDR_PRAGMA = "Pragma"; //$NON-NLS-1$
  82. /** The {@code User-Agent} header. */
  83. public static final String HDR_USER_AGENT = "User-Agent"; //$NON-NLS-1$
  84. /**
  85. * The {@code Server} header.
  86. * @since 4.0
  87. */
  88. public static final String HDR_SERVER = "Server"; //$NON-NLS-1$
  89. /** The {@code Date} header. */
  90. public static final String HDR_DATE = "Date"; //$NON-NLS-1$
  91. /** The {@code Expires} header. */
  92. public static final String HDR_EXPIRES = "Expires"; //$NON-NLS-1$
  93. /** The {@code ETag} header. */
  94. public static final String HDR_ETAG = "ETag"; //$NON-NLS-1$
  95. /** The {@code If-None-Match} header. */
  96. public static final String HDR_IF_NONE_MATCH = "If-None-Match"; //$NON-NLS-1$
  97. /** The {@code Last-Modified} header. */
  98. public static final String HDR_LAST_MODIFIED = "Last-Modified"; //$NON-NLS-1$
  99. /** The {@code If-Modified-Since} header. */
  100. public static final String HDR_IF_MODIFIED_SINCE = "If-Modified-Since"; //$NON-NLS-1$
  101. /** The {@code Accept} header. */
  102. public static final String HDR_ACCEPT = "Accept"; //$NON-NLS-1$
  103. /** The {@code Content-Type} header. */
  104. public static final String HDR_CONTENT_TYPE = "Content-Type"; //$NON-NLS-1$
  105. /** The {@code Content-Length} header. */
  106. public static final String HDR_CONTENT_LENGTH = "Content-Length"; //$NON-NLS-1$
  107. /** The {@code Content-Encoding} header. */
  108. public static final String HDR_CONTENT_ENCODING = "Content-Encoding"; //$NON-NLS-1$
  109. /** The {@code Content-Range} header. */
  110. public static final String HDR_CONTENT_RANGE = "Content-Range"; //$NON-NLS-1$
  111. /** The {@code Accept-Ranges} header. */
  112. public static final String HDR_ACCEPT_RANGES = "Accept-Ranges"; //$NON-NLS-1$
  113. /** The {@code If-Range} header. */
  114. public static final String HDR_IF_RANGE = "If-Range"; //$NON-NLS-1$
  115. /** The {@code Range} header. */
  116. public static final String HDR_RANGE = "Range"; //$NON-NLS-1$
  117. /** The {@code Accept-Encoding} header. */
  118. public static final String HDR_ACCEPT_ENCODING = "Accept-Encoding"; //$NON-NLS-1$
  119. /**
  120. * The {@code Location} header.
  121. * @since 4.7
  122. */
  123. public static final String HDR_LOCATION = "Location"; //$NON-NLS-1$
  124. /** The {@code gzip} encoding value for {@link #HDR_ACCEPT_ENCODING}. */
  125. public static final String ENCODING_GZIP = "gzip"; //$NON-NLS-1$
  126. /**
  127. * The {@code x-gzip} encoding value for {@link #HDR_ACCEPT_ENCODING}.
  128. * @since 4.6
  129. */
  130. public static final String ENCODING_X_GZIP = "x-gzip"; //$NON-NLS-1$
  131. /** The standard {@code text/plain} MIME type. */
  132. public static final String TEXT_PLAIN = "text/plain"; //$NON-NLS-1$
  133. /** The {@code Authorization} header. */
  134. public static final String HDR_AUTHORIZATION = "Authorization"; //$NON-NLS-1$
  135. /** The {@code WWW-Authenticate} header. */
  136. public static final String HDR_WWW_AUTHENTICATE = "WWW-Authenticate"; //$NON-NLS-1$
  137. /**
  138. * URL encode a value string into an output buffer.
  139. *
  140. * @param urlstr
  141. * the output buffer.
  142. * @param key
  143. * value which must be encoded to protected special characters.
  144. */
  145. public static void encode(StringBuilder urlstr, String key) {
  146. if (key == null || key.length() == 0)
  147. return;
  148. try {
  149. urlstr.append(URLEncoder.encode(key, UTF_8.name()));
  150. } catch (UnsupportedEncodingException e) {
  151. throw new RuntimeException(JGitText.get().couldNotURLEncodeToUTF8, e);
  152. }
  153. }
  154. /**
  155. * Get the HTTP response code from the request.
  156. * <p>
  157. * Roughly the same as <code>c.getResponseCode()</code> but the
  158. * ConnectException is translated to be more understandable.
  159. *
  160. * @param c
  161. * connection the code should be obtained from.
  162. * @return r HTTP status code, usually 200 to indicate success. See
  163. * {@link org.eclipse.jgit.transport.http.HttpConnection} for other
  164. * defined constants.
  165. * @throws java.io.IOException
  166. * communications error prevented obtaining the response code.
  167. * @since 3.3
  168. */
  169. public static int response(HttpConnection c) throws IOException {
  170. try {
  171. return c.getResponseCode();
  172. } catch (ConnectException ce) {
  173. final URL url = c.getURL();
  174. final String host = (url == null) ? "<null>" : url.getHost(); //$NON-NLS-1$
  175. // The standard J2SE error message is not very useful.
  176. //
  177. if ("Connection timed out: connect".equals(ce.getMessage())) //$NON-NLS-1$
  178. throw new ConnectException(MessageFormat.format(JGitText.get().connectionTimeOut, host));
  179. throw new ConnectException(ce.getMessage() + " " + host); //$NON-NLS-1$
  180. }
  181. }
  182. /**
  183. * Get the HTTP response code from the request.
  184. * <p>
  185. * Roughly the same as <code>c.getResponseCode()</code> but the
  186. * ConnectException is translated to be more understandable.
  187. *
  188. * @param c
  189. * connection the code should be obtained from.
  190. * @return r HTTP status code, usually 200 to indicate success. See
  191. * {@link org.eclipse.jgit.transport.http.HttpConnection} for other
  192. * defined constants.
  193. * @throws java.io.IOException
  194. * communications error prevented obtaining the response code.
  195. */
  196. public static int response(java.net.HttpURLConnection c)
  197. throws IOException {
  198. try {
  199. return c.getResponseCode();
  200. } catch (ConnectException ce) {
  201. final URL url = c.getURL();
  202. final String host = (url == null) ? "<null>" : url.getHost(); //$NON-NLS-1$
  203. // The standard J2SE error message is not very useful.
  204. //
  205. if ("Connection timed out: connect".equals(ce.getMessage())) //$NON-NLS-1$
  206. throw new ConnectException(MessageFormat.format(
  207. JGitText.get().connectionTimeOut, host));
  208. throw new ConnectException(ce.getMessage() + " " + host); //$NON-NLS-1$
  209. }
  210. }
  211. /**
  212. * Extract a HTTP header from the response.
  213. *
  214. * @param c
  215. * connection the header should be obtained from.
  216. * @param headerName
  217. * the header name
  218. * @return the header value
  219. * @throws java.io.IOException
  220. * communications error prevented obtaining the header.
  221. * @since 4.7
  222. */
  223. public static String responseHeader(final HttpConnection c,
  224. final String headerName) throws IOException {
  225. return c.getHeaderField(headerName);
  226. }
  227. /**
  228. * Determine the proxy server (if any) needed to obtain a URL.
  229. *
  230. * @param proxySelector
  231. * proxy support for the caller.
  232. * @param u
  233. * location of the server caller wants to talk to.
  234. * @return proxy to communicate with the supplied URL.
  235. * @throws java.net.ConnectException
  236. * the proxy could not be computed as the supplied URL could not
  237. * be read. This failure should never occur.
  238. */
  239. public static Proxy proxyFor(ProxySelector proxySelector, URL u)
  240. throws ConnectException {
  241. try {
  242. return proxySelector.select(u.toURI()).get(0);
  243. } catch (URISyntaxException e) {
  244. final ConnectException err;
  245. err = new ConnectException(MessageFormat.format(JGitText.get().cannotDetermineProxyFor, u));
  246. err.initCause(e);
  247. throw err;
  248. }
  249. }
  250. /**
  251. * Disable SSL and hostname verification for given HTTP connection
  252. *
  253. * @param conn
  254. * a {@link org.eclipse.jgit.transport.http.HttpConnection}
  255. * object.
  256. * @throws java.io.IOException
  257. * @since 4.3
  258. */
  259. public static void disableSslVerify(HttpConnection conn)
  260. throws IOException {
  261. final TrustManager[] trustAllCerts = new TrustManager[] {
  262. new DummyX509TrustManager() };
  263. try {
  264. conn.configure(null, trustAllCerts, null);
  265. conn.setHostnameVerifier(new DummyHostnameVerifier());
  266. } catch (KeyManagementException e) {
  267. throw new IOException(e.getMessage());
  268. } catch (NoSuchAlgorithmException e) {
  269. throw new IOException(e.getMessage());
  270. }
  271. }
  272. private static class DummyX509TrustManager implements X509TrustManager {
  273. @Override
  274. public X509Certificate[] getAcceptedIssuers() {
  275. return null;
  276. }
  277. @Override
  278. public void checkClientTrusted(X509Certificate[] certs,
  279. String authType) {
  280. // no check
  281. }
  282. @Override
  283. public void checkServerTrusted(X509Certificate[] certs,
  284. String authType) {
  285. // no check
  286. }
  287. }
  288. private static class DummyHostnameVerifier implements HostnameVerifier {
  289. @Override
  290. public boolean verify(String hostname, SSLSession session) {
  291. // always accept
  292. return true;
  293. }
  294. }
  295. private HttpSupport() {
  296. // Utility class only.
  297. }
  298. }