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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. // We can't parse out an extension for classic "dotfiles", so make a general assumption that
  210. // they're text files to allow presenting them in browser instead of only for download.
  211. //
  212. // However, that only holds for files with no other extension included, for files that happen
  213. // to start with a dot but also include an extension, process the extension normally.
  214. // This logic covers .gitattributes, .gitignore, .zshrc, etc., but does not cover .mongorc.js, .zshrc.bak
  215. boolean isExtensionlessDotfile = file.charAt(0) == '.' && (file.length() == 1 || file.indexOf('.', 1) < 0);
  216. String contentType = isExtensionlessDotfile ? "text/plain" : quickContentTypes.get(ext);
  217. if (contentType == null) {
  218. List<String> exts = runtimeManager.getSettings().getStrings(Keys.web.prettyPrintExtensions);
  219. if (exts.contains(ext)) {
  220. // extension is a registered text type for pretty printing
  221. contentType = "text/plain";
  222. } else {
  223. // query Tika for the content type
  224. Tika tika = new Tika();
  225. contentType = tika.detect(file);
  226. }
  227. }
  228. if (contentType == null) {
  229. // ask the container for the content type
  230. contentType = context.getMimeType(requestedPath);
  231. if (contentType == null) {
  232. // still unknown content type, assume binary
  233. contentType = "application/octet-stream";
  234. }
  235. }
  236. if (isTextType(contentType) || isTextDataType(contentType)) {
  237. // load, interpret, and serve text content as UTF-8
  238. String [] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings).toArray(new String[0]);
  239. String content = JGitUtils.getStringContent(r, commit.getTree(), requestedPath, encodings);
  240. if (content == null) {
  241. logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
  242. notFound(response, requestedPath, branch);
  243. return;
  244. }
  245. byte [] bytes = content.getBytes(Constants.ENCODING);
  246. setContentType(response, contentType);
  247. response.setContentLength(bytes.length);
  248. ByteArrayInputStream is = new ByteArrayInputStream(bytes);
  249. sendContent(response, JGitUtils.getCommitDate(commit), is);
  250. } else {
  251. // stream binary content directly from the repository
  252. if (!streamFromRepo(request, response, r, commit, requestedPath)) {
  253. logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
  254. notFound(response, requestedPath, branch);
  255. }
  256. }
  257. return;
  258. } catch (Exception e) {
  259. logger.error(null, e);
  260. }
  261. } else {
  262. // path request
  263. if (!request.getPathInfo().endsWith("/")) {
  264. // redirect to trailing '/' url
  265. response.sendRedirect(request.getServletPath() + request.getPathInfo() + "/");
  266. return;
  267. }
  268. if (renderIndex()) {
  269. // locate and render an index file
  270. Map<String, String> names = new TreeMap<String, String>();
  271. for (PathModel entry : pathEntries) {
  272. names.put(entry.name.toLowerCase(), entry.name);
  273. }
  274. List<String> extensions = new ArrayList<String>();
  275. extensions.add("html");
  276. extensions.add("htm");
  277. String content = null;
  278. for (String ext : extensions) {
  279. String key = "index." + ext;
  280. if (names.containsKey(key)) {
  281. String fileName = names.get(key);
  282. String fullPath = fileName;
  283. if (!requestedPath.isEmpty()) {
  284. fullPath = requestedPath + "/" + fileName;
  285. }
  286. String [] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings).toArray(new String[0]);
  287. String stringContent = JGitUtils.getStringContent(r, commit.getTree(), fullPath, encodings);
  288. if (stringContent == null) {
  289. continue;
  290. }
  291. content = stringContent;
  292. requestedPath = fullPath;
  293. break;
  294. }
  295. }
  296. response.setContentType("text/html; charset=" + Constants.ENCODING);
  297. byte [] bytes = content.getBytes(Constants.ENCODING);
  298. response.setContentLength(bytes.length);
  299. ByteArrayInputStream is = new ByteArrayInputStream(bytes);
  300. sendContent(response, JGitUtils.getCommitDate(commit), is);
  301. return;
  302. }
  303. }
  304. // no content, document list or 404 page
  305. if (pathEntries.isEmpty()) {
  306. // default 404 page
  307. notFound(response, requestedPath, branch);
  308. return;
  309. } else {
  310. //
  311. // directory list
  312. //
  313. response.setContentType("text/html");
  314. response.getWriter().append("<style>table th, table td { min-width: 150px; text-align: left; }</style>");
  315. response.getWriter().append("<table>");
  316. response.getWriter().append("<thead><tr><th>path</th><th>mode</th><th>size</th></tr>");
  317. response.getWriter().append("</thead>");
  318. response.getWriter().append("<tbody>");
  319. String pattern = "<tr><td><a href=\"{0}/{1}\">{1}</a></td><td>{2}</td><td>{3}</td></tr>";
  320. final ByteFormat byteFormat = new ByteFormat();
  321. if (!pathEntries.isEmpty()) {
  322. if (pathEntries.get(0).path.indexOf('/') > -1) {
  323. // we are in a subdirectory, add parent directory link
  324. String pp = URLEncoder.encode(requestedPath, Constants.ENCODING);
  325. pathEntries.add(0, new PathModel("..", pp + "/..", 0, FileMode.TREE.getBits(), null, null));
  326. }
  327. }
  328. String basePath = request.getServletPath() + request.getPathInfo();
  329. if (basePath.charAt(basePath.length() - 1) == '/') {
  330. // strip trailing slash
  331. basePath = basePath.substring(0, basePath.length() - 1);
  332. }
  333. for (PathModel entry : pathEntries) {
  334. String pp = URLEncoder.encode(entry.name, Constants.ENCODING);
  335. response.getWriter().append(MessageFormat.format(pattern, basePath, pp,
  336. JGitUtils.getPermissionsFromMode(entry.mode),
  337. entry.isFile() ? byteFormat.format(entry.size) : ""));
  338. }
  339. response.getWriter().append("</tbody>");
  340. response.getWriter().append("</table>");
  341. }
  342. } catch (Throwable t) {
  343. logger.error("Failed to write page to client", t);
  344. } finally {
  345. r.close();
  346. }
  347. }
  348. protected boolean isTextType(String contentType) {
  349. if (contentType.startsWith("text/")
  350. || "application/json".equals(contentType)
  351. || "application/xml".equals(contentType)) {
  352. return true;
  353. }
  354. return false;
  355. }
  356. protected boolean isTextDataType(String contentType) {
  357. if ("image/svg+xml".equals(contentType)) {
  358. return true;
  359. }
  360. return false;
  361. }
  362. /**
  363. * Override all text types to be plain text.
  364. *
  365. * @param response
  366. * @param contentType
  367. */
  368. protected void setContentType(HttpServletResponse response, String contentType) {
  369. if (isTextType(contentType)) {
  370. response.setContentType("text/plain");
  371. } else {
  372. response.setContentType(contentType);
  373. }
  374. }
  375. protected boolean streamFromRepo(HttpServletRequest request, HttpServletResponse response, Repository repository,
  376. RevCommit commit, String requestedPath) throws IOException {
  377. boolean served = false;
  378. RevWalk rw = new RevWalk(repository);
  379. TreeWalk tw = new TreeWalk(repository);
  380. try {
  381. tw.reset();
  382. tw.addTree(commit.getTree());
  383. PathFilter f = PathFilter.create(requestedPath);
  384. tw.setFilter(f);
  385. tw.setRecursive(true);
  386. MutableObjectId id = new MutableObjectId();
  387. ObjectReader reader = tw.getObjectReader();
  388. while (tw.next()) {
  389. FileMode mode = tw.getFileMode(0);
  390. if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
  391. continue;
  392. }
  393. tw.getObjectId(id, 0);
  394. String filename = StringUtils.getLastPathElement(requestedPath);
  395. try {
  396. String userAgent = request.getHeader("User-Agent");
  397. if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) {
  398. response.setHeader("Content-Disposition", "filename=\""
  399. + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
  400. } else if (userAgent != null && userAgent.indexOf("MSIE") > -1) {
  401. response.setHeader("Content-Disposition", "attachment; filename=\""
  402. + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
  403. } else {
  404. response.setHeader("Content-Disposition", "attachment; filename=\""
  405. + new String(filename.getBytes(Constants.ENCODING), "latin1") + "\"");
  406. }
  407. }
  408. catch (UnsupportedEncodingException e) {
  409. response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
  410. }
  411. long len = reader.getObjectSize(id, org.eclipse.jgit.lib.Constants.OBJ_BLOB);
  412. setContentType(response, "application/octet-stream");
  413. response.setIntHeader("Content-Length", (int) len);
  414. ObjectLoader ldr = repository.open(id);
  415. ldr.copyTo(response.getOutputStream());
  416. served = true;
  417. }
  418. } finally {
  419. tw.close();
  420. rw.dispose();
  421. }
  422. response.flushBuffer();
  423. return served;
  424. }
  425. protected void sendContent(HttpServletResponse response, Date date, InputStream is) throws ServletException, IOException {
  426. try {
  427. byte[] tmp = new byte[8192];
  428. int len = 0;
  429. while ((len = is.read(tmp)) > -1) {
  430. response.getOutputStream().write(tmp, 0, len);
  431. }
  432. } finally {
  433. is.close();
  434. }
  435. response.flushBuffer();
  436. }
  437. protected void notFound(HttpServletResponse response, String requestedPath, String branch)
  438. throws ParseException, ServletException, IOException {
  439. String str = MessageFormat.format(
  440. "# Error\nSorry, the requested resource **{0}** was not found in **{1}**.",
  441. requestedPath, branch);
  442. response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  443. error(response, str);
  444. }
  445. private void error(HttpServletResponse response, String mkd) throws ServletException,
  446. IOException, ParseException {
  447. String content = MarkdownUtils.transformMarkdown(mkd);
  448. response.setContentType("text/html; charset=" + Constants.ENCODING);
  449. response.getWriter().write(content);
  450. }
  451. @Override
  452. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  453. throws ServletException, IOException {
  454. processRequest(request, response);
  455. }
  456. @Override
  457. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  458. throws ServletException, IOException {
  459. processRequest(request, response);
  460. }
  461. }