View Javadoc
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  
45  package org.eclipse.jgit.util;
46  
47  import static java.nio.charset.StandardCharsets.UTF_8;
48  
49  import java.io.IOException;
50  import java.io.UnsupportedEncodingException;
51  import java.net.ConnectException;
52  import java.net.Proxy;
53  import java.net.ProxySelector;
54  import java.net.URISyntaxException;
55  import java.net.URL;
56  import java.net.URLEncoder;
57  import java.security.KeyManagementException;
58  import java.security.NoSuchAlgorithmException;
59  import java.security.cert.X509Certificate;
60  import java.text.MessageFormat;
61  
62  import javax.net.ssl.HostnameVerifier;
63  import javax.net.ssl.SSLSession;
64  import javax.net.ssl.TrustManager;
65  import javax.net.ssl.X509TrustManager;
66  
67  import org.eclipse.jgit.internal.JGitText;
68  import org.eclipse.jgit.transport.http.HttpConnection;
69  
70  /**
71   * Extra utilities to support usage of HTTP.
72   */
73  public class HttpSupport {
74  	/** The {@code GET} HTTP method. */
75  	public static final String METHOD_GET = "GET"; //$NON-NLS-1$
76  
77  	/** The {@code HEAD} HTTP method.
78  	 * @since 4.3 */
79  	public static final String METHOD_HEAD = "HEAD"; //$NON-NLS-1$
80  
81  	/** The {@code POST} HTTP method.
82  	 * @since 4.3 */
83  	public static final String METHOD_PUT = "PUT"; //$NON-NLS-1$
84  
85  	/** The {@code POST} HTTP method. */
86  	public static final String METHOD_POST = "POST"; //$NON-NLS-1$
87  
88  	/** The {@code Cache-Control} header. */
89  	public static final String HDR_CACHE_CONTROL = "Cache-Control"; //$NON-NLS-1$
90  
91  	/** The {@code Pragma} header. */
92  	public static final String HDR_PRAGMA = "Pragma"; //$NON-NLS-1$
93  
94  	/** The {@code User-Agent} header. */
95  	public static final String HDR_USER_AGENT = "User-Agent"; //$NON-NLS-1$
96  
97  	/**
98  	 * The {@code Server} header.
99  	 * @since 4.0
100 	 */
101 	public static final String HDR_SERVER = "Server"; //$NON-NLS-1$
102 
103 	/** The {@code Date} header. */
104 	public static final String HDR_DATE = "Date"; //$NON-NLS-1$
105 
106 	/** The {@code Expires} header. */
107 	public static final String HDR_EXPIRES = "Expires"; //$NON-NLS-1$
108 
109 	/** The {@code ETag} header. */
110 	public static final String HDR_ETAG = "ETag"; //$NON-NLS-1$
111 
112 	/** The {@code If-None-Match} header. */
113 	public static final String HDR_IF_NONE_MATCH = "If-None-Match"; //$NON-NLS-1$
114 
115 	/** The {@code Last-Modified} header. */
116 	public static final String HDR_LAST_MODIFIED = "Last-Modified"; //$NON-NLS-1$
117 
118 	/** The {@code If-Modified-Since} header. */
119 	public static final String HDR_IF_MODIFIED_SINCE = "If-Modified-Since"; //$NON-NLS-1$
120 
121 	/** The {@code Accept} header. */
122 	public static final String HDR_ACCEPT = "Accept"; //$NON-NLS-1$
123 
124 	/** The {@code Content-Type} header. */
125 	public static final String HDR_CONTENT_TYPE = "Content-Type"; //$NON-NLS-1$
126 
127 	/** The {@code Content-Length} header. */
128 	public static final String HDR_CONTENT_LENGTH = "Content-Length"; //$NON-NLS-1$
129 
130 	/** The {@code Content-Encoding} header. */
131 	public static final String HDR_CONTENT_ENCODING = "Content-Encoding"; //$NON-NLS-1$
132 
133 	/** The {@code Content-Range} header. */
134 	public static final String HDR_CONTENT_RANGE = "Content-Range"; //$NON-NLS-1$
135 
136 	/** The {@code Accept-Ranges} header. */
137 	public static final String HDR_ACCEPT_RANGES = "Accept-Ranges"; //$NON-NLS-1$
138 
139 	/** The {@code If-Range} header. */
140 	public static final String HDR_IF_RANGE = "If-Range"; //$NON-NLS-1$
141 
142 	/** The {@code Range} header. */
143 	public static final String HDR_RANGE = "Range"; //$NON-NLS-1$
144 
145 	/** The {@code Accept-Encoding} header. */
146 	public static final String HDR_ACCEPT_ENCODING = "Accept-Encoding"; //$NON-NLS-1$
147 
148 	/**
149 	 * The {@code Location} header.
150 	 * @since 4.7
151 	 */
152 	public static final String HDR_LOCATION = "Location"; //$NON-NLS-1$
153 
154 	/** The {@code gzip} encoding value for {@link #HDR_ACCEPT_ENCODING}. */
155 	public static final String ENCODING_GZIP = "gzip"; //$NON-NLS-1$
156 
157 	/**
158 	 * The {@code x-gzip} encoding value for {@link #HDR_ACCEPT_ENCODING}.
159 	 * @since 4.6
160 	 */
161 	public static final String ENCODING_X_GZIP = "x-gzip"; //$NON-NLS-1$
162 
163 	/** The standard {@code text/plain} MIME type. */
164 	public static final String TEXT_PLAIN = "text/plain"; //$NON-NLS-1$
165 
166 	/** The {@code Authorization} header. */
167 	public static final String HDR_AUTHORIZATION = "Authorization"; //$NON-NLS-1$
168 
169 	/** The {@code WWW-Authenticate} header. */
170 	public static final String HDR_WWW_AUTHENTICATE = "WWW-Authenticate"; //$NON-NLS-1$
171 
172 	/**
173 	 * The {@code Cookie} header.
174 	 *
175 	 * @since 5.4
176 	 */
177 	public static final String HDR_COOKIE = "Cookie"; //$NON-NLS-1$
178 
179 	/**
180 	 * The {@code Set-Cookie} header.
181 	 *
182 	 * @since 5.4
183 	 */
184 	public static final String HDR_SET_COOKIE = "Set-Cookie"; //$NON-NLS-1$
185 
186 	/**
187 	 * The {@code Set-Cookie2} header.
188 	 *
189 	 * @since 5.4
190 	 */
191 	public static final String HDR_SET_COOKIE2 = "Set-Cookie2"; //$NON-NLS-1$
192 
193 	/**
194 	 * URL encode a value string into an output buffer.
195 	 *
196 	 * @param urlstr
197 	 *            the output buffer.
198 	 * @param key
199 	 *            value which must be encoded to protected special characters.
200 	 */
201 	public static void encode(StringBuilder urlstr, String key) {
202 		if (key == null || key.length() == 0)
203 			return;
204 		try {
205 			urlstr.append(URLEncoder.encode(key, UTF_8.name()));
206 		} catch (UnsupportedEncodingException e) {
207 			throw new RuntimeException(JGitText.get().couldNotURLEncodeToUTF8, e);
208 		}
209 	}
210 
211 	/**
212 	 * Get the HTTP response code from the request.
213 	 * <p>
214 	 * Roughly the same as <code>c.getResponseCode()</code> but the
215 	 * ConnectException is translated to be more understandable.
216 	 *
217 	 * @param c
218 	 *            connection the code should be obtained from.
219 	 * @return r HTTP status code, usually 200 to indicate success. See
220 	 *         {@link org.eclipse.jgit.transport.http.HttpConnection} for other
221 	 *         defined constants.
222 	 * @throws java.io.IOException
223 	 *             communications error prevented obtaining the response code.
224 	 * @since 3.3
225 	 */
226 	public static int response(HttpConnection c) throws IOException {
227 		try {
228 			return c.getResponseCode();
229 		} catch (ConnectException ce) {
230 			final URL url = c.getURL();
231 			final String host = (url == null) ? "<null>" : url.getHost(); //$NON-NLS-1$
232 			// The standard J2SE error message is not very useful.
233 			//
234 			if ("Connection timed out: connect".equals(ce.getMessage())) //$NON-NLS-1$
235 				throw new ConnectException(MessageFormat.format(JGitText.get().connectionTimeOut, host));
236 			throw new ConnectException(ce.getMessage() + " " + host); //$NON-NLS-1$
237 		}
238 	}
239 
240 	/**
241 	 * Get the HTTP response code from the request.
242 	 * <p>
243 	 * Roughly the same as <code>c.getResponseCode()</code> but the
244 	 * ConnectException is translated to be more understandable.
245 	 *
246 	 * @param c
247 	 *            connection the code should be obtained from.
248 	 * @return r HTTP status code, usually 200 to indicate success. See
249 	 *         {@link org.eclipse.jgit.transport.http.HttpConnection} for other
250 	 *         defined constants.
251 	 * @throws java.io.IOException
252 	 *             communications error prevented obtaining the response code.
253 	 */
254 	public static int response(java.net.HttpURLConnection c)
255 			throws IOException {
256 		try {
257 			return c.getResponseCode();
258 		} catch (ConnectException ce) {
259 			final URL url = c.getURL();
260 			final String host = (url == null) ? "<null>" : url.getHost(); //$NON-NLS-1$
261 			// The standard J2SE error message is not very useful.
262 			//
263 			if ("Connection timed out: connect".equals(ce.getMessage())) //$NON-NLS-1$
264 				throw new ConnectException(MessageFormat.format(
265 						JGitText.get().connectionTimeOut, host));
266 			throw new ConnectException(ce.getMessage() + " " + host); //$NON-NLS-1$
267 		}
268 	}
269 
270 	/**
271 	 * Extract a HTTP header from the response.
272 	 *
273 	 * @param c
274 	 *            connection the header should be obtained from.
275 	 * @param headerName
276 	 *            the header name
277 	 * @return the header value
278 	 * @throws java.io.IOException
279 	 *             communications error prevented obtaining the header.
280 	 * @since 4.7
281 	 */
282 	public static String responseHeader(final HttpConnection c,
283 			final String headerName) throws IOException {
284 		return c.getHeaderField(headerName);
285 	}
286 
287 	/**
288 	 * Determine the proxy server (if any) needed to obtain a URL.
289 	 *
290 	 * @param proxySelector
291 	 *            proxy support for the caller.
292 	 * @param u
293 	 *            location of the server caller wants to talk to.
294 	 * @return proxy to communicate with the supplied URL.
295 	 * @throws java.net.ConnectException
296 	 *             the proxy could not be computed as the supplied URL could not
297 	 *             be read. This failure should never occur.
298 	 */
299 	public static Proxy proxyFor(ProxySelector proxySelector, URL u)
300 			throws ConnectException {
301 		try {
302 			return proxySelector.select(u.toURI()).get(0);
303 		} catch (URISyntaxException e) {
304 			final ConnectException err;
305 			err = new ConnectException(MessageFormat.format(JGitText.get().cannotDetermineProxyFor, u));
306 			err.initCause(e);
307 			throw err;
308 		}
309 	}
310 
311 	/**
312 	 * Disable SSL and hostname verification for given HTTP connection
313 	 *
314 	 * @param conn
315 	 *            a {@link org.eclipse.jgit.transport.http.HttpConnection}
316 	 *            object.
317 	 * @throws java.io.IOException
318 	 * @since 4.3
319 	 */
320 	public static void disableSslVerify(HttpConnection conn)
321 			throws IOException {
322 		final TrustManager[] trustAllCerts = new TrustManager[] {
323 				new DummyX509TrustManager() };
324 		try {
325 			conn.configure(null, trustAllCerts, null);
326 			conn.setHostnameVerifier(new DummyHostnameVerifier());
327 		} catch (KeyManagementException | NoSuchAlgorithmException e) {
328 			throw new IOException(e.getMessage());
329 		}
330 	}
331 
332 	private static class DummyX509TrustManager implements X509TrustManager {
333 		@Override
334 		public X509Certificate[] getAcceptedIssuers() {
335 			return null;
336 		}
337 
338 		@Override
339 		public void checkClientTrusted(X509Certificate[] certs,
340 				String authType) {
341 			// no check
342 		}
343 
344 		@Override
345 		public void checkServerTrusted(X509Certificate[] certs,
346 				String authType) {
347 			// no check
348 		}
349 	}
350 
351 	private static class DummyHostnameVerifier implements HostnameVerifier {
352 		@Override
353 		public boolean verify(String hostname, SSLSession session) {
354 			// always accept
355 			return true;
356 		}
357 	}
358 
359 	private HttpSupport() {
360 		// Utility class only.
361 	}
362 }