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.

ServletUtils.java 9.9KB

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