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.

RawServlet.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. * Copyright 2014 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.ByteArrayInputStream;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.UnsupportedEncodingException;
  21. import java.net.URLEncoder;
  22. import java.text.MessageFormat;
  23. import java.text.ParseException;
  24. import java.util.ArrayList;
  25. import java.util.Date;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.TreeMap;
  29. import com.google.inject.Inject;
  30. import com.google.inject.Singleton;
  31. import javax.servlet.ServletContext;
  32. import javax.servlet.ServletException;
  33. import javax.servlet.http.HttpServlet;
  34. import javax.servlet.http.HttpServletRequest;
  35. import javax.servlet.http.HttpServletResponse;
  36. import org.apache.tika.Tika;
  37. import org.eclipse.jgit.lib.FileMode;
  38. import org.eclipse.jgit.lib.MutableObjectId;
  39. import org.eclipse.jgit.lib.ObjectLoader;
  40. import org.eclipse.jgit.lib.ObjectReader;
  41. import org.eclipse.jgit.lib.Repository;
  42. import org.eclipse.jgit.revwalk.RevCommit;
  43. import org.eclipse.jgit.revwalk.RevWalk;
  44. import org.eclipse.jgit.treewalk.TreeWalk;
  45. import org.eclipse.jgit.treewalk.filter.PathFilter;
  46. import org.slf4j.Logger;
  47. import org.slf4j.LoggerFactory;
  48. import com.gitblit.Constants;
  49. import com.gitblit.Keys;
  50. import com.gitblit.manager.IRepositoryManager;
  51. import com.gitblit.manager.IRuntimeManager;
  52. import com.gitblit.models.PathModel;
  53. import com.gitblit.utils.ByteFormat;
  54. import com.gitblit.utils.JGitUtils;
  55. import com.gitblit.utils.MarkdownUtils;
  56. import com.gitblit.utils.StringUtils;
  57. /**
  58. * Serves the content of a branch.
  59. *
  60. * @author James Moger
  61. *
  62. */
  63. @Singleton
  64. public class RawServlet extends HttpServlet {
  65. private static final long serialVersionUID = 1L;
  66. private transient Logger logger = LoggerFactory.getLogger(RawServlet.class);
  67. private final IRuntimeManager runtimeManager;
  68. private final IRepositoryManager repositoryManager;
  69. @Inject
  70. public RawServlet(
  71. IRuntimeManager runtimeManager,
  72. IRepositoryManager repositoryManager) {
  73. this.runtimeManager = runtimeManager;
  74. this.repositoryManager = repositoryManager;
  75. }
  76. /**
  77. * Returns an url to this servlet for the specified parameters.
  78. *
  79. * @param baseURL
  80. * @param repository
  81. * @param branch
  82. * @param path
  83. * @return an url
  84. */
  85. public static String asLink(String baseURL, String repository, String branch, String path) {
  86. if (baseURL.length() > 0 && baseURL.charAt(baseURL.length() - 1) == '/') {
  87. baseURL = baseURL.substring(0, baseURL.length() - 1);
  88. }
  89. char fsc = '!';
  90. char c = GitblitContext.getManager(IRuntimeManager.class).getSettings().getChar(Keys.web.forwardSlashCharacter, '/');
  91. if (c != '/') {
  92. fsc = c;
  93. }
  94. if (branch != null) {
  95. branch = Repository.shortenRefName(branch).replace('/', fsc);
  96. }
  97. String encodedPath = path == null ? "" : path.replace('/', fsc);
  98. return baseURL + Constants.RAW_PATH + repository + "/" + (branch == null ? "" : (branch + "/" + encodedPath));
  99. }
  100. protected String getBranch(String repository, HttpServletRequest request) {
  101. String pi = request.getPathInfo();
  102. String branch = pi.substring(pi.indexOf(repository) + repository.length() + 1);
  103. int fs = branch.indexOf('/');
  104. if (fs > -1) {
  105. branch = branch.substring(0, fs);
  106. }
  107. char c = runtimeManager.getSettings().getChar(Keys.web.forwardSlashCharacter, '/');
  108. return branch.replace('!', '/').replace(c, '/');
  109. }
  110. protected String getPath(String repository, String branch, HttpServletRequest request) {
  111. String base = repository + "/" + branch;
  112. String pi = request.getPathInfo().substring(1);
  113. if (pi.equals(base)) {
  114. return "";
  115. }
  116. String path = pi.substring(pi.indexOf(base) + base.length() + 1);
  117. if (path.endsWith("/")) {
  118. path = path.substring(0, path.length() - 1);
  119. }
  120. char c = runtimeManager.getSettings().getChar(Keys.web.forwardSlashCharacter, '/');
  121. return path.replace('!', '/').replace(c, '/');
  122. }
  123. protected boolean renderIndex() {
  124. return false;
  125. }
  126. /**
  127. * Retrieves the specified resource from the specified branch of the
  128. * repository.
  129. *
  130. * @param request
  131. * @param response
  132. * @throws javax.servlet.ServletException
  133. * @throws java.io.IOException
  134. */
  135. private void processRequest(HttpServletRequest request, HttpServletResponse response)
  136. throws ServletException, IOException {
  137. String path = request.getPathInfo();
  138. if (path.toLowerCase().endsWith(".git")) {
  139. // forward to url with trailing /
  140. // this is important for relative pages links
  141. response.sendRedirect(request.getServletPath() + path + "/");
  142. return;
  143. }
  144. if (path.charAt(0) == '/') {
  145. // strip leading /
  146. path = path.substring(1);
  147. }
  148. // determine repository and resource from url
  149. String repository = "";
  150. Repository r = null;
  151. int offset = 0;
  152. while (r == null) {
  153. int slash = path.indexOf('/', offset);
  154. if (slash == -1) {
  155. repository = path;
  156. } else {
  157. repository = path.substring(0, slash);
  158. }
  159. offset = ( slash + 1 );
  160. r = repositoryManager.getRepository(repository, false);
  161. if (repository.equals(path)) {
  162. // either only repository in url or no repository found
  163. break;
  164. }
  165. }
  166. ServletContext context = request.getSession().getServletContext();
  167. try {
  168. if (r == null) {
  169. // repository not found!
  170. String mkd = MessageFormat.format(
  171. "# Error\nSorry, no valid **repository** specified in this url: {0}!",
  172. path);
  173. error(response, mkd);
  174. return;
  175. }
  176. // identify the branch
  177. String branch = getBranch(repository, request);
  178. if (StringUtils.isEmpty(branch)) {
  179. branch = r.getBranch();
  180. if (branch == null) {
  181. // no branches found! empty?
  182. String mkd = MessageFormat.format(
  183. "# Error\nSorry, no valid **branch** specified in this url: {0}!",
  184. path);
  185. error(response, mkd);
  186. } else {
  187. // redirect to default branch
  188. String base = request.getRequestURI();
  189. String url = base + branch + "/";
  190. response.sendRedirect(url);
  191. }
  192. return;
  193. }
  194. // identify the requested path
  195. String requestedPath = getPath(repository, branch, request);
  196. // identify the commit
  197. RevCommit commit = JGitUtils.getCommit(r, branch);
  198. if (commit == null) {
  199. // branch not found!
  200. String mkd = MessageFormat.format(
  201. "# Error\nSorry, the repository {0} does not have a **{1}** branch!",
  202. repository, branch);
  203. error(response, mkd);
  204. return;
  205. }
  206. List<PathModel> pathEntries = JGitUtils.getFilesInPath(r, requestedPath, commit);
  207. if (pathEntries.isEmpty()) {
  208. // requested a specific resource
  209. String file = StringUtils.getLastPathElement(requestedPath);
  210. try {
  211. // query Tika for the content type
  212. Tika tika = new Tika();
  213. String contentType = tika.detect(file);
  214. if (contentType == null) {
  215. // ask the container for the content type
  216. contentType = context.getMimeType(requestedPath);
  217. if (contentType == null) {
  218. // still unknown content type, assume binary
  219. contentType = "application/octet-stream";
  220. }
  221. }
  222. if (isTextType(contentType)) {
  223. // load, interpret, and serve text content as UTF-8
  224. String [] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings).toArray(new String[0]);
  225. String content = JGitUtils.getStringContent(r, commit.getTree(), requestedPath, encodings);
  226. if (content == null) {
  227. logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
  228. notFound(response, requestedPath, branch);
  229. return;
  230. }
  231. byte [] bytes = content.getBytes(Constants.ENCODING);
  232. setContentType(response, contentType);
  233. response.setContentLength(bytes.length);
  234. ByteArrayInputStream is = new ByteArrayInputStream(bytes);
  235. sendContent(response, JGitUtils.getCommitDate(commit), is);
  236. } else {
  237. // stream binary content directly from the repository
  238. if (!streamFromRepo(request, response, r, commit, requestedPath)) {
  239. logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
  240. notFound(response, requestedPath, branch);
  241. }
  242. }
  243. return;
  244. } catch (Exception e) {
  245. logger.error(null, e);
  246. }
  247. } else {
  248. // path request
  249. if (!request.getPathInfo().endsWith("/")) {
  250. // redirect to trailing '/' url
  251. response.sendRedirect(request.getServletPath() + request.getPathInfo() + "/");
  252. return;
  253. }
  254. if (renderIndex()) {
  255. // locate and render an index file
  256. Map<String, String> names = new TreeMap<String, String>();
  257. for (PathModel entry : pathEntries) {
  258. names.put(entry.name.toLowerCase(), entry.name);
  259. }
  260. List<String> extensions = new ArrayList<String>();
  261. extensions.add("html");
  262. extensions.add("htm");
  263. String content = null;
  264. for (String ext : extensions) {
  265. String key = "index." + ext;
  266. if (names.containsKey(key)) {
  267. String fileName = names.get(key);
  268. String fullPath = fileName;
  269. if (!requestedPath.isEmpty()) {
  270. fullPath = requestedPath + "/" + fileName;
  271. }
  272. String [] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings).toArray(new String[0]);
  273. String stringContent = JGitUtils.getStringContent(r, commit.getTree(), fullPath, encodings);
  274. if (stringContent == null) {
  275. continue;
  276. }
  277. content = stringContent;
  278. requestedPath = fullPath;
  279. break;
  280. }
  281. }
  282. response.setContentType("text/html; charset=" + Constants.ENCODING);
  283. byte [] bytes = content.getBytes(Constants.ENCODING);
  284. response.setContentLength(bytes.length);
  285. ByteArrayInputStream is = new ByteArrayInputStream(bytes);
  286. sendContent(response, JGitUtils.getCommitDate(commit), is);
  287. return;
  288. }
  289. }
  290. // no content, document list or 404 page
  291. if (pathEntries.isEmpty()) {
  292. // default 404 page
  293. notFound(response, requestedPath, branch);
  294. return;
  295. } else {
  296. //
  297. // directory list
  298. //
  299. response.setContentType("text/html");
  300. response.getWriter().append("<style>table th, table td { min-width: 150px; text-align: left; }</style>");
  301. response.getWriter().append("<table>");
  302. response.getWriter().append("<thead><tr><th>path</th><th>mode</th><th>size</th></tr>");
  303. response.getWriter().append("</thead>");
  304. response.getWriter().append("<tbody>");
  305. String pattern = "<tr><td><a href=\"{0}/{1}\">{1}</a></td><td>{2}</td><td>{3}</td></tr>";
  306. final ByteFormat byteFormat = new ByteFormat();
  307. if (!pathEntries.isEmpty()) {
  308. if (pathEntries.get(0).path.indexOf('/') > -1) {
  309. // we are in a subdirectory, add parent directory link
  310. String pp = URLEncoder.encode(requestedPath, Constants.ENCODING);
  311. pathEntries.add(0, new PathModel("..", pp + "/..", 0, FileMode.TREE.getBits(), null, null));
  312. }
  313. }
  314. String basePath = request.getServletPath() + request.getPathInfo();
  315. if (basePath.charAt(basePath.length() - 1) == '/') {
  316. // strip trailing slash
  317. basePath = basePath.substring(0, basePath.length() - 1);
  318. }
  319. for (PathModel entry : pathEntries) {
  320. String pp = URLEncoder.encode(entry.name, Constants.ENCODING);
  321. response.getWriter().append(MessageFormat.format(pattern, basePath, pp,
  322. JGitUtils.getPermissionsFromMode(entry.mode),
  323. entry.isFile() ? byteFormat.format(entry.size) : ""));
  324. }
  325. response.getWriter().append("</tbody>");
  326. response.getWriter().append("</table>");
  327. }
  328. } catch (Throwable t) {
  329. logger.error("Failed to write page to client", t);
  330. } finally {
  331. r.close();
  332. }
  333. }
  334. protected boolean isTextType(String contentType) {
  335. if (contentType.startsWith("text/")
  336. || "application/json".equals(contentType)
  337. || "application/xml".equals(contentType)) {
  338. return true;
  339. }
  340. return false;
  341. }
  342. /**
  343. * Override all text types to be plain text.
  344. *
  345. * @param response
  346. * @param contentType
  347. */
  348. protected void setContentType(HttpServletResponse response, String contentType) {
  349. if (isTextType(contentType)) {
  350. response.setContentType("text/plain");
  351. } else {
  352. response.setContentType(contentType);
  353. }
  354. }
  355. protected boolean streamFromRepo(HttpServletRequest request, HttpServletResponse response, Repository repository,
  356. RevCommit commit, String requestedPath) throws IOException {
  357. boolean served = false;
  358. RevWalk rw = new RevWalk(repository);
  359. TreeWalk tw = new TreeWalk(repository);
  360. try {
  361. tw.reset();
  362. tw.addTree(commit.getTree());
  363. PathFilter f = PathFilter.create(requestedPath);
  364. tw.setFilter(f);
  365. tw.setRecursive(true);
  366. MutableObjectId id = new MutableObjectId();
  367. ObjectReader reader = tw.getObjectReader();
  368. while (tw.next()) {
  369. FileMode mode = tw.getFileMode(0);
  370. if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
  371. continue;
  372. }
  373. tw.getObjectId(id, 0);
  374. String filename = StringUtils.getLastPathElement(requestedPath);
  375. try {
  376. String userAgent = request.getHeader("User-Agent");
  377. if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) {
  378. response.setHeader("Content-Disposition", "filename=\""
  379. + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
  380. } else if (userAgent != null && userAgent.indexOf("MSIE") > -1) {
  381. response.setHeader("Content-Disposition", "attachment; filename=\""
  382. + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
  383. } else {
  384. response.setHeader("Content-Disposition", "attachment; filename=\""
  385. + new String(filename.getBytes(Constants.ENCODING), "latin1") + "\"");
  386. }
  387. }
  388. catch (UnsupportedEncodingException e) {
  389. response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
  390. }
  391. long len = reader.getObjectSize(id, org.eclipse.jgit.lib.Constants.OBJ_BLOB);
  392. setContentType(response, "application/octet-stream");
  393. response.setIntHeader("Content-Length", (int) len);
  394. ObjectLoader ldr = repository.open(id);
  395. ldr.copyTo(response.getOutputStream());
  396. served = true;
  397. }
  398. } finally {
  399. tw.release();
  400. rw.dispose();
  401. }
  402. response.flushBuffer();
  403. return served;
  404. }
  405. protected void sendContent(HttpServletResponse response, Date date, InputStream is) throws ServletException, IOException {
  406. try {
  407. byte[] tmp = new byte[8192];
  408. int len = 0;
  409. while ((len = is.read(tmp)) > -1) {
  410. response.getOutputStream().write(tmp, 0, len);
  411. }
  412. } finally {
  413. is.close();
  414. }
  415. response.flushBuffer();
  416. }
  417. protected void notFound(HttpServletResponse response, String requestedPath, String branch)
  418. throws ParseException, ServletException, IOException {
  419. String str = MessageFormat.format(
  420. "# Error\nSorry, the requested resource **{0}** was not found in **{1}**.",
  421. requestedPath, branch);
  422. response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  423. error(response, str);
  424. }
  425. private void error(HttpServletResponse response, String mkd) throws ServletException,
  426. IOException, ParseException {
  427. String content = MarkdownUtils.transformMarkdown(mkd);
  428. response.setContentType("text/html; charset=" + Constants.ENCODING);
  429. response.getWriter().write(content);
  430. }
  431. @Override
  432. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  433. throws ServletException, IOException {
  434. processRequest(request, response);
  435. }
  436. @Override
  437. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  438. throws ServletException, IOException {
  439. processRequest(request, response);
  440. }
  441. }