View Javadoc
1   /*
2    * Copyright (C) 2009-2010, Google Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.http.server;
45  
46  import static org.eclipse.jgit.util.HttpSupport.ENCODING_GZIP;
47  import static org.eclipse.jgit.util.HttpSupport.ENCODING_X_GZIP;
48  import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT_ENCODING;
49  import static org.eclipse.jgit.util.HttpSupport.HDR_CONTENT_ENCODING;
50  import static org.eclipse.jgit.util.HttpSupport.HDR_ETAG;
51  import static org.eclipse.jgit.util.HttpSupport.TEXT_PLAIN;
52  
53  import java.io.ByteArrayOutputStream;
54  import java.io.IOException;
55  import java.io.InputStream;
56  import java.io.OutputStream;
57  import java.security.MessageDigest;
58  import java.text.MessageFormat;
59  import java.util.zip.GZIPInputStream;
60  import java.util.zip.GZIPOutputStream;
61  
62  import javax.servlet.ServletRequest;
63  import javax.servlet.http.HttpServletRequest;
64  import javax.servlet.http.HttpServletResponse;
65  
66  import org.eclipse.jgit.internal.storage.dfs.DfsRepository;
67  import org.eclipse.jgit.lib.Constants;
68  import org.eclipse.jgit.lib.ObjectId;
69  import org.eclipse.jgit.lib.Repository;
70  
71  /** Common utility functions for servlets. */
72  public final class ServletUtils {
73  	/** Request attribute which stores the {@link Repository} instance. */
74  	public static final String ATTRIBUTE_REPOSITORY = "org.eclipse.jgit.Repository";
75  
76  	/** Request attribute storing either UploadPack or ReceivePack. */
77  	public static final String ATTRIBUTE_HANDLER = "org.eclipse.jgit.transport.UploadPackOrReceivePack";
78  
79  	/**
80  	 * Get the selected repository from the request.
81  	 *
82  	 * @param req
83  	 *            the current request.
84  	 * @return the repository; never null.
85  	 * @throws IllegalStateException
86  	 *             the repository was not set by the filter, the servlet is
87  	 *             being invoked incorrectly and the programmer should ensure
88  	 *             the filter runs before the servlet.
89  	 * @see #ATTRIBUTE_REPOSITORY
90  	 */
91  	public static Repository getRepository(final ServletRequest req) {
92  		Repository db = (Repository) req.getAttribute(ATTRIBUTE_REPOSITORY);
93  		if (db == null)
94  			throw new IllegalStateException(HttpServerText.get().expectedRepositoryAttribute);
95  		return db;
96  	}
97  
98  	/**
99  	 * Open the request input stream, automatically inflating if necessary.
100 	 * <p>
101 	 * This method automatically inflates the input stream if the request
102 	 * {@code Content-Encoding} header was set to {@code gzip} or the legacy
103 	 * {@code x-gzip}.
104 	 *
105 	 * @param req
106 	 *            the incoming request whose input stream needs to be opened.
107 	 * @return an input stream to read the raw, uncompressed request body.
108 	 * @throws IOException
109 	 *             if an input or output exception occurred.
110 	 */
111 	public static InputStream getInputStream(final HttpServletRequest req)
112 			throws IOException {
113 		InputStream in = req.getInputStream();
114 		final String enc = req.getHeader(HDR_CONTENT_ENCODING);
115 		if (ENCODING_GZIP.equals(enc) || ENCODING_X_GZIP.equals(enc)) //$NON-NLS-1$
116 			in = new GZIPInputStream(in);
117 		else if (enc != null)
118 			throw new IOException(MessageFormat.format(HttpServerText.get().encodingNotSupportedByThisLibrary
119 					, HDR_CONTENT_ENCODING, enc));
120 		return in;
121 	}
122 
123 	/**
124 	 * Consume the entire request body, if one was supplied.
125 	 *
126 	 * @param req
127 	 *            the request whose body must be consumed.
128 	 */
129 	public static void consumeRequestBody(HttpServletRequest req) {
130 		if (0 < req.getContentLength() || isChunked(req)) {
131 			try {
132 				consumeRequestBody(req.getInputStream());
133 			} catch (IOException e) {
134 				// Ignore any errors obtaining the input stream.
135 			}
136 		}
137 	}
138 
139 	static boolean isChunked(HttpServletRequest req) {
140 		return "chunked".equals(req.getHeader("Transfer-Encoding"));
141 	}
142 
143 	/**
144 	 * Consume the rest of the input stream and discard it.
145 	 *
146 	 * @param in
147 	 *            the stream to discard, closed if not null.
148 	 */
149 	public static void consumeRequestBody(InputStream in) {
150 		if (in == null)
151 			return;
152 		try {
153 			while (0 < in.skip(2048) || 0 <= in.read()) {
154 				// Discard until EOF.
155 			}
156 		} catch (IOException err) {
157 			// Discard IOException during read or skip.
158 		} finally {
159 			try {
160 				in.close();
161 			} catch (IOException err) {
162 				// Discard IOException during close of input stream.
163 			}
164 		}
165 	}
166 
167 	/**
168 	 * Send a plain text response to a {@code GET} or {@code HEAD} HTTP request.
169 	 * <p>
170 	 * The text response is encoded in the Git character encoding, UTF-8.
171 	 * <p>
172 	 * If the user agent supports a compressed transfer encoding and the content
173 	 * is large enough, the content may be compressed before sending.
174 	 * <p>
175 	 * The {@code ETag} and {@code Content-Length} headers are automatically set
176 	 * by this method. {@code Content-Encoding} is conditionally set if the user
177 	 * agent supports a compressed transfer. Callers are responsible for setting
178 	 * any cache control headers.
179 	 *
180 	 * @param content
181 	 *            to return to the user agent as this entity's body.
182 	 * @param req
183 	 *            the incoming request.
184 	 * @param rsp
185 	 *            the outgoing response.
186 	 * @throws IOException
187 	 *             the servlet API rejected sending the body.
188 	 */
189 	public static void sendPlainText(final String content,
190 			final HttpServletRequest req, final HttpServletResponse rsp)
191 			throws IOException {
192 		final byte[] raw = content.getBytes(Constants.CHARACTER_ENCODING);
193 		rsp.setContentType(TEXT_PLAIN);
194 		rsp.setCharacterEncoding(Constants.CHARACTER_ENCODING);
195 		send(raw, req, rsp);
196 	}
197 
198 	/**
199 	 * Send a response to a {@code GET} or {@code HEAD} HTTP request.
200 	 * <p>
201 	 * If the user agent supports a compressed transfer encoding and the content
202 	 * is large enough, the content may be compressed before sending.
203 	 * <p>
204 	 * The {@code ETag} and {@code Content-Length} headers are automatically set
205 	 * by this method. {@code Content-Encoding} is conditionally set if the user
206 	 * agent supports a compressed transfer. Callers are responsible for setting
207 	 * {@code Content-Type} and any cache control headers.
208 	 *
209 	 * @param content
210 	 *            to return to the user agent as this entity's body.
211 	 * @param req
212 	 *            the incoming request.
213 	 * @param rsp
214 	 *            the outgoing response.
215 	 * @throws IOException
216 	 *             the servlet API rejected sending the body.
217 	 */
218 	public static void send(byte[] content, final HttpServletRequest req,
219 			final HttpServletResponse rsp) throws IOException {
220 		content = sendInit(content, req, rsp);
221 		final OutputStream out = rsp.getOutputStream();
222 		try {
223 			out.write(content);
224 			out.flush();
225 		} finally {
226 			out.close();
227 		}
228 	}
229 
230 	private static byte[] sendInit(byte[] content,
231 			final HttpServletRequest req, final HttpServletResponse rsp)
232 			throws IOException {
233 		rsp.setHeader(HDR_ETAG, etag(content));
234 		if (256 < content.length && acceptsGzipEncoding(req)) {
235 			content = compress(content);
236 			rsp.setHeader(HDR_CONTENT_ENCODING, ENCODING_GZIP);
237 		}
238 		rsp.setContentLength(content.length);
239 		return content;
240 	}
241 
242 	static boolean acceptsGzipEncoding(final HttpServletRequest req) {
243 		return acceptsGzipEncoding(req.getHeader(HDR_ACCEPT_ENCODING));
244 	}
245 
246 	static boolean acceptsGzipEncoding(String accepts) {
247 		if (accepts == null)
248 			return false;
249 
250 		int b = 0;
251 		while (b < accepts.length()) {
252 			int comma = accepts.indexOf(',', b);
253 			int e = 0 <= comma ? comma : accepts.length();
254 			String term = accepts.substring(b, e).trim();
255 			if (term.equals(ENCODING_GZIP))
256 				return true;
257 			b = e + 1;
258 		}
259 		return false;
260 	}
261 
262 	private static byte[] compress(final byte[] raw) throws IOException {
263 		final int maxLen = raw.length + 32;
264 		final ByteArrayOutputStream out = new ByteArrayOutputStream(maxLen);
265 		final GZIPOutputStream gz = new GZIPOutputStream(out);
266 		gz.write(raw);
267 		gz.finish();
268 		gz.flush();
269 		return out.toByteArray();
270 	}
271 
272 	private static String etag(final byte[] content) {
273 		final MessageDigest md = Constants.newMessageDigest();
274 		md.update(content);
275 		return ObjectId.fromRaw(md.digest()).getName();
276 	}
277 
278 	static String identify(Repository git) {
279 		if (git instanceof DfsRepository) {
280 			return ((DfsRepository) git).getDescription().getRepositoryName();
281 		} else if (git.getDirectory() != null) {
282 			return git.getDirectory().getPath();
283 		}
284 		return "unknown";
285 	}
286 
287 	private ServletUtils() {
288 		// static utility class only
289 	}
290 }