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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. * The {@code Cookie} header.
  139. *
  140. * @since 5.4
  141. */
  142. public static final String HDR_COOKIE = "Cookie"; //$NON-NLS-1$
  143. /**
  144. * The {@code Set-Cookie} header.
  145. *
  146. * @since 5.4
  147. */
  148. public static final String HDR_SET_COOKIE = "Set-Cookie"; //$NON-NLS-1$
  149. /**
  150. * The {@code Set-Cookie2} header.
  151. *
  152. * @since 5.4
  153. */
  154. public static final String HDR_SET_COOKIE2 = "Set-Cookie2"; //$NON-NLS-1$
  155. /**
  156. * URL encode a value string into an output buffer.
  157. *
  158. * @param urlstr
  159. * the output buffer.
  160. * @param key
  161. * value which must be encoded to protected special characters.
  162. */
  163. public static void encode(StringBuilder urlstr, String key) {
  164. if (key == null || key.length() == 0)
  165. return;
  166. try {
  167. urlstr.append(URLEncoder.encode(key, UTF_8.name()));
  168. } catch (UnsupportedEncodingException e) {
  169. throw new RuntimeException(JGitText.get().couldNotURLEncodeToUTF8, e);
  170. }
  171. }
  172. /**
  173. * Get the HTTP response code from the request.
  174. * <p>
  175. * Roughly the same as <code>c.getResponseCode()</code> but the
  176. * ConnectException is translated to be more understandable.
  177. *
  178. * @param c
  179. * connection the code should be obtained from.
  180. * @return r HTTP status code, usually 200 to indicate success. See
  181. * {@link org.eclipse.jgit.transport.http.HttpConnection} for other
  182. * defined constants.
  183. * @throws java.io.IOException
  184. * communications error prevented obtaining the response code.
  185. * @since 3.3
  186. */
  187. public static int response(HttpConnection c) throws IOException {
  188. try {
  189. return c.getResponseCode();
  190. } catch (ConnectException ce) {
  191. final URL url = c.getURL();
  192. final String host = (url == null) ? "<null>" : url.getHost(); //$NON-NLS-1$
  193. // The standard J2SE error message is not very useful.
  194. //
  195. if ("Connection timed out: connect".equals(ce.getMessage())) //$NON-NLS-1$
  196. throw new ConnectException(MessageFormat.format(JGitText.get().connectionTimeOut, host));
  197. throw new ConnectException(ce.getMessage() + " " + host); //$NON-NLS-1$
  198. }
  199. }
  200. /**
  201. * Get the HTTP response code from the request.
  202. * <p>
  203. * Roughly the same as <code>c.getResponseCode()</code> but the
  204. * ConnectException is translated to be more understandable.
  205. *
  206. * @param c
  207. * connection the code should be obtained from.
  208. * @return r HTTP status code, usually 200 to indicate success. See
  209. * {@link org.eclipse.jgit.transport.http.HttpConnection} for other
  210. * defined constants.
  211. * @throws java.io.IOException
  212. * communications error prevented obtaining the response code.
  213. */
  214. public static int response(java.net.HttpURLConnection c)
  215. throws IOException {
  216. try {
  217. return c.getResponseCode();
  218. } catch (ConnectException ce) {
  219. final URL url = c.getURL();
  220. final String host = (url == null) ? "<null>" : url.getHost(); //$NON-NLS-1$
  221. // The standard J2SE error message is not very useful.
  222. //
  223. if ("Connection timed out: connect".equals(ce.getMessage())) //$NON-NLS-1$
  224. throw new ConnectException(MessageFormat.format(
  225. JGitText.get().connectionTimeOut, host));
  226. throw new ConnectException(ce.getMessage() + " " + host); //$NON-NLS-1$
  227. }
  228. }
  229. /**
  230. * Extract a HTTP header from the response.
  231. *
  232. * @param c
  233. * connection the header should be obtained from.
  234. * @param headerName
  235. * the header name
  236. * @return the header value
  237. * @throws java.io.IOException
  238. * communications error prevented obtaining the header.
  239. * @since 4.7
  240. */
  241. public static String responseHeader(final HttpConnection c,
  242. final String headerName) throws IOException {
  243. return c.getHeaderField(headerName);
  244. }
  245. /**
  246. * Determine the proxy server (if any) needed to obtain a URL.
  247. *
  248. * @param proxySelector
  249. * proxy support for the caller.
  250. * @param u
  251. * location of the server caller wants to talk to.
  252. * @return proxy to communicate with the supplied URL.
  253. * @throws java.net.ConnectException
  254. * the proxy could not be computed as the supplied URL could not
  255. * be read. This failure should never occur.
  256. */
  257. public static Proxy proxyFor(ProxySelector proxySelector, URL u)
  258. throws ConnectException {
  259. try {
  260. return proxySelector.select(u.toURI()).get(0);
  261. } catch (URISyntaxException e) {
  262. final ConnectException err;
  263. err = new ConnectException(MessageFormat.format(JGitText.get().cannotDetermineProxyFor, u));
  264. err.initCause(e);
  265. throw err;
  266. }
  267. }
  268. /**
  269. * Disable SSL and hostname verification for given HTTP connection
  270. *
  271. * @param conn
  272. * a {@link org.eclipse.jgit.transport.http.HttpConnection}
  273. * object.
  274. * @throws java.io.IOException
  275. * @since 4.3
  276. */
  277. public static void disableSslVerify(HttpConnection conn)
  278. throws IOException {
  279. final TrustManager[] trustAllCerts = new TrustManager[] {
  280. new DummyX509TrustManager() };
  281. try {
  282. conn.configure(null, trustAllCerts, null);
  283. conn.setHostnameVerifier(new DummyHostnameVerifier());
  284. } catch (KeyManagementException | NoSuchAlgorithmException e) {
  285. throw new IOException(e.getMessage());
  286. }
  287. }
  288. private static class DummyX509TrustManager implements X509TrustManager {
  289. @Override
  290. public X509Certificate[] getAcceptedIssuers() {
  291. return null;
  292. }
  293. @Override
  294. public void checkClientTrusted(X509Certificate[] certs,
  295. String authType) {
  296. // no check
  297. }
  298. @Override
  299. public void checkServerTrusted(X509Certificate[] certs,
  300. String authType) {
  301. // no check
  302. }
  303. }
  304. private static class DummyHostnameVerifier implements HostnameVerifier {
  305. @Override
  306. public boolean verify(String hostname, SSLSession session) {
  307. // always accept
  308. return true;
  309. }
  310. }
  311. private HttpSupport() {
  312. // Utility class only.
  313. }
  314. }