From 48ded2421114c4c87ef3f8005c9f793a5d077cbd Mon Sep 17 00:00:00 2001 From: Mike Lockwood Date: Tue, 10 Jan 2012 14:24:22 -0800 Subject: ganymed-ssh2-build251beta1 Signed-off-by: Mike Lockwood --- .../java/ch/ethz/ssh2/channel/StreamForwarder.java | 116 +++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 src/main/java/ch/ethz/ssh2/channel/StreamForwarder.java (limited to 'src/main/java/ch/ethz/ssh2/channel/StreamForwarder.java') diff --git a/src/main/java/ch/ethz/ssh2/channel/StreamForwarder.java b/src/main/java/ch/ethz/ssh2/channel/StreamForwarder.java new file mode 100644 index 0000000..b32b6f9 --- /dev/null +++ b/src/main/java/ch/ethz/ssh2/channel/StreamForwarder.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2006-2011 Christian Plattner. All rights reserved. + * Please refer to the LICENSE.txt for licensing details. + */ +package ch.ethz.ssh2.channel; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; + +/** + * A StreamForwarder forwards data between two given streams. + * If two StreamForwarder threads are used (one for each direction) + * then one can be configured to shutdown the underlying channel/socket + * if both threads have finished forwarding (EOF). + * + * @author Christian Plattner + * @version 2.50, 03/15/10 + */ +public class StreamForwarder extends Thread +{ + OutputStream os; + InputStream is; + byte[] buffer = new byte[Channel.CHANNEL_BUFFER_SIZE]; + Channel c; + StreamForwarder sibling; + Socket s; + String mode; + + StreamForwarder(Channel c, StreamForwarder sibling, Socket s, InputStream is, OutputStream os, String mode) + throws IOException + { + this.is = is; + this.os = os; + this.mode = mode; + this.c = c; + this.sibling = sibling; + this.s = s; + } + + @Override + public void run() + { + try + { + while (true) + { + int len = is.read(buffer); + if (len <= 0) + break; + os.write(buffer, 0, len); + os.flush(); + } + } + catch (IOException ignore) + { + try + { + c.cm.closeChannel(c, "Closed due to exception in StreamForwarder (" + mode + "): " + + ignore.getMessage(), true); + } + catch (IOException ignored) + { + } + } + finally + { + try + { + os.close(); + } + catch (IOException ignored) + { + } + try + { + is.close(); + } + catch (IOException ignored) + { + } + + if (sibling != null) + { + while (sibling.isAlive()) + { + try + { + sibling.join(); + } + catch (InterruptedException ignored) + { + } + } + + try + { + c.cm.closeChannel(c, "StreamForwarder (" + mode + ") is cleaning up the connection", true); + } + catch (IOException ignored) + { + } + + try + { + if (s != null) + s.close(); + } + catch (IOException ignored) + { + } + } + } + } +} \ No newline at end of file -- cgit v1.2.3