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

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