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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. * Copyright (C) 2011, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.http.server;
  44. import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
  45. import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
  46. import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
  47. import static org.eclipse.jgit.http.server.ServletUtils.ATTRIBUTE_HANDLER;
  48. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_SIDE_BAND_64K;
  49. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND;
  50. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND_64K;
  51. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_ERROR;
  52. import static org.eclipse.jgit.transport.SideBandOutputStream.SMALL_BUF;
  53. import java.io.ByteArrayOutputStream;
  54. import java.io.IOException;
  55. import java.io.OutputStream;
  56. import java.util.Arrays;
  57. import java.util.Collections;
  58. import java.util.List;
  59. import javax.servlet.http.HttpServletRequest;
  60. import javax.servlet.http.HttpServletResponse;
  61. import org.eclipse.jgit.internal.transport.parser.FirstCommand;
  62. import org.eclipse.jgit.internal.transport.parser.FirstWant;
  63. import org.eclipse.jgit.lib.Constants;
  64. import org.eclipse.jgit.transport.PacketLineIn;
  65. import org.eclipse.jgit.transport.PacketLineOut;
  66. import org.eclipse.jgit.transport.ReceivePack;
  67. import org.eclipse.jgit.transport.RequestNotYetReadException;
  68. import org.eclipse.jgit.transport.SideBandOutputStream;
  69. import org.eclipse.jgit.transport.UploadPack;
  70. /**
  71. * Utility functions for handling the Git-over-HTTP protocol.
  72. */
  73. public class GitSmartHttpTools {
  74. private static final String INFO_REFS = Constants.INFO_REFS;
  75. /** Name of the git-upload-pack service. */
  76. public static final String UPLOAD_PACK = "git-upload-pack";
  77. /** Name of the git-receive-pack service. */
  78. public static final String RECEIVE_PACK = "git-receive-pack";
  79. /** Content type supplied by the client to the /git-upload-pack handler. */
  80. public static final String UPLOAD_PACK_REQUEST_TYPE =
  81. "application/x-git-upload-pack-request";
  82. /** Content type returned from the /git-upload-pack handler. */
  83. public static final String UPLOAD_PACK_RESULT_TYPE =
  84. "application/x-git-upload-pack-result";
  85. /** Content type supplied by the client to the /git-receive-pack handler. */
  86. public static final String RECEIVE_PACK_REQUEST_TYPE =
  87. "application/x-git-receive-pack-request";
  88. /** Content type returned from the /git-receive-pack handler. */
  89. public static final String RECEIVE_PACK_RESULT_TYPE =
  90. "application/x-git-receive-pack-result";
  91. /** Git service names accepted by the /info/refs?service= handler. */
  92. public static final List<String> VALID_SERVICES =
  93. Collections.unmodifiableList(Arrays.asList(new String[] {
  94. UPLOAD_PACK, RECEIVE_PACK }));
  95. private static final String INFO_REFS_PATH = "/" + INFO_REFS;
  96. private static final String UPLOAD_PACK_PATH = "/" + UPLOAD_PACK;
  97. private static final String RECEIVE_PACK_PATH = "/" + RECEIVE_PACK;
  98. private static final List<String> SERVICE_SUFFIXES =
  99. Collections.unmodifiableList(Arrays.asList(new String[] {
  100. INFO_REFS_PATH, UPLOAD_PACK_PATH, RECEIVE_PACK_PATH }));
  101. /**
  102. * Check a request for Git-over-HTTP indicators.
  103. *
  104. * @param req
  105. * the current HTTP request that may have been made by Git.
  106. * @return true if the request is likely made by a Git client program.
  107. */
  108. public static boolean isGitClient(HttpServletRequest req) {
  109. return isInfoRefs(req) || isUploadPack(req) || isReceivePack(req);
  110. }
  111. /**
  112. * Send an error to the Git client or browser.
  113. * <p>
  114. * Server implementors may use this method to send customized error messages
  115. * to a Git protocol client using an HTTP 200 OK response with the error
  116. * embedded in the payload. If the request was not issued by a Git client,
  117. * an HTTP response code is returned instead.
  118. *
  119. * @param req
  120. * current request.
  121. * @param res
  122. * current response.
  123. * @param httpStatus
  124. * HTTP status code to set if the client is not a Git client.
  125. * @throws IOException
  126. * the response cannot be sent.
  127. */
  128. public static void sendError(HttpServletRequest req,
  129. HttpServletResponse res, int httpStatus) throws IOException {
  130. sendError(req, res, httpStatus, null);
  131. }
  132. /**
  133. * Send an error to the Git client or browser.
  134. * <p>
  135. * Server implementors may use this method to send customized error messages
  136. * to a Git protocol client using an HTTP 200 OK response with the error
  137. * embedded in the payload. If the request was not issued by a Git client,
  138. * an HTTP response code is returned instead.
  139. * <p>
  140. * This method may only be called before handing off the request to
  141. * {@link org.eclipse.jgit.transport.UploadPack#upload(java.io.InputStream, OutputStream, OutputStream)}
  142. * or
  143. * {@link org.eclipse.jgit.transport.ReceivePack#receive(java.io.InputStream, OutputStream, OutputStream)}.
  144. *
  145. * @param req
  146. * current request.
  147. * @param res
  148. * current response.
  149. * @param httpStatus
  150. * HTTP status code to set if the client is not a Git client.
  151. * @param textForGit
  152. * plain text message to display on the user's console. This is
  153. * shown only if the client is likely to be a Git client. If null
  154. * or the empty string a default text is chosen based on the HTTP
  155. * response code.
  156. * @throws IOException
  157. * the response cannot be sent.
  158. */
  159. public static void sendError(HttpServletRequest req,
  160. HttpServletResponse res, int httpStatus, String textForGit)
  161. throws IOException {
  162. if (textForGit == null || textForGit.length() == 0) {
  163. switch (httpStatus) {
  164. case SC_FORBIDDEN:
  165. textForGit = HttpServerText.get().repositoryAccessForbidden;
  166. break;
  167. case SC_NOT_FOUND:
  168. textForGit = HttpServerText.get().repositoryNotFound;
  169. break;
  170. case SC_INTERNAL_SERVER_ERROR:
  171. textForGit = HttpServerText.get().internalServerError;
  172. break;
  173. default:
  174. textForGit = "HTTP " + httpStatus;
  175. break;
  176. }
  177. }
  178. if (isInfoRefs(req)) {
  179. sendInfoRefsError(req, res, textForGit);
  180. } else if (isUploadPack(req)) {
  181. sendUploadPackError(req, res, textForGit);
  182. } else if (isReceivePack(req)) {
  183. sendReceivePackError(req, res, textForGit);
  184. } else {
  185. if (httpStatus < 400)
  186. ServletUtils.consumeRequestBody(req);
  187. res.sendError(httpStatus, textForGit);
  188. }
  189. }
  190. private static void sendInfoRefsError(HttpServletRequest req,
  191. HttpServletResponse res, String textForGit) throws IOException {
  192. ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
  193. PacketLineOut pck = new PacketLineOut(buf);
  194. String svc = req.getParameter("service");
  195. pck.writeString("# service=" + svc + "\n");
  196. pck.end();
  197. pck.writeString("ERR " + textForGit);
  198. send(req, res, infoRefsResultType(svc), buf.toByteArray());
  199. }
  200. private static void sendUploadPackError(HttpServletRequest req,
  201. HttpServletResponse res, String textForGit) throws IOException {
  202. ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
  203. PacketLineOut pckOut = new PacketLineOut(buf);
  204. boolean sideband;
  205. UploadPack up = (UploadPack) req.getAttribute(ATTRIBUTE_HANDLER);
  206. if (up != null) {
  207. try {
  208. sideband = up.isSideBand();
  209. } catch (RequestNotYetReadException e) {
  210. sideband = isUploadPackSideBand(req);
  211. }
  212. } else
  213. sideband = isUploadPackSideBand(req);
  214. if (sideband)
  215. writeSideBand(buf, textForGit);
  216. else
  217. writePacket(pckOut, textForGit);
  218. send(req, res, UPLOAD_PACK_RESULT_TYPE, buf.toByteArray());
  219. }
  220. private static boolean isUploadPackSideBand(HttpServletRequest req) {
  221. try {
  222. // The client may be in a state where they have sent the sideband
  223. // capability and are expecting a response in the sideband, but we might
  224. // not have an UploadPack, or it might not have read any of the request.
  225. // So, cheat and read the first line.
  226. String line = new PacketLineIn(req.getInputStream()).readString();
  227. FirstWant parsed = FirstWant.fromLine(line);
  228. return (parsed.getCapabilities().contains(OPTION_SIDE_BAND)
  229. || parsed.getCapabilities().contains(OPTION_SIDE_BAND_64K));
  230. } catch (IOException e) {
  231. // Probably the connection is closed and a subsequent write will fail, but
  232. // try it just in case.
  233. return false;
  234. }
  235. }
  236. private static void sendReceivePackError(HttpServletRequest req,
  237. HttpServletResponse res, String textForGit) throws IOException {
  238. ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
  239. PacketLineOut pckOut = new PacketLineOut(buf);
  240. boolean sideband;
  241. ReceivePack rp = (ReceivePack) req.getAttribute(ATTRIBUTE_HANDLER);
  242. if (rp != null) {
  243. try {
  244. sideband = rp.isSideBand();
  245. } catch (RequestNotYetReadException e) {
  246. sideband = isReceivePackSideBand(req);
  247. }
  248. } else
  249. sideband = isReceivePackSideBand(req);
  250. if (sideband)
  251. writeSideBand(buf, textForGit);
  252. else
  253. writePacket(pckOut, textForGit);
  254. send(req, res, RECEIVE_PACK_RESULT_TYPE, buf.toByteArray());
  255. }
  256. private static boolean isReceivePackSideBand(HttpServletRequest req) {
  257. try {
  258. // The client may be in a state where they have sent the sideband
  259. // capability and are expecting a response in the sideband, but we might
  260. // not have a ReceivePack, or it might not have read any of the request.
  261. // So, cheat and read the first line.
  262. String line = new PacketLineIn(req.getInputStream()).readString();
  263. FirstCommand parsed = FirstCommand.fromLine(line);
  264. return parsed.getCapabilities().contains(CAPABILITY_SIDE_BAND_64K);
  265. } catch (IOException e) {
  266. // Probably the connection is closed and a subsequent write will fail, but
  267. // try it just in case.
  268. return false;
  269. }
  270. }
  271. private static void writeSideBand(OutputStream out, String textForGit)
  272. throws IOException {
  273. try (OutputStream msg = new SideBandOutputStream(CH_ERROR, SMALL_BUF,
  274. out)) {
  275. msg.write(Constants.encode("error: " + textForGit));
  276. msg.flush();
  277. }
  278. }
  279. private static void writePacket(PacketLineOut pckOut, String textForGit)
  280. throws IOException {
  281. pckOut.writeString("error: " + textForGit);
  282. }
  283. private static void send(HttpServletRequest req, HttpServletResponse res,
  284. String type, byte[] buf) throws IOException {
  285. ServletUtils.consumeRequestBody(req);
  286. res.setStatus(HttpServletResponse.SC_OK);
  287. res.setContentType(type);
  288. res.setContentLength(buf.length);
  289. try (OutputStream os = res.getOutputStream()) {
  290. os.write(buf);
  291. }
  292. }
  293. /**
  294. * Get the response Content-Type a client expects for the request.
  295. * <p>
  296. * This method should only be invoked if
  297. * {@link #isGitClient(HttpServletRequest)} is true.
  298. *
  299. * @param req
  300. * current request.
  301. * @return the Content-Type the client expects.
  302. * @throws IllegalArgumentException
  303. * the request is not a Git client request. See
  304. * {@link #isGitClient(HttpServletRequest)}.
  305. */
  306. public static String getResponseContentType(HttpServletRequest req) {
  307. if (isInfoRefs(req))
  308. return infoRefsResultType(req.getParameter("service"));
  309. else if (isUploadPack(req))
  310. return UPLOAD_PACK_RESULT_TYPE;
  311. else if (isReceivePack(req))
  312. return RECEIVE_PACK_RESULT_TYPE;
  313. else
  314. throw new IllegalArgumentException();
  315. }
  316. static String infoRefsResultType(String svc) {
  317. return "application/x-" + svc + "-advertisement";
  318. }
  319. /**
  320. * Strip the Git service suffix from a request path.
  321. *
  322. * Generally the suffix is stripped by the {@code SuffixPipeline} handling
  323. * the request, so this method is rarely needed.
  324. *
  325. * @param path
  326. * the path of the request.
  327. * @return the path up to the last path component before the service suffix;
  328. * the path as-is if it contains no service suffix.
  329. */
  330. public static String stripServiceSuffix(String path) {
  331. for (String suffix : SERVICE_SUFFIXES) {
  332. if (path.endsWith(suffix))
  333. return path.substring(0, path.length() - suffix.length());
  334. }
  335. return path;
  336. }
  337. /**
  338. * Check if the HTTP request was for the /info/refs?service= Git handler.
  339. *
  340. * @param req
  341. * current request.
  342. * @return true if the request is for the /info/refs service.
  343. */
  344. public static boolean isInfoRefs(HttpServletRequest req) {
  345. return req.getRequestURI().endsWith(INFO_REFS_PATH)
  346. && VALID_SERVICES.contains(req.getParameter("service"));
  347. }
  348. /**
  349. * Check if the HTTP request path ends with the /git-upload-pack handler.
  350. *
  351. * @param pathOrUri
  352. * path or URI of the request.
  353. * @return true if the request is for the /git-upload-pack handler.
  354. */
  355. public static boolean isUploadPack(String pathOrUri) {
  356. return pathOrUri != null && pathOrUri.endsWith(UPLOAD_PACK_PATH);
  357. }
  358. /**
  359. * Check if the HTTP request was for the /git-upload-pack Git handler.
  360. *
  361. * @param req
  362. * current request.
  363. * @return true if the request is for the /git-upload-pack handler.
  364. */
  365. public static boolean isUploadPack(HttpServletRequest req) {
  366. return isUploadPack(req.getRequestURI())
  367. && UPLOAD_PACK_REQUEST_TYPE.equals(req.getContentType());
  368. }
  369. /**
  370. * Check if the HTTP request was for the /git-receive-pack Git handler.
  371. *
  372. * @param req
  373. * current request.
  374. * @return true if the request is for the /git-receive-pack handler.
  375. */
  376. public static boolean isReceivePack(HttpServletRequest req) {
  377. String uri = req.getRequestURI();
  378. return uri != null && uri.endsWith(RECEIVE_PACK_PATH)
  379. && RECEIVE_PACK_REQUEST_TYPE.equals(req.getContentType());
  380. }
  381. private GitSmartHttpTools() {
  382. }
  383. }