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