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

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