comparison app/src/main/java/ch/ethz/ssh2/SFTPv3Client.java @ 438:d29cce60f393

migrate from Eclipse to Android Studio
author Carl Byington <carl@five-ten-sg.com>
date Thu, 03 Dec 2015 11:23:55 -0800
parents src/ch/ethz/ssh2/SFTPv3Client.java@071eccdff8ea
children
comparison
equal deleted inserted replaced
437:208b31032318 438:d29cce60f393
1 /*
2 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved.
3 * Please refer to the LICENSE.txt for licensing details.
4 */
5 package ch.ethz.ssh2;
6
7 import java.io.IOException;
8 import java.util.ArrayList;
9 import java.util.List;
10
11 import ch.ethz.ssh2.log.Logger;
12 import ch.ethz.ssh2.packets.TypesReader;
13 import ch.ethz.ssh2.packets.TypesWriter;
14 import ch.ethz.ssh2.sftp.ErrorCodes;
15 import ch.ethz.ssh2.sftp.Packet;
16
17 /**
18 * A <code>SFTPv3Client</code> represents a SFTP (protocol version 3)
19 * client connection tunnelled over a SSH-2 connection. This is a very simple
20 * (synchronous) implementation.
21 * <p/>
22 * Basically, most methods in this class map directly to one of
23 * the packet types described in draft-ietf-secsh-filexfer-02.txt.
24 * <p/>
25 * Note: this is experimental code.
26 * <p/>
27 * Error handling: the methods of this class throw IOExceptions. However, unless
28 * there is catastrophic failure, exceptions of the type {@link SFTPv3Client} will
29 * be thrown (a subclass of IOException). Therefore, you can implement more verbose
30 * behavior by checking if a thrown exception if of this type. If yes, then you
31 * can cast the exception and access detailed information about the failure.
32 * <p/>
33 * Notes about file names, directory names and paths, copy-pasted
34 * from the specs:
35 * <ul>
36 * <li>SFTP v3 represents file names as strings. File names are
37 * assumed to use the slash ('/') character as a directory separator.</li>
38 * <li>File names starting with a slash are "absolute", and are relative to
39 * the root of the file system. Names starting with any other character
40 * are relative to the user's default directory (home directory).</li>
41 * <li>Servers SHOULD interpret a path name component ".." as referring to
42 * the parent directory, and "." as referring to the current directory.
43 * If the server implementation limits access to certain parts of the
44 * file system, it must be extra careful in parsing file names when
45 * enforcing such restrictions. There have been numerous reported
46 * security bugs where a ".." in a path name has allowed access outside
47 * the intended area.</li>
48 * <li>An empty path name is valid, and it refers to the user's default
49 * directory (usually the user's home directory).</li>
50 * </ul>
51 * <p/>
52 * If you are still not tired then please go on and read the comment for
53 * {@link #setCharset(String)}.
54 *
55 * @author Christian Plattner, plattner@inf.ethz.ch
56 * @version $Id: SFTPv3Client.java 133 2014-04-14 12:26:29Z dkocher@sudo.ch $
57 */
58 public class SFTPv3Client extends AbstractSFTPClient {
59 private static final Logger log = Logger.getLogger(SFTPv3Client.class);
60
61 /**
62 * Open the file for reading.
63 */
64 public static final int SSH_FXF_READ = 0x00000001;
65 /**
66 * Open the file for writing. If both this and SSH_FXF_READ are
67 * specified, the file is opened for both reading and writing.
68 */
69 public static final int SSH_FXF_WRITE = 0x00000002;
70 /**
71 * Force all writes to append data at the end of the file.
72 */
73 public static final int SSH_FXF_APPEND = 0x00000004;
74 /**
75 * If this flag is specified, then a new file will be created if one
76 * does not alread exist (if O_TRUNC is specified, the new file will
77 * be truncated to zero length if it previously exists).
78 */
79 public static final int SSH_FXF_CREAT = 0x00000008;
80 /**
81 * Forces an existing file with the same name to be truncated to zero
82 * length when creating a file by specifying SSH_FXF_CREAT.
83 * SSH_FXF_CREAT MUST also be specified if this flag is used.
84 */
85 public static final int SSH_FXF_TRUNC = 0x00000010;
86 /**
87 * Causes the request to fail if the named file already exists.
88 */
89 public static final int SSH_FXF_EXCL = 0x00000020;
90
91 private PacketListener listener;
92
93 /**
94 * Create a SFTP v3 client.
95 *
96 * @param conn The underlying SSH-2 connection to be used.
97 * @throws IOException
98 */
99 public SFTPv3Client(Connection conn) throws IOException {
100 this(conn, new PacketListener() {
101 public void read(String packet) {
102 log.debug("Read packet " + packet);
103 }
104 public void write(String packet) {
105 log.debug("Write packet " + packet);
106 }
107 });
108 }
109
110 /**
111 * Create a SFTP v3 client.
112 *
113 * @param conn The underlying SSH-2 connection to be used.
114 * @throws IOException
115 */
116 public SFTPv3Client(Connection conn, PacketListener listener) throws IOException {
117 super(conn, 3, listener);
118 this.listener = listener;
119 }
120
121 public SFTPv3FileAttributes fstat(SFTPFileHandle handle) throws IOException {
122 int req_id = generateNextRequestID();
123 TypesWriter tw = new TypesWriter();
124 tw.writeString(handle.getHandle(), 0, handle.getHandle().length);
125 sendMessage(Packet.SSH_FXP_FSTAT, req_id, tw.getBytes());
126 byte[] resp = receiveMessage(34000);
127 TypesReader tr = new TypesReader(resp);
128 int t = tr.readByte();
129 listener.read(Packet.forName(t));
130 int rep_id = tr.readUINT32();
131
132 if (rep_id != req_id) {
133 throw new RequestMismatchException();
134 }
135
136 if (t == Packet.SSH_FXP_ATTRS) {
137 return new SFTPv3FileAttributes(tr);
138 }
139
140 if (t != Packet.SSH_FXP_STATUS) {
141 throw new PacketTypeException(t);
142 }
143
144 int errorCode = tr.readUINT32();
145 String errorMessage = tr.readString();
146 listener.read(errorMessage);
147 throw new SFTPException(errorMessage, errorCode);
148 }
149
150 private SFTPv3FileAttributes statBoth(String path, int statMethod) throws IOException {
151 int req_id = generateNextRequestID();
152 TypesWriter tw = new TypesWriter();
153 tw.writeString(path, this.getCharset());
154 sendMessage(statMethod, req_id, tw.getBytes());
155 byte[] resp = receiveMessage(34000);
156 TypesReader tr = new TypesReader(resp);
157 int t = tr.readByte();
158 listener.read(Packet.forName(t));
159 int rep_id = tr.readUINT32();
160
161 if (rep_id != req_id) {
162 throw new RequestMismatchException();
163 }
164
165 if (t == Packet.SSH_FXP_ATTRS) {
166 return new SFTPv3FileAttributes(tr);
167 }
168
169 if (t != Packet.SSH_FXP_STATUS) {
170 throw new PacketTypeException(t);
171 }
172
173 int errorCode = tr.readUINT32();
174 String errorMessage = tr.readString();
175 listener.read(errorMessage);
176 throw new SFTPException(errorMessage, errorCode);
177 }
178
179 public SFTPv3FileAttributes stat(String path) throws IOException {
180 return statBoth(path, Packet.SSH_FXP_STAT);
181 }
182
183 public SFTPv3FileAttributes lstat(String path) throws IOException {
184 return statBoth(path, Packet.SSH_FXP_LSTAT);
185 }
186
187
188 private List<SFTPv3DirectoryEntry> scanDirectory(byte[] handle) throws IOException {
189 List<SFTPv3DirectoryEntry> files = new ArrayList<SFTPv3DirectoryEntry>();
190
191 while (true) {
192 int req_id = generateNextRequestID();
193 TypesWriter tw = new TypesWriter();
194 tw.writeString(handle, 0, handle.length);
195 sendMessage(Packet.SSH_FXP_READDIR, req_id, tw.getBytes());
196 byte[] resp = receiveMessage(34000);
197 TypesReader tr = new TypesReader(resp);
198 int t = tr.readByte();
199 listener.read(Packet.forName(t));
200 int rep_id = tr.readUINT32();
201
202 if (rep_id != req_id) {
203 throw new RequestMismatchException();
204 }
205
206 if (t == Packet.SSH_FXP_NAME) {
207 int count = tr.readUINT32();
208
209 if (log.isDebugEnabled()) {
210 log.debug(String.format("Parsing %d name entries", count));
211 }
212
213 while (count > 0) {
214 SFTPv3DirectoryEntry file = new SFTPv3DirectoryEntry();
215 file.filename = tr.readString(this.getCharset());
216 file.longEntry = tr.readString(this.getCharset());
217 listener.read(file.longEntry);
218 file.attributes = new SFTPv3FileAttributes(tr);
219
220 if (log.isDebugEnabled()) {
221 log.debug(String.format("Adding file %s", file));
222 }
223
224 files.add(file);
225 count--;
226 }
227
228 continue;
229 }
230
231 if (t != Packet.SSH_FXP_STATUS) {
232 throw new PacketTypeException(t);
233 }
234
235 int errorCode = tr.readUINT32();
236
237 if (errorCode == ErrorCodes.SSH_FX_EOF) {
238 return files;
239 }
240
241 String errorMessage = tr.readString();
242 listener.read(errorMessage);
243 throw new SFTPException(errorMessage, errorCode);
244 }
245 }
246
247 public final SFTPv3FileHandle openDirectory(String path) throws IOException {
248 int req_id = generateNextRequestID();
249 TypesWriter tw = new TypesWriter();
250 tw.writeString(path, this.getCharset());
251 sendMessage(Packet.SSH_FXP_OPENDIR, req_id, tw.getBytes());
252 byte[] resp = receiveMessage(34000);
253 TypesReader tr = new TypesReader(resp);
254 int t = tr.readByte();
255 listener.read(Packet.forName(t));
256 int rep_id = tr.readUINT32();
257
258 if (rep_id != req_id) {
259 throw new RequestMismatchException();
260 }
261
262 if (t == Packet.SSH_FXP_HANDLE) {
263 return new SFTPv3FileHandle(this, tr.readByteString());
264 }
265
266 if (t != Packet.SSH_FXP_STATUS) {
267 throw new PacketTypeException(t);
268 }
269
270 int errorCode = tr.readUINT32();
271 String errorMessage = tr.readString();
272 listener.read(errorMessage);
273 throw new SFTPException(errorMessage, errorCode);
274 }
275
276 /**
277 * List the contents of a directory.
278 *
279 * @param dirName See the {@link SFTPv3Client comment} for the class for more details.
280 * @return A Vector containing {@link SFTPv3DirectoryEntry} objects.
281 * @throws IOException
282 */
283 public List<SFTPv3DirectoryEntry> ls(String dirName) throws IOException {
284 SFTPv3FileHandle handle = openDirectory(dirName);
285 List<SFTPv3DirectoryEntry> result = scanDirectory(handle.getHandle());
286 closeFile(handle);
287 return result;
288 }
289
290 /**
291 * Open a file for reading.
292 *
293 * @param filename See the {@link SFTPv3Client comment} for the class for more details.
294 * @return a SFTPv3FileHandle handle
295 * @throws IOException
296 */
297 public SFTPv3FileHandle openFileRO(String filename) throws IOException {
298 return openFile(filename, SSH_FXF_READ, new SFTPv3FileAttributes());
299 }
300
301 /**
302 * Open a file for reading and writing.
303 *
304 * @param filename See the {@link SFTPv3Client comment} for the class for more details.
305 * @return a SFTPv3FileHandle handle
306 * @throws IOException
307 */
308 public SFTPv3FileHandle openFileRW(String filename) throws IOException {
309 return openFile(filename, SSH_FXF_READ | SSH_FXF_WRITE, new SFTPv3FileAttributes());
310 }
311
312 /**
313 * Open a file in append mode. The SFTP v3 draft says nothing but assuming normal POSIX
314 * behavior, all writes will be appendend to the end of the file, no matter which offset
315 * one specifies.
316 * <p/>
317 * A side note for the curious: OpenSSH does an lseek() to the specified writing offset before each write(),
318 * even for writes to files opened in O_APPEND mode. However, bear in mind that when working
319 * in the O_APPEND mode, each write() includes an implicit lseek() to the end of the file
320 * (well, this is what the newsgroups say).
321 *
322 * @param filename See the {@link SFTPv3Client comment} for the class for more details.
323 * @return a SFTPv3FileHandle handle
324 * @throws IOException
325 */
326 public SFTPv3FileHandle openFileRWAppend(String filename) throws IOException {
327 return openFile(filename, SSH_FXF_READ | SSH_FXF_WRITE | SSH_FXF_APPEND, new SFTPv3FileAttributes());
328 }
329
330 /**
331 * Open a file in append mode. The SFTP v3 draft says nothing but assuming normal POSIX
332 * behavior, all writes will be appendend to the end of the file, no matter which offset
333 * one specifies.
334 * <p/>
335 * A side note for the curious: OpenSSH does an lseek() to the specified writing offset before each write(),
336 * even for writes to files opened in O_APPEND mode. However, bear in mind that when working
337 * in the O_APPEND mode, each write() includes an implicit lseek() to the end of the file
338 * (well, this is what the newsgroups say).
339 *
340 * @param filename See the {@link SFTPv3Client comment} for the class for more details.
341 * @return a SFTPv3FileHandle handle
342 * @throws IOException
343 */
344 public SFTPv3FileHandle openFileWAppend(String filename) throws IOException {
345 return openFile(filename, SSH_FXF_WRITE | SSH_FXF_APPEND, new SFTPv3FileAttributes());
346 }
347
348 public SFTPv3FileHandle createFile(String filename) throws IOException {
349 return createFile(filename, new SFTPv3FileAttributes());
350 }
351
352 public SFTPv3FileHandle createFile(String filename, SFTPFileAttributes attr) throws IOException {
353 return openFile(filename, SSH_FXF_CREAT | SSH_FXF_READ | SSH_FXF_WRITE, attr);
354 }
355
356 /**
357 * Create a file (truncate it if it already exists) and open it for writing.
358 * Same as {@link #createFileTruncate(String, SFTPFileAttributes) createFileTruncate(filename, null)}.
359 *
360 * @param filename See the {@link SFTPv3Client comment} for the class for more details.
361 * @return a SFTPv3FileHandle handle
362 * @throws IOException
363 */
364 public SFTPv3FileHandle createFileTruncate(String filename) throws IOException {
365 return createFileTruncate(filename, new SFTPv3FileAttributes());
366 }
367
368 /**
369 * reate a file (truncate it if it already exists) and open it for writing.
370 * You can specify the default attributes of the file (the server may or may
371 * not respect your wishes).
372 *
373 * @param filename See the {@link SFTPv3Client comment} for the class for more details.
374 * @param attr may be <code>null</code> to use server defaults. Probably only
375 * the <code>uid</code>, <code>gid</code> and <code>permissions</code>
376 * (remember the server may apply a umask) entries of the {@link SFTPv3FileHandle}
377 * structure make sense. You need only to set those fields where you want
378 * to override the server's defaults.
379 * @return a SFTPv3FileHandle handle
380 * @throws IOException
381 */
382 public SFTPv3FileHandle createFileTruncate(String filename, SFTPFileAttributes attr) throws IOException {
383 return openFile(filename, SSH_FXF_CREAT | SSH_FXF_TRUNC | SSH_FXF_WRITE, attr);
384 }
385
386 public SFTPv3FileHandle openFile(String filename, int flags) throws IOException {
387 return openFile(filename, flags, new SFTPv3FileAttributes());
388 }
389
390 @Override
391 public SFTPv3FileHandle openFile(String filename, int flags, SFTPFileAttributes attr) throws IOException {
392 int req_id = generateNextRequestID();
393 TypesWriter tw = new TypesWriter();
394 tw.writeString(filename, this.getCharset());
395 tw.writeUINT32(flags);
396 tw.writeBytes(attr.toBytes());
397 sendMessage(Packet.SSH_FXP_OPEN, req_id, tw.getBytes());
398 byte[] resp = receiveMessage(34000);
399 TypesReader tr = new TypesReader(resp);
400 int t = tr.readByte();
401 listener.read(Packet.forName(t));
402 int rep_id = tr.readUINT32();
403
404 if (rep_id != req_id) {
405 throw new RequestMismatchException();
406 }
407
408 if (t == Packet.SSH_FXP_HANDLE) {
409 return new SFTPv3FileHandle(this, tr.readByteString());
410 }
411
412 if (t != Packet.SSH_FXP_STATUS) {
413 throw new PacketTypeException(t);
414 }
415
416 int errorCode = tr.readUINT32();
417 String errorMessage = tr.readString();
418 listener.read(errorMessage);
419 throw new SFTPException(errorMessage, errorCode);
420 }
421
422 @Override
423 public void createSymlink(String src, String target) throws IOException {
424 int req_id = generateNextRequestID();
425 // Changed semantics of src and target. The bug is known on SFTP servers shipped with all
426 // versions of OpenSSH (Bug #861).
427 TypesWriter tw = new TypesWriter();
428 tw.writeString(target, this.getCharset());
429 tw.writeString(src, this.getCharset());
430 sendMessage(Packet.SSH_FXP_SYMLINK, req_id, tw.getBytes());
431 expectStatusOKMessage(req_id);
432 }
433 }