comparison app/src/main/java/ch/ethz/ssh2/SCPClient.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/SCPClient.java@071eccdff8ea
children
comparison
equal deleted inserted replaced
437:208b31032318 438:d29cce60f393
1 package ch.ethz.ssh2;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.OutputStream;
11 import java.nio.charset.Charset;
12 import java.nio.charset.UnsupportedCharsetException;
13
14 /**
15 * A very basic <code>SCPClient</code> that can be used to copy files from/to
16 * the SSH-2 server. On the server side, the "scp" program must be in the PATH.
17 * <p/>
18 * This scp client is thread safe - you can download (and upload) different sets
19 * of files concurrently without any troubles. The <code>SCPClient</code> is
20 * actually mapping every request to a distinct {@link ch.ethz.ssh2.Session}.
21 *
22 * @author Christian Plattner, plattner@inf.ethz.ch
23 * @version $Id: SCPClient.java 85 2014-04-07 14:05:09Z dkocher@sudo.ch $
24 */
25
26 public class SCPClient {
27 Connection conn;
28
29 String charsetName = null;
30
31 /**
32 * Set the charset used to convert between Java Unicode Strings and byte encodings
33 * used by the server for paths and file names.
34 *
35 * @param charset the name of the charset to be used or <code>null</code> to use the platform's
36 * default encoding.
37 * @throws IOException
38 * @see #getCharset()
39 */
40 public void setCharset(String charset) throws IOException {
41 if (charset == null) {
42 charsetName = charset;
43 return;
44 }
45
46 try {
47 Charset.forName(charset);
48 }
49 catch (UnsupportedCharsetException e) {
50 throw new IOException("This charset is not supported", e);
51 }
52
53 charsetName = charset;
54 }
55
56 /**
57 * The currently used charset for filename encoding/decoding.
58 *
59 * @return The name of the charset (<code>null</code> if the platform's default charset is being used)
60 * @see #setCharset(String)
61 */
62 public String getCharset() {
63 return charsetName;
64 }
65
66 public class LenNamePair {
67 public long length;
68 String filename;
69 }
70
71 public SCPClient(Connection conn) {
72 if (conn == null)
73 throw new IllegalArgumentException("Cannot accept null argument!");
74
75 this.conn = conn;
76 }
77
78 protected void readResponse(InputStream is) throws IOException {
79 int c = is.read();
80
81 if (c == 0)
82 return;
83
84 if (c == -1)
85 throw new IOException("Remote scp terminated unexpectedly.");
86
87 if ((c != 1) && (c != 2))
88 throw new IOException("Remote scp sent illegal error code.");
89
90 if (c == 2)
91 throw new IOException("Remote scp terminated with error.");
92
93 String err = receiveLine(is);
94 throw new IOException("Remote scp terminated with error (" + err + ").");
95 }
96
97 protected String receiveLine(InputStream is) throws IOException {
98 StringBuilder sb = new StringBuilder(30);
99
100 while (true) {
101 /* This is a random limit - if your path names are longer, then adjust it */
102 if (sb.length() > 8192)
103 throw new IOException("Remote scp sent a too long line");
104
105 int c = is.read();
106
107 if (c < 0)
108 throw new IOException("Remote scp terminated unexpectedly.");
109
110 if (c == '\n')
111 break;
112
113 sb.append((char) c);
114 }
115
116 return sb.toString();
117 }
118
119 protected LenNamePair parseCLine(String line) throws IOException {
120 /* Minimum line: "xxxx y z" ---> 8 chars */
121 if (line.length() < 8)
122 throw new IOException("Malformed C line sent by remote SCP binary, line too short.");
123
124 if ((line.charAt(4) != ' ') || (line.charAt(5) == ' '))
125 throw new IOException("Malformed C line sent by remote SCP binary.");
126
127 int length_name_sep = line.indexOf(' ', 5);
128
129 if (length_name_sep == -1)
130 throw new IOException("Malformed C line sent by remote SCP binary.");
131
132 String length_substring = line.substring(5, length_name_sep);
133 String name_substring = line.substring(length_name_sep + 1);
134
135 if ((length_substring.length() <= 0) || (name_substring.length() <= 0))
136 throw new IOException("Malformed C line sent by remote SCP binary.");
137
138 if ((6 + length_substring.length() + name_substring.length()) != line.length())
139 throw new IOException("Malformed C line sent by remote SCP binary.");
140
141 final long len;
142
143 try {
144 len = Long.parseLong(length_substring);
145 }
146 catch (NumberFormatException e) {
147 throw new IOException("Malformed C line sent by remote SCP binary, cannot parse file length.");
148 }
149
150 if (len < 0)
151 throw new IOException("Malformed C line sent by remote SCP binary, illegal file length.");
152
153 LenNamePair lnp = new LenNamePair();
154 lnp.length = len;
155 lnp.filename = name_substring;
156 return lnp;
157 }
158
159 /**
160 * The session for opened for this SCP transfer must be closed using
161 * SCPOutputStream#close
162 *
163 * @param remoteFile
164 * @param length The size of the file to send
165 * @param remoteTargetDirectory
166 * @param mode
167 * @return
168 * @throws IOException
169 */
170 public SCPOutputStream put(final String remoteFile, long length, String remoteTargetDirectory, String mode)
171 throws IOException {
172 Session sess = null;
173
174 if (null == remoteFile)
175 throw new IllegalArgumentException("Null argument.");
176
177 if (null == remoteTargetDirectory)
178 remoteTargetDirectory = "";
179
180 if (null == mode)
181 mode = "0600";
182
183 if (mode.length() != 4)
184 throw new IllegalArgumentException("Invalid mode.");
185
186 for (int i = 0; i < mode.length(); i++)
187 if (Character.isDigit(mode.charAt(i)) == false)
188 throw new IllegalArgumentException("Invalid mode.");
189
190 remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory : ".";
191 String cmd = "scp -t -d \"" + remoteTargetDirectory + "\"";
192 sess = conn.openSession();
193 sess.execCommand(cmd, charsetName);
194 return new SCPOutputStream(this, sess, remoteFile, length, mode);
195 }
196
197 /**
198 * The session for opened for this SCP transfer must be closed using
199 * SCPInputStream#close
200 *
201 * @param remoteFile
202 * @return
203 * @throws IOException
204 */
205 public SCPInputStream get(final String remoteFile) throws IOException {
206 Session sess = null;
207
208 if (null == remoteFile)
209 throw new IllegalArgumentException("Null argument.");
210
211 if (remoteFile.length() == 0)
212 throw new IllegalArgumentException("Cannot accept empty filename.");
213
214 String cmd = "scp -f";
215 cmd += (" \"" + remoteFile + "\"");
216 sess = conn.openSession();
217 sess.execCommand(cmd, charsetName);
218 return new SCPInputStream(this, sess);
219 }
220 private void sendBytes(Session sess, byte[] data, String fileName, String mode) throws IOException {
221 OutputStream os = sess.getStdin();
222 InputStream is = new BufferedInputStream(sess.getStdout(), 512);
223 readResponse(is);
224 String cline = "C" + mode + " " + data.length + " " + fileName + "\n";
225 os.write(cline.getBytes("ISO-8859-1"));
226 os.flush();
227 readResponse(is);
228 os.write(data, 0, data.length);
229 os.write(0);
230 os.flush();
231 readResponse(is);
232 os.write("E\n".getBytes("ISO-8859-1"));
233 os.flush();
234 }
235
236 private void sendFiles(Session sess, String[] files, String[] remoteFiles, String mode) throws IOException {
237 byte[] buffer = new byte[8192];
238 OutputStream os = new BufferedOutputStream(sess.getStdin(), 40000);
239 InputStream is = new BufferedInputStream(sess.getStdout(), 512);
240 readResponse(is);
241
242 for (int i = 0; i < files.length; i++) {
243 File f = new File(files[i]);
244 long remain = f.length();
245 String remoteName;
246
247 if ((remoteFiles != null) && (remoteFiles.length > i) && (remoteFiles[i] != null))
248 remoteName = remoteFiles[i];
249 else
250 remoteName = f.getName();
251
252 String cline = "C" + mode + " " + remain + " " + remoteName + "\n";
253 os.write(cline.getBytes("ISO-8859-1"));
254 os.flush();
255 readResponse(is);
256 FileInputStream fis = null;
257
258 try {
259 fis = new FileInputStream(f);
260
261 while (remain > 0) {
262 int trans;
263
264 if (remain > buffer.length)
265 trans = buffer.length;
266 else
267 trans = (int) remain;
268
269 if (fis.read(buffer, 0, trans) != trans)
270 throw new IOException("Cannot read enough from local file " + files[i]);
271
272 os.write(buffer, 0, trans);
273 remain -= trans;
274 }
275 }
276 finally {
277 if (fis != null)
278 fis.close();
279 }
280
281 os.write(0);
282 os.flush();
283 readResponse(is);
284 }
285
286 os.write("E\n".getBytes("ISO-8859-1"));
287 os.flush();
288 }
289
290 private void receiveFiles(Session sess, OutputStream[] targets) throws IOException {
291 byte[] buffer = new byte[8192];
292 OutputStream os = new BufferedOutputStream(sess.getStdin(), 512);
293 InputStream is = new BufferedInputStream(sess.getStdout(), 40000);
294 os.write(0x0);
295 os.flush();
296
297 for (int i = 0; i < targets.length; i++) {
298 LenNamePair lnp = null;
299
300 while (true) {
301 int c = is.read();
302
303 if (c < 0)
304 throw new IOException("Remote scp terminated unexpectedly.");
305
306 String line = receiveLine(is);
307
308 if (c == 'T') {
309 /* Ignore modification times */
310 continue;
311 }
312
313 if ((c == 1) || (c == 2))
314 throw new IOException("Remote SCP error: " + line);
315
316 if (c == 'C') {
317 lnp = parseCLine(line);
318 break;
319 }
320
321 throw new IOException("Remote SCP error: " + ((char) c) + line);
322 }
323
324 os.write(0x0);
325 os.flush();
326 long remain = lnp.length;
327
328 while (remain > 0) {
329 int trans;
330
331 if (remain > buffer.length)
332 trans = buffer.length;
333 else
334 trans = (int) remain;
335
336 int this_time_received = is.read(buffer, 0, trans);
337
338 if (this_time_received < 0) {
339 throw new IOException("Remote scp terminated connection unexpectedly");
340 }
341
342 targets[i].write(buffer, 0, this_time_received);
343 remain -= this_time_received;
344 }
345
346 readResponse(is);
347 os.write(0x0);
348 os.flush();
349 }
350 }
351
352 private void receiveFiles(Session sess, String[] files, String target) throws IOException {
353 byte[] buffer = new byte[8192];
354 OutputStream os = new BufferedOutputStream(sess.getStdin(), 512);
355 InputStream is = new BufferedInputStream(sess.getStdout(), 40000);
356 os.write(0x0);
357 os.flush();
358
359 for (int i = 0; i < files.length; i++) {
360 LenNamePair lnp = null;
361
362 while (true) {
363 int c = is.read();
364
365 if (c < 0)
366 throw new IOException("Remote scp terminated unexpectedly.");
367
368 String line = receiveLine(is);
369
370 if (c == 'T') {
371 /* Ignore modification times */
372 continue;
373 }
374
375 if ((c == 1) || (c == 2))
376 throw new IOException("Remote SCP error: " + line);
377
378 if (c == 'C') {
379 lnp = parseCLine(line);
380 break;
381 }
382
383 throw new IOException("Remote SCP error: " + ((char) c) + line);
384 }
385
386 os.write(0x0);
387 os.flush();
388 File f = new File(target + File.separatorChar + lnp.filename);
389 FileOutputStream fop = null;
390
391 try {
392 fop = new FileOutputStream(f);
393 long remain = lnp.length;
394
395 while (remain > 0) {
396 int trans;
397
398 if (remain > buffer.length)
399 trans = buffer.length;
400 else
401 trans = (int) remain;
402
403 int this_time_received = is.read(buffer, 0, trans);
404
405 if (this_time_received < 0) {
406 throw new IOException("Remote scp terminated connection unexpectedly");
407 }
408
409 fop.write(buffer, 0, this_time_received);
410 remain -= this_time_received;
411 }
412 }
413 finally {
414 if (fop != null)
415 fop.close();
416 }
417
418 readResponse(is);
419 os.write(0x0);
420 os.flush();
421 }
422 }
423
424 /**
425 * Copy a local file to a remote directory, uses mode 0600 when creating the
426 * file on the remote side.
427 *
428 * @param localFile
429 * Path and name of local file.
430 * @param remoteTargetDirectory
431 * Remote target directory. Use an empty string to specify the
432 * default directory.
433 *
434 * @throws IOException
435 */
436 public void put(String localFile, String remoteTargetDirectory) throws IOException {
437 put(new String[] { localFile }, remoteTargetDirectory, "0600");
438 }
439
440 /**
441 * Copy a set of local files to a remote directory, uses mode 0600 when
442 * creating files on the remote side.
443 *
444 * @param localFiles
445 * Paths and names of local file names.
446 * @param remoteTargetDirectory
447 * Remote target directory. Use an empty string to specify the
448 * default directory.
449 *
450 * @throws IOException
451 */
452
453 public void put(String[] localFiles, String remoteTargetDirectory) throws IOException {
454 put(localFiles, remoteTargetDirectory, "0600");
455 }
456
457 /**
458 * Copy a local file to a remote directory, uses the specified mode when
459 * creating the file on the remote side.
460 *
461 * @param localFile
462 * Path and name of local file.
463 * @param remoteTargetDirectory
464 * Remote target directory. Use an empty string to specify the
465 * default directory.
466 * @param mode
467 * a four digit string (e.g., 0644, see "man chmod", "man open")
468 * @throws IOException
469 */
470 public void put(String localFile, String remoteTargetDirectory, String mode) throws IOException {
471 put(new String[] { localFile }, remoteTargetDirectory, mode);
472 }
473
474 /**
475 * Copy a local file to a remote directory, uses the specified mode and
476 * remote filename when creating the file on the remote side.
477 *
478 * @param localFile
479 * Path and name of local file.
480 * @param remoteFileName
481 * The name of the file which will be created in the remote
482 * target directory.
483 * @param remoteTargetDirectory
484 * Remote target directory. Use an empty string to specify the
485 * default directory.
486 * @param mode
487 * a four digit string (e.g., 0644, see "man chmod", "man open")
488 * @throws IOException
489 */
490 public void put(String localFile, String remoteFileName, String remoteTargetDirectory, String mode)
491 throws IOException {
492 put(new String[] { localFile }, new String[] { remoteFileName }, remoteTargetDirectory, mode);
493 }
494
495 /**
496 * Create a remote file and copy the contents of the passed byte array into
497 * it. Uses mode 0600 for creating the remote file.
498 *
499 * @param data
500 * the data to be copied into the remote file.
501 * @param remoteFileName
502 * The name of the file which will be created in the remote
503 * target directory.
504 * @param remoteTargetDirectory
505 * Remote target directory. Use an empty string to specify the
506 * default directory.
507 * @throws IOException
508 */
509
510 public void put(byte[] data, String remoteFileName, String remoteTargetDirectory) throws IOException {
511 put(data, remoteFileName, remoteTargetDirectory, "0600");
512 }
513
514 /**
515 * Create a remote file and copy the contents of the passed byte array into
516 * it. The method use the specified mode when creating the file on the
517 * remote side.
518 *
519 * @param data
520 * the data to be copied into the remote file.
521 * @param remoteFileName
522 * The name of the file which will be created in the remote
523 * target directory.
524 * @param remoteTargetDirectory
525 * Remote target directory. Use an empty string to specify the
526 * default directory.
527 * @param mode
528 * a four digit string (e.g., 0644, see "man chmod", "man open")
529 * @throws IOException
530 */
531 public void put(byte[] data, String remoteFileName, String remoteTargetDirectory, String mode) throws IOException {
532 Session sess = null;
533
534 if ((remoteFileName == null) || (remoteTargetDirectory == null) || (mode == null))
535 throw new IllegalArgumentException("Null argument.");
536
537 if (mode.length() != 4)
538 throw new IllegalArgumentException("Invalid mode.");
539
540 for (int i = 0; i < mode.length(); i++)
541 if (Character.isDigit(mode.charAt(i)) == false)
542 throw new IllegalArgumentException("Invalid mode.");
543
544 remoteTargetDirectory = remoteTargetDirectory.trim();
545 remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory : ".";
546 String cmd = "scp -t -d " + remoteTargetDirectory;
547
548 try {
549 sess = conn.openSession();
550 sess.execCommand(cmd);
551 sendBytes(sess, data, remoteFileName, mode);
552 }
553 catch (IOException e) {
554 throw(IOException) new IOException("Error during SCP transfer.").initCause(e);
555 }
556 finally {
557 if (sess != null)
558 sess.close();
559 }
560 }
561
562 /**
563 * Copy a set of local files to a remote directory, uses the specified mode
564 * when creating the files on the remote side.
565 *
566 * @param localFiles
567 * Paths and names of the local files.
568 * @param remoteTargetDirectory
569 * Remote target directory. Use an empty string to specify the
570 * default directory.
571 * @param mode
572 * a four digit string (e.g., 0644, see "man chmod", "man open")
573 * @throws IOException
574 */
575 public void put(String[] localFiles, String remoteTargetDirectory, String mode) throws IOException {
576 put(localFiles, null, remoteTargetDirectory, mode);
577 }
578
579 public void put(String[] localFiles, String[] remoteFiles, String remoteTargetDirectory, String mode)
580 throws IOException {
581 Session sess = null;
582
583 /*
584 * remoteFiles may be null, indicating that the local filenames shall be
585 * used
586 */
587
588 if ((localFiles == null) || (remoteTargetDirectory == null) || (mode == null))
589 throw new IllegalArgumentException("Null argument.");
590
591 if (mode.length() != 4)
592 throw new IllegalArgumentException("Invalid mode.");
593
594 for (int i = 0; i < mode.length(); i++)
595 if (Character.isDigit(mode.charAt(i)) == false)
596 throw new IllegalArgumentException("Invalid mode.");
597
598 if (localFiles.length == 0)
599 return;
600
601 remoteTargetDirectory = remoteTargetDirectory.trim();
602 remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory : ".";
603 String cmd = "scp -t -d " + remoteTargetDirectory;
604
605 for (int i = 0; i < localFiles.length; i++) {
606 if (localFiles[i] == null)
607 throw new IllegalArgumentException("Cannot accept null filename.");
608 }
609
610 try {
611 sess = conn.openSession();
612 sess.execCommand(cmd);
613 sendFiles(sess, localFiles, remoteFiles, mode);
614 }
615 catch (IOException e) {
616 throw(IOException) new IOException("Error during SCP transfer.").initCause(e);
617 }
618 finally {
619 if (sess != null)
620 sess.close();
621 }
622 }
623
624 /**
625 * Download a file from the remote server to a local directory.
626 *
627 * @param remoteFile
628 * Path and name of the remote file.
629 * @param localTargetDirectory
630 * Local directory to put the downloaded file.
631 *
632 * @throws IOException
633 */
634 public void get(String remoteFile, String localTargetDirectory) throws IOException {
635 get(new String[] { remoteFile }, localTargetDirectory);
636 }
637
638 /**
639 * Download a file from the remote server and pipe its contents into an
640 * <code>OutputStream</code>. Please note that, to enable flexible usage
641 * of this method, the <code>OutputStream</code> will not be closed nor
642 * flushed.
643 *
644 * @param remoteFile
645 * Path and name of the remote file.
646 * @param target
647 * OutputStream where the contents of the file will be sent to.
648 * @throws IOException
649 */
650 public void get(String remoteFile, OutputStream target) throws IOException {
651 get(new String[] { remoteFile }, new OutputStream[] { target });
652 }
653
654 private void get(String remoteFiles[], OutputStream[] targets) throws IOException {
655 Session sess = null;
656
657 if ((remoteFiles == null) || (targets == null))
658 throw new IllegalArgumentException("Null argument.");
659
660 if (remoteFiles.length != targets.length)
661 throw new IllegalArgumentException("Length of arguments does not match.");
662
663 if (remoteFiles.length == 0)
664 return;
665
666 String cmd = "scp -f";
667
668 for (int i = 0; i < remoteFiles.length; i++) {
669 if (remoteFiles[i] == null)
670 throw new IllegalArgumentException("Cannot accept null filename.");
671
672 String tmp = remoteFiles[i].trim();
673
674 if (tmp.length() == 0)
675 throw new IllegalArgumentException("Cannot accept empty filename.");
676
677 cmd += (" " + tmp);
678 }
679
680 try {
681 sess = conn.openSession();
682 sess.execCommand(cmd);
683 receiveFiles(sess, targets);
684 }
685 catch (IOException e) {
686 throw(IOException) new IOException("Error during SCP transfer.").initCause(e);
687 }
688 finally {
689 if (sess != null)
690 sess.close();
691 }
692 }
693
694 /**
695 * Download a set of files from the remote server to a local directory.
696 *
697 * @param remoteFiles
698 * Paths and names of the remote files.
699 * @param localTargetDirectory
700 * Local directory to put the downloaded files.
701 *
702 * @throws IOException
703 */
704 public void get(String remoteFiles[], String localTargetDirectory) throws IOException {
705 Session sess = null;
706
707 if ((remoteFiles == null) || (localTargetDirectory == null))
708 throw new IllegalArgumentException("Null argument.");
709
710 if (remoteFiles.length == 0)
711 return;
712
713 String cmd = "scp -f";
714
715 for (int i = 0; i < remoteFiles.length; i++) {
716 if (remoteFiles[i] == null)
717 throw new IllegalArgumentException("Cannot accept null filename.");
718
719 String tmp = remoteFiles[i].trim();
720
721 if (tmp.length() == 0)
722 throw new IllegalArgumentException("Cannot accept empty filename.");
723
724 cmd += (" " + tmp);
725 }
726
727 try {
728 sess = conn.openSession();
729 sess.execCommand(cmd);
730 receiveFiles(sess, remoteFiles, localTargetDirectory);
731 }
732 catch (IOException e) {
733 throw(IOException) new IOException("Error during SCP transfer.").initCause(e);
734 }
735 finally {
736 if (sess != null)
737 sess.close();
738 }
739 }
740 }
741
742