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

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