Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

GitSmartHttpTools.java 15KB

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