View Javadoc
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>
5    * and other copyright owners as documented in the project's IP log.
6    *
7    * This program and the accompanying materials are made available
8    * under the terms of the Eclipse Distribution License v1.0 which
9    * accompanies this distribution, is reproduced below, and is
10   * available at http://www.eclipse.org/org/documents/edl-v10.php
11   *
12   * All rights reserved.
13   *
14   * Redistribution and use in source and binary forms, with or
15   * without modification, are permitted provided that the following
16   * conditions are met:
17   *
18   * - Redistributions of source code must retain the above copyright
19   *   notice, this list of conditions and the following disclaimer.
20   *
21   * - Redistributions in binary form must reproduce the above
22   *   copyright notice, this list of conditions and the following
23   *   disclaimer in the documentation and/or other materials provided
24   *   with the distribution.
25   *
26   * - Neither the name of the Eclipse Foundation, Inc. nor the
27   *   names of its contributors may be used to endorse or promote
28   *   products derived from this software without specific prior
29   *   written permission.
30   *
31   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
32   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
33   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
43   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44   */
45  
46  package org.eclipse.jgit.transport;
47  
48  import java.io.IOException;
49  import java.io.InputStream;
50  import java.text.MessageFormat;
51  
52  import org.eclipse.jgit.errors.PackProtocolException;
53  import org.eclipse.jgit.internal.JGitText;
54  import org.eclipse.jgit.lib.Constants;
55  import org.eclipse.jgit.lib.MutableObjectId;
56  import org.eclipse.jgit.util.IO;
57  import org.eclipse.jgit.util.RawParseUtils;
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  
61  /**
62   * Read Git style pkt-line formatting from an input stream.
63   * <p>
64   * This class is not thread safe and may issue multiple reads to the underlying
65   * stream for each method call made.
66   * <p>
67   * This class performs no buffering on its own. This makes it suitable to
68   * interleave reads performed by this class with reads performed directly
69   * against the underlying InputStream.
70   */
71  public class PacketLineIn {
72  	private static final Logger log = LoggerFactory.getLogger(PacketLineIn.class);
73  
74  	/** Magic return from {@link #readString()} when a flush packet is found. */
75  	public static final String END = new StringBuilder(0).toString(); 	/* must not string pool */
76  
77  	/**
78  	 * Magic return from {@link #readString()} when a delim packet is found.
79  	 *
80  	 * @since 5.0
81  	 */
82  	public static final String DELIM = new StringBuilder(0).toString(); 	/* must not string pool */
83  
84  	static enum AckNackResult {
85  		/** NAK */
86  		NAK,
87  		/** ACK */
88  		ACK,
89  		/** ACK + continue */
90  		ACK_CONTINUE,
91  		/** ACK + common */
92  		ACK_COMMON,
93  		/** ACK + ready */
94  		ACK_READY;
95  	}
96  
97  	private final byte[] lineBuffer = new byte[SideBandOutputStream.SMALL_BUF];
98  	private final InputStream in;
99  	private long limit;
100 
101 	/**
102 	 * Create a new packet line reader.
103 	 *
104 	 * @param in
105 	 *            the input stream to consume.
106 	 */
107 	public PacketLineIn(InputStream in) {
108 		this(in, 0);
109 	}
110 
111 	/**
112 	 * Create a new packet line reader.
113 	 *
114 	 * @param in
115 	 *            the input stream to consume.
116 	 * @param limit
117 	 *            bytes to read from the input; unlimited if set to 0.
118 	 * @since 4.7
119 	 */
120 	public PacketLineIn(InputStream in, long limit) {
121 		this.in = in;
122 		this.limit = limit;
123 	}
124 
125 	AckNackResult readACK(MutableObjectId returnedId) throws IOException {
126 		final String line = readString();
127 		if (line.length() == 0)
128 			throw new PackProtocolException(JGitText.get().expectedACKNAKFoundEOF);
129 		if ("NAK".equals(line)) //$NON-NLS-1$
130 			return AckNackResult.NAK;
131 		if (line.startsWith("ACK ")) { //$NON-NLS-1$
132 			returnedId.fromString(line.substring(4, 44));
133 			if (line.length() == 44)
134 				return AckNackResult.ACK;
135 
136 			final String arg = line.substring(44);
137 			if (arg.equals(" continue")) //$NON-NLS-1$
138 				return AckNackResult.ACK_CONTINUE;
139 			else if (arg.equals(" common")) //$NON-NLS-1$
140 				return AckNackResult.ACK_COMMON;
141 			else if (arg.equals(" ready")) //$NON-NLS-1$
142 				return AckNackResult.ACK_READY;
143 		}
144 		if (line.startsWith("ERR ")) //$NON-NLS-1$
145 			throw new PackProtocolException(line.substring(4));
146 		throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedACKNAKGot, line));
147 	}
148 
149 	/**
150 	 * Read a single UTF-8 encoded string packet from the input stream.
151 	 * <p>
152 	 * If the string ends with an LF, it will be removed before returning the
153 	 * value to the caller. If this automatic trimming behavior is not desired,
154 	 * use {@link #readStringRaw()} instead.
155 	 *
156 	 * @return the string. {@link #END} if the string was the magic flush
157 	 *         packet, {@link #DELIM} if the string was the magic DELIM
158 	 *         packet.
159 	 * @throws java.io.IOException
160 	 *             the stream cannot be read.
161 	 */
162 	public String readString() throws IOException {
163 		int len = readLength();
164 		if (len == 0) {
165 			log.debug("git< 0000"); //$NON-NLS-1$
166 			return END;
167 		}
168 		if (len == 1) {
169 			log.debug("git< 0001"); //$NON-NLS-1$
170 			return DELIM;
171 		}
172 
173 		len -= 4; // length header (4 bytes)
174 		if (len == 0) {
175 			log.debug("git< "); //$NON-NLS-1$
176 			return ""; //$NON-NLS-1$
177 		}
178 
179 		byte[] raw;
180 		if (len <= lineBuffer.length)
181 			raw = lineBuffer;
182 		else
183 			raw = new byte[len];
184 
185 		IO.readFully(in, raw, 0, len);
186 		if (raw[len - 1] == '\n')
187 			len--;
188 
189 		String s = RawParseUtils.decode(Constants.CHARSET, raw, 0, len);
190 		log.debug("git< " + s); //$NON-NLS-1$
191 		return s;
192 	}
193 
194 	/**
195 	 * Read a single UTF-8 encoded string packet from the input stream.
196 	 * <p>
197 	 * Unlike {@link #readString()} a trailing LF will be retained.
198 	 *
199 	 * @return the string. {@link #END} if the string was the magic flush
200 	 *         packet.
201 	 * @throws java.io.IOException
202 	 *             the stream cannot be read.
203 	 */
204 	public String readStringRaw() throws IOException {
205 		int len = readLength();
206 		if (len == 0) {
207 			log.debug("git< 0000"); //$NON-NLS-1$
208 			return END;
209 		}
210 
211 		len -= 4; // length header (4 bytes)
212 
213 		byte[] raw;
214 		if (len <= lineBuffer.length)
215 			raw = lineBuffer;
216 		else
217 			raw = new byte[len];
218 
219 		IO.readFully(in, raw, 0, len);
220 
221 		String s = RawParseUtils.decode(Constants.CHARSET, raw, 0, len);
222 		log.debug("git< " + s); //$NON-NLS-1$
223 		return s;
224 	}
225 
226 	void discardUntilEnd() throws IOException {
227 		for (;;) {
228 			int n = readLength();
229 			if (n == 0) {
230 				break;
231 			}
232 			IO.skipFully(in, n - 4);
233 		}
234 	}
235 
236 	int readLength() throws IOException {
237 		IO.readFully(in, lineBuffer, 0, 4);
238 		int len;
239 		try {
240 			len = RawParseUtils.parseHexInt16(lineBuffer, 0);
241 		} catch (ArrayIndexOutOfBoundsException err) {
242 			throw invalidHeader();
243 		}
244 
245 		if (len == 0) {
246 			return 0;
247 		} else if (len == 1) {
248 			return 1;
249 		} else if (len < 4) {
250 			throw invalidHeader();
251 		}
252 
253 		if (limit != 0) {
254 			int n = len - 4;
255 			if (limit < n) {
256 				limit = -1;
257 				try {
258 					IO.skipFully(in, n);
259 				} catch (IOException e) {
260 					// Ignore failure discarding packet over limit.
261 				}
262 				throw new InputOverLimitIOException();
263 			}
264 			// if set limit must not be 0 (means unlimited).
265 			limit = n < limit ? limit - n : -1;
266 		}
267 		return len;
268 	}
269 
270 	private IOException invalidHeader() {
271 		return new IOException(MessageFormat.format(JGitText.get().invalidPacketLineHeader,
272 				"" + (char) lineBuffer[0] + (char) lineBuffer[1] //$NON-NLS-1$
273 				+ (char) lineBuffer[2] + (char) lineBuffer[3]));
274 	}
275 
276 	/**
277 	 * IOException thrown by read when the configured input limit is exceeded.
278 	 *
279 	 * @since 4.7
280 	 */
281 	public static class InputOverLimitIOException extends IOException {
282 		private static final long serialVersionUID = 1L;
283 	}
284 }