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  /**
72   * Common utility functions for servlets.
73   */
74  public final class ServletUtils {
75  	/** Request attribute which stores the {@link Repository} instance. */
76  	public static final String ATTRIBUTE_REPOSITORY = "org.eclipse.jgit.Repository";
77  
78  	/** Request attribute storing either UploadPack or ReceivePack. */
79  	public static final String ATTRIBUTE_HANDLER = "org.eclipse.jgit.transport.UploadPackOrReceivePack";
80  
81  	/**
82  	 * Get the selected repository from the request.
83  	 *
84  	 * @param req
85  	 *            the current request.
86  	 * @return the repository; never null.
87  	 * @throws IllegalStateException
88  	 *             the repository was not set by the filter, the servlet is
89  	 *             being invoked incorrectly and the programmer should ensure
90  	 *             the filter runs before the servlet.
91  	 * @see #ATTRIBUTE_REPOSITORY
92  	 */
93  	public static Repository getRepository(final ServletRequest req) {
94  		Repository db = (Repository) req.getAttribute(ATTRIBUTE_REPOSITORY);
95  		if (db == null)
96  			throw new IllegalStateException(HttpServerText.get().expectedRepositoryAttribute);
97  		return db;
98  	}
99  
100 	/**
101 	 * Open the request input stream, automatically inflating if necessary.
102 	 * <p>
103 	 * This method automatically inflates the input stream if the request
104 	 * {@code Content-Encoding} header was set to {@code gzip} or the legacy
105 	 * {@code x-gzip}.
106 	 *
107 	 * @param req
108 	 *            the incoming request whose input stream needs to be opened.
109 	 * @return an input stream to read the raw, uncompressed request body.
110 	 * @throws IOException
111 	 *             if an input or output exception occurred.
112 	 */
113 	public static InputStream getInputStream(final HttpServletRequest req)
114 			throws IOException {
115 		InputStream in = req.getInputStream();
116 		final String enc = req.getHeader(HDR_CONTENT_ENCODING);
117 		if (ENCODING_GZIP.equals(enc) || ENCODING_X_GZIP.equals(enc))
118 			in = new GZIPInputStream(in);
119 		else if (enc != null)
120 			throw new IOException(MessageFormat.format(HttpServerText.get().encodingNotSupportedByThisLibrary
121 					, HDR_CONTENT_ENCODING, enc));
122 		return in;
123 	}
124 
125 	/**
126 	 * Consume the entire request body, if one was supplied.
127 	 *
128 	 * @param req
129 	 *            the request whose body must be consumed.
130 	 */
131 	public static void consumeRequestBody(HttpServletRequest req) {
132 		if (0 < req.getContentLength() || isChunked(req)) {
133 			try {
134 				consumeRequestBody(req.getInputStream());
135 			} catch (IOException e) {
136 				// Ignore any errors obtaining the input stream.
137 			}
138 		}
139 	}
140 
141 	static boolean isChunked(HttpServletRequest req) {
142 		return "chunked".equals(req.getHeader("Transfer-Encoding"));
143 	}
144 
145 	/**
146 	 * Consume the rest of the input stream and discard it.
147 	 *
148 	 * @param in
149 	 *            the stream to discard, closed if not null.
150 	 */
151 	public static void consumeRequestBody(InputStream in) {
152 		if (in == null)
153 			return;
154 		try {
155 			while (0 < in.skip(2048) || 0 <= in.read()) {
156 				// Discard until EOF.
157 			}
158 		} catch (IOException err) {
159 			// Discard IOException during read or skip.
160 		} finally {
161 			try {
162 				in.close();
163 			} catch (IOException err) {
164 				// Discard IOException during close of input stream.
165 			}
166 		}
167 	}
168 
169 	/**
170 	 * Send a plain text response to a {@code GET} or {@code HEAD} HTTP request.
171 	 * <p>
172 	 * The text response is encoded in the Git character encoding, UTF-8.
173 	 * <p>
174 	 * If the user agent supports a compressed transfer encoding and the content
175 	 * is large enough, the content may be compressed before sending.
176 	 * <p>
177 	 * The {@code ETag} and {@code Content-Length} headers are automatically set
178 	 * by this method. {@code Content-Encoding} is conditionally set if the user
179 	 * agent supports a compressed transfer. Callers are responsible for setting
180 	 * any cache control headers.
181 	 *
182 	 * @param content
183 	 *            to return to the user agent as this entity's body.
184 	 * @param req
185 	 *            the incoming request.
186 	 * @param rsp
187 	 *            the outgoing response.
188 	 * @throws IOException
189 	 *             the servlet API rejected sending the body.
190 	 */
191 	public static void sendPlainText(final String content,
192 			final HttpServletRequest req, final HttpServletResponse rsp)
193 			throws IOException {
194 		final byte[] raw = content.getBytes(Constants.CHARACTER_ENCODING);
195 		rsp.setContentType(TEXT_PLAIN);
196 		rsp.setCharacterEncoding(Constants.CHARACTER_ENCODING);
197 		send(raw, req, rsp);
198 	}
199 
200 	/**
201 	 * Send a response to a {@code GET} or {@code HEAD} HTTP request.
202 	 * <p>
203 	 * If the user agent supports a compressed transfer encoding and the content
204 	 * is large enough, the content may be compressed before sending.
205 	 * <p>
206 	 * The {@code ETag} and {@code Content-Length} headers are automatically set
207 	 * by this method. {@code Content-Encoding} is conditionally set if the user
208 	 * agent supports a compressed transfer. Callers are responsible for setting
209 	 * {@code Content-Type} and any cache control headers.
210 	 *
211 	 * @param content
212 	 *            to return to the user agent as this entity's body.
213 	 * @param req
214 	 *            the incoming request.
215 	 * @param rsp
216 	 *            the outgoing response.
217 	 * @throws IOException
218 	 *             the servlet API rejected sending the body.
219 	 */
220 	public static void send(byte[] content, final HttpServletRequest req,
221 			final HttpServletResponse rsp) throws IOException {
222 		content = sendInit(content, req, rsp);
223 		final OutputStream out = rsp.getOutputStream();
224 		try {
225 			out.write(content);
226 			out.flush();
227 		} finally {
228 			out.close();
229 		}
230 	}
231 
232 	private static byte[] sendInit(byte[] content,
233 			final HttpServletRequest req, final HttpServletResponse rsp)
234 			throws IOException {
235 		rsp.setHeader(HDR_ETAG, etag(content));
236 		if (256 < content.length && acceptsGzipEncoding(req)) {
237 			content = compress(content);
238 			rsp.setHeader(HDR_CONTENT_ENCODING, ENCODING_GZIP);
239 		}
240 		rsp.setContentLength(content.length);
241 		return content;
242 	}
243 
244 	static boolean acceptsGzipEncoding(final HttpServletRequest req) {
245 		return acceptsGzipEncoding(req.getHeader(HDR_ACCEPT_ENCODING));
246 	}
247 
248 	static boolean acceptsGzipEncoding(String accepts) {
249 		if (accepts == null)
250 			return false;
251 
252 		int b = 0;
253 		while (b < accepts.length()) {
254 			int comma = accepts.indexOf(',', b);
255 			int e = 0 <= comma ? comma : accepts.length();
256 			String term = accepts.substring(b, e).trim();
257 			if (term.equals(ENCODING_GZIP))
258 				return true;
259 			b = e + 1;
260 		}
261 		return false;
262 	}
263 
264 	private static byte[] compress(final byte[] raw) throws IOException {
265 		final int maxLen = raw.length + 32;
266 		final ByteArrayOutputStream out = new ByteArrayOutputStream(maxLen);
267 		final GZIPOutputStream gz = new GZIPOutputStream(out);
268 		gz.write(raw);
269 		gz.finish();
270 		gz.flush();
271 		return out.toByteArray();
272 	}
273 
274 	private static String etag(final byte[] content) {
275 		final MessageDigest md = Constants.newMessageDigest();
276 		md.update(content);
277 		return ObjectId.fromRaw(md.digest()).getName();
278 	}
279 
280 	static String identify(Repository git) {
281 		if (git instanceof DfsRepository) {
282 			return ((DfsRepository) git).getDescription().getRepositoryName();
283 		} else if (git.getDirectory() != null) {
284 			return git.getDirectory().getPath();
285 		}
286 		return "unknown";
287 	}
288 
289 	private ServletUtils() {
290 		// static utility class only
291 	}
292 }