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.

PacketLineIn.java 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 2008-2009, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
  5. *
  6. * This program and the accompanying materials are made available under the
  7. * terms of the Eclipse Distribution License v. 1.0 which is available at
  8. * https://www.eclipse.org/org/documents/edl-v10.php.
  9. *
  10. * SPDX-License-Identifier: BSD-3-Clause
  11. */
  12. package org.eclipse.jgit.transport;
  13. import static java.nio.charset.StandardCharsets.UTF_8;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.io.UncheckedIOException;
  17. import java.text.MessageFormat;
  18. import java.util.Iterator;
  19. import org.eclipse.jgit.errors.PackProtocolException;
  20. import org.eclipse.jgit.internal.JGitText;
  21. import org.eclipse.jgit.lib.MutableObjectId;
  22. import org.eclipse.jgit.util.IO;
  23. import org.eclipse.jgit.util.RawParseUtils;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. /**
  27. * Read Git style pkt-line formatting from an input stream.
  28. * <p>
  29. * This class is not thread safe and may issue multiple reads to the underlying
  30. * stream for each method call made.
  31. * <p>
  32. * This class performs no buffering on its own. This makes it suitable to
  33. * interleave reads performed by this class with reads performed directly
  34. * against the underlying InputStream.
  35. */
  36. public class PacketLineIn {
  37. private static final Logger log = LoggerFactory.getLogger(PacketLineIn.class);
  38. /**
  39. * Magic return from {@link #readString()} when a flush packet is found.
  40. *
  41. * @deprecated Callers should use {@link #isEnd(String)} to check if a
  42. * string is the end marker, or
  43. * {@link PacketLineIn#readStrings()} to iterate over all
  44. * strings in the input stream until the marker is reached.
  45. */
  46. @Deprecated
  47. public static final String END = new StringBuilder(0).toString(); /* must not string pool */
  48. /**
  49. * Magic return from {@link #readString()} when a delim packet is found.
  50. *
  51. * @since 5.0
  52. * @deprecated Callers should use {@link #isDelimiter(String)} to check if a
  53. * string is the delimiter.
  54. */
  55. @Deprecated
  56. public static final String DELIM = new StringBuilder(0).toString(); /* must not string pool */
  57. enum AckNackResult {
  58. /** NAK */
  59. NAK,
  60. /** ACK */
  61. ACK,
  62. /** ACK + continue */
  63. ACK_CONTINUE,
  64. /** ACK + common */
  65. ACK_COMMON,
  66. /** ACK + ready */
  67. ACK_READY;
  68. }
  69. private final byte[] lineBuffer = new byte[SideBandOutputStream.SMALL_BUF];
  70. private final InputStream in;
  71. private long limit;
  72. /**
  73. * Create a new packet line reader.
  74. *
  75. * @param in
  76. * the input stream to consume.
  77. */
  78. public PacketLineIn(InputStream in) {
  79. this(in, 0);
  80. }
  81. /**
  82. * Create a new packet line reader.
  83. *
  84. * @param in
  85. * the input stream to consume.
  86. * @param limit
  87. * bytes to read from the input; unlimited if set to 0.
  88. * @since 4.7
  89. */
  90. public PacketLineIn(InputStream in, long limit) {
  91. this.in = in;
  92. this.limit = limit;
  93. }
  94. AckNackResult readACK(MutableObjectId returnedId) throws IOException {
  95. final String line = readString();
  96. if (line.length() == 0)
  97. throw new PackProtocolException(JGitText.get().expectedACKNAKFoundEOF);
  98. if ("NAK".equals(line)) //$NON-NLS-1$
  99. return AckNackResult.NAK;
  100. if (line.startsWith("ACK ")) { //$NON-NLS-1$
  101. returnedId.fromString(line.substring(4, 44));
  102. if (line.length() == 44)
  103. return AckNackResult.ACK;
  104. final String arg = line.substring(44);
  105. switch (arg) {
  106. case " continue": //$NON-NLS-1$
  107. return AckNackResult.ACK_CONTINUE;
  108. case " common": //$NON-NLS-1$
  109. return AckNackResult.ACK_COMMON;
  110. case " ready": //$NON-NLS-1$
  111. return AckNackResult.ACK_READY;
  112. default:
  113. break;
  114. }
  115. }
  116. if (line.startsWith("ERR ")) //$NON-NLS-1$
  117. throw new PackProtocolException(line.substring(4));
  118. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedACKNAKGot, line));
  119. }
  120. /**
  121. * Read a single UTF-8 encoded string packet from the input stream.
  122. * <p>
  123. * If the string ends with an LF, it will be removed before returning the
  124. * value to the caller. If this automatic trimming behavior is not desired,
  125. * use {@link #readStringRaw()} instead.
  126. *
  127. * @return the string. {@link #END} if the string was the magic flush
  128. * packet, {@link #DELIM} if the string was the magic DELIM
  129. * packet.
  130. * @throws java.io.IOException
  131. * the stream cannot be read.
  132. */
  133. public String readString() throws IOException {
  134. int len = readLength();
  135. if (len == 0) {
  136. log.debug("git< 0000"); //$NON-NLS-1$
  137. return END;
  138. }
  139. if (len == 1) {
  140. log.debug("git< 0001"); //$NON-NLS-1$
  141. return DELIM;
  142. }
  143. len -= 4; // length header (4 bytes)
  144. if (len == 0) {
  145. log.debug("git< "); //$NON-NLS-1$
  146. return ""; //$NON-NLS-1$
  147. }
  148. byte[] raw;
  149. if (len <= lineBuffer.length)
  150. raw = lineBuffer;
  151. else
  152. raw = new byte[len];
  153. IO.readFully(in, raw, 0, len);
  154. if (raw[len - 1] == '\n')
  155. len--;
  156. String s = RawParseUtils.decode(UTF_8, raw, 0, len);
  157. log.debug("git< " + s); //$NON-NLS-1$
  158. return s;
  159. }
  160. /**
  161. * Get an iterator to read strings from the input stream.
  162. *
  163. * @return an iterator that calls {@link #readString()} until {@link #END}
  164. * is encountered.
  165. *
  166. * @throws IOException
  167. * on failure to read the initial packet line.
  168. * @since 5.4
  169. */
  170. public PacketLineInIterator readStrings() throws IOException {
  171. return new PacketLineInIterator(this);
  172. }
  173. /**
  174. * Read a single UTF-8 encoded string packet from the input stream.
  175. * <p>
  176. * Unlike {@link #readString()} a trailing LF will be retained.
  177. *
  178. * @return the string. {@link #END} if the string was the magic flush
  179. * packet.
  180. * @throws java.io.IOException
  181. * the stream cannot be read.
  182. */
  183. public String readStringRaw() throws IOException {
  184. int len = readLength();
  185. if (len == 0) {
  186. log.debug("git< 0000"); //$NON-NLS-1$
  187. return END;
  188. }
  189. len -= 4; // length header (4 bytes)
  190. byte[] raw;
  191. if (len <= lineBuffer.length)
  192. raw = lineBuffer;
  193. else
  194. raw = new byte[len];
  195. IO.readFully(in, raw, 0, len);
  196. String s = RawParseUtils.decode(UTF_8, raw, 0, len);
  197. log.debug("git< " + s); //$NON-NLS-1$
  198. return s;
  199. }
  200. /**
  201. * Check if a string is the delimiter marker.
  202. *
  203. * @param s
  204. * the string to check
  205. * @return true if the given string is {@link #DELIM}, otherwise false.
  206. * @since 5.4
  207. */
  208. @SuppressWarnings({ "ReferenceEquality", "StringEquality" })
  209. public static boolean isDelimiter(String s) {
  210. return s == DELIM;
  211. }
  212. /**
  213. * Get the delimiter marker.
  214. * <p>
  215. * Intended for use only in tests.
  216. *
  217. * @return The delimiter marker.
  218. */
  219. static String delimiter() {
  220. return DELIM;
  221. }
  222. /**
  223. * Get the end marker.
  224. * <p>
  225. * Intended for use only in tests.
  226. *
  227. * @return The end marker.
  228. */
  229. static String end() {
  230. return END;
  231. }
  232. /**
  233. * Check if a string is the packet end marker.
  234. *
  235. * @param s
  236. * the string to check
  237. * @return true if the given string is {@link #END}, otherwise false.
  238. * @since 5.4
  239. */
  240. @SuppressWarnings({ "ReferenceEquality", "StringEquality" })
  241. public static boolean isEnd(String s) {
  242. return s == END;
  243. }
  244. void discardUntilEnd() throws IOException {
  245. for (;;) {
  246. int n = readLength();
  247. if (n == 0) {
  248. break;
  249. }
  250. IO.skipFully(in, n - 4);
  251. }
  252. }
  253. int readLength() throws IOException {
  254. IO.readFully(in, lineBuffer, 0, 4);
  255. int len;
  256. try {
  257. len = RawParseUtils.parseHexInt16(lineBuffer, 0);
  258. } catch (ArrayIndexOutOfBoundsException err) {
  259. throw invalidHeader(err);
  260. }
  261. if (len == 0) {
  262. return 0;
  263. } else if (len == 1) {
  264. return 1;
  265. } else if (len < 4) {
  266. throw invalidHeader();
  267. }
  268. if (limit != 0) {
  269. int n = len - 4;
  270. if (limit < n) {
  271. limit = -1;
  272. try {
  273. IO.skipFully(in, n);
  274. } catch (IOException e) {
  275. // Ignore failure discarding packet over limit.
  276. }
  277. throw new InputOverLimitIOException();
  278. }
  279. // if set limit must not be 0 (means unlimited).
  280. limit = n < limit ? limit - n : -1;
  281. }
  282. return len;
  283. }
  284. private IOException invalidHeader() {
  285. return new IOException(MessageFormat.format(JGitText.get().invalidPacketLineHeader,
  286. "" + (char) lineBuffer[0] + (char) lineBuffer[1] //$NON-NLS-1$
  287. + (char) lineBuffer[2] + (char) lineBuffer[3]));
  288. }
  289. private IOException invalidHeader(Throwable cause) {
  290. IOException ioe = invalidHeader();
  291. ioe.initCause(cause);
  292. return ioe;
  293. }
  294. /**
  295. * IOException thrown by read when the configured input limit is exceeded.
  296. *
  297. * @since 4.7
  298. */
  299. public static class InputOverLimitIOException extends IOException {
  300. private static final long serialVersionUID = 1L;
  301. }
  302. /**
  303. * Iterator over packet lines.
  304. * <p>
  305. * Calls {@link #readString()} on the {@link PacketLineIn} until
  306. * {@link #END} is encountered.
  307. *
  308. * @since 5.4
  309. *
  310. */
  311. public static class PacketLineInIterator implements Iterable<String> {
  312. private PacketLineIn in;
  313. private String current;
  314. PacketLineInIterator(PacketLineIn in) throws IOException {
  315. this.in = in;
  316. current = in.readString();
  317. }
  318. @Override
  319. public Iterator<String> iterator() {
  320. return new Iterator<String>() {
  321. @Override
  322. public boolean hasNext() {
  323. return !PacketLineIn.isEnd(current);
  324. }
  325. @Override
  326. public String next() {
  327. String next = current;
  328. try {
  329. current = in.readString();
  330. } catch (IOException e) {
  331. throw new UncheckedIOException(e);
  332. }
  333. return next;
  334. }
  335. };
  336. }
  337. }
  338. }