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

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