1/*
2 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved.
3 * Please refer to the LICENSE.txt for licensing details.
4 */
5package ch.ethz.ssh2.channel;
6
7import java.io.IOException;
8import java.io.InputStream;
9
10/**
11 * ChannelInputStream.
12 *
13 * @author Christian Plattner
14 * @version 2.50, 03/15/10
15 */
16public final class ChannelInputStream extends InputStream
17{
18	Channel c;
19
20	boolean isClosed = false;
21	boolean isEOF = false;
22	boolean extendedFlag = false;
23
24	ChannelInputStream(Channel c, boolean isExtended)
25	{
26		this.c = c;
27		this.extendedFlag = isExtended;
28	}
29
30	@Override
31	public int available() throws IOException
32	{
33		if (isEOF)
34			return 0;
35
36		int avail = c.cm.getAvailable(c, extendedFlag);
37
38		/* We must not return -1 on EOF */
39
40		return (avail > 0) ? avail : 0;
41	}
42
43	@Override
44	public void close() throws IOException
45	{
46		isClosed = true;
47	}
48
49	@Override
50	public int read(byte[] b, int off, int len) throws IOException
51	{
52		if (b == null)
53			throw new NullPointerException();
54
55		if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0) || (off > b.length))
56			throw new IndexOutOfBoundsException();
57
58		if (len == 0)
59			return 0;
60
61		if (isEOF)
62			return -1;
63
64		int ret = c.cm.getChannelData(c, extendedFlag, b, off, len);
65
66		if (ret == -1)
67		{
68			isEOF = true;
69		}
70
71		return ret;
72	}
73
74	@Override
75	public int read(byte[] b) throws IOException
76	{
77		return read(b, 0, b.length);
78	}
79
80	@Override
81	public int read() throws IOException
82	{
83		/* Yes, this stream is pure and unbuffered, a single byte read() is slow */
84
85		final byte b[] = new byte[1];
86
87		int ret = read(b, 0, 1);
88
89		if (ret != 1)
90			return -1;
91
92		return b[0] & 0xff;
93	}
94}
95