aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/ch/ethz/ssh2/SCPInputStream.java
blob: 3fc77a8978dfe6502244ff4c7a92cf088647a1e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
 * Copyright (c) 2011 David Kocher. All rights reserved.
 * Please refer to the LICENSE.txt for licensing details.
 */
package ch.ethz.ssh2;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @version $Id:$
 */
public class SCPInputStream extends BufferedInputStream
{
	private Session session;

	/**
	 * Bytes remaining to be read from the stream
	 */
	private long remaining;

	public SCPInputStream(SCPClient client, Session session) throws IOException
	{
		super(session.getStdout());

		this.session = session;

		OutputStream os = new BufferedOutputStream(session.getStdin(), 512);

		os.write(0x0);
		os.flush();

		final SCPClient.LenNamePair lnp;

		while (true)
		{
			int c = session.getStdout().read();
			if (c < 0)
			{
				throw new IOException("Remote scp terminated unexpectedly.");
			}

			String line = client.receiveLine(session.getStdout());

			if (c == 'T')
			{
				/* Ignore modification times */
				continue;
			}

			if ((c == 1) || (c == 2))
			{
				throw new IOException("Remote SCP error: " + line);
			}

			if (c == 'C')
			{
				lnp = client.parseCLine(line);
				break;

			}
			throw new IOException("Remote SCP error: " + ((char) c) + line);
		}

		os.write(0x0);
		os.flush();

		this.remaining = lnp.length;
	}

	@Override
	public int read() throws IOException
	{
		if (!(remaining > 0))
		{
			return -1;
		}

		int read = super.read();
		if (read < 0)
		{
			throw new IOException("Remote scp terminated connection unexpectedly");
		}

		remaining -= read;

		return read;
	}

	@Override
	public int read(byte b[], int off, int len) throws IOException
	{
		if (!(remaining > 0))
		{
			return -1;
		}

		int trans = (int) remaining;
		if (remaining > len)
		{
			trans = len;
		}

		int read = super.read(b, off, trans);
		if (read < 0)
		{
			throw new IOException("Remote scp terminated connection unexpectedly");
		}

		remaining -= read;

		return read;
	}

	@Override
	public void close() throws IOException
	{
		try
		{
			session.getStdin().write(0x0);
			session.getStdin().flush();
		}
		finally
		{
			if (session != null)
			{
				session.close();
			}
		}
	}
}