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.lib.Constants;
  62. import org.eclipse.jgit.transport.PacketLineIn;
  63. import org.eclipse.jgit.transport.PacketLineOut;
  64. import org.eclipse.jgit.transport.ReceivePack;
  65. import org.eclipse.jgit.transport.RequestNotYetReadException;
  66. import org.eclipse.jgit.transport.SideBandOutputStream;
  67. import org.eclipse.jgit.transport.UploadPack;
  68. /**
  69. * Utility functions for handling the Git-over-HTTP protocol.
  70. */
  71. public class GitSmartHttpTools {
  72. private static final String INFO_REFS = Constants.INFO_REFS;
  73. /** Name of the git-upload-pack service. */
  74. public static final String UPLOAD_PACK = "git-upload-pack";
  75. /** Name of the git-receive-pack service. */
  76. public static final String RECEIVE_PACK = "git-receive-pack";
  77. /** Content type supplied by the client to the /git-upload-pack handler. */
  78. public static final String UPLOAD_PACK_REQUEST_TYPE =
  79. "application/x-git-upload-pack-request";
  80. /** Content type returned from the /git-upload-pack handler. */
  81. public static final String UPLOAD_PACK_RESULT_TYPE =
  82. "application/x-git-upload-pack-result";
  83. /** Content type supplied by the client to the /git-receive-pack handler. */
  84. public static final String RECEIVE_PACK_REQUEST_TYPE =
  85. "application/x-git-receive-pack-request";
  86. /** Content type returned from the /git-receive-pack handler. */
  87. public static final String RECEIVE_PACK_RESULT_TYPE =
  88. "application/x-git-receive-pack-result";
  89. /** Git service names accepted by the /info/refs?service= handler. */
  90. public static final List<String> VALID_SERVICES =
  91. Collections.unmodifiableList(Arrays.asList(new String[] {
  92. UPLOAD_PACK, RECEIVE_PACK }));
  93. private static final String INFO_REFS_PATH = "/" + INFO_REFS;
  94. private static final String UPLOAD_PACK_PATH = "/" + UPLOAD_PACK;
  95. private static final String RECEIVE_PACK_PATH = "/" + RECEIVE_PACK;
  96. private static final List<String> SERVICE_SUFFIXES =
  97. Collections.unmodifiableList(Arrays.asList(new String[] {
  98. INFO_REFS_PATH, UPLOAD_PACK_PATH, RECEIVE_PACK_PATH }));
  99. /**
  100. * Check a request for Git-over-HTTP indicators.
  101. *
  102. * @param req
  103. * the current HTTP request that may have been made by Git.
  104. * @return true if the request is likely made by a Git client program.
  105. */
  106. public static boolean isGitClient(HttpServletRequest req) {
  107. return isInfoRefs(req) || isUploadPack(req) || isReceivePack(req);
  108. }
  109. /**
  110. * Send an error to the Git client or browser.
  111. * <p>
  112. * Server implementors may use this method to send customized error messages
  113. * to a Git protocol client using an HTTP 200 OK response with the error
  114. * embedded in the payload. If the request was not issued by a Git client,
  115. * an HTTP response code is returned instead.
  116. *
  117. * @param req
  118. * current request.
  119. * @param res
  120. * current response.
  121. * @param httpStatus
  122. * HTTP status code to set if the client is not a Git client.
  123. * @throws IOException
  124. * the response cannot be sent.
  125. */
  126. public static void sendError(HttpServletRequest req,
  127. HttpServletResponse res, int httpStatus) throws IOException {
  128. sendError(req, res, httpStatus, null);
  129. }
  130. /**
  131. * Send an error to the Git client or browser.
  132. * <p>
  133. * Server implementors may use this method to send customized error messages
  134. * to a Git protocol client using an HTTP 200 OK response with the error
  135. * embedded in the payload. If the request was not issued by a Git client,
  136. * an HTTP response code is returned instead.
  137. * <p>
  138. * This method may only be called before handing off the request to
  139. * {@link UploadPack#upload(java.io.InputStream, OutputStream, OutputStream)}
  140. * or
  141. * {@link ReceivePack#receive(java.io.InputStream, OutputStream, OutputStream)}.
  142. *
  143. * @param req
  144. * current request.
  145. * @param res
  146. * current response.
  147. * @param httpStatus
  148. * HTTP status code to set if the client is not a Git client.
  149. * @param textForGit
  150. * plain text message to display on the user's console. This is
  151. * shown only if the client is likely to be a Git client. If null
  152. * or the empty string a default text is chosen based on the HTTP
  153. * response code.
  154. * @throws IOException
  155. * the response cannot be sent.
  156. */
  157. public static void sendError(HttpServletRequest req,
  158. HttpServletResponse res, int httpStatus, String textForGit)
  159. throws IOException {
  160. if (textForGit == null || textForGit.length() == 0) {
  161. switch (httpStatus) {
  162. case SC_FORBIDDEN:
  163. textForGit = HttpServerText.get().repositoryAccessForbidden;
  164. break;
  165. case SC_NOT_FOUND:
  166. textForGit = HttpServerText.get().repositoryNotFound;
  167. break;
  168. case SC_INTERNAL_SERVER_ERROR:
  169. textForGit = HttpServerText.get().internalServerError;
  170. break;
  171. default:
  172. textForGit = "HTTP " + httpStatus;
  173. break;
  174. }
  175. }
  176. if (isInfoRefs(req)) {
  177. sendInfoRefsError(req, res, textForGit);
  178. } else if (isUploadPack(req)) {
  179. sendUploadPackError(req, res, textForGit);
  180. } else if (isReceivePack(req)) {
  181. sendReceivePackError(req, res, textForGit);
  182. } else {
  183. if (httpStatus < 400)
  184. ServletUtils.consumeRequestBody(req);
  185. res.sendError(httpStatus);
  186. }
  187. }
  188. private static void sendInfoRefsError(HttpServletRequest req,
  189. HttpServletResponse res, String textForGit) throws IOException {
  190. ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
  191. PacketLineOut pck = new PacketLineOut(buf);
  192. String svc = req.getParameter("service");
  193. pck.writeString("# service=" + svc + "\n");
  194. pck.end();
  195. pck.writeString("ERR " + textForGit);
  196. send(req, res, infoRefsResultType(svc), buf.toByteArray());
  197. }
  198. private static void sendUploadPackError(HttpServletRequest req,
  199. HttpServletResponse res, String textForGit) throws IOException {
  200. ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
  201. PacketLineOut pckOut = new PacketLineOut(buf);
  202. boolean sideband;
  203. UploadPack up = (UploadPack) req.getAttribute(ATTRIBUTE_HANDLER);
  204. if (up != null) {
  205. try {
  206. sideband = up.isSideBand();
  207. } catch (RequestNotYetReadException e) {
  208. sideband = isUploadPackSideBand(req);
  209. }
  210. } else
  211. sideband = isUploadPackSideBand(req);
  212. if (sideband)
  213. writeSideBand(buf, textForGit);
  214. else
  215. writePacket(pckOut, textForGit);
  216. send(req, res, UPLOAD_PACK_RESULT_TYPE, buf.toByteArray());
  217. }
  218. private static boolean isUploadPackSideBand(HttpServletRequest req) {
  219. try {
  220. // The client may be in a state where they have sent the sideband
  221. // capability and are expecting a response in the sideband, but we might
  222. // not have an UploadPack, or it might not have read any of the request.
  223. // So, cheat and read the first line.
  224. String line = new PacketLineIn(req.getInputStream()).readString();
  225. UploadPack.FirstLine parsed = new UploadPack.FirstLine(line);
  226. return (parsed.getOptions().contains(OPTION_SIDE_BAND)
  227. || parsed.getOptions().contains(OPTION_SIDE_BAND_64K));
  228. } catch (IOException e) {
  229. // Probably the connection is closed and a subsequent write will fail, but
  230. // try it just in case.
  231. return false;
  232. }
  233. }
  234. private static void sendReceivePackError(HttpServletRequest req,
  235. HttpServletResponse res, String textForGit) throws IOException {
  236. ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
  237. PacketLineOut pckOut = new PacketLineOut(buf);
  238. boolean sideband;
  239. ReceivePack rp = (ReceivePack) req.getAttribute(ATTRIBUTE_HANDLER);
  240. if (rp != null) {
  241. try {
  242. sideband = rp.isSideBand();
  243. } catch (RequestNotYetReadException e) {
  244. sideband = isReceivePackSideBand(req);
  245. }
  246. } else
  247. sideband = isReceivePackSideBand(req);
  248. if (sideband)
  249. writeSideBand(buf, textForGit);
  250. else
  251. writePacket(pckOut, textForGit);
  252. send(req, res, RECEIVE_PACK_RESULT_TYPE, buf.toByteArray());
  253. }
  254. private static boolean isReceivePackSideBand(HttpServletRequest req) {
  255. try {
  256. // The client may be in a state where they have sent the sideband
  257. // capability and are expecting a response in the sideband, but we might
  258. // not have a ReceivePack, or it might not have read any of the request.
  259. // So, cheat and read the first line.
  260. String line = new PacketLineIn(req.getInputStream()).readString();
  261. ReceivePack.FirstLine parsed = new ReceivePack.FirstLine(line);
  262. return parsed.getCapabilities().contains(CAPABILITY_SIDE_BAND_64K);
  263. } catch (IOException e) {
  264. // Probably the connection is closed and a subsequent write will fail, but
  265. // try it just in case.
  266. return false;
  267. }
  268. }
  269. private static void writeSideBand(OutputStream out, String textForGit)
  270. throws IOException {
  271. @SuppressWarnings("resource" /* java 7 */)
  272. OutputStream msg = new SideBandOutputStream(CH_ERROR, SMALL_BUF, out);
  273. msg.write(Constants.encode("error: " + textForGit));
  274. msg.flush();
  275. }
  276. private static void writePacket(PacketLineOut pckOut, String textForGit)
  277. throws IOException {
  278. pckOut.writeString("error: " + textForGit);
  279. }
  280. private static void send(HttpServletRequest req, HttpServletResponse res,
  281. String type, byte[] buf) throws IOException {
  282. ServletUtils.consumeRequestBody(req);
  283. res.setStatus(HttpServletResponse.SC_OK);
  284. res.setContentType(type);
  285. res.setContentLength(buf.length);
  286. OutputStream os = res.getOutputStream();
  287. try {
  288. os.write(buf);
  289. } finally {
  290. os.close();
  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. }