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 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /*
  2. * Copyright (C) 2009-2010, Google Inc. and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.http.server;
  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import static org.eclipse.jgit.util.HttpSupport.ENCODING_GZIP;
  13. import static org.eclipse.jgit.util.HttpSupport.ENCODING_X_GZIP;
  14. import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT_ENCODING;
  15. import static org.eclipse.jgit.util.HttpSupport.HDR_CONTENT_ENCODING;
  16. import static org.eclipse.jgit.util.HttpSupport.HDR_ETAG;
  17. import static org.eclipse.jgit.util.HttpSupport.TEXT_PLAIN;
  18. import java.io.ByteArrayOutputStream;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.security.MessageDigest;
  23. import java.text.MessageFormat;
  24. import java.util.zip.GZIPInputStream;
  25. import java.util.zip.GZIPOutputStream;
  26. import javax.servlet.ServletRequest;
  27. import javax.servlet.http.HttpServletRequest;
  28. import javax.servlet.http.HttpServletResponse;
  29. import org.eclipse.jgit.lib.Constants;
  30. import org.eclipse.jgit.lib.ObjectId;
  31. import org.eclipse.jgit.lib.Repository;
  32. /**
  33. * Common utility functions for servlets.
  34. */
  35. public final class ServletUtils {
  36. /** Request attribute which stores the {@link Repository} instance. */
  37. public static final String ATTRIBUTE_REPOSITORY = "org.eclipse.jgit.Repository";
  38. /** Request attribute storing either UploadPack or ReceivePack. */
  39. public static final String ATTRIBUTE_HANDLER = "org.eclipse.jgit.transport.UploadPackOrReceivePack";
  40. /**
  41. * Get the selected repository from the request.
  42. *
  43. * @param req
  44. * the current request.
  45. * @return the repository; never null.
  46. * @throws IllegalStateException
  47. * the repository was not set by the filter, the servlet is
  48. * being invoked incorrectly and the programmer should ensure
  49. * the filter runs before the servlet.
  50. * @see #ATTRIBUTE_REPOSITORY
  51. */
  52. public static Repository getRepository(ServletRequest req) {
  53. Repository db = (Repository) req.getAttribute(ATTRIBUTE_REPOSITORY);
  54. if (db == null)
  55. throw new IllegalStateException(HttpServerText.get().expectedRepositoryAttribute);
  56. return db;
  57. }
  58. /**
  59. * Open the request input stream, automatically inflating if necessary.
  60. * <p>
  61. * This method automatically inflates the input stream if the request
  62. * {@code Content-Encoding} header was set to {@code gzip} or the legacy
  63. * {@code x-gzip}.
  64. *
  65. * @param req
  66. * the incoming request whose input stream needs to be opened.
  67. * @return an input stream to read the raw, uncompressed request body.
  68. * @throws IOException
  69. * if an input or output exception occurred.
  70. */
  71. public static InputStream getInputStream(HttpServletRequest req)
  72. throws IOException {
  73. InputStream in = req.getInputStream();
  74. final String enc = req.getHeader(HDR_CONTENT_ENCODING);
  75. if (ENCODING_GZIP.equals(enc) || ENCODING_X_GZIP.equals(enc))
  76. in = new GZIPInputStream(in);
  77. else if (enc != null)
  78. throw new IOException(MessageFormat.format(HttpServerText.get().encodingNotSupportedByThisLibrary
  79. , HDR_CONTENT_ENCODING, enc));
  80. return in;
  81. }
  82. /**
  83. * Consume the entire request body, if one was supplied.
  84. *
  85. * @param req
  86. * the request whose body must be consumed.
  87. */
  88. public static void consumeRequestBody(HttpServletRequest req) {
  89. if (0 < req.getContentLength() || isChunked(req)) {
  90. try {
  91. consumeRequestBody(req.getInputStream());
  92. } catch (IOException e) {
  93. // Ignore any errors obtaining the input stream.
  94. }
  95. }
  96. }
  97. static boolean isChunked(HttpServletRequest req) {
  98. return "chunked".equals(req.getHeader("Transfer-Encoding"));
  99. }
  100. /**
  101. * Consume the rest of the input stream and discard it.
  102. *
  103. * @param in
  104. * the stream to discard, closed if not null.
  105. */
  106. public static void consumeRequestBody(InputStream in) {
  107. if (in == null)
  108. return;
  109. try {
  110. while (0 < in.skip(2048) || 0 <= in.read()) {
  111. // Discard until EOF.
  112. }
  113. } catch (IOException err) {
  114. // Discard IOException during read or skip.
  115. } finally {
  116. try {
  117. in.close();
  118. } catch (IOException err) {
  119. // Discard IOException during close of input stream.
  120. }
  121. }
  122. }
  123. /**
  124. * Send a plain text response to a {@code GET} or {@code HEAD} HTTP request.
  125. * <p>
  126. * The text response is encoded in the Git character encoding, UTF-8.
  127. * <p>
  128. * If the user agent supports a compressed transfer encoding and the content
  129. * is large enough, the content may be compressed before sending.
  130. * <p>
  131. * The {@code ETag} and {@code Content-Length} headers are automatically set
  132. * by this method. {@code Content-Encoding} is conditionally set if the user
  133. * agent supports a compressed transfer. Callers are responsible for setting
  134. * any cache control headers.
  135. *
  136. * @param content
  137. * to return to the user agent as this entity's body.
  138. * @param req
  139. * the incoming request.
  140. * @param rsp
  141. * the outgoing response.
  142. * @throws IOException
  143. * the servlet API rejected sending the body.
  144. */
  145. public static void sendPlainText(final String content,
  146. final HttpServletRequest req, final HttpServletResponse rsp)
  147. throws IOException {
  148. final byte[] raw = content.getBytes(UTF_8);
  149. rsp.setContentType(TEXT_PLAIN);
  150. rsp.setCharacterEncoding(UTF_8.name());
  151. send(raw, req, rsp);
  152. }
  153. /**
  154. * Send a response to a {@code GET} or {@code HEAD} HTTP request.
  155. * <p>
  156. * If the user agent supports a compressed transfer encoding and the content
  157. * is large enough, the content may be compressed before sending.
  158. * <p>
  159. * The {@code ETag} and {@code Content-Length} headers are automatically set
  160. * by this method. {@code Content-Encoding} is conditionally set if the user
  161. * agent supports a compressed transfer. Callers are responsible for setting
  162. * {@code Content-Type} and any cache control headers.
  163. *
  164. * @param content
  165. * to return to the user agent as this entity's body.
  166. * @param req
  167. * the incoming request.
  168. * @param rsp
  169. * the outgoing response.
  170. * @throws IOException
  171. * the servlet API rejected sending the body.
  172. */
  173. public static void send(byte[] content, final HttpServletRequest req,
  174. final HttpServletResponse rsp) throws IOException {
  175. content = sendInit(content, req, rsp);
  176. try (OutputStream out = rsp.getOutputStream()) {
  177. out.write(content);
  178. out.flush();
  179. }
  180. }
  181. private static byte[] sendInit(byte[] content,
  182. final HttpServletRequest req, final HttpServletResponse rsp)
  183. throws IOException {
  184. rsp.setHeader(HDR_ETAG, etag(content));
  185. if (256 < content.length && acceptsGzipEncoding(req)) {
  186. content = compress(content);
  187. rsp.setHeader(HDR_CONTENT_ENCODING, ENCODING_GZIP);
  188. }
  189. rsp.setContentLength(content.length);
  190. return content;
  191. }
  192. static boolean acceptsGzipEncoding(HttpServletRequest req) {
  193. return acceptsGzipEncoding(req.getHeader(HDR_ACCEPT_ENCODING));
  194. }
  195. static boolean acceptsGzipEncoding(String accepts) {
  196. if (accepts == null)
  197. return false;
  198. int b = 0;
  199. while (b < accepts.length()) {
  200. int comma = accepts.indexOf(',', b);
  201. int e = 0 <= comma ? comma : accepts.length();
  202. String term = accepts.substring(b, e).trim();
  203. if (term.equals(ENCODING_GZIP))
  204. return true;
  205. b = e + 1;
  206. }
  207. return false;
  208. }
  209. private static byte[] compress(byte[] raw) throws IOException {
  210. final int maxLen = raw.length + 32;
  211. final ByteArrayOutputStream out = new ByteArrayOutputStream(maxLen);
  212. final GZIPOutputStream gz = new GZIPOutputStream(out);
  213. gz.write(raw);
  214. gz.finish();
  215. gz.flush();
  216. return out.toByteArray();
  217. }
  218. private static String etag(byte[] content) {
  219. final MessageDigest md = Constants.newMessageDigest();
  220. md.update(content);
  221. return ObjectId.fromRaw(md.digest()).getName();
  222. }
  223. static String identify(Repository git) {
  224. String identifier = git.getIdentifier();
  225. if (identifier == null) {
  226. return "unknown";
  227. }
  228. return identifier;
  229. }
  230. private ServletUtils() {
  231. // static utility class only
  232. }
  233. }