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.

DownloadZipServlet.java 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. /*
  2. * Copyright 2011 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.servlet;
  17. import java.io.IOException;
  18. import java.text.MessageFormat;
  19. import java.text.ParseException;
  20. import java.util.Date;
  21. import javax.servlet.ServletException;
  22. import javax.servlet.http.HttpServletResponse;
  23. import org.eclipse.jgit.lib.Repository;
  24. import org.eclipse.jgit.revwalk.RevCommit;
  25. import org.slf4j.Logger;
  26. import org.slf4j.LoggerFactory;
  27. import com.gitblit.Constants;
  28. import com.gitblit.IStoredSettings;
  29. import com.gitblit.Keys;
  30. import com.gitblit.dagger.DaggerServlet;
  31. import com.gitblit.manager.IRepositoryManager;
  32. import com.gitblit.utils.CompressionUtils;
  33. import com.gitblit.utils.JGitUtils;
  34. import com.gitblit.utils.MarkdownUtils;
  35. import com.gitblit.utils.StringUtils;
  36. import dagger.ObjectGraph;
  37. /**
  38. * Streams out a zip file from the specified repository for any tree path at any
  39. * revision.
  40. *
  41. * @author James Moger
  42. *
  43. */
  44. public class DownloadZipServlet extends DaggerServlet {
  45. private static final long serialVersionUID = 1L;
  46. private transient Logger logger = LoggerFactory.getLogger(DownloadZipServlet.class);
  47. private IStoredSettings settings;
  48. private IRepositoryManager repositoryManager;
  49. public static enum Format {
  50. zip(".zip"), tar(".tar"), gz(".tar.gz"), xz(".tar.xz"), bzip2(".tar.bzip2");
  51. public final String extension;
  52. Format(String ext) {
  53. this.extension = ext;
  54. }
  55. public static Format fromName(String name) {
  56. for (Format format : values()) {
  57. if (format.name().equalsIgnoreCase(name)) {
  58. return format;
  59. }
  60. }
  61. return zip;
  62. }
  63. }
  64. @Override
  65. protected void inject(ObjectGraph dagger) {
  66. this.settings = dagger.get(IStoredSettings.class);
  67. this.repositoryManager = dagger.get(IRepositoryManager.class);
  68. }
  69. /**
  70. * Returns an url to this servlet for the specified parameters.
  71. *
  72. * @param baseURL
  73. * @param repository
  74. * @param objectId
  75. * @param path
  76. * @param format
  77. * @return an url
  78. */
  79. public static String asLink(String baseURL, String repository, String objectId, String path, Format format) {
  80. if (baseURL.length() > 0 && baseURL.charAt(baseURL.length() - 1) == '/') {
  81. baseURL = baseURL.substring(0, baseURL.length() - 1);
  82. }
  83. return baseURL + Constants.ZIP_PATH + "?r=" + repository
  84. + (path == null ? "" : ("&p=" + path))
  85. + (objectId == null ? "" : ("&h=" + objectId))
  86. + (format == null ? "" : ("&format=" + format.name()));
  87. }
  88. /**
  89. * Creates a zip stream from the repository of the requested data.
  90. *
  91. * @param request
  92. * @param response
  93. * @throws javax.servlet.ServletException
  94. * @throws java.io.IOException
  95. */
  96. private void processRequest(javax.servlet.http.HttpServletRequest request,
  97. javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException,
  98. java.io.IOException {
  99. if (!settings.getBoolean(Keys.web.allowZipDownloads, true)) {
  100. logger.warn("Zip downloads are disabled");
  101. response.sendError(HttpServletResponse.SC_FORBIDDEN);
  102. return;
  103. }
  104. Format format = Format.zip;
  105. String repository = request.getParameter("r");
  106. String basePath = request.getParameter("p");
  107. String objectId = request.getParameter("h");
  108. String f = request.getParameter("format");
  109. if (!StringUtils.isEmpty(f)) {
  110. format = Format.fromName(f);
  111. }
  112. try {
  113. String name = repository;
  114. if (name.indexOf('/') > -1) {
  115. name = name.substring(name.lastIndexOf('/') + 1);
  116. }
  117. name = StringUtils.stripDotGit(name);
  118. if (!StringUtils.isEmpty(basePath)) {
  119. name += "-" + basePath.replace('/', '_');
  120. }
  121. if (!StringUtils.isEmpty(objectId)) {
  122. name += "-" + objectId;
  123. }
  124. Repository r = repositoryManager.getRepository(repository);
  125. if (r == null) {
  126. if (repositoryManager.isCollectingGarbage(repository)) {
  127. error(response, MessageFormat.format("# Error\nGitblit is busy collecting garbage in {0}", repository));
  128. return;
  129. } else {
  130. error(response, MessageFormat.format("# Error\nFailed to find repository {0}", repository));
  131. return;
  132. }
  133. }
  134. RevCommit commit = JGitUtils.getCommit(r, objectId);
  135. if (commit == null) {
  136. error(response, MessageFormat.format("# Error\nFailed to find commit {0}", objectId));
  137. r.close();
  138. return;
  139. }
  140. Date date = JGitUtils.getCommitDate(commit);
  141. String contentType = "application/octet-stream";
  142. response.setContentType(contentType + "; charset=" + response.getCharacterEncoding());
  143. response.setHeader("Content-Disposition", "attachment; filename=\"" + name + format.extension + "\"");
  144. response.setDateHeader("Last-Modified", date.getTime());
  145. response.setHeader("Cache-Control", "no-cache");
  146. response.setHeader("Pragma", "no-cache");
  147. response.setDateHeader("Expires", 0);
  148. try {
  149. switch (format) {
  150. case zip:
  151. CompressionUtils.zip(r, basePath, objectId, response.getOutputStream());
  152. break;
  153. case tar:
  154. CompressionUtils.tar(r, basePath, objectId, response.getOutputStream());
  155. break;
  156. case gz:
  157. CompressionUtils.gz(r, basePath, objectId, response.getOutputStream());
  158. break;
  159. case xz:
  160. CompressionUtils.xz(r, basePath, objectId, response.getOutputStream());
  161. break;
  162. case bzip2:
  163. CompressionUtils.bzip2(r, basePath, objectId, response.getOutputStream());
  164. break;
  165. }
  166. response.flushBuffer();
  167. } catch (IOException t) {
  168. String message = t.getMessage() == null ? "" : t.getMessage().toLowerCase();
  169. if (message.contains("reset") || message.contains("broken pipe")) {
  170. logger.error("Client aborted zip download: " + message);
  171. } else {
  172. logger.error("Failed to write attachment to client", t);
  173. }
  174. } catch (Throwable t) {
  175. logger.error("Failed to write attachment to client", t);
  176. }
  177. // close the repository
  178. r.close();
  179. } catch (Throwable t) {
  180. logger.error("Failed to write attachment to client", t);
  181. }
  182. }
  183. private void error(HttpServletResponse response, String mkd) throws ServletException,
  184. IOException, ParseException {
  185. String content = MarkdownUtils.transformMarkdown(mkd);
  186. response.setContentType("text/html; charset=" + Constants.ENCODING);
  187. response.getWriter().write(content);
  188. }
  189. @Override
  190. protected void doPost(javax.servlet.http.HttpServletRequest request,
  191. javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException,
  192. java.io.IOException {
  193. processRequest(request, response);
  194. }
  195. @Override
  196. protected void doGet(javax.servlet.http.HttpServletRequest request,
  197. javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException,
  198. java.io.IOException {
  199. processRequest(request, response);
  200. }
  201. }