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.

GitSmartHttpTools.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /*
  2. * Copyright (C) 2011, Google Inc. and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.http.server;
  11. import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
  12. import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
  13. import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
  14. import static org.eclipse.jgit.http.server.ServletUtils.ATTRIBUTE_HANDLER;
  15. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_SIDE_BAND_64K;
  16. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_ERROR;
  17. import static org.eclipse.jgit.transport.SideBandOutputStream.SMALL_BUF;
  18. import java.io.ByteArrayOutputStream;
  19. import java.io.IOException;
  20. import java.io.OutputStream;
  21. import java.util.Arrays;
  22. import java.util.Collections;
  23. import java.util.List;
  24. import javax.servlet.http.HttpServletRequest;
  25. import javax.servlet.http.HttpServletResponse;
  26. import org.eclipse.jgit.internal.transport.parser.FirstCommand;
  27. import org.eclipse.jgit.lib.Constants;
  28. import org.eclipse.jgit.transport.PacketLineIn;
  29. import org.eclipse.jgit.transport.PacketLineOut;
  30. import org.eclipse.jgit.transport.ReceivePack;
  31. import org.eclipse.jgit.transport.RequestNotYetReadException;
  32. import org.eclipse.jgit.transport.SideBandOutputStream;
  33. /**
  34. * Utility functions for handling the Git-over-HTTP protocol.
  35. */
  36. public class GitSmartHttpTools {
  37. private static final String INFO_REFS = Constants.INFO_REFS;
  38. /** Name of the git-upload-pack service. */
  39. public static final String UPLOAD_PACK = "git-upload-pack";
  40. /** Name of the git-receive-pack service. */
  41. public static final String RECEIVE_PACK = "git-receive-pack";
  42. /** Content type supplied by the client to the /git-upload-pack handler. */
  43. public static final String UPLOAD_PACK_REQUEST_TYPE =
  44. "application/x-git-upload-pack-request";
  45. /** Content type returned from the /git-upload-pack handler. */
  46. public static final String UPLOAD_PACK_RESULT_TYPE =
  47. "application/x-git-upload-pack-result";
  48. /** Content type supplied by the client to the /git-receive-pack handler. */
  49. public static final String RECEIVE_PACK_REQUEST_TYPE =
  50. "application/x-git-receive-pack-request";
  51. /** Content type returned from the /git-receive-pack handler. */
  52. public static final String RECEIVE_PACK_RESULT_TYPE =
  53. "application/x-git-receive-pack-result";
  54. /** Git service names accepted by the /info/refs?service= handler. */
  55. public static final List<String> VALID_SERVICES =
  56. Collections.unmodifiableList(Arrays.asList(new String[] {
  57. UPLOAD_PACK, RECEIVE_PACK }));
  58. private static final String INFO_REFS_PATH = "/" + INFO_REFS;
  59. private static final String UPLOAD_PACK_PATH = "/" + UPLOAD_PACK;
  60. private static final String RECEIVE_PACK_PATH = "/" + RECEIVE_PACK;
  61. private static final List<String> SERVICE_SUFFIXES =
  62. Collections.unmodifiableList(Arrays.asList(new String[] {
  63. INFO_REFS_PATH, UPLOAD_PACK_PATH, RECEIVE_PACK_PATH }));
  64. /**
  65. * Check a request for Git-over-HTTP indicators.
  66. *
  67. * @param req
  68. * the current HTTP request that may have been made by Git.
  69. * @return true if the request is likely made by a Git client program.
  70. */
  71. public static boolean isGitClient(HttpServletRequest req) {
  72. return isInfoRefs(req) || isUploadPack(req) || isReceivePack(req);
  73. }
  74. /**
  75. * Send an error to the Git client or browser.
  76. * <p>
  77. * Server implementors may use this method to send customized error messages
  78. * to a Git protocol client using an HTTP 200 OK response with the error
  79. * embedded in the payload. If the request was not issued by a Git client,
  80. * an HTTP response code is returned instead.
  81. *
  82. * @param req
  83. * current request.
  84. * @param res
  85. * current response.
  86. * @param httpStatus
  87. * HTTP status code to set if the client is not a Git client.
  88. * @throws IOException
  89. * the response cannot be sent.
  90. */
  91. public static void sendError(HttpServletRequest req,
  92. HttpServletResponse res, int httpStatus) throws IOException {
  93. sendError(req, res, httpStatus, null);
  94. }
  95. /**
  96. * Send an error to the Git client or browser.
  97. * <p>
  98. * Server implementors may use this method to send customized error messages
  99. * to a Git protocol client using an HTTP 200 OK response with the error
  100. * embedded in the payload. If the request was not issued by a Git client,
  101. * an HTTP response code is returned instead.
  102. * <p>
  103. * This method may only be called before handing off the request to
  104. * {@link org.eclipse.jgit.transport.UploadPack#upload(java.io.InputStream, OutputStream, OutputStream)}
  105. * or
  106. * {@link org.eclipse.jgit.transport.ReceivePack#receive(java.io.InputStream, OutputStream, OutputStream)}.
  107. *
  108. * @param req
  109. * current request.
  110. * @param res
  111. * current response.
  112. * @param httpStatus
  113. * HTTP status code to set if the client is not a Git client.
  114. * @param textForGit
  115. * plain text message to display on the user's console. This is
  116. * shown only if the client is likely to be a Git client. If null
  117. * or the empty string a default text is chosen based on the HTTP
  118. * response code.
  119. * @throws IOException
  120. * the response cannot be sent.
  121. */
  122. public static void sendError(HttpServletRequest req,
  123. HttpServletResponse res, int httpStatus, String textForGit)
  124. throws IOException {
  125. if (textForGit == null || textForGit.length() == 0) {
  126. switch (httpStatus) {
  127. case SC_FORBIDDEN:
  128. textForGit = HttpServerText.get().repositoryAccessForbidden;
  129. break;
  130. case SC_NOT_FOUND:
  131. textForGit = HttpServerText.get().repositoryNotFound;
  132. break;
  133. case SC_INTERNAL_SERVER_ERROR:
  134. textForGit = HttpServerText.get().internalServerError;
  135. break;
  136. default:
  137. textForGit = "HTTP " + httpStatus;
  138. break;
  139. }
  140. }
  141. if (isInfoRefs(req)) {
  142. sendInfoRefsError(req, res, textForGit);
  143. } else if (isUploadPack(req)) {
  144. sendUploadPackError(req, res, textForGit);
  145. } else if (isReceivePack(req)) {
  146. sendReceivePackError(req, res, textForGit);
  147. } else {
  148. if (httpStatus < 400)
  149. ServletUtils.consumeRequestBody(req);
  150. res.sendError(httpStatus, textForGit);
  151. }
  152. }
  153. private static void sendInfoRefsError(HttpServletRequest req,
  154. HttpServletResponse res, String textForGit) throws IOException {
  155. ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
  156. PacketLineOut pck = new PacketLineOut(buf);
  157. String svc = req.getParameter("service");
  158. pck.writeString("# service=" + svc + "\n");
  159. pck.end();
  160. pck.writeString("ERR " + textForGit);
  161. send(req, res, infoRefsResultType(svc), buf.toByteArray());
  162. }
  163. private static void sendUploadPackError(HttpServletRequest req,
  164. HttpServletResponse res, String textForGit) throws IOException {
  165. // Do not use sideband. Sideband is acceptable only while packfile is
  166. // being sent. Other places, like acknowledgement section, do not
  167. // support sideband. Use an error packet.
  168. ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
  169. PacketLineOut pckOut = new PacketLineOut(buf);
  170. writePacket(pckOut, textForGit);
  171. send(req, res, UPLOAD_PACK_RESULT_TYPE, buf.toByteArray());
  172. }
  173. private static void sendReceivePackError(HttpServletRequest req,
  174. HttpServletResponse res, String textForGit) throws IOException {
  175. ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
  176. PacketLineOut pckOut = new PacketLineOut(buf);
  177. boolean sideband;
  178. ReceivePack rp = (ReceivePack) req.getAttribute(ATTRIBUTE_HANDLER);
  179. if (rp != null) {
  180. try {
  181. sideband = rp.isSideBand();
  182. } catch (RequestNotYetReadException e) {
  183. sideband = isReceivePackSideBand(req);
  184. }
  185. } else
  186. sideband = isReceivePackSideBand(req);
  187. if (sideband)
  188. writeSideBand(buf, textForGit);
  189. else
  190. writePacket(pckOut, textForGit);
  191. send(req, res, RECEIVE_PACK_RESULT_TYPE, buf.toByteArray());
  192. }
  193. private static boolean isReceivePackSideBand(HttpServletRequest req) {
  194. try {
  195. // The client may be in a state where they have sent the sideband
  196. // capability and are expecting a response in the sideband, but we might
  197. // not have a ReceivePack, or it might not have read any of the request.
  198. // So, cheat and read the first line.
  199. String line = new PacketLineIn(req.getInputStream()).readString();
  200. FirstCommand parsed = FirstCommand.fromLine(line);
  201. return parsed.getCapabilities().contains(CAPABILITY_SIDE_BAND_64K);
  202. } catch (IOException e) {
  203. // Probably the connection is closed and a subsequent write will fail, but
  204. // try it just in case.
  205. return false;
  206. }
  207. }
  208. private static void writeSideBand(OutputStream out, String textForGit)
  209. throws IOException {
  210. try (OutputStream msg = new SideBandOutputStream(CH_ERROR, SMALL_BUF,
  211. out)) {
  212. msg.write(Constants.encode("error: " + textForGit));
  213. msg.flush();
  214. }
  215. }
  216. private static void writePacket(PacketLineOut pckOut, String textForGit)
  217. throws IOException {
  218. pckOut.writeString("ERR " + textForGit);
  219. }
  220. private static void send(HttpServletRequest req, HttpServletResponse res,
  221. String type, byte[] buf) throws IOException {
  222. ServletUtils.consumeRequestBody(req);
  223. res.setStatus(HttpServletResponse.SC_OK);
  224. res.setContentType(type);
  225. res.setContentLength(buf.length);
  226. try (OutputStream os = res.getOutputStream()) {
  227. os.write(buf);
  228. }
  229. }
  230. /**
  231. * Get the response Content-Type a client expects for the request.
  232. * <p>
  233. * This method should only be invoked if
  234. * {@link #isGitClient(HttpServletRequest)} is true.
  235. *
  236. * @param req
  237. * current request.
  238. * @return the Content-Type the client expects.
  239. * @throws IllegalArgumentException
  240. * the request is not a Git client request. See
  241. * {@link #isGitClient(HttpServletRequest)}.
  242. */
  243. public static String getResponseContentType(HttpServletRequest req) {
  244. if (isInfoRefs(req))
  245. return infoRefsResultType(req.getParameter("service"));
  246. else if (isUploadPack(req))
  247. return UPLOAD_PACK_RESULT_TYPE;
  248. else if (isReceivePack(req))
  249. return RECEIVE_PACK_RESULT_TYPE;
  250. else
  251. throw new IllegalArgumentException();
  252. }
  253. static String infoRefsResultType(String svc) {
  254. return "application/x-" + svc + "-advertisement";
  255. }
  256. /**
  257. * Strip the Git service suffix from a request path.
  258. *
  259. * Generally the suffix is stripped by the {@code SuffixPipeline} handling
  260. * the request, so this method is rarely needed.
  261. *
  262. * @param path
  263. * the path of the request.
  264. * @return the path up to the last path component before the service suffix;
  265. * the path as-is if it contains no service suffix.
  266. */
  267. public static String stripServiceSuffix(String path) {
  268. for (String suffix : SERVICE_SUFFIXES) {
  269. if (path.endsWith(suffix))
  270. return path.substring(0, path.length() - suffix.length());
  271. }
  272. return path;
  273. }
  274. /**
  275. * Check if the HTTP request was for the /info/refs?service= Git handler.
  276. *
  277. * @param req
  278. * current request.
  279. * @return true if the request is for the /info/refs service.
  280. */
  281. public static boolean isInfoRefs(HttpServletRequest req) {
  282. return req.getRequestURI().endsWith(INFO_REFS_PATH)
  283. && VALID_SERVICES.contains(req.getParameter("service"));
  284. }
  285. /**
  286. * Check if the HTTP request path ends with the /git-upload-pack handler.
  287. *
  288. * @param pathOrUri
  289. * path or URI of the request.
  290. * @return true if the request is for the /git-upload-pack handler.
  291. */
  292. public static boolean isUploadPack(String pathOrUri) {
  293. return pathOrUri != null && pathOrUri.endsWith(UPLOAD_PACK_PATH);
  294. }
  295. /**
  296. * Check if the HTTP request was for the /git-upload-pack Git handler.
  297. *
  298. * @param req
  299. * current request.
  300. * @return true if the request is for the /git-upload-pack handler.
  301. */
  302. public static boolean isUploadPack(HttpServletRequest req) {
  303. return isUploadPack(req.getRequestURI())
  304. && UPLOAD_PACK_REQUEST_TYPE.equals(req.getContentType());
  305. }
  306. /**
  307. * Check if the HTTP request was for the /git-receive-pack Git handler.
  308. *
  309. * @param req
  310. * current request.
  311. * @return true if the request is for the /git-receive-pack handler.
  312. */
  313. public static boolean isReceivePack(HttpServletRequest req) {
  314. String uri = req.getRequestURI();
  315. return uri != null && uri.endsWith(RECEIVE_PACK_PATH)
  316. && RECEIVE_PACK_REQUEST_TYPE.equals(req.getContentType());
  317. }
  318. private GitSmartHttpTools() {
  319. }
  320. }