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

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