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.

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